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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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 [ options, setOptions ] = useState({ ...initialOptions });
  138. const localImages = jitsiLocalStorage.getItem('virtualBackgrounds');
  139. const [ storedImages, setStoredImages ] = useState<Array<Image>>((localImages && Bourne.parse(localImages)) || []);
  140. const [ loading, setLoading ] = useState(false);
  141. const uploadImageButton: Object = useRef(null);
  142. const [ activeDesktopVideo ] = useState(_virtualBackground?.virtualSource?.videoType === VIDEO_TYPE.DESKTOP
  143. ? _virtualBackground.virtualSource
  144. : null);
  145. const [ initialVirtualBackground ] = useState(_virtualBackground);
  146. const deleteStoredImage = useCallback(e => {
  147. const imageId = e.currentTarget.getAttribute('data-imageid');
  148. setStoredImages(storedImages.filter(item => item.id !== imageId));
  149. }, [ storedImages ]);
  150. const deleteStoredImageKeyPress = useCallback(e => {
  151. if (e.key === ' ' || e.key === 'Enter') {
  152. e.preventDefault();
  153. deleteStoredImage(e);
  154. }
  155. }, [ deleteStoredImage ]);
  156. /**
  157. * Updates stored images on local storage.
  158. */
  159. useEffect(() => {
  160. try {
  161. jitsiLocalStorage.setItem('virtualBackgrounds', JSON.stringify(storedImages));
  162. } catch (err) {
  163. // Preventing localStorage QUOTA_EXCEEDED_ERR
  164. err && setStoredImages(storedImages.slice(1));
  165. }
  166. if (storedImages.length === backgroundsLimit) {
  167. setStoredImages(storedImages.slice(1));
  168. }
  169. }, [ storedImages ]);
  170. const enableBlur = useCallback(async () => {
  171. setOptions({
  172. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  173. enabled: true,
  174. blurValue: 25,
  175. selectedThumbnail: 'blur'
  176. });
  177. logger.info('"Blur" option setted for virtual background preview!');
  178. }, []);
  179. const enableBlurKeyPress = useCallback(e => {
  180. if (e.key === ' ' || e.key === 'Enter') {
  181. e.preventDefault();
  182. enableBlur();
  183. }
  184. }, [ enableBlur ]);
  185. const enableSlideBlur = useCallback(async () => {
  186. setOptions({
  187. backgroundType: VIRTUAL_BACKGROUND_TYPE.BLUR,
  188. enabled: true,
  189. blurValue: 8,
  190. selectedThumbnail: 'slight-blur'
  191. });
  192. logger.info('"Slight-blur" option setted for virtual background preview!');
  193. }, []);
  194. const enableSlideBlurKeyPress = useCallback(e => {
  195. if (e.key === ' ' || e.key === 'Enter') {
  196. e.preventDefault();
  197. enableSlideBlur();
  198. }
  199. }, [ enableSlideBlur ]);
  200. const shareDesktop = useCallback(async () => {
  201. let isCancelled = false, url;
  202. try {
  203. url = await createLocalTrack('desktop', '');
  204. } catch (e) {
  205. if (e.name === JitsiTrackErrors.SCREENSHARING_USER_CANCELED) {
  206. isCancelled = true;
  207. } else {
  208. logger.error(e);
  209. }
  210. }
  211. if (!url) {
  212. if (!isCancelled) {
  213. dispatch(showErrorNotification({
  214. titleKey: 'virtualBackground.desktopShareError'
  215. }));
  216. logger.error('Could not create desktop share as a virtual background!');
  217. }
  218. /**
  219. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  220. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  221. * and restore the current state through {@code initialOptions} prop.
  222. */
  223. if (browser.isElectron()) {
  224. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: options }));
  225. }
  226. return;
  227. }
  228. const newOptions = {
  229. backgroundType: VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE,
  230. enabled: true,
  231. selectedThumbnail: 'desktop-share',
  232. url
  233. };
  234. /**
  235. * For electron createLocalTrack will open the {@code DesktopPicker} dialog and hide the
  236. * {@code VirtualBackgroundDialog}. That's why we need to reopen the {@code VirtualBackgroundDialog}
  237. * and force it to show desktop share virtual background through {@code initialOptions} prop.
  238. */
  239. if (browser.isElectron()) {
  240. dispatch(openDialog(VirtualBackgroundDialog, { initialOptions: newOptions }));
  241. } else {
  242. setOptions(newOptions);
  243. logger.info('"Desktop-share" option setted for virtual background preview!');
  244. }
  245. }, [ dispatch, options ]);
  246. const shareDesktopKeyPress = useCallback(e => {
  247. if (e.key === ' ' || e.key === 'Enter') {
  248. e.preventDefault();
  249. shareDesktop();
  250. }
  251. }, [ shareDesktop ]);
  252. const removeBackground = useCallback(async () => {
  253. setOptions({
  254. enabled: false,
  255. selectedThumbnail: 'none'
  256. });
  257. logger.info('"None" option setted for virtual background preview!');
  258. }, []);
  259. const removeBackgroundKeyPress = useCallback(e => {
  260. if (e.key === ' ' || e.key === 'Enter') {
  261. e.preventDefault();
  262. removeBackground();
  263. }
  264. }, [ removeBackground ]);
  265. const setUploadedImageBackground = useCallback(async e => {
  266. const imageId = e.currentTarget.getAttribute('data-imageid');
  267. const image = storedImages.find(img => img.id === imageId);
  268. if (image) {
  269. setOptions({
  270. backgroundType: 'image',
  271. enabled: true,
  272. url: image.src,
  273. selectedThumbnail: image.id
  274. });
  275. logger.info('Uploaded image setted for virtual background preview!');
  276. }
  277. }, [ storedImages ]);
  278. const setImageBackground = useCallback(async e => {
  279. const imageId = e.currentTarget.getAttribute('data-imageid');
  280. const image = images.find(img => img.id === imageId);
  281. if (image) {
  282. const url = await toDataURL(image.src);
  283. setOptions({
  284. backgroundType: 'image',
  285. enabled: true,
  286. url,
  287. selectedThumbnail: image.id
  288. });
  289. logger.info('Image setted for virtual background preview!');
  290. setLoading(false);
  291. }
  292. }, []);
  293. const uploadImage = useCallback(async e => {
  294. const reader = new FileReader();
  295. const imageFile = e.target.files;
  296. reader.readAsDataURL(imageFile[0]);
  297. reader.onload = async () => {
  298. const url = await resizeImage(reader.result);
  299. const uuId = uuid.v4();
  300. setStoredImages([
  301. ...storedImages,
  302. {
  303. id: uuId,
  304. src: url
  305. }
  306. ]);
  307. setOptions({
  308. backgroundType: VIRTUAL_BACKGROUND_TYPE.IMAGE,
  309. enabled: true,
  310. url,
  311. selectedThumbnail: uuId
  312. });
  313. };
  314. logger.info('New virtual background image uploaded!');
  315. reader.onerror = () => {
  316. setLoading(false);
  317. logger.error('Failed to upload virtual image!');
  318. };
  319. }, [ dispatch, storedImages ]);
  320. const uploadImageKeyPress = useCallback(e => {
  321. if (uploadImageButton.current && (e.key === ' ' || e.key === 'Enter')) {
  322. e.preventDefault();
  323. uploadImageButton.current.click();
  324. }
  325. }, [ uploadImageButton.current ]);
  326. const setImageBackgroundKeyPress = useCallback(e => {
  327. if (e.key === ' ' || e.key === 'Enter') {
  328. e.preventDefault();
  329. setImageBackground(e);
  330. }
  331. }, [ setImageBackground ]);
  332. const setUploadedImageBackgroundKeyPress = useCallback(e => {
  333. if (e.key === ' ' || e.key === 'Enter') {
  334. e.preventDefault();
  335. setUploadedImageBackground(e);
  336. }
  337. }, [ setUploadedImageBackground ]);
  338. const applyVirtualBackground = useCallback(async () => {
  339. if (activeDesktopVideo) {
  340. await activeDesktopVideo.dispose();
  341. }
  342. setLoading(true);
  343. await dispatch(toggleBackgroundEffect(options, _jitsiTrack));
  344. await setLoading(false);
  345. if (_localFlipX && options.backgroundType === VIRTUAL_BACKGROUND_TYPE.DESKTOP_SHARE) {
  346. dispatch(updateSettings({
  347. localFlipX: !_localFlipX
  348. }));
  349. } else {
  350. // Set x scale to default value.
  351. dispatch(updateSettings({
  352. localFlipX: true
  353. }));
  354. }
  355. dispatch(hideDialog());
  356. logger.info(`Virtual background type: '${typeof options.backgroundType === 'undefined'
  357. ? 'none' : options.backgroundType}' applied!`);
  358. }, [ dispatch, options, _localFlipX ]);
  359. // Prevent the selection of a new virtual background if it has not been applied by default
  360. const cancelVirtualBackground = useCallback(async () => {
  361. await setOptions({
  362. backgroundType: initialVirtualBackground.backgroundType,
  363. enabled: initialVirtualBackground.backgroundEffectEnabled,
  364. url: initialVirtualBackground.virtualSource,
  365. selectedThumbnail: initialVirtualBackground.selectedThumbnail,
  366. blurValue: initialVirtualBackground.blurValue
  367. });
  368. dispatch(hideDialog());
  369. });
  370. return (
  371. <Dialog
  372. hideCancelButton = { false }
  373. okKey = { 'virtualBackground.apply' }
  374. onCancel = { cancelVirtualBackground }
  375. onSubmit = { applyVirtualBackground }
  376. submitDisabled = { !options || loading }
  377. titleKey = { 'virtualBackground.title' } >
  378. <VirtualBackgroundPreview options = { options } />
  379. {loading ? (
  380. <div className = 'virtual-background-loading'>
  381. <Spinner
  382. isCompleting = { false }
  383. size = 'medium' />
  384. </div>
  385. ) : (
  386. <div>
  387. <label
  388. aria-label = { t('virtualBackground.uploadImage') }
  389. className = 'file-upload-label'
  390. htmlFor = 'file-upload'
  391. onKeyPress = { uploadImageKeyPress }
  392. tabIndex = { 0 } >
  393. <Icon
  394. className = { 'add-background' }
  395. size = { 20 }
  396. src = { IconPlusCircle } />
  397. {t('virtualBackground.addBackground')}
  398. </label>
  399. <input
  400. accept = 'image/*'
  401. className = 'file-upload-btn'
  402. id = 'file-upload'
  403. onChange = { uploadImage }
  404. ref = { uploadImageButton }
  405. type = 'file' />
  406. <div
  407. className = 'virtual-background-dialog'
  408. role = 'radiogroup'
  409. tabIndex = '-1'>
  410. <Tooltip
  411. content = { t('virtualBackground.removeBackground') }
  412. position = { 'top' }>
  413. <div
  414. aria-checked = { _selectedThumbnail === 'none' }
  415. aria-label = { t('virtualBackground.removeBackground') }
  416. className = { _selectedThumbnail === 'none' ? 'background-option none-selected'
  417. : 'background-option virtual-background-none' }
  418. onClick = { removeBackground }
  419. onKeyPress = { removeBackgroundKeyPress }
  420. role = 'radio'
  421. tabIndex = { 0 } >
  422. {t('virtualBackground.none')}
  423. </div>
  424. </Tooltip>
  425. <Tooltip
  426. content = { t('virtualBackground.slightBlur') }
  427. position = { 'top' }>
  428. <div
  429. aria-checked = { _selectedThumbnail === 'slight-blur' }
  430. aria-label = { t('virtualBackground.slightBlur') }
  431. className = { _selectedThumbnail === 'slight-blur'
  432. ? 'background-option slight-blur-selected' : 'background-option slight-blur' }
  433. onClick = { enableSlideBlur }
  434. onKeyPress = { enableSlideBlurKeyPress }
  435. role = 'radio'
  436. tabIndex = { 0 }>
  437. {t('virtualBackground.slightBlur')}
  438. </div>
  439. </Tooltip>
  440. <Tooltip
  441. content = { t('virtualBackground.blur') }
  442. position = { 'top' }>
  443. <div
  444. aria-checked = { _selectedThumbnail === 'blur' }
  445. aria-label = { t('virtualBackground.blur') }
  446. className = { _selectedThumbnail === 'blur' ? 'background-option blur-selected'
  447. : 'background-option blur' }
  448. onClick = { enableBlur }
  449. onKeyPress = { enableBlurKeyPress }
  450. role = 'radio'
  451. tabIndex = { 0 }>
  452. {t('virtualBackground.blur')}
  453. </div>
  454. </Tooltip>
  455. <Tooltip
  456. content = { t('virtualBackground.desktopShare') }
  457. position = { 'top' }>
  458. <div
  459. aria-checked = { _selectedThumbnail === 'desktop-share' }
  460. aria-label = { t('virtualBackground.desktopShare') }
  461. className = { _selectedThumbnail === 'desktop-share'
  462. ? 'background-option desktop-share-selected'
  463. : 'background-option desktop-share' }
  464. onClick = { shareDesktop }
  465. onKeyPress = { shareDesktopKeyPress }
  466. role = 'radio'
  467. tabIndex = { 0 }>
  468. <Icon
  469. className = 'share-desktop-icon'
  470. size = { 30 }
  471. src = { IconShareDesktop } />
  472. </div>
  473. </Tooltip>
  474. {images.map(image => (
  475. <Tooltip
  476. content = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  477. key = { image.id }
  478. position = { 'top' }>
  479. <img
  480. alt = { image.tooltip && t(`virtualBackground.${image.tooltip}`) }
  481. aria-checked = { options.selectedThumbnail === image.id
  482. || _selectedThumbnail === image.id }
  483. className = {
  484. options.selectedThumbnail === image.id || _selectedThumbnail === image.id
  485. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  486. data-imageid = { image.id }
  487. onClick = { setImageBackground }
  488. onError = { onError }
  489. onKeyPress = { setImageBackgroundKeyPress }
  490. role = 'radio'
  491. src = { image.src }
  492. tabIndex = { 0 } />
  493. </Tooltip>
  494. ))}
  495. {storedImages.map((image, index) => (
  496. <div
  497. className = { 'thumbnail-container' }
  498. key = { image.id }>
  499. <img
  500. alt = { t('virtualBackground.uploadedImage', { index: index + 1 }) }
  501. aria-checked = { _selectedThumbnail === image.id }
  502. className = { _selectedThumbnail === image.id
  503. ? 'background-option thumbnail-selected' : 'background-option thumbnail' }
  504. data-imageid = { image.id }
  505. onClick = { setUploadedImageBackground }
  506. onError = { onError }
  507. onKeyPress = { setUploadedImageBackgroundKeyPress }
  508. role = 'radio'
  509. src = { image.src }
  510. tabIndex = { 0 } />
  511. <Icon
  512. ariaLabel = { t('virtualBackground.deleteImage') }
  513. className = { 'delete-image-icon' }
  514. data-imageid = { image.id }
  515. onClick = { deleteStoredImage }
  516. onKeyPress = { deleteStoredImageKeyPress }
  517. role = 'button'
  518. size = { 15 }
  519. src = { IconCloseSmall }
  520. tabIndex = { 0 } />
  521. </div>
  522. ))}
  523. </div>
  524. </div>
  525. )}
  526. </Dialog>
  527. );
  528. }
  529. export default VirtualBackgroundDialog;