You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VirtualBackgroundDialog.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // @flow
  2. import Spinner from '@atlaskit/spinner';
  3. import Bourne from '@hapi/bourne';
  4. import { jitsiLocalStorage } from '@jitsi/js-utils/jitsi-local-storage';
  5. import React, { useState, useEffect, useCallback, useRef } from 'react';
  6. import uuid from 'uuid';
  7. import { Dialog, hideDialog, openDialog } from '../../base/dialog';
  8. import { translate } from '../../base/i18n';
  9. import { Icon, IconCloseSmall, IconPlusCircle, IconShareDesktop } from '../../base/icons';
  10. import { browser, JitsiTrackErrors } from '../../base/lib-jitsi-meet';
  11. import { createLocalTrack } from '../../base/lib-jitsi-meet/functions';
  12. import { VIDEO_TYPE } from '../../base/media';
  13. import { connect } from '../../base/redux';
  14. import { updateSettings } from '../../base/settings';
  15. import { Tooltip } from '../../base/tooltip';
  16. import { getLocalVideoTrack } from '../../base/tracks';
  17. import { showErrorNotification } from '../../notifications';
  18. import { toggleBackgroundEffect } from '../actions';
  19. import { VIRTUAL_BACKGROUND_TYPE } from '../constants';
  20. import { resizeImage, toDataURL } from '../functions';
  21. import logger from '../logger';
  22. import VirtualBackgroundPreview from './VirtualBackgroundPreview';
  23. type Image = {
  24. tooltip?: string,
  25. id: string,
  26. src: string
  27. }
  28. // The limit of virtual background uploads is 24. When the number
  29. // of uploads is 25 we trigger the deleteStoredImage function to delete
  30. // the first/oldest uploaded background.
  31. const backgroundsLimit = 25;
  32. const images: Array<Image> = [
  33. {
  34. tooltip: 'image1',
  35. id: '1',
  36. src: 'images/virtual-background/background-1.jpg'
  37. },
  38. {
  39. tooltip: 'image2',
  40. id: '2',
  41. src: 'images/virtual-background/background-2.jpg'
  42. },
  43. {
  44. tooltip: 'image3',
  45. id: '3',
  46. src: 'images/virtual-background/background-3.jpg'
  47. },
  48. {
  49. tooltip: 'image4',
  50. id: '4',
  51. src: 'images/virtual-background/background-4.jpg'
  52. },
  53. {
  54. tooltip: 'image5',
  55. id: '5',
  56. src: 'images/virtual-background/background-5.jpg'
  57. },
  58. {
  59. tooltip: 'image6',
  60. id: '6',
  61. src: 'images/virtual-background/background-6.jpg'
  62. },
  63. {
  64. tooltip: 'image7',
  65. id: '7',
  66. src: 'images/virtual-background/background-7.jpg'
  67. }
  68. ];
  69. type Props = {
  70. /**
  71. * The current local flip x status.
  72. */
  73. _localFlipX: boolean,
  74. /**
  75. * Returns the jitsi track that will have backgraund effect applied.
  76. */
  77. _jitsiTrack: Object,
  78. /**
  79. * Returns the selected thumbnail identifier.
  80. */
  81. _selectedThumbnail: string,
  82. /**
  83. * Returns the selected virtual background object.
  84. */
  85. _virtualBackground: Object,
  86. /**
  87. * The redux {@code dispatch} function.
  88. */
  89. dispatch: Function,
  90. /**
  91. * The initial options copied in the state for the {@code VirtualBackground} component.
  92. *
  93. * NOTE: currently used only for electron in order to open the dialog in the correct state after desktop sharing
  94. * selection.
  95. */
  96. initialOptions: Object,
  97. /**
  98. * Invoked to obtain translated strings.
  99. */
  100. t: Function
  101. };
  102. const onError = event => {
  103. event.target.style.display = 'none';
  104. };
  105. /**
  106. * Maps (parts of) the redux state to the associated props for the
  107. * {@code VirtualBackground} component.
  108. *
  109. * @param {Object} state - The Redux state.
  110. * @private
  111. * @returns {{Props}}
  112. */
  113. function _mapStateToProps(state): Object {
  114. const { localFlipX } = state['features/base/settings'];
  115. return {
  116. _localFlipX: Boolean(localFlipX),
  117. _virtualBackground: state['features/virtual-background'],
  118. _selectedThumbnail: state['features/virtual-background'].selectedThumbnail,
  119. _jitsiTrack: getLocalVideoTrack(state['features/base/tracks'])?.jitsiTrack
  120. };
  121. }
  122. const VirtualBackgroundDialog = translate(connect(_mapStateToProps)(VirtualBackground));
  123. /**
  124. * Renders virtual background dialog.
  125. *
  126. * @returns {ReactElement}
  127. */
  128. function VirtualBackground({
  129. _localFlipX,
  130. _jitsiTrack,
  131. _selectedThumbnail,
  132. _virtualBackground,
  133. dispatch,
  134. initialOptions,
  135. t
  136. }: Props) {
  137. const [ previewIsLoaded, setPreviewIsLoaded ] = useState(false);
  138. const [ options, setOptions ] = useState({ ...initialOptions });
  139. const localImages = jitsiLocalStorage.getItem('virtualBackgrounds');
  140. const [ storedImages, setStoredImages ] = useState<Array<Image>>((localImages && Bourne.parse(localImages)) || []);
  141. const [ loading, setLoading ] = useState(false);
  142. const uploadImageButton: Object = useRef(null);
  143. const [ activeDesktopVideo ] = useState(_virtualBackground?.virtualSource?.videoType === VIDEO_TYPE.DESKTOP
  144. ? _virtualBackground.virtualSource
  145. : null);
  146. const [ initialVirtualBackground ] = useState(_virtualBackground);
  147. const deleteStoredImage = useCallback(e => {
  148. const imageId = e.currentTarget.getAttribute('data-imageid');
  149. setStoredImages(storedImages.filter(item => item.id !== imageId));
  150. }, [ storedImages ]);
  151. const deleteStoredImageKeyPress = useCallback(e => {
  152. if (e.key === ' ' || e.key === 'Enter') {
  153. e.preventDefault();
  154. deleteStoredImage(e);
  155. }
  156. }, [ deleteStoredImage ]);
  157. /**
  158. * Updates stored images on local storage.
  159. */
  160. useEffect(() => {
  161. try {
  162. jitsiLocalStorage.setItem('virtualBackgrounds', JSON.stringify(storedImages));
  163. } catch (err) {
  164. // Preventing localStorage QUOTA_EXCEEDED_ERR
  165. err && setStoredImages(storedImages.slice(1));
  166. }
  167. if (storedImages.length === backgroundsLimit) {
  168. setStoredImages(storedImages.slice(1));
  169. }
  170. }, [ storedImages ]);
  171. const enableBlur = useCallback(async () => {
  172. setOptions({
  173. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  174. enabled: true,
  175. blurValue: 25,
  176. selectedThumbnail: 'blur'
  177. });
  178. logger.info('"Blur" option setted for virtual background preview!');
  179. }, []);
  180. const enableBlurKeyPress = useCallback(e => {
  181. if (e.key === ' ' || e.key === 'Enter') {
  182. e.preventDefault();
  183. enableBlur();
  184. }
  185. }, [ enableBlur ]);
  186. const enableSlideBlur = useCallback(async () => {
  187. setOptions({
  188. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  189. enabled: true,
  190. blurValue: 8,
  191. selectedThumbnail: 'slight-blur'
  192. });
  193. logger.info('"Slight-blur" option setted for virtual background preview!');
  194. }, []);
  195. const enableSlideBlurKeyPress = useCallback(e => {
  196. if (e.key === ' ' || e.key === 'Enter') {
  197. e.preventDefault();
  198. enableSlideBlur();
  199. }
  200. }, [ enableSlideBlur ]);
  201. const shareDesktop = useCallback(async () => {
  202. let isCancelled = false, url;
  203. try {
  204. url = await createLocalTrack('desktop', '');
  205. } catch (e) {
  206. if (e.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  207. isCancelled = true;
  208. } else {
  209. logger.error(e);
  210. }
  211. }
  212. if (!url) {
  213. if (!isCancelled) {
  214. dispatch(showErrorNotification({
  215. titleKey: 'virtualBackground.desktopShareError'
  216. }));
  217. logger.error('Could not create desktop share as a virtual background!');
  218. }
  219. /**
  220. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  221. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  222. * and restore the current state through {@code initialOptions} prop.
  223. */
  224. if (browser.isElectron()) {
  225. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: options }));
  226. }
  227. return;
  228. }
  229. const newOptions = {
  230. backgroundType: VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE,
  231. enabled: true,
  232. selectedThumbnail: 'desktop-share',
  233. url
  234. };
  235. /**
  236. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  237. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  238. * and force it to show desktop share virtual background through {@code initialOptions} prop.
  239. */
  240. if (browser.isElectron()) {
  241. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: newOptions }));
  242. } else {
  243. setOptions(newOptions);
  244. logger.info('"Desktop-share" option setted for virtual background preview!');
  245. }
  246. }, [ dispatch, options ]);
  247. const shareDesktopKeyPress = useCallback(e => {
  248. if (e.key === ' ' || e.key === 'Enter') {
  249. e.preventDefault();
  250. shareDesktop();
  251. }
  252. }, [ shareDesktop ]);
  253. const removeBackground = useCallback(async () => {
  254. setOptions({
  255. enabled: false,
  256. selectedThumbnail: 'none'
  257. });
  258. logger.info('"None" option setted for virtual background preview!');
  259. }, []);
  260. const removeBackgroundKeyPress = useCallback(e => {
  261. if (e.key === ' ' || e.key === 'Enter') {
  262. e.preventDefault();
  263. removeBackground();
  264. }
  265. }, [ removeBackground ]);
  266. const setUploadedImageBackground = useCallback(async e => {
  267. const imageId = e.currentTarget.getAttribute('data-imageid');
  268. const image = storedImages.find(img => img.id === imageId);
  269. if (image) {
  270. setOptions({
  271. backgroundType: 'image',
  272. enabled: true,
  273. url: image.src,
  274. selectedThumbnail: image.id
  275. });
  276. logger.info('Uploaded image setted for virtual background preview!');
  277. }
  278. }, [ storedImages ]);
  279. const setImageBackground = useCallback(async e => {
  280. const imageId = e.currentTarget.getAttribute('data-imageid');
  281. const image = images.find(img => img.id === imageId);
  282. if (image) {
  283. const url = await toDataURL(image.src);
  284. setOptions({
  285. backgroundType: 'image',
  286. enabled: true,
  287. url,
  288. selectedThumbnail: image.id
  289. });
  290. logger.info('Image setted for virtual background preview!');
  291. setLoading(false);
  292. }
  293. }, []);
  294. const uploadImage = useCallback(async e => {
  295. const reader = new FileReader();
  296. const imageFile = e.target.files;
  297. reader.readAsDataURL(imageFile[0]);
  298. reader.onload = async () => {
  299. const url = await resizeImage(reader.result);
  300. const uuId = uuid.v4();
  301. setStoredImages([
  302. ...storedImages,
  303. {
  304. id: uuId,
  305. src: url
  306. }
  307. ]);
  308. setOptions({
  309. backgroundType: VIRTUAL_BACKGROUND_TYPE.IMAGE,
  310. enabled: true,
  311. url,
  312. selectedThumbnail: uuId
  313. });
  314. };
  315. logger.info('New virtual background image uploaded!');
  316. reader.onerror = () => {
  317. setLoading(false);
  318. logger.error('Failed to upload virtual image!');
  319. };
  320. }, [ dispatch, storedImages ]);
  321. const uploadImageKeyPress = useCallback(e => {
  322. if (uploadImageButton.current && (e.key === ' ' || e.key === 'Enter')) {
  323. e.preventDefault();
  324. uploadImageButton.current.click();
  325. }
  326. }, [ uploadImageButton.current ]);
  327. const setImageBackgroundKeyPress = useCallback(e => {
  328. if (e.key === ' ' || e.key === 'Enter') {
  329. e.preventDefault();
  330. setImageBackground(e);
  331. }
  332. }, [ setImageBackground ]);
  333. const setUploadedImageBackgroundKeyPress = useCallback(e => {
  334. if (e.key === ' ' || e.key === 'Enter') {
  335. e.preventDefault();
  336. setUploadedImageBackground(e);
  337. }
  338. }, [ setUploadedImageBackground ]);
  339. const applyVirtualBackground = useCallback(async () => {
  340. if (activeDesktopVideo) {
  341. await activeDesktopVideo.dispose();
  342. }
  343. setLoading(true);
  344. await dispatch(toggleBackgroundEffect(options, _jitsiTrack));
  345. await setLoading(false);
  346. if (_localFlipX && options.backgroundType === VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE) {
  347. dispatch(updateSettings({
  348. localFlipX: !_localFlipX
  349. }));
  350. } else {
  351. // Set x scale to default value.
  352. dispatch(updateSettings({
  353. localFlipX: true
  354. }));
  355. }
  356. dispatch(hideDialog());
  357. logger.info(`Virtual background type: '${typeof options.backgroundType === 'undefined'
  358. ? 'none' : options.backgroundType}' applied!`);
  359. }, [ dispatch, options, _localFlipX ]);
  360. // Prevent the selection of a new virtual background if it has not been applied by default
  361. const cancelVirtualBackground = useCallback(async () => {
  362. await setOptions({
  363. backgroundType: initialVirtualBackground.backgroundType,
  364. enabled: initialVirtualBackground.backgroundEffectEnabled,
  365. url: initialVirtualBackground.virtualSource,
  366. selectedThumbnail: initialVirtualBackground.selectedThumbnail,
  367. blurValue: initialVirtualBackground.blurValue
  368. });
  369. dispatch(hideDialog());
  370. });
  371. const loadedPreviewState = useCallback(async loaded => {
  372. await setPreviewIsLoaded(loaded);
  373. });
  374. return (
  375. <Dialog
  376. hideCancelButton = { false }
  377. okKey = { 'virtualBackground.apply' }
  378. onCancel = { cancelVirtualBackground }
  379. onSubmit = { applyVirtualBackground }
  380. submitDisabled = { !options || loading || !previewIsLoaded }
  381. titleKey = { 'virtualBackground.title' } >
  382. <VirtualBackgroundPreview
  383. loadedPreview = { loadedPreviewState }
  384. options = { options } />
  385. {loading ? (
  386. <div className = 'virtual-background-loading'>
  387. <Spinner
  388. isCompleting = { false }
  389. size = 'medium' />
  390. </div>
  391. ) : (
  392. <div>
  393. {previewIsLoaded && <label
  394. aria-label = { t('virtualBackground.uploadImage') }
  395. className = 'file-upload-label'
  396. htmlFor = 'file-upload'
  397. onKeyPress = { uploadImageKeyPress }
  398. tabIndex = { 0 } >
  399. <Icon
  400. className = { 'add-background' }
  401. size = { 20 }
  402. src = { IconPlusCircle } />
  403. {t('virtualBackground.addBackground')}
  404. </label> }
  405. <input
  406. accept = 'image/*'
  407. className = 'file-upload-btn'
  408. id = 'file-upload'
  409. onChange = { uploadImage }
  410. ref = { uploadImageButton }
  411. type = 'file' />
  412. <div
  413. className = 'virtual-background-dialog'
  414. role = 'radiogroup'
  415. tabIndex = '-1'>
  416. <Tooltip
  417. content = { t('virtualBackground.removeBackground') }
  418. position = { 'top' }>
  419. <div
  420. aria-checked = { _selectedThumbnail === 'none' }
  421. aria-label = { t('virtualBackground.removeBackground') }
  422. className = { _selectedThumbnail === 'none' ? 'background-option none-selected'
  423. : 'background-option virtual-background-none' }
  424. onClick = { removeBackground }
  425. onKeyPress = { removeBackgroundKeyPress }
  426. role = 'radio'
  427. tabIndex = { 0 } >
  428. {t('virtualBackground.none')}
  429. </div>
  430. </Tooltip>
  431. <Tooltip
  432. content = { t('virtualBackground.slightBlur') }
  433. position = { 'top' }>
  434. <div
  435. aria-checked = { _selectedThumbnail === 'slight-blur' }
  436. aria-label = { t('virtualBackground.slightBlur') }
  437. className = { _selectedThumbnail === 'slight-blur'
  438. ? 'background-option slight-blur-selected' : 'background-option slight-blur' }
  439. onClick = { enableSlideBlur }
  440. onKeyPress = { enableSlideBlurKeyPress }
  441. role = 'radio'
  442. tabIndex = { 0 }>
  443. {t('virtualBackground.slightBlur')}
  444. </div>
  445. </Tooltip>
  446. <Tooltip
  447. content = { t('virtualBackground.blur') }
  448. position = { 'top' }>
  449. <div
  450. aria-checked = { _selectedThumbnail === 'blur' }
  451. aria-label = { t('virtualBackground.blur') }
  452. className = { _selectedThumbnail === 'blur' ? 'background-option blur-selected'
  453. : 'background-option blur' }
  454. onClick = { enableBlur }
  455. onKeyPress = { enableBlurKeyPress }
  456. role = 'radio'
  457. tabIndex = { 0 }>
  458. {t('virtualBackground.blur')}
  459. </div>
  460. </Tooltip>
  461. <Tooltip
  462. content = { t('virtualBackground.desktopShare') }
  463. position = { 'top' }>
  464. <div
  465. aria-checked = { _selectedThumbnail === 'desktop-share' }
  466. aria-label = { t('virtualBackground.desktopShare') }
  467. className = { _selectedThumbnail === 'desktop-share'
  468. ? 'background-option desktop-share-selected'
  469. : 'background-option desktop-share' }
  470. onClick = { shareDesktop }
  471. onKeyPress = { shareDesktopKeyPress }
  472. role = 'radio'
  473. tabIndex = { 0 }>
  474. <Icon
  475. className = 'share-desktop-icon'
  476. size = { 30 }
  477. src = { IconShareDesktop } />
  478. </div>
  479. </Tooltip>
  480. {images.map(image => (
  481. <Tooltip
  482. content = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  483. key = { image.id }
  484. position = { 'top' }>
  485. <img
  486. alt = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  487. aria-checked = { options.selectedThumbnail === image.id
  488. || _selectedThumbnail === image.id }
  489. className = {
  490. options.selectedThumbnail === image.id || _selectedThumbnail === image.id
  491. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  492. data-imageid = { image.id }
  493. onClick = { setImageBackground }
  494. onError = { onError }
  495. onKeyPress = { setImageBackgroundKeyPress }
  496. role = 'radio'
  497. src = { image.src }
  498. tabIndex = { 0 } />
  499. </Tooltip>
  500. ))}
  501. {storedImages.map((image, index) => (
  502. <div
  503. className = { 'thumbnail-container' }
  504. key = { image.id }>
  505. <img
  506. alt = { t('virtualBackground.uploadedImage', { index: index + 1 }) }
  507. aria-checked = { _selectedThumbnail === image.id }
  508. className = { _selectedThumbnail === image.id
  509. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  510. data-imageid = { image.id }
  511. onClick = { setUploadedImageBackground }
  512. onError = { onError }
  513. onKeyPress = { setUploadedImageBackgroundKeyPress }
  514. role = 'radio'
  515. src = { image.src }
  516. tabIndex = { 0 } />
  517. <Icon
  518. ariaLabel = { t('virtualBackground.deleteImage') }
  519. className = { 'delete-image-icon' }
  520. data-imageid = { image.id }
  521. onClick = { deleteStoredImage }
  522. onKeyPress = { deleteStoredImageKeyPress }
  523. role = 'button'
  524. size = { 15 }
  525. src = { IconCloseSmall }
  526. tabIndex = { 0 } />
  527. </div>
  528. ))}
  529. </div>
  530. </div>
  531. )}
  532. </Dialog>
  533. );
  534. }
  535. export default VirtualBackgroundDialog;