Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(multi-screen): in-app triggers for the second screen (#17666)
Abhay Madanec0efb6b90f6
diff --git a/lang/main.json b/lang/main.jsonindex 6d4e7cc746..bf998415da 100644--- a/lang/main.json+++ b/lang/main.json@@ -839,6 +839,12 @@"me": "me","multiScreen": {"noParticipants": "No participants",+ "openFailed": "Something went wrong. Please try again.",+ "openFailedTitle": "Could not open the second screen",+ "permissionDenied": "Allow this site to manage windows and try again.",+ "popupBlocked": "Allow pop-ups for this site and try again.",+ "removeFromSecondScreen": "Remove from second screen",+ "sendToSecondScreen": "Show on second screen","sharedVideoError": "The shared video could not be played on this screen","sharedVideoInactive": "Share a video in the meeting to show it on the second screen","showOnStage": "Show {{name}} on the second screen",diff --git a/react/features/filmstrip/components/web/Thumbnail.tsx b/react/features/filmstrip/components/web/Thumbnail.tsxindex 09c3473ee9..5c5ea428fb 100644--- a/react/features/filmstrip/components/web/Thumbnail.tsx+++ b/react/features/filmstrip/components/web/Thumbnail.tsx@@ -39,6 +39,8 @@ import { ITrack } from '../../../base/tracks/types';import { getVideoObjectPosition } from '../../../face-landmarks/functions';import { hideGif, showGif } from '../../../gifs/actions';import { getGifDisplayMode, getGifForParticipant } from '../../../gifs/functions';+import SendToSecondScreenIcon from '../../../multi-screen/components/SendToSecondScreenIcon';+import { ISecondScreenSource } from '../../../multi-screen/types';import PresenceLabel from '../../../presence-status/components/PresenceLabel';import { LAYOUTS } from '../../../video-layout/constants';import { getCurrentLayout } from '../../../video-layout/functions.web';@@ -66,6 +68,12 @@ import ThumbnailTopIndicators from './ThumbnailTopIndicators';import TranslationPendingChip from './TranslationPendingChip';import VirtualScreenshareParticipant from './VirtualScreenshareParticipant';+/**+ * Module-scoped so the second-screen trigger's click handler stays stable+ * across renders.+ */+const SHARED_VIDEO_SECOND_SCREEN_SOURCE: ISecondScreenSource = { role: 'sharedvideo' };+/*** The type of the React {@code Component} state of {@link Thumbnail}.*/@@ -289,6 +297,23 @@ const defaultStyles = (theme: Theme) => {bottom: 0},+ /**+ * The shared-video thumbnail has no indicators row, so its second-screen+ * trigger is placed on its own, where the menu trigger sits on the other+ * thumbnails. Applied to the trigger itself rather than to a container+ * around it: the trigger renders nothing at all where the feature is off,+ * and an empty box here would still take the corner of a thumbnail that+ * is itself the click target for pinning.+ */+ sharedVideoTopRight: {+ position: 'absolute' as const,+ top: 0,+ right: 0,+ padding: theme.spacing(1),+ zIndex: 10,+ display: 'flex'+ },+indicatorsBackground: {backgroundColor: 'rgba(0, 0, 0, 0.7)',borderRadius: '4px',@@ -844,6 +869,8 @@ class Thumbnail extends Component<IProps, IState> {*/_renderFakeParticipant() {const { _isMobile, _participant: { avatarURL, pinned, name } } = this.props;+ const { isHovered } = this.state;+ const classes = withStyles.getClasses(this.props);const styles = this._getStyles();const containerClassName = this._getContainerClassName();@@ -871,6 +898,10 @@ class Thumbnail extends Component<IProps, IState> {src = { avatarURL } />): this._renderAvatar(styles.avatar)}+ <SendToSecondScreenIcon+ className = { classes.sharedVideoTopRight }+ source = { SHARED_VIDEO_SECOND_SCREEN_SOURCE }+ visible = { isHovered } /></span>);}diff --git a/react/features/filmstrip/components/web/ThumbnailTopIndicators.tsx b/react/features/filmstrip/components/web/ThumbnailTopIndicators.tsxindex aaccf9a5d1..a3a42becf0 100644--- a/react/features/filmstrip/components/web/ThumbnailTopIndicators.tsx+++ b/react/features/filmstrip/components/web/ThumbnailTopIndicators.tsx@@ -1,4 +1,4 @@-import React from 'react';+import React, { useMemo } from 'react';import { useSelector } from 'react-redux';import { makeStyles } from 'tss-react/mui';@@ -6,6 +6,8 @@ import { IReduxState } from '../../../app/types';import { isMobileBrowser } from '../../../base/environment/utils';import { isScreenShareParticipantById } from '../../../base/participants/functions';import ConnectionIndicator from '../../../connection-indicator/components/web/ConnectionIndicator';+import SendToSecondScreenIcon from '../../../multi-screen/components/SendToSecondScreenIcon';+import { ISecondScreenSource } from '../../../multi-screen/types';import { STATS_POPOVER_POSITION, THUMBNAIL_TYPE } from '../../constants';import { getIndicatorsTooltipPosition } from '../../functions.web';@@ -99,6 +101,13 @@ const ThumbnailTopIndicators = ({(state: IReduxState) => isScreenShareParticipantById(state, participantId));+ // Kept stable so the trigger's click handler is too: this thumbnail+ // re-renders on every hover and every connection-stats tick.+ const screenshareSource: ISecondScreenSource = useMemo(+ () => ({ participant: participantId,+ role: 'screenshare' }),+ [ participantId ]);+if (isVirtualScreenshareParticipant) {return (<div className = { styles.container }>@@ -110,6 +119,12 @@ const ThumbnailTopIndicators = ({participantId = { participantId }statsPopoverPosition = { STATS_POPOVER_POSITION[thumbnailType] } />}++ {/* This thumbnail has no menu to add an entry to, so the second+ screen gets its own button, where the menu trigger would be. */}+ <SendToSecondScreenIcon+ source = { screenshareSource }+ visible = { isHovered } /></div>);}diff --git a/react/features/multi-screen/actions.web.ts b/react/features/multi-screen/actions.web.tsindex 298d0ac590..045109e3fc 100644--- a/react/features/multi-screen/actions.web.ts+++ b/react/features/multi-screen/actions.web.ts@@ -24,7 +24,11 @@ export function setSecondScreen(id: string, source?: ISecondScreenSource, screentype: SET_SECOND_SCREEN,id,source,- screenId+ screenId,++ // Stamped here rather than in the reducer to keep the reducer pure; it+ // orders the in-app windows by how recently they were targeted.+ setAt: Date.now()};}diff --git a/react/features/multi-screen/components/SecondScreenView.web.tsx b/react/features/multi-screen/components/SecondScreenView.web.tsxindex f20e064664..0ff1b8314a 100644--- a/react/features/multi-screen/components/SecondScreenView.web.tsx+++ b/react/features/multi-screen/components/SecondScreenView.web.tsx@@ -29,7 +29,8 @@ interface IProps {* Routes a single second-screen window to a layout from its redux source* descriptor. A {@code whiteboard} source renders the {@link SecondScreenWhiteboard}* iframe; a {@code sharedvideo} source renders the meeting's shared video via- * {@link SecondScreenSharedVideo}; a {@code tile} source renders the+ * {@link SecondScreenSharedVideo}; a {@code screenshare} source renders that+ * screenshare full-bleed; a {@code tile} source renders the* {@link SecondScreenGallery} grid; a stage or participant source renders the* {@link SecondScreenStage} layout (featured participant plus filmstrip); any* other source renders the single track/avatar via {@link SecondScreenSingle}.@@ -54,6 +55,17 @@ const SecondScreenView = ({ id, win }: IProps) => {);}+ // Before the participant check below: a screenshare names its virtual+ // screenshare participant to say which one to show, but it is still shown+ // full-bleed on its own rather than in the stage layout.+ if (source?.role === 'screenshare') {+ return (+ <SecondScreenSingle+ id = { id }+ win = { win } />+ );+ }+if (source?.role === 'tile') {return (<SecondScreenGallerydiff --git a/react/features/multi-screen/components/SendToSecondScreenButton.web.tsx b/react/features/multi-screen/components/SendToSecondScreenButton.web.tsxnew file mode 100644index 0000000000..649ce5532f--- /dev/null+++ b/react/features/multi-screen/components/SendToSecondScreenButton.web.tsx@@ -0,0 +1,78 @@+import React, { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { IconScreenshare } from '../../base/icons/svg';+import ContextMenuItem from '../../base/ui/components/web/ContextMenuItem';+import { NOTIFY_CLICK_MODE } from '../../toolbox/types';+import { IButtonProps } from '../../video-menu/types';+import { useSendToSecondScreen } from '../hooks.web';+import { ISecondScreenSource } from '../types';++interface IProps extends IButtonProps {++ /**+ * Button text class name.+ */+ className?: string;++ /**+ * Whether the icon should be hidden or not.+ */+ noIcon?: boolean;++ /**+ * Click handler executed aside from the main action.+ */+ onClick?: Function;++ /**+ * What to show on the second screen.+ */+ source: ISecondScreenSource;+}++/**+ * A context-menu entry that sends its source to a second screen, and takes it+ * off again once it is there. Renders nothing when the feature is unavailable,+ * so it can be added unconditionally to a menu.+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement | null}+ */+const SendToSecondScreenButton = ({+ className,+ noIcon = false,+ notifyClick,+ notifyMode,+ onClick,+ source+}: IProps) => {+ const { t } = useTranslation();+ const { active, onClick: sendToSecondScreen, visible } = useSendToSecondScreen(source);++ const _onClick = useCallback(() => {+ notifyClick?.();+ if (notifyMode === NOTIFY_CLICK_MODE.PREVENT_AND_NOTIFY) {+ return;+ }+ sendToSecondScreen();+ onClick?.();+ }, [ notifyClick, notifyMode, onClick, sendToSecondScreen ]);++ if (!visible) {+ return null;+ }++ const text = t(active ? 'multiScreen.removeFromSecondScreen' : 'multiScreen.sendToSecondScreen');++ return (+ <ContextMenuItem+ accessibilityLabel = { text }+ icon = { noIcon ? null : IconScreenshare }+ onClick = { _onClick }+ text = { text }+ textClassName = { className } />+ );+};++export default SendToSecondScreenButton;diff --git a/react/features/multi-screen/components/SendToSecondScreenIcon.web.tsx b/react/features/multi-screen/components/SendToSecondScreenIcon.web.tsxnew file mode 100644index 0000000000..e7cf3808fc--- /dev/null+++ b/react/features/multi-screen/components/SendToSecondScreenIcon.web.tsx@@ -0,0 +1,96 @@+import React, { useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { makeStyles } from 'tss-react/mui';++import { isMobileBrowser } from '../../base/environment/utils';+import { IconScreenshare } from '../../base/icons/svg';+import Button from '../../base/ui/components/web/Button';+import { useSendToSecondScreen } from '../hooks.web';+import { ISecondScreenSource } from '../types';++interface IProps {++ /**+ * Class name for the button's wrapper. Applied here rather than to a+ * container around this component so that a thumbnail that positions the+ * trigger itself does not lay out an empty box over its own corner on the+ * deployments where the feature is off and nothing renders.+ */+ className?: string;++ /**+ * What to show on the second screen.+ */+ source: ISecondScreenSource;++ /**+ * Whether the tile is hovered, i.e. whether to show the button at all.+ */+ visible: boolean;+}++const useStyles = makeStyles()(() => {+ return {+ button: {+ padding: '3px !important',+ borderRadius: '4px',++ '& svg': {+ width: '18px',+ height: '18px'+ }+ }+ };+});++/**+ * The tile counterpart of {@link SendToSecondScreenButton}, for the thumbnails+ * that have no context menu to add an entry to (a screenshare, the shared+ * video). It sits where the menu trigger sits on the other thumbnails and, like+ * it, appears on hover.+ *+ * @param {IProps} props - The component props.+ * @returns {ReactElement | null}+ */+const SendToSecondScreenIcon = ({ className, source, visible }: IProps) => {+ const { classes } = useStyles();+ const { t } = useTranslation();+ const { active, onClick, visible: enabled } = useSendToSecondScreen(source);++ // The thumbnails this sits on are themselves clickable (they pin), so the+ // click must not reach them.+ const _onClick = useCallback((e?: React.MouseEvent) => {+ e?.stopPropagation();+ onClick();+ }, [ onClick ]);++ const _onKeyDown = useCallback((e: React.KeyboardEvent) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.stopPropagation();+ }+ }, []);++ // Stays put while its source is on a second screen, even once the pointer+ // leaves: it is the only way to take it off again, and a control that+ // vanishes on unhover would leave the tile with no sign that it is being+ // shown elsewhere.+ if (!enabled || (!visible && !active) || isMobileBrowser()) {+ return null;+ }++ return (+ <span+ className = { className }+ onKeyDown = { _onKeyDown }>+ <Button+ accessibilityLabel = {+ t(active ? 'multiScreen.removeFromSecondScreen' : 'multiScreen.sendToSecondScreen') }+ className = { classes.button }+ icon = { IconScreenshare }+ onClick = { _onClick }+ size = 'small' />+ </span>+ );+};++export default SendToSecondScreenIcon;diff --git a/react/features/multi-screen/constants.ts b/react/features/multi-screen/constants.tsindex 489177a745..2322f48cec 100644--- a/react/features/multi-screen/constants.ts+++ b/react/features/multi-screen/constants.ts@@ -2,3 +2,12 @@* The default window id used when the embedder does not specify one.*/export const DEFAULT_SECOND_SCREEN_ID = 'default';++/**+ * The id prefix of the second-screen windows opened from the in-app triggers,+ * as opposed to the ones an embedder opens through the external API. The+ * in-app triggers only ever take over a window of their own (see+ * {@code pickSecondScreenTarget}), so an embedder's windows keep showing what+ * the embedder put on them.+ */+export const UI_SECOND_SCREEN_ID_PREFIX = 'ui-screen-';diff --git a/react/features/multi-screen/functions.web.ts b/react/features/multi-screen/functions.web.tsindex 3062ee6ebb..b68beeb460 100644--- a/react/features/multi-screen/functions.web.ts+++ b/react/features/multi-screen/functions.web.ts@@ -11,10 +11,15 @@ import {getVirtualScreenshareParticipantTrack} from '../base/tracks/functions.any';import { getLargeVideoParticipant } from '../large-video/functions';+import { showWarningNotification } from '../notifications/actions';+import { NOTIFICATION_TIMEOUT_TYPE } from '../notifications/constants';+import { isVideoPlaying } from '../shared-video/functions';+import { isWhiteboardPresent } from '../whiteboard/functions';import { removeSecondScreen, setSecondScreenWindow } from './actions.web';+import { UI_SECOND_SCREEN_ID_PREFIX } from './constants';import logger from './logger';-import { ISecondScreenSource } from './types';+import { ISecondScreenEntry, ISecondScreenSource } from './types';// The Window Management API typings (Window.getScreenDetails, ScreenDetails, ScreenDetailed) come// from the `@types/webscreens-window-placement` devDependency.@@ -48,6 +53,37 @@ const SECOND_SCREEN_LOAD_TIMEOUT = 10000;*/const SECOND_SCREEN_LOAD_POLL_INTERVAL = 250;+/**+ * How long to wait for the window-management permission before giving up on+ * placing a window. A call to {@code getScreenDetails()} does not settle while+ * its prompt is on screen, and one that is never answered never settles it at+ * all. The prompt is only ever raised where the call carries transient user+ * activation, which is the in-app triggers; without it Chromium rejects at once+ * with {@code NotAllowedError}, which is why the external API path fails fast+ * rather than hanging, and why headless does too. Without a bound the window+ * would sit unplaced on the meeting's own screen indefinitely, with nobody told+ * anything either way. Generous enough for someone to read the prompt before+ * answering, and a later answer is not wasted, since {@link loadScreenDetails}+ * still caches the result for the next attempt.+ */+const SECOND_SCREEN_PERMISSION_TIMEOUT = 30000;++/**+ * How long a source that names a participant is given to come back before its+ * window is closed. Absence is not proof of a departure: a participant whose+ * presence flaps, or whose client rejoins the room, is removed and re-added, and+ * the check that runs in between cannot tell that apart from someone leaving for+ * good. Closing is one-way, because the send was a one-shot action whose trigger+ * left with the tile, so being wrong costs a window the user cannot get back+ * while being slow costs a few seconds of a window that is already showing an+ * avatar. Only the participant-backed sources wait: the whiteboard and the+ * shared video go when the local user stops them, which is deliberate and should+ * not lag. A teardown of the whole participant list needs the room to be left,+ * which ends the conference and resets every window anyway, so nothing here+ * covers that case or could.+ */+const SECOND_SCREEN_SOURCE_GONE_GRACE = 5000;+/*** The name of the {@code meta} marker carried by the shell page (see* {@link getSecondScreenPageUrl}). A {@code load} event only says that@@ -141,8 +177,16 @@ export function resolveSource(state: IReduxState, source: ISecondScreenSource) {participant = getLargeVideoParticipant(state);iTrack = getVideoTrackByParticipant(state, participant);} else if (source.role === 'screenshare') {- iTrack = tracks.find(t => t.videoType === VIDEO_TYPE.DESKTOP && !t.muted && Boolean(t.jitsiTrack));- participant = iTrack ? getParticipantById(state, iTrack.participantId) : undefined;+ // A screenshare sent from its own tile names the virtual screenshare+ // participant that owns it, so the right one is rendered when several+ // are live at once; without one, fall back to whatever is being shared.+ if (source.participant) {+ iTrack = getVirtualScreenshareParticipantTrack(tracks, source.participant);+ participant = getParticipantById(state, source.participant);+ } else {+ iTrack = tracks.find(t => t.videoType === VIDEO_TYPE.DESKTOP && !t.muted && Boolean(t.jitsiTrack));+ participant = iTrack ? getParticipantById(state, iTrack.participantId) : undefined;+ }} else if (source.participant) {participant = getParticipantById(state, source.participant);@@ -169,12 +213,42 @@ export function resolveSource(state: IReduxState, source: ISecondScreenSource) {};}+/**+ * A stable signature of what a single source should currently render. Includes+ * the avatar identity (id/url/name) so the fallback avatar redraws even while no+ * track is present.+ *+ * @param {IReduxState} state - The redux state.+ * @param {ISecondScreenSource} source - The source descriptor.+ * @returns {string}+ */+function getSourceSignature(state: IReduxState, source: ISecondScreenSource): string {++ // The shared video and the whiteboard resolve to neither a track nor a+ // participant (each owns its own element: a player, an iframe), so what has+ // to be signed is whether the thing is there at all. Without this both sign+ // as the constant `avatar:::`, so stopping the share or closing the+ // whiteboard reads exactly like still having it and nothing re-runs.+ if (source.role === 'sharedvideo') {+ return `sharedvideo:${isVideoPlaying(state)}`;+ }++ if (source.role === 'whiteboard') {+ return `whiteboard:${isWhiteboardPresent(state)}`;+ }++ const { track, participant } = resolveSource(state, source);++ return track+ ? track.id+ : `avatar:${participant?.id ?? ''}:${participant?.loadableAvatarUrl ?? ''}:${participant?.name ?? ''}`;+}+/*** A stable signature of what every second-screen window should currently render.- * When it changes — the active speaker switches, a source mutes/unmutes, or an- * avatar finishes loading — the subscriber re-applies the sources, swapping the- * window content in place. Includes the avatar identity (id/url/name) so the- * fallback avatar redraws even while no track is present.+ * When it changes — the active speaker switches, a source mutes/unmutes, an+ * avatar finishes loading, or a source goes away entirely — the subscriber+ * re-applies the sources, swapping the window content in place.** @param {IReduxState} state - The redux state.* @returns {string}@@ -183,14 +257,7 @@ export function getSecondScreenSignature(state: IReduxState): string {const { screens } = state['features/multi-screen'];return Object.keys(screens).sort()- .map(id => {- const { track, participant } = resolveSource(state, screens[id].source);- const key = track- ? track.id- : `avatar:${participant?.id ?? ''}:${participant?.loadableAvatarUrl ?? ''}:${participant?.name ?? ''}`;-- return `${id}:${key}`;- })+ .map(id => `${id}:${getSourceSignature(state, screens[id].source)}`).join('|');}@@ -239,23 +306,396 @@ function getSecondScreenPageUrl(state: IReduxState): string {}/**- * Computes the {@code window.open} features string, placing the window on a- * physical screen via the Window Management API. Rejects if the API is- * unavailable/denied (the feature requires it).+ * The {@code ScreenDetails} object, cached after the first successful call. The+ * object is live: the browser keeps its {@code screens} and+ * {@code currentScreen} up to date as displays come and go, so it never needs to+ * be invalidated. Nothing subscribes to its {@code screenschange} event either,+ * because every read happens at the point of use. That matters for the indices+ * into {@code screens}: the browser renumbers the array on a display change, so+ * an index only means anything at the moment it is read, which is why occupancy+ * is derived from where the windows actually are (see+ * {@link getWindowScreenIndex}) rather than from the indices they were opened+ * with.+ *+ * Caching it is also what lets a window be opened synchronously:+ * {@code window.open} then runs in the same task as the click that asked for it,+ * keeping the user activation that the popup blocker requires.+ */+let screenDetails: ScreenDetails | undefined;++/**+ * Obtains and caches the {@code ScreenDetails}. The first call requests the+ * window-management permission, so it may prompt.+ *+ * @returns {Promise<ScreenDetails>}+ */+export async function loadScreenDetails(): Promise<ScreenDetails> {+ screenDetails = screenDetails ?? await window.getScreenDetails();++ return screenDetails;+}++/**+ * Bounds a wait on the screen details, so an open cannot be left pending forever+ * behind a permission prompt nobody answers (see+ * {@link SECOND_SCREEN_PERMISSION_TIMEOUT}). Rejects on the timeout, which the+ * caller treats exactly like a denial: either way the window cannot be placed.+ *+ * @param {Promise<ScreenDetails>} pending - The in-flight request.+ * @returns {Promise<ScreenDetails>}+ */+function awaitScreenDetails(pending: Promise<ScreenDetails>): Promise<ScreenDetails> {+ return new Promise<ScreenDetails>((resolve, reject) => {+ const timeout = setTimeout(+ () => reject(new Error('Timed out waiting for the window-management permission')),+ SECOND_SCREEN_PERMISSION_TIMEOUT);++ pending.then(resolve, reject).finally(() => clearTimeout(timeout));+ });+}++/**+ * Pre-loads the {@code ScreenDetails} when the window-management permission has+ * already been granted, so the first in-app trigger can open its window without+ * awaiting anything. Deliberately does not prompt: permission is only ever+ * requested by an actual open, never just to decide what to draw.+ *+ * @returns {void}+ */+export function preloadScreenDetails() {+ if (screenDetails || !isSecondScreenSupported()) {+ return;+ }++ navigator.permissions?.query({ name: 'window-management' as PermissionName })+ .then(status => (status.state === 'granted' ? loadScreenDetails() : undefined))+ .catch(e => logger.debug('Could not pre-load the screen details', e));+}++/**+ * The indices of the screens the meeting window is not on, in the order the+ * Window Management API reports them.+ *+ * @param {ScreenDetails} details - The screen details.+ * @returns {number[]}+ */+function getExternalScreenIndices(details: ScreenDetails): number[] {+ const { currentScreen } = details;++ return details.screens+ .map((screen, index) => ({ screen,+ index }))+ .filter(({ screen }) => screen.left !== currentScreen.left || screen.top !== currentScreen.top)+ .map(({ index }) => index);+}++/**+ * The index of the screen a live second-screen window is actually on, derived+ * from the window's own position in the multi-screen coordinate space. The+ * {@code screenId} on its entry cannot answer this: it records where the window+ * was asked to go at open time, and a window is never re-placed afterwards+ * (neither when the user drags it nor when the browser renumbers+ * {@code details.screens} on a display change), so it goes stale while the+ * window stays put. Uses the window's centre, so one straddling a boundary+ * counts as being on the screen showing most of it.+ *+ * @param {ScreenDetails} details - The screen details.+ * @param {Window} win - The window to locate.+ * @returns {number | undefined} The screen index, or {@code undefined} if the+ * window could not be read or sits outside every reported screen.+ */+function getWindowScreenIndex(details: ScreenDetails, win: Window): number | undefined {+ let index;++ try {+ const x = win.screenLeft + (win.outerWidth / 2);+ const y = win.screenTop + (win.outerHeight / 2);++ index = details.screens.findIndex(screen =>+ x >= screen.left && x < screen.left + screen.width+ && y >= screen.top && y < screen.top + screen.height);+ } catch (_e) {++ // The second-screen windows are same-origin by the time they have a+ // handle, so this is not expected. Answering "unknown" rather than+ // guessing a screen leaves it to the caller, which fails closed (see+ // {@link getEntryScreenIndex}).+ return undefined;+ }++ return index === -1 ? undefined : index;+}++/**+ * The screen a second-screen entry counts as being on: where its window actually+ * is, else the screen it asked for, else {@code fallback} (an entry that named+ * no screen is placed on the first external one, which is what+ * {@link getTargetScreen} does with it).+ *+ * The position is preferred because {@code screenId} only records where the+ * window was asked to go at open time: a window is never re-placed afterwards,+ * so it goes stale when the user drags the window or the browser renumbers+ * {@code details.screens} on a display change. Falling back rather than+ * answering "nowhere" is deliberate: a window whose position cannot be read+ * (still opening, or centred outside every reported screen, as a minimized+ * popup may report) still holds a screen, and treating it as free would open+ * another window on top of it.+ *+ * @param {ScreenDetails} details - The screen details.+ * @param {ISecondScreenEntry} entry - The entry to locate.+ * @param {number} fallback - The screen an entry that named none is placed on.+ * @returns {number}+ */+function getEntryScreenIndex(details: ScreenDetails, entry: ISecondScreenEntry, fallback: number): number {+ const win = (entry.handle as ISecondScreenHandle | undefined)?.win;++ // A ternary rather than && so an unreadable position and a window without a+ // handle both arrive here as undefined; ?? would pass a false straight+ // through as the answer.+ const index = win && !win.closed ? getWindowScreenIndex(details, win) : undefined;++ return index ?? entry.screenId ?? fallback;+}++/**+ * The screen indices the second-screen windows currently occupy. Read from the+ * live windows rather than from the entries, so it survives the browser+ * renumbering the screens and follows a window the user moved.+ *+ * @param {ScreenDetails} details - The screen details.+ * @param {Object} screens - The second-screen entries.+ * @param {number} fallback - The screen an entry that named none is placed on,+ * i.e. what {@link getTargetScreen} picks for it.+ * @returns {Set<number>}+ */+function getOccupiedScreens(+ details: ScreenDetails,+ screens: { [id: string]: ISecondScreenEntry; },+ fallback: number): Set<number> {+ const occupied = new Set<number>();++ Object.values(screens).forEach(entry => {+ const win = (entry.handle as ISecondScreenHandle | undefined)?.win;++ // A window the user closed by hand frees its screen. One that has no+ // handle yet does not: it is still opening onto the screen it asked for.+ if (win?.closed) {+ return;+ }++ occupied.add(getEntryScreenIndex(details, entry, fallback));+ });++ return occupied;+}++/**+ * An id no second-screen window is using. Deliberately carries no screen index:+ * occupancy is positional now, and an id that encodes a screen is a second,+ * conflicting answer to "which window is on that screen" that goes stale the+ * moment a display is undocked. It only has to be unique, or a "nothing is on+ * that screen, open one" decision hands back the id of a window that exists and+ * re-sources it instead, leaving the screen empty.+ *+ * @param {Object} screens - The second-screen entries.+ * @returns {string}+ */+function mintSecondScreenId(screens: { [id: string]: ISecondScreenEntry; }): string {+ let n = 0;++ while (screens[`${UI_SECOND_SCREEN_ID_PREFIX}${n}`]) {+ n++;+ }++ return `${UI_SECOND_SCREEN_ID_PREFIX}${n}`;+}++/**+ * Picks which second-screen window an in-app trigger should target. Each screen+ * shows its own source, so a trigger fills the first external screen that has no+ * window on it; once they all have one it takes over the window this feature+ * targeted longest ago, on the screen that window is on now. Windows opened+ * through the external API are never taken over, only counted as occupying their+ * screen.+ *+ * Falls back to a single window on the current screen when there is no external+ * screen at all, which is what {@link getTargetScreen} places it on. That is+ * also the answer before the screen details have been obtained: the very first+ * send cannot enumerate the screens without prompting for the window-management+ * permission, and the open does that (see {@link openSecondScreenWindow}).+ *+ * @param {IReduxState} state - The redux state.+ * @returns {Object} The window id to target and the screen index to place it on.+ */+export function pickSecondScreenTarget(state: IReduxState): { id: string; screenId?: number; } {+ const details = screenDetails;+ const external = details ? getExternalScreenIndices(details) : [];+ const { screens } = state['features/multi-screen'];++ // One screen, so one window: a fixed id, which re-targets the window already+ // up instead of opening another on top of it.+ if (!details || !external.length) {+ return { id: `${UI_SECOND_SCREEN_ID_PREFIX}0` };+ }++ const taken = getOccupiedScreens(details, screens, external[0]);+ const free = external.find(index => !taken.has(index));++ if (typeof free === 'number') {+ return { id: mintSecondScreenId(screens),+ screenId: free };+ }++ // Only a window that is actually on an external screen can be taken over. One+ // that has ended up on the meeting's own screen (dragged there, or relocated+ // by the browser when its display was undocked) would otherwise be the oldest+ // and get picked, putting the content on top of the meeting while the+ // external screens keep what they were already showing.+ const ours = Object.entries(screens).filter(([ id, entry ]) =>+ id.startsWith(UI_SECOND_SCREEN_ID_PREFIX)+ && external.includes(getEntryScreenIndex(details, entry, external[0])));++ // Every external screen is taken by windows this trigger must not touch:+ // open on the first one anyway rather than taking one of them over.+ if (!ours.length) {+ return { id: mintSecondScreenId(screens),+ screenId: external[0] };+ }++ const [ id, entry ] = ours.reduce((oldest, current) =>+ ((current[1].setAt ?? 0) < (oldest[1].setAt ?? 0) ? current : oldest));++ // Re-target where that window is now, not where it was first sent, so taking+ // it over does not also move it. Only used if it has to be re-opened: a+ // window that is still up keeps its position either way.+ return { id,+ screenId: getEntryScreenIndex(details, entry, external[0]) };+}++/**+ * Whether two source descriptors select the same thing, so a trigger can tell+ * that what it would send is already on a second screen. Only {@code media} is+ * defaulted: an absent {@code role} is not the same as {@code 'stage'} (it pins+ * the named participant rather than following the large video), so the roles are+ * compared as they are.+ *+ * @param {ISecondScreenSource} a - A source descriptor.+ * @param {ISecondScreenSource} b - The source descriptor to compare it against.+ * @returns {boolean}+ */+export function isSameSecondScreenSource(a?: ISecondScreenSource, b?: ISecondScreenSource): boolean {+ if (!a || !b) {+ return false;+ }++ return a.role === b.role+ && a.participant === b.participant+ && (a.media ?? 'camera') === (b.media ?? 'camera');+}++/**+ * The id of the in-app second-screen window already showing {@code source}, if+ * there is one. Only the in-app windows are considered, for the same reason+ * {@link pickSecondScreenTarget} only takes those over: a trigger must not turn+ * off a window the embedder opened and is managing through the external API.+ *+ * @param {IReduxState} state - The redux state.+ * @param {ISecondScreenSource} source - The source to look for.+ * @returns {string | undefined} The window id, if any.+ */+export function getSecondScreenShowing(state: IReduxState, source: ISecondScreenSource): string | undefined {+ const { screens } = state['features/multi-screen'];++ return Object.keys(screens).find(id =>+ id.startsWith(UI_SECOND_SCREEN_ID_PREFIX) && isSameSecondScreenSource(screens[id].source, source));+}++/**+ * Whether what a source names has gone from the meeting, leaving its window with+ * nothing to render. Every in-app trigger lives on the thing it sends (a+ * screenshare's own thumbnail, the shared video's thumbnail, a participant's+ * context menu), so when that thing goes the trigger goes with it, and the only+ * control that could take the window down is gone before the user can use it.+ * What is left is a window showing an anonymous avatar on black that nobody in+ * the meeting can close, only somebody standing at the other display.+ *+ * Only a source that selects one particular thing can go away this way:+ * {@code stage} and {@code tile} follow the meeting itself, and a+ * {@code screenshare} with no participant falls back to whatever is being+ * shared. The rest are asked either by the participant they name or, where they+ * name none, by role.+ *+ * @param {IReduxState} state - The redux state.+ * @param {ISecondScreenSource} source - The source to check.+ * @returns {boolean}+ */+function isSecondScreenSourceGone(state: IReduxState, source: ISecondScreenSource): boolean {+ if (source.role === 'sharedvideo') {+ return !isVideoPlaying(state);+ }++ // Closing the whiteboard removes its fake participant, taking the tile and+ // the context menu holding the only trigger with it. The source names no+ // participant, so it has to be asked for by role like the shared video.+ if (source.role === 'whiteboard') {+ return !isWhiteboardPresent(state);+ }++ // A screenshare names the virtual participant that owns it, which is removed+ // when the share stops; anything else names a real participant, removed when+ // they leave.+ return Boolean(source.participant) && !getParticipantById(state, source.participant ?? '');+}++/**+ * The screen a second-screen window should end up on: the one it named, else the+ * first screen the meeting window is not on, else the meeting's own screen when+ * that is all there is.*+ * @param {ScreenDetails} details - The screen details.* @param {number} screenId - Optional target screen index.- * @returns {Promise<string>}+ * @returns {ScreenDetailed}*/-async function computeFeatures(screenId?: number): Promise<string> {- const details = await window.getScreenDetails();- const target = (typeof screenId === 'number' && details.screens[screenId])+function getTargetScreen(details: ScreenDetails, screenId?: number): ScreenDetailed {+ return (typeof screenId === 'number' && details.screens[screenId])|| details.screens.find(s => s.left !== details.currentScreen.left || s.top !== details.currentScreen.top)|| details.currentScreen;+}++/**+ * Computes the {@code window.open} features string, placing the window on a+ * physical screen via the Window Management API.+ *+ * @param {ScreenDetails} details - The screen details.+ * @param {number} screenId - Optional target screen index.+ * @returns {string}+ */+function computeFeatures(details: ScreenDetails, screenId?: number): string {+ const target = getTargetScreen(details, screenId);// No avail* offsets: the window is auto-fullscreened, so the full screen bounds are what matter.return `popup,left=${target.left},top=${target.top},width=${target.width},height=${target.height}`;}+/**+ * Moves an already-open second-screen window onto its target screen, for the+ * open that could not place it at {@code window.open} time (see+ * {@link openSecondScreenWindow}). Placing a window on another screen needs the+ * window-management permission, which is exactly what the caller has just+ * awaited.+ *+ * @param {Window} win - The window to place.+ * @param {ScreenDetails} details - The screen details.+ * @param {number} screenId - Optional target screen index.+ * @returns {void}+ */+function placeSecondScreenWindow(win: Window, details: ScreenDetails, screenId?: number) {+ const target = getTargetScreen(details, screenId);++ win.moveTo(target.left, target.top);+ win.resizeTo(target.width, target.height);+}+/*** Whether the document currently in a second-screen window is the shell page,* identified by its {@code meta} marker (see {@link SECOND_SCREEN_MARKER}) rather@@ -291,24 +731,6 @@ function readWindowLocation(win: Window): string | undefined {}}-/**- * Whether a second-screen window has already loaded its shell page, in which- * case waiting for its {@code load} event would never resolve (the event has- * already fired). Happens when a window is opened again for an id whose window- * is still open, since {@code window.open} reuses the window with the same name.- *- * @param {Window} win - The opened window.- * @returns {boolean}- */-function isShellPageLoaded(win: Window): boolean {- try {- return win.document.readyState === 'complete' && hasShellMarker(win);- } catch (_e) {- // Mid-navigation (or an unreadable document); treat it as not loaded and wait.- return false;- }-}-/*** How a wait for a second-screen window's shell page ended: the shell loaded,* the window was closed while it was loading, the load timed out, or something@@ -335,14 +757,16 @@ type SecondScreenLoadResult = 'loaded' | 'closed' | 'timeout' | 'wrong-page';* that delivered something other than the shell page is reported separately,* since the event fires for any served response.*+ * There is deliberately no fast path for a window that has already loaded: the+ * caller always opens with the shell URL, and navigating a reused named context+ * loads it again, so {@code load} is always still to come. A document that reads+ * as complete here is a stale outgoing one, which carries the marker too, so+ * taking it would build the handle on a document that is about to be replaced.+ ** @param {Window} win - The opened window.* @returns {Promise<SecondScreenLoadResult>}*/function awaitSecondScreenLoad(win: Window): Promise<SecondScreenLoadResult> {- if (isShellPageLoaded(win)) {- return Promise.resolve('loaded');- }-return new Promise<SecondScreenLoadResult>(resolve => {let poll = 0;let timeout = 0;@@ -470,6 +894,23 @@ function handleWindowClosed(store: IStore, id: string) {store.dispatch(removeSecondScreen(id));}+/**+ * Handles the user closing a second-screen window while it is still being set+ * up, i.e. before it has a handle for {@link handleWindowClosed} to work from.+ * Closing it then is the same action as closing it a moment later, so it reports+ * the same event rather than an error, and there is no window left to close.+ *+ * @param {IStore} store - The redux store.+ * @param {string} id - The window id.+ * @param {string} phase - What the open was waiting on, for the log line.+ * @returns {void}+ */+function handleWindowClosedWhileOpening(store: IStore, id: string, phase: string) {+ logger.debug(`Second-screen window "${id}" was closed while ${phase}`);+ store.dispatch(removeSecondScreen(id));+ APP.API?.notifySecondScreenClosed?.({ id });+}+/*** The ids whose windows are currently being opened, i.e. the calls that are past* the handle check below but have not stored a handle yet.@@ -490,14 +931,64 @@ const opening = new Set<string>();* @returns {void}*/function failSecondScreenOpen(store: IStore, id: string, error: string, win?: Window | null) {++ // Detach the handle before removing the entry, so the middleware's REMOVE+ // handler finds none and the removal stays silent: a failed open reports+ // secondScreenError alone, as it does on master, and never a+ // secondScreenClosed on top of it. Only the window-management denial reaches+ // here with a handle in state, since that is the one failure that now comes+ // after the window was registered, but the detach covers any later one too.+ // An embedder that reopens on secondScreenClosed would otherwise loop on it.+ // Detaching first also unmounts the portal while the window is still open,+ // which is the ordering the REMOVE handler documents. Nothing awaits between+ // the two dispatches, so no cancel or resend can observe the entry without+ // its handle.+ if (getHandle(store.getState(), id)) {+ store.dispatch(setSecondScreenWindow(id, undefined));+ }+if (win && !win.closed) {win.close();}APP.API?.notifySecondScreenError?.({ id, error });+ notifySecondScreenOpenFailed(store, id, error);store.dispatch(removeSecondScreen(id));}+/**+ * The notification shown for a failed in-app send, keyed by the error reported+ * to the embedder. The two listed here are the ones the user can act on; the+ * rest fall back to a generic message.+ */+const OPEN_ERROR_DESCRIPTIONS: { [error: string]: string; } = {+ 'popup-blocked': 'multiScreen.popupBlocked',+ 'window-management-unavailable': 'multiScreen.permissionDenied'+};++/**+ * Tells the user that a send to a second screen failed. Only for the windows+ * opened by the in-app triggers: an embedder handles its own windows' failures+ * through {@code notifySecondScreenError}, and a notification in the meeting+ * would be talking about a window the user never asked for. Without this an+ * in-app click that is blocked does nothing observable at all.+ *+ * @param {IStore} store - The redux store.+ * @param {string} id - The window id.+ * @param {string} error - The error reported to the embedder.+ * @returns {void}+ */+export function notifySecondScreenOpenFailed(store: IStore, id: string, error: string) {+ if (!id.startsWith(UI_SECOND_SCREEN_ID_PREFIX)) {+ return;+ }++ store.dispatch(showWarningNotification({+ descriptionKey: OPEN_ERROR_DESCRIPTIONS[error] ?? 'multiScreen.openFailed',+ titleKey: 'multiScreen.openFailedTitle'+ }, NOTIFICATION_TIMEOUT_TYPE.MEDIUM));+}+/*** Handles an unexpected rejection from {@link openOrUpdateSecondScreen}, which is* otherwise all-catching. Reading the popup's document can throw now that it@@ -548,9 +1039,20 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen// would reach window.open with the same window name and re-navigate (or, on// the initial empty document, share) the window the first call is building// on, which orphans load listeners, duplicates roots and pagehide listeners,- // and can close a window that was just set up. Nothing is lost by returning:- // the source lives in redux, so the open already in flight picks up the- // newest one when it applies it at the end. A screenId that changed in the+ // and can close a window that was just set up. The dropped request is not+ // re-run later, so what it leaves behind depends on how the open in flight+ // ends. If that one succeeds, nothing is lost: the source lives in redux, so+ // it applies the newest one at the end. If it fails, its teardown dispatches+ // removeSecondScreen(id), which also removes the entry the dropped request+ // had just written, leaving that request with neither a window nor an entry+ // of its own. That is accepted rather than handled: the end state is+ // consistent rather than corrupt, the embedder is told through+ // secondScreenError for the id and can retry, and whatever caused the+ // failure usually applies to both requests anyway. This spans the page load+ // and nothing else: the window-management permission is answered after the+ // handle is in state, by a tail that holds no guard (see+ // {@link openSecondScreenWindow}), so a request arriving during a prompt+ // finds a live handle above and re-sources it. A screenId that changed in the// meantime is ignored, exactly as it is for a window that is already open.if (opening.has(id)) {return;@@ -565,6 +1067,78 @@ export async function openOrUpdateSecondScreen(store: IStore, id: string, screen}}+/**+ * Fullscreens a second-screen window. Needs the AutomaticFullscreen permission on+ * a managed device; without it the window simply stays windowed, which is why a+ * refusal is logged rather than failing the open.+ *+ * @param {Window} win - The window to fullscreen.+ * @param {string} id - The window id, for the log line.+ * @returns {Promise<void>}+ */+async function fullscreenSecondScreen(win: Window, id: string): Promise<void> {+ try {+ await win.document.documentElement.requestFullscreen();+ } catch (e) {+ logger.debug(`Auto-fullscreen not granted for second screen "${id}"`, e);+ }+}++/**+ * Places and fullscreens a window once the window-management permission has been+ * answered, for the open that could not place it at {@code window.open} time. Runs+ * after the window is already registered and rendering, so everything it touches+ * has to be re-checked: the answer can arrive long after the open finished, and+ * the meeting has been free to close the window or open another for the same id+ * in the meantime.+ *+ * Ownership is compared by handle identity rather than by asking whether an entry+ * exists, so a window that was closed and opened again for the same id is neither+ * placed nor torn down by the open it replaced.+ *+ * A denial (or a prompt left unanswered past {@link SECOND_SCREEN_PERMISSION_TIMEOUT})+ * fails the open as it does everywhere else: without the permission the window+ * cannot be put on another screen, which is the point of the feature, so it is+ * closed and reported rather than left on the meeting's own display.+ *+ * @param {IStore} store - The redux store.+ * @param {string} id - The window id.+ * @param {ISecondScreenHandle} handle - The handle this open registered.+ * @param {Promise<ScreenDetails>} pending - The in-flight permission request.+ * @param {number} screenId - Optional target screen index.+ * @returns {Promise<void>}+ */+async function placeSecondScreenWhenPermitted(+ store: IStore,+ id: string,+ handle: ISecondScreenHandle,+ pending: Promise<ScreenDetails>,+ screenId?: number): Promise<void> {+ let error: unknown;+ const resolved = await pending.then(details => details, e => {+ error = e;++ return undefined;+ });++ if (getHandle(store.getState(), id) !== handle || handle.win.closed) {+ logger.debug(`Dropping the window-management answer for second screen "${id}": `+ + 'it no longer owns that window');++ return;+ }++ if (!resolved) {+ logger.warn(`Window Management API unavailable; cannot place second-screen window "${id}"`, error);+ failSecondScreenOpen(store, id, 'window-management-unavailable', handle.win);++ return;+ }++ placeSecondScreenWindow(handle.win, resolved, screenId);+ await fullscreenSecondScreen(handle.win, id);+}+/*** Opens and sets up the window for an id, having established that it has no live* window and no other open in flight (see {@link openOrUpdateSecondScreen}).@@ -580,19 +1154,19 @@ async function openSecondScreenWindow(store: IStore, id: string, screenId?: numb// overwritten below and React unmounts its portal content (stopping the cloned// track and its Emotion cache) on its own, so there is nothing to tear down.- let features;-- try {- features = await computeFeatures(screenId);- } catch (e) {- logger.warn(`Window Management API unavailable; cannot place second-screen window "${id}"`, e);- failSecondScreenOpen(store, id, 'window-management-unavailable');-- return;- }-+ const details = screenDetails;const url = getSecondScreenPageUrl(store.getState());- const win = window.open(url, `jitsiSecondScreen_${id}`, features);++ // Nothing above this awaits, so window.open runs in the task that dispatched+ // and a window opened from a click still counts as user-initiated to the+ // popup blocker. With the details cached the window is placed as it opens,+ // which is every open but the first. Without them, obtaining them here first+ // would put the window-management permission prompt between the click and+ // the open: Chromium expires transient user activation after 5s while the+ // prompt sits until it is answered, so a user who reads it before pressing+ // Allow would have their window blocked rather than opened. Open unplaced+ // instead and move it once the answer arrives.+ const win = window.open(url, `jitsiSecondScreen_${id}`, details ? computeFeatures(details, screenId) : 'popup');if (!win) {logger.warn(`Failed to open second-screen window "${id}" (popup blocked?)`);@@ -601,18 +1175,19 @@ async function openSecondScreenWindow(store: IStore, id: string, screenId?: numbreturn;}+ // Start the request now so it runs alongside the page load rather than after+ // it. Its outcome is handled once there is a handle to hang it on; this only+ // keeps a rejection that arrives first from counting as unhandled.+ const pendingDetails = details ? undefined : awaitScreenDetails(loadScreenDetails());++ pendingDetails?.catch(() => undefined);+// Wait for the shell page to replace the popup's initial empty document// before building the handle on it.const result = win.closed ? 'closed' : await awaitSecondScreenLoad(win);if (result === 'closed' || win.closed) {-- // The user closed the popup while it was loading. That is the same action- // as closing it a moment later, so it reports the same event rather than- // an error, and there is no window left to close.- logger.debug(`Second-screen window "${id}" was closed while loading`);- store.dispatch(removeSecondScreen(id));- APP.API?.notifySecondScreenClosed?.({ id });+ handleWindowClosedWhileOpening(store, id, 'loading');return;}@@ -675,13 +1250,40 @@ async function openSecondScreenWindow(store: IStore, id: string, screenId?: numbstore.dispatch(setSecondScreenWindow(id, handle));win.addEventListener('pagehide', () => handleWindowClosed(store, id), { once: true });- try {- await win.document.documentElement.requestFullscreen();- } catch (e) {- logger.debug(`Auto-fullscreen not granted for second screen "${id}"`, e);+ // From here the window has the ordinary lifecycle rather than a half-open one:+ // a cancel, a source leaving the meeting, or the conference ending all close+ // it through closeSecondScreenHandle and report secondScreenClosed, and a+ // repeat send finds a live handle above and re-sources it. Registering only+ // after the permission was answered is what left all three of those with an+ // entry, no handle, and nothing reported.+ //+ // applySource runs here rather than behind placement. The window renders the+ // source from this point, so the event is true when it is sent, and holding+ // it back would not make "no event before placement" hold anyway: the+ // subscriber calls applySource for every entry that has a handle, so a live+ // role that resolves to someone else while the prompt is up emits it+ // regardless. Deferring would only make the first event intermittent, and+ // would drop it altogether where placement throws on a window that is live+ // and rendering.+ applySource(store, id);++ if (!pendingDetails) {+ await fullscreenSecondScreen(win, id);++ return;}- applySource(store, id);+ // Placement waits on the permission, so it becomes a tail rather than part of+ // the open. Deliberately not awaited: holding the in-flight guard until a user+ // answers a prompt is exactly what made a cancel silent. Fullscreen goes with+ // it, and only after placement, or the window would fill the meeting's own+ // screen for as long as the prompt is up.+ // Caught here rather than by handleSecondScreenOpenError: the tail outlives the+ // open, so it is no longer inside that catch-all. The window is live and+ // registered by this point, so a throw costs it its placement, not its+ // existence, and the meeting can still close it.+ placeSecondScreenWhenPermitted(store, id, handle, pendingDetails, screenId)+ .catch(e => logger.warn(`Could not place second-screen window "${id}" after the permission answer`, e));}/**@@ -722,24 +1324,142 @@ export function closeSecondScreen(store: IStore, id: string) {* @returns {void}*/export function closeAllSecondScreens(store: IStore) {- Object.keys(store.getState()['features/multi-screen'].screens).forEach(id => closeSecondScreen(store, id));+ Object.keys(store.getState()['features/multi-screen'].screens).forEach(id => {+ cancelSourceGoneClose(id);+ closeSecondScreen(store, id);+ });+}++/**+ * The countdowns started for windows whose source has gone, keyed by window id+ * and stamped with the send they belong to.+ */+const sourceGoneTimers = new Map<string, { setAt?: number; timeoutId: number; }>();++/**+ * Closes a window whose source did not come back within+ * {@link SECOND_SCREEN_SOURCE_GONE_GRACE}.+ *+ * @param {IStore} store - The redux store.+ * @param {string} id - The window id.+ * @param {number} setAt - The send this countdown was started for.+ * @returns {void}+ */+function closeGoneSource(store: IStore, id: string, setAt?: number) {+ sourceGoneTimers.delete(id);++ const state = store.getState();+ const entry = state['features/multi-screen'].screens[id];++ // The entry has to still be the one this was scheduled for. The in-app ids+ // are reused (a one-monitor machine always sends to ui-screen-0), so a window+ // closed and reopened, or re-sourced, while the countdown ran must not be+ // torn down by it; setAt identifies the send rather than the id. Re-checking+ // the source covers the rest: a refresh cancels a countdown when the source+ // is back, but the entry may also have been given a different one.+ if (!entry || entry.setAt !== setAt || !isSecondScreenSourceGone(state, entry.source)) {+ return;+ }++ logger.debug(`Closing second screen "${id}": its source did not come back`);+ store.dispatch(removeSecondScreen(id));+}++/**+ * Starts the countdown to closing a window whose source has gone, if one is not+ * already running for that send. Deliberately not restarted on every refresh:+ * the subscriber runs on any window's signature change, so restarting would let+ * unrelated traffic hold the deadline open indefinitely.+ *+ * @param {IStore} store - The redux store.+ * @param {string} id - The window id.+ * @param {number} setAt - The send the countdown belongs to.+ * @returns {void}+ */+function scheduleSourceGoneClose(store: IStore, id: string, setAt?: number) {+ const pending = sourceGoneTimers.get(id);++ if (pending) {+ if (pending.setAt === setAt) {+ return;+ }++ window.clearTimeout(pending.timeoutId);+ }++ logger.debug(`Second screen "${id}" lost its source; closing it in `+ + `${SECOND_SCREEN_SOURCE_GONE_GRACE}ms unless it comes back`);++ sourceGoneTimers.set(id, {+ setAt,+ timeoutId: window.setTimeout(+ () => closeGoneSource(store, id, setAt),+ SECOND_SCREEN_SOURCE_GONE_GRACE)+ });}/**- * Re-resolves and re-renders every open second-screen window. Called by the- * subscriber when the active speaker / tracks change.+ * Stops the countdown for a window, if one is running.+ *+ * @param {string} id - The window id.+ * @returns {void}+ */+function cancelSourceGoneClose(id: string) {+ const pending = sourceGoneTimers.get(id);++ if (!pending) {+ return;+ }++ window.clearTimeout(pending.timeoutId);+ sourceGoneTimers.delete(id);+}++/**+ * Re-resolves and re-renders every open second-screen window, and closes the+ * in-app ones whose source has left the meeting. Called by the subscriber when+ * the active speaker / tracks change.+ *+ * Only the in-app windows are closed: an embedder's window is the embedder's to+ * manage, it is told what happened through {@code secondScreenSourceChanged} and+ * the ordinary participant events, and closing it from here would change the+ * external API's behaviour for input it already accepts today.** @param {IStore} store - The redux store.* @returns {void}*/export function refreshSecondScreens(store: IStore) {Object.keys(store.getState()['features/multi-screen'].screens).forEach(id => {- const handle = getHandle(store.getState(), id);+ const state = store.getState();+ const handle = getHandle(state, id);+ const entry = state['features/multi-screen'].screens[id];if (handle?.win.closed) {handleWindowClosed(store, id);- } else if (handle) {- applySource(store, id);+ } else if (entry && id.startsWith(UI_SECOND_SCREEN_ID_PREFIX) && isSecondScreenSourceGone(state, entry.source)) {++ // Closing the window reports secondScreenClosed, the same as the+ // trigger the user no longer has. An entry whose window is still+ // opening is left with none, which that open already handles. A+ // participant-backed source gets the grace period first, since its+ // absence may be a flap rather than a departure; the whiteboard and+ // the shared video go at once, because those only stop when someone+ // stops them.+ if (entry.source.participant) {+ scheduleSourceGoneClose(store, id, entry.setAt);+ } else {+ logger.debug(`Closing second screen "${id}": its source is no longer in the meeting`);+ store.dispatch(removeSecondScreen(id));+ }+ } else {++ // Either it never went or it came back within the grace period, so+ // drop any countdown before re-applying.+ cancelSourceGoneClose(id);++ if (handle) {+ applySource(store, id);+ }}});}diff --git a/react/features/multi-screen/hooks.web.ts b/react/features/multi-screen/hooks.web.tsindex 495fd7f6c2..e3affb86e7 100644--- a/react/features/multi-screen/hooks.web.ts+++ b/react/features/multi-screen/hooks.web.ts@@ -1,5 +1,5 @@-import { useMemo } from 'react';-import { useSelector } from 'react-redux';+import { useCallback, useMemo } from 'react';+import { useSelector, useStore } from 'react-redux';import { IReduxState } from '../app/types';import {@@ -8,6 +8,14 @@ import {getLocalScreenShareParticipant} from '../base/participants/functions';+import { removeSecondScreen, setSecondScreen } from './actions.web';+import {+ getSecondScreenShowing,+ isSecondScreenEnabled,+ pickSecondScreenTarget+} from './functions.web';+import { ISecondScreenSource } from './types';+/*** Returns the ordered participant ids for a second-screen layout: the local* participant first, then your own shared screen (a virtual participant) when@@ -48,3 +56,58 @@ export function useSecondScreenParticipantIds(): string[] {export function useDominantSpeakerId(): string | null {return useSelector((state: IReduxState) => getDominantSpeakerParticipant(state)?.id ?? null);}++/**+ * Backs the in-app "send to second screen" triggers: whether to show one,+ * whether the source is already on a screen, and the handler that toggles it.+ * The handler dispatches {@code setSecondScreen}, the same action the external+ * API dispatches, so the API stays the single control plane;+ * {@link pickSecondScreenTarget} chooses which window it lands on.+ *+ * The trigger is shown whenever the feature is enabled and the browser can+ * place a window on another screen, without checking that a second monitor is+ * actually attached: that answer needs the window-management permission, and+ * the click itself is what should ask for it. With no second monitor the window+ * opens on the current screen.+ *+ * @param {ISecondScreenSource} source - What to send.+ * @returns {Object} Whether the trigger is visible, whether its source is+ * already on a second screen, and its click handler.+ */+export function useSendToSecondScreen(source: ISecondScreenSource): {+ active: boolean; onClick: () => void; visible: boolean;+} {+ const store = useStore<IReduxState>();+ const visible = useSelector(isSecondScreenEnabled);+ const activeId = useSelector((state: IReduxState) => getSecondScreenShowing(state, source));++ const onClick = useCallback(() => {++ // Already on a screen: the trigger turns it off again. This is the only+ // way to close an in-app second screen from the meeting window, short of+ // closing the popup by hand on the other display.+ if (activeId) {+ store.dispatch(removeSecondScreen(activeId));++ return;+ }++ // Dispatch synchronously, always. window.open has to run in this click's+ // own task for the popup blocker to see it as user-initiated, and on a+ // profile that has not granted window-management yet, obtaining the+ // screen details here would spend that activation waiting on a+ // permission prompt: Chromium expires it after 5s and the prompt sits+ // until the user answers it. The open asks for the permission itself and+ // places the window once it has an answer (see openSecondScreenWindow),+ // which is also why the target picked here has no screen index on that+ // first send: without the details there are no screens to choose between,+ // and the open puts it on the first external one.+ const { id, screenId } = pickSecondScreenTarget(store.getState());++ store.dispatch(setSecondScreen(id, source, screenId));+ }, [ activeId, source, store ]);++ return { active: Boolean(activeId),+ onClick,+ visible };+}diff --git a/react/features/multi-screen/middleware.web.ts b/react/features/multi-screen/middleware.web.tsindex b1b87c3d5f..d79bc6f129 100644--- a/react/features/multi-screen/middleware.web.ts+++ b/react/features/multi-screen/middleware.web.ts@@ -1,5 +1,5 @@import { IStore } from '../app/types';-import { CONFERENCE_FAILED, CONFERENCE_LEFT } from '../base/conference/actionTypes';+import { CONFERENCE_FAILED, CONFERENCE_JOINED, CONFERENCE_LEFT } from '../base/conference/actionTypes';import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';import { REMOVE_SECOND_SCREEN, RESET_SECOND_SCREENS, SET_SECOND_SCREEN } from './actionTypes';@@ -9,7 +9,9 @@ import {closeSecondScreenHandle,getHandle,handleSecondScreenOpenError,- openOrUpdateSecondScreen+ isSecondScreenEnabled,+ openOrUpdateSecondScreen,+ preloadScreenDetails} from './functions.web';import './subscriber.web';@@ -65,6 +67,18 @@ MiddlewareRegistry.register((store: IStore) => {closeAllSecondScreens(store);return next(action);+ case CONFERENCE_JOINED: {+ const result = next(action);++ // Warm the screen details so an in-app trigger can open its window+ // without awaiting, which is what keeps the click's user activation+ // (see openOrUpdateSecondScreen). Never prompts on its own.+ if (isSecondScreenEnabled(store.getState())) {+ preloadScreenDetails();+ }++ return result;+ }case CONFERENCE_FAILED:case CONFERENCE_LEFT:diff --git a/react/features/multi-screen/reducer.ts b/react/features/multi-screen/reducer.tsindex deb64defc1..937480c9bc 100644--- a/react/features/multi-screen/reducer.ts+++ b/react/features/multi-screen/reducer.ts@@ -39,7 +39,15 @@ ReducerRegistry.register<IMultiScreenState>('features/multi-screen',[action.id]: {...state.screens[action.id],source: action.source,- screenId: action.screenId++ // Keep the screen an existing window was configured for when+ // the new request names none: re-sourcing a window (a+ // setSecondScreen with no `screen`) says what it should show,+ // not that it should go back to the default screen. Dropping+ // it would also be read as "wherever a window with no screen+ // goes" everywhere the id is used.+ screenId: action.screenId ?? state.screens[action.id]?.screenId,+ setAt: action.setAt}}};diff --git a/react/features/multi-screen/types.ts b/react/features/multi-screen/types.tsindex c3b84b481c..54999d01d1 100644--- a/react/features/multi-screen/types.ts+++ b/react/features/multi-screen/types.ts@@ -13,14 +13,17 @@ export interface ISecondScreenSource {media?: 'camera' | 'desktop';/**- * The id of an explicitly pinned participant to render.+ * The id of an explicitly pinned participant to render. On its own it+ * selects the stage layout with that participant featured; combined with+ * {@code role: 'screenshare'} it names which screenshare to render, so a+ * specific one can be shown full-bleed when several are live at once.*/participant?: string;/**- * What the window shows: the active-speaker stage, the current screenshare,- * a tile grid of every participant, the shared whiteboard, or the video- * (e.g. YouTube) shared in the meeting.+ * What the window shows: the active-speaker stage, a screenshare, a tile+ * grid of every participant, the shared whiteboard, or the video (e.g.+ * YouTube) shared in the meeting.*/role?: 'stage' | 'screenshare' | 'tile' | 'whiteboard' | 'sharedvideo';}@@ -47,6 +50,15 @@ export interface ISecondScreenEntry {*/screenId?: number;+ /**+ * When this entry's source was last set. Used to pick which of the in-app+ * windows to take over once every screen already has one (the least+ * recently targeted). Absent for an entry configured by dispatching the+ * raw action rather than through {@code setSecondScreen}, which counts as+ * the oldest.+ */+ setAt?: number;+/*** What the window renders.*/diff --git a/react/features/video-menu/components/web/FakeParticipantContextMenu.tsx b/react/features/video-menu/components/web/FakeParticipantContextMenu.tsxindex 37ce9bf174..b76696f731 100644--- a/react/features/video-menu/components/web/FakeParticipantContextMenu.tsx+++ b/react/features/video-menu/components/web/FakeParticipantContextMenu.tsx@@ -1,14 +1,16 @@-import React, { useCallback } from 'react';+import React, { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useDispatch, useSelector } from 'react-redux';import TogglePinToStageButton from '../../../../features/video-menu/components/web/TogglePinToStageButton';import Avatar from '../../../base/avatar/components/Avatar';import { IconPlay } from '../../../base/icons/svg';-import { isWhiteboardParticipant } from '../../../base/participants/functions';+import { isSharedVideoParticipant, isWhiteboardParticipant } from '../../../base/participants/functions';import { IParticipant } from '../../../base/participants/types';import ContextMenu from '../../../base/ui/components/web/ContextMenu';import ContextMenuItemGroup from '../../../base/ui/components/web/ContextMenuItemGroup';+import SendToSecondScreenButton from '../../../multi-screen/components/SendToSecondScreenButton';+import { ISecondScreenSource } from '../../../multi-screen/types';import { stopSharedVideo } from '../../../shared-video/actions';import { getParticipantMenuButtonsWithNotifyClick, showOverflowDrawer } from '../../../toolbox/functions.web';import { NOTIFY_CLICK_MODE } from '../../../toolbox/types';@@ -16,6 +18,14 @@ import { setWhiteboardOpen } from '../../../whiteboard/actions';import { WHITEBOARD_ID } from '../../../whiteboard/constants';import { PARTICIPANT_MENU_BUTTONS as BUTTONS } from '../../constants';+/**+ * Module-scoped so the second-screen trigger's click handler stays stable+ * across renders. Both of the participants this menu serves have a second-screen+ * view of their own, so neither goes to the second screen as a video track.+ */+const WHITEBOARD_SECOND_SCREEN_SOURCE: ISecondScreenSource = { role: 'whiteboard' };+const SHARED_VIDEO_SECOND_SCREEN_SOURCE: ISecondScreenSource = { role: 'sharedvideo' };+interface IProps {/**@@ -118,6 +128,14 @@ const FakeParticipantContextMenu = ({dispatch(setWhiteboardOpen(false));}, [ setWhiteboardOpen ]);+ const secondScreenSource = useMemo(() => {+ if (isWhiteboardParticipant(participant)) {+ return WHITEBOARD_SECOND_SCREEN_SOURCE;+ }++ return isSharedVideoParticipant(participant) ? SHARED_VIDEO_SECOND_SCREEN_SOURCE : undefined;+ }, [ participant ]);+const _getActions = useCallback(() => {if (isWhiteboardParticipant(participant)) {return [ {@@ -171,6 +189,15 @@ const FakeParticipantContextMenu = ({notifyMode = { buttonsWithNotifyClick?.get(BUTTONS.PIN_TO_STAGE) }participantID = { WHITEBOARD_ID } />)}+ {secondScreenSource && (+ <SendToSecondScreenButton+ key = 'sendToSecondScreen'+ // eslint-disable-next-line react/jsx-no-bind+ notifyClick = { () => notifyClick(BUTTONS.SEND_TO_SECOND_SCREEN, participant.id) }+ notifyMode = { buttonsWithNotifyClick?.get(BUTTONS.SEND_TO_SECOND_SCREEN) }+ participantID = { participant.id }+ source = { secondScreenSource } />+ )}</ContextMenuItemGroup></ContextMenu>diff --git a/react/features/video-menu/components/web/LocalVideoMenuTriggerButton.tsx b/react/features/video-menu/components/web/LocalVideoMenuTriggerButton.tsxindex 84eb6b0049..a6f5a71ceb 100644--- a/react/features/video-menu/components/web/LocalVideoMenuTriggerButton.tsx+++ b/react/features/video-menu/components/web/LocalVideoMenuTriggerButton.tsx@@ -1,4 +1,4 @@-import React, { useCallback } from 'react';+import React, { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { batch, connect, useSelector } from 'react-redux';import { makeStyles } from 'tss-react/mui';@@ -17,6 +17,9 @@ import ContextMenuItemGroup from '../../../base/ui/components/web/ContextMenuIteimport ConnectionIndicatorContent from '../../../connection-indicator/components/web/ConnectionIndicatorContent';import { THUMBNAIL_TYPE } from '../../../filmstrip/constants';import { isStageFilmstripAvailable } from '../../../filmstrip/functions.web';+import SendToSecondScreenButton from '../../../multi-screen/components/SendToSecondScreenButton';+import { isSecondScreenEnabled } from '../../../multi-screen/functions.web';+import { ISecondScreenSource } from '../../../multi-screen/types';import { getParticipantMenuButtonsWithNotifyClick } from '../../../toolbox/functions.web';import { NOTIFY_CLICK_MODE } from '../../../toolbox/types';import { renderConnectionStatus } from '../../actions.web';@@ -75,6 +78,11 @@ interface IProps {*/_showPinToStage: boolean;+ /**+ * Whether to render the send to second screen button.+ */+ _showSendToSecondScreen: boolean;+/*** Whether or not the button should be visible.*/@@ -141,6 +149,7 @@ const LocalVideoMenuTriggerButton = ({_showHideSelfViewButton,_showLocalVideoFlipButton,_showPinToStage,+ _showSendToSecondScreen,buttonVisible,dispatch,hidePopover,@@ -151,6 +160,10 @@ const LocalVideoMenuTriggerButton = ({const { t } = useTranslation();const buttonsWithNotifyClick = useSelector(getParticipantMenuButtonsWithNotifyClick);const visitorsSupported = useSelector((state: IReduxState) => state['features/visitors'].supported);+ const localSource: ISecondScreenSource = useMemo(+ () => ({ media: 'camera',+ participant: _localParticipantId }),+ [ _localParticipantId ]);const notifyClick = useCallback((buttonKey: string) => {@@ -214,6 +227,15 @@ const LocalVideoMenuTriggerButton = ({onClick = { hidePopover }participantID = { _localParticipantId } />}+ <SendToSecondScreenButton+ className = { _overflowDrawer ? classes.flipText : '' }+ noIcon = { true }+ // eslint-disable-next-line react/jsx-no-bind+ notifyClick = { () => notifyClick(BUTTONS.SEND_TO_SECOND_SCREEN) }+ notifyMode = { buttonsWithNotifyClick?.get(BUTTONS.SEND_TO_SECOND_SCREEN) }+ onClick = { hidePopover }+ participantID = { _localParticipantId }+ source = { localSource } />{_showDemote && visitorsSupported && <DemoteToVisitorButtonclassName = { _overflowDrawer ? classes.flipText : '' }@@ -236,7 +258,7 @@ const LocalVideoMenuTriggerButton = ({);return (- isMobileBrowser() || _showLocalVideoFlipButton || _showHideSelfViewButton+ isMobileBrowser() || _showLocalVideoFlipButton || _showHideSelfViewButton || _showSendToSecondScreen? <Popovercontent = { content }headingLabel = { t('dialog.localUserControls') }@@ -298,7 +320,8 @@ function _mapStateToProps(state: IReduxState, ownProps: Partial<IProps>) {_overflowDrawer: overflowDrawer,_localParticipantId: localParticipant?.id ?? '',_showConnectionInfo: Boolean(showConnectionInfo),- _showPinToStage: isStageFilmstripAvailable(state)+ _showPinToStage: isStageFilmstripAvailable(state),+ _showSendToSecondScreen: isSecondScreenEnabled(state)};}diff --git a/react/features/video-menu/components/web/ParticipantContextMenu.tsx b/react/features/video-menu/components/web/ParticipantContextMenu.tsxindex c27091272c..3c1f7300c6 100644--- a/react/features/video-menu/components/web/ParticipantContextMenu.tsx+++ b/react/features/video-menu/components/web/ParticipantContextMenu.tsx@@ -21,6 +21,8 @@ import { IRoom } from '../../../breakout-rooms/types';import { displayVerification } from '../../../e2ee/functions';import { setVolume } from '../../../filmstrip/actions.web';import { isStageFilmstripAvailable } from '../../../filmstrip/functions.web';+import SendToSecondScreenButton from '../../../multi-screen/components/SendToSecondScreenButton';+import { ISecondScreenSource } from '../../../multi-screen/types';import { QUICK_ACTION_BUTTON } from '../../../participants-pane/constants';import { getQuickActionButtonType } from '../../../participants-pane/functions';import { requestRemoteControl, stopController } from '../../../remote-control/actions';@@ -212,6 +214,13 @@ const ParticipantContextMenu = ({&& typeof _volume === 'number'&& !isNaN(_volume);+ // Kept stable so the trigger's click handler is too; this menu re-renders+ // while it is open.+ const secondScreenSource: ISecondScreenSource = useMemo(+ () => ({ media: 'camera',+ participant: _getCurrentParticipantId() }),+ [ _getCurrentParticipantId ]);+const getButtonProps = useCallback((key: string) => {const notifyMode = buttonsWithNotifyClick?.get(key);const shouldNotifyClick = typeof notifyMode !== 'undefined';@@ -289,6 +298,12 @@ const ParticipantContextMenu = ({buttons2.push(<TogglePinToStageButton { ...getButtonProps(BUTTONS.PIN_TO_STAGE) } />);}+ buttons2.push(+ <SendToSecondScreenButton+ { ...getButtonProps(BUTTONS.SEND_TO_SECOND_SCREEN) }+ source = { secondScreenSource } />+ );+if (enablePrivateChat) {buttons2.push(<PrivateMessageMenuButton { ...getButtonProps(BUTTONS.PRIVATE_MESSAGE) } />);}diff --git a/react/features/video-menu/constants.ts b/react/features/video-menu/constants.tsindex cab9b204e5..bbc56f3d94 100644--- a/react/features/video-menu/constants.ts+++ b/react/features/video-menu/constants.ts@@ -37,6 +37,7 @@ export const PARTICIPANT_MENU_BUTTONS = {PRIVATE_MESSAGE: 'privateMessage',REMOTE_CONTROL: 'remote-control',SEND_PARTICIPANT_TO_ROOM: 'send-participant-to-room',+ SEND_TO_SECOND_SCREEN: 'send-to-second-screen',TRANSLATE_AUDIO: 'translate-audio',VERIFY: 'verify'};