diff options
author | John Molakvoæ <skjnldsv@users.noreply.github.com> | 2022-04-22 12:32:14 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-22 12:32:14 +0200 |
commit | 9a76f06ecadf05ef1d26bd735df1bea0dfb15d59 (patch) | |
tree | ebdd458b0969c07d5ce77b21684a8bdf1db8434d /apps/theming | |
parent | e1cb1bdce94fa2a6395b2d3a35556944111e66b1 (diff) | |
parent | 850d8ac1cd9e5b28e37668469237d8daa5c5d51d (diff) | |
download | nextcloud-server-9a76f06ecadf05ef1d26bd735df1bea0dfb15d59.tar.gz nextcloud-server-9a76f06ecadf05ef1d26bd735df1bea0dfb15d59.zip |
Merge pull request #31751 from nextcloud/theming-providers
Diffstat (limited to 'apps/theming')
48 files changed, 2577 insertions, 402 deletions
diff --git a/apps/theming/appinfo/info.xml b/apps/theming/appinfo/info.xml index 3d7cabe7213..b67b461c410 100644 --- a/apps/theming/appinfo/info.xml +++ b/apps/theming/appinfo/info.xml @@ -5,7 +5,7 @@ <name>Theming</name> <summary>Adjust the Nextcloud theme</summary> <description>Adjust the Nextcloud theme</description> - <version>1.16.0</version> + <version>2.0.0</version> <licence>agpl</licence> <author>Nextcloud</author> <namespace>Theming</namespace> @@ -23,8 +23,17 @@ <settings> <admin>OCA\Theming\Settings\Admin</admin> - <admin-section>OCA\Theming\Settings\Section</admin-section> + <admin-section>OCA\Theming\Settings\AdminSection</admin-section> + <personal>OCA\Theming\Settings\Personal</personal> + <personal-section>OCA\Theming\Settings\PersonalSection</personal-section> </settings> + + <repair-steps> + <pre-migration> + <step>OCA\Theming\Migration\MigrateUserConfig</step> + </pre-migration> + </repair-steps> + <commands> <command>OCA\Theming\Command\UpdateConfig</command> </commands> diff --git a/apps/theming/appinfo/routes.php b/apps/theming/appinfo/routes.php index 0628ade8032..fa8dde90786 100644 --- a/apps/theming/appinfo/routes.php +++ b/apps/theming/appinfo/routes.php @@ -27,54 +27,68 @@ * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ -return ['routes' => [ - [ - 'name' => 'Theming#updateStylesheet', - 'url' => '/ajax/updateStylesheet', - 'verb' => 'POST' +return [ + 'routes' => [ + [ + 'name' => 'Theming#updateStylesheet', + 'url' => '/ajax/updateStylesheet', + 'verb' => 'POST' + ], + [ + 'name' => 'Theming#undo', + 'url' => '/ajax/undoChanges', + 'verb' => 'POST' + ], + [ + 'name' => 'Theming#uploadImage', + 'url' => '/ajax/uploadImage', + 'verb' => 'POST' + ], + [ + 'name' => 'Theming#getThemeStylesheet', + 'url' => '/theme/{themeId}.css', + 'verb' => 'GET', + ], + [ + 'name' => 'Theming#getImage', + 'url' => '/image/{key}', + 'verb' => 'GET', + ], + [ + 'name' => 'Theming#getManifest', + 'url' => '/manifest/{app}', + 'verb' => 'GET', + 'defaults' => ['app' => 'core'] + ], + [ + 'name' => 'Icon#getFavicon', + 'url' => '/favicon/{app}', + 'verb' => 'GET', + 'defaults' => ['app' => 'core'], + ], + [ + 'name' => 'Icon#getTouchIcon', + 'url' => '/icon/{app}', + 'verb' => 'GET', + 'defaults' => ['app' => 'core'], + ], + [ + 'name' => 'Icon#getThemedIcon', + 'url' => '/img/{app}/{image}', + 'verb' => 'GET', + 'requirements' => ['image' => '.+'] + ], ], - [ - 'name' => 'Theming#undo', - 'url' => '/ajax/undoChanges', - 'verb' => 'POST' - ], - [ - 'name' => 'Theming#uploadImage', - 'url' => '/ajax/uploadImage', - 'verb' => 'POST' - ], - [ - 'name' => 'Theming#getStylesheet', - 'url' => '/styles', - 'verb' => 'GET', - ], - [ - 'name' => 'Theming#getImage', - 'url' => '/image/{key}', - 'verb' => 'GET', - ], - [ - 'name' => 'Theming#getManifest', - 'url' => '/manifest/{app}', - 'verb' => 'GET', - 'defaults' => ['app' => 'core'] - ], - [ - 'name' => 'Icon#getFavicon', - 'url' => '/favicon/{app}', - 'verb' => 'GET', - 'defaults' => ['app' => 'core'], - ], - [ - 'name' => 'Icon#getTouchIcon', - 'url' => '/icon/{app}', - 'verb' => 'GET', - 'defaults' => ['app' => 'core'], - ], - [ - 'name' => 'Icon#getThemedIcon', - 'url' => '/img/{app}/{image}', - 'verb' => 'GET', - 'requirements' => ['image' => '.+'] - ], -]]; + 'ocs' => [ + [ + 'name' => 'userTheme#enableTheme', + 'url' => '/api/v1/theme/{themeId}/enable', + 'verb' => 'PUT', + ], + [ + 'name' => 'userTheme#disableTheme', + 'url' => '/api/v1/theme/{themeId}', + 'verb' => 'DELETE', + ], + ] +]; diff --git a/apps/theming/css/default.css b/apps/theming/css/default.css new file mode 100644 index 00000000000..f7bf3a20d09 --- /dev/null +++ b/apps/theming/css/default.css @@ -0,0 +1,57 @@ +:root { + --color-main-background: #ffffff; + --color-main-background-rgb: 255,255,255; + --color-main-background-translucent: rgba(var(--color-main-background-rgb), .97); + --gradient-main-background: var(--color-main-background) 0%, var(--color-main-background-translucent) 85%, transparent 100%; + --color-background-hover: #f5f5f5; + --color-background-dark: #ededed; + --color-background-darker: #dbdbdb; + --color-placeholder-light: #e6e6e6; + --color-placeholder-dark: #cccccc; + --color-primary: #0082c9; + --color-primary-text: #ffffff; + --color-primary-hover: #198ece; + --color-primary-light: #72bae1; + --color-primary-light-text: #0082c9; + --color-primary-light-hover: #0f567d; + --color-primary-text-dark: #ededed; + --color-primary-element: #0082c9; + --color-primary-element-hover: #198ece; + --color-primary-element-light: #17adff; + --color-primary-element-lighter: #6cb7df; + --color-main-text: #222222; + --color-text-maxcontrast: #767676; + --color-text-light: #222222; + --color-text-lighter: #767676; + --color-error: #e9322d; + --color-error-hover: #eb4642; + --color-warning: #eca700; + --color-warning-hover: #edaf19; + --color-success: #46ba61; + --color-success-hover: #58c070; + --color-loading-light: #cccccc; + --color-loading-dark: #444444; + --color-box-shadow-rgb: 77,77,77; + --color-box-shadow: rgba(var(--color-box-shadow-rgb), 0.5); + --color-border: #ededed; + --color-border-dark: #dbdbdb; + --font-face: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Cantarell, Ubuntu, 'Helvetica Neue', Arial, sans-serif, 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; + --default-font-size: 15px; + --animation-quick: 100ms; + --animation-slow: 300ms; + --border-radius: 3px; + --border-radius-large: 10px; + --border-radius-pill: 100px; + --default-line-height: 24px; + --header-height: 50px; + --navigation-width: 300px; + --sidebar-min-width: 300px; + --sidebar-max-width: 500px; + --list-min-width: 200px; + --list-max-width: 300px; + --header-menu-item-height: 44px; + --header-menu-profile-item-height: 66px; + --breakpoint-mobile: 1024px; + --primary-invert-if-bright: unset; + --background-invert-if-dark: unset; +} diff --git a/apps/theming/css/settings-admin.scss b/apps/theming/css/settings-admin.scss index 504760d4596..5cec0e98199 100644 --- a/apps/theming/css/settings-admin.scss +++ b/apps/theming/css/settings-admin.scss @@ -100,6 +100,8 @@ margin-top: 10px; margin-bottom: 20px; cursor: pointer; + background-color: var(--color-primary); + background-image: var(--image-background, var(--image-background-plain, url('../../../core/img/background.svg'), linear-gradient(40deg, #0082c9 0%, #30b6ff 100%))); #theming-preview-logo { cursor: pointer; @@ -110,6 +112,7 @@ background-position: center; background-repeat: no-repeat; background-size: contain; + background-image: var(--image-logo, url('../../../core/img/logo/logo.svg')); } } @@ -125,6 +128,15 @@ background-repeat: no-repeat; background-size: contain; } + + #theming-preview-logoheader { + // Only using --image-logoheader to show the custom value only + background-image: var(--image-logoheader); + } + + #theming-preview-favicon { + background-image: var(--image-favicon); + } } /* transition effects for theming value changes */ diff --git a/apps/theming/css/theming.scss b/apps/theming/css/theming.scss index 52337d2105f..a5b55a5a738 100644 --- a/apps/theming/css/theming.scss +++ b/apps/theming/css/theming.scss @@ -45,18 +45,6 @@ $invert: luma($color-primary) > 0.6; } } -.nc-theming-main-background { - background-color: $color-primary; -} - -.nc-theming-main-text { - color: $color-primary-text; -} - -.nc-theming-contrast { - color: $color-primary-text; -} - @if ($invert) { // too bright, use dark text to mix the primary $color-primary-light: mix($color-primary, $color-main-text, 10%); @@ -157,16 +145,6 @@ $invert: luma($color-primary) > 0.6; } } -@if variable_exists('theming-favicon-mime') and $theming-favicon-mime != '' { - #theming .advanced-option-favicon .image-preview { - background-image: $image-favicon; - } -} @else { - #theming .advanced-option-favicon .image-preview { - background-image: none; - } -} - input.primary { background-color: $color-primary-element; border: 1px solid $color-primary-text; @@ -305,9 +283,3 @@ input.primary { border: 1px solid #ebebeb; } } - -@if ($has-legal-links == 'true') { - footer { - height: 92px; - } -} diff --git a/apps/theming/fonts/OpenDyslexic-Bold.otf b/apps/theming/fonts/OpenDyslexic-Bold.otf Binary files differnew file mode 100644 index 00000000000..4c492e2fcc2 --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Bold.otf diff --git a/apps/theming/fonts/OpenDyslexic-Bold.ttf b/apps/theming/fonts/OpenDyslexic-Bold.ttf Binary files differnew file mode 100644 index 00000000000..7c97eb4329b --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Bold.ttf diff --git a/apps/theming/fonts/OpenDyslexic-Bold.woff b/apps/theming/fonts/OpenDyslexic-Bold.woff Binary files differnew file mode 100644 index 00000000000..755476f6b4a --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Bold.woff diff --git a/apps/theming/fonts/OpenDyslexic-Regular.otf b/apps/theming/fonts/OpenDyslexic-Regular.otf Binary files differnew file mode 100644 index 00000000000..1226d2ab281 --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Regular.otf diff --git a/apps/theming/fonts/OpenDyslexic-Regular.ttf b/apps/theming/fonts/OpenDyslexic-Regular.ttf Binary files differnew file mode 100644 index 00000000000..e7849348cdb --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Regular.ttf diff --git a/apps/theming/fonts/OpenDyslexic-Regular.woff b/apps/theming/fonts/OpenDyslexic-Regular.woff Binary files differnew file mode 100644 index 00000000000..fdf9e37dd43 --- /dev/null +++ b/apps/theming/fonts/OpenDyslexic-Regular.woff diff --git a/apps/theming/img/dark-highcontrast.jpg b/apps/theming/img/dark-highcontrast.jpg Binary files differnew file mode 100644 index 00000000000..5fce8ef0851 --- /dev/null +++ b/apps/theming/img/dark-highcontrast.jpg diff --git a/apps/theming/img/dark.jpg b/apps/theming/img/dark.jpg Binary files differnew file mode 100644 index 00000000000..b207c390cfa --- /dev/null +++ b/apps/theming/img/dark.jpg diff --git a/apps/theming/img/default.jpg b/apps/theming/img/default.jpg Binary files differnew file mode 100644 index 00000000000..ad3fafd96f2 --- /dev/null +++ b/apps/theming/img/default.jpg diff --git a/apps/theming/img/highcontrast.jpg b/apps/theming/img/highcontrast.jpg Binary files differnew file mode 100644 index 00000000000..e9087e898ee --- /dev/null +++ b/apps/theming/img/highcontrast.jpg diff --git a/apps/theming/img/opendyslexic.jpg b/apps/theming/img/opendyslexic.jpg Binary files differnew file mode 100644 index 00000000000..f56ea33e6c4 --- /dev/null +++ b/apps/theming/img/opendyslexic.jpg diff --git a/apps/theming/js/settings-admin.js b/apps/theming/js/settings-admin.js index 335492fdae2..7efdab6dda4 100644 --- a/apps/theming/js/settings-admin.js +++ b/apps/theming/js/settings-admin.js @@ -28,9 +28,9 @@ function setThemingValue(setting, value) { startLoading(); $.post( OC.generateUrl('/apps/theming/ajax/updateStylesheet'), {'setting' : setting, 'value' : value} - ).done(function(response) { + ).done(function() { hideUndoButton(setting, value); - preview(setting, value, response.data.serverCssUrl); + preview(setting, value); }).fail(function(response) { OC.msg.finishedSaving('#theming_settings_msg', response.responseJSON); $('#theming_settings_loading').hide(); @@ -39,41 +39,31 @@ function setThemingValue(setting, value) { function preview(setting, value, serverCssUrl) { OC.msg.startAction('#theming_settings_msg', t('theming', 'Loading preview…')); - var stylesheetsLoaded = 1; - var reloadStylesheets = function(cssFile) { - var queryString = '?reload=' + new Date().getTime(); - var url = cssFile + queryString; - var old = $('link[href*="' + cssFile + '"]'); - var stylesheet = $("<link/>", { - rel: "stylesheet", - type: "text/css", - href: url - }); - stylesheet.load(function () { - $(old).remove(); - stylesheetsLoaded--; - if(stylesheetsLoaded === 0) { - $('#theming_settings_loading').hide(); - var response = { status: 'success', data: {message: t('theming', 'Saved')}}; - OC.msg.finishedSaving('#theming_settings_msg', response); - } - }); - stylesheet.appendTo("head"); - }; - - if (serverCssUrl !== undefined) { - stylesheetsLoaded++; - reloadStylesheets(serverCssUrl); - } - reloadStylesheets(OC.generateUrl('/apps/theming/styles')); + // Get all theming themes css links and force reload them + [...document.querySelectorAll('link.theme')] + .forEach(theme => { + // Only edit the clone to not remove applied one + var clone = theme.cloneNode() + var url = new URL(clone.href) + // Set current timestamp as cache buster + url.searchParams.set('v', Date.now()) + clone.href = url.toString() + clone.onload = function() { + theme.remove() + } + document.head.append(clone) + }) if (setting === 'name') { window.document.title = t('core', 'Admin') + " - " + value; } - + + // Finish + $('#theming_settings_loading').hide(); + var response = { status: 'success', data: {message: t('theming', 'Saved')}}; + OC.msg.finishedSaving('#theming_settings_msg', response); hideUndoButton(setting, value); - } function hideUndoButton(setting, value) { diff --git a/apps/theming/lib/Controller/ThemingController.php b/apps/theming/lib/Controller/ThemingController.php index a735dfafc2c..94deb2e7376 100644 --- a/apps/theming/lib/Controller/ThemingController.php +++ b/apps/theming/lib/Controller/ThemingController.php @@ -37,12 +37,13 @@ */ namespace OCA\Theming\Controller; -use OC\Template\SCSSCacher; use OCA\Theming\ImageManager; +use OCA\Theming\Service\ThemesService; use OCA\Theming\ThemingDefaults; use OCP\App\IAppManager; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\DataDisplayResponse; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\FileDisplayResponse; use OCP\AppFramework\Http\NotFoundResponse; @@ -54,6 +55,7 @@ use OCP\IL10N; use OCP\IRequest; use OCP\ITempManager; use OCP\IURLGenerator; +use ScssPhp\ScssPhp\Compiler; /** * Class ThemingController @@ -63,40 +65,16 @@ use OCP\IURLGenerator; * @package OCA\Theming\Controller */ class ThemingController extends Controller { - /** @var ThemingDefaults */ - private $themingDefaults; - /** @var IL10N */ - private $l10n; - /** @var IConfig */ - private $config; - /** @var ITempManager */ - private $tempManager; - /** @var IAppData */ - private $appData; - /** @var SCSSCacher */ - private $scssCacher; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IAppManager */ - private $appManager; - /** @var ImageManager */ - private $imageManager; + private ThemingDefaults $themingDefaults; + private IL10N $l10n; + private IConfig $config; + private ITempManager $tempManager; + private IAppData $appData; + private IURLGenerator $urlGenerator; + private IAppManager $appManager; + private ImageManager $imageManager; + private ThemesService $themesService; - /** - * ThemingController constructor. - * - * @param string $appName - * @param IRequest $request - * @param IConfig $config - * @param ThemingDefaults $themingDefaults - * @param IL10N $l - * @param ITempManager $tempManager - * @param IAppData $appData - * @param SCSSCacher $scssCacher - * @param IURLGenerator $urlGenerator - * @param IAppManager $appManager - * @param ImageManager $imageManager - */ public function __construct( $appName, IRequest $request, @@ -105,10 +83,10 @@ class ThemingController extends Controller { IL10N $l, ITempManager $tempManager, IAppData $appData, - SCSSCacher $scssCacher, IURLGenerator $urlGenerator, IAppManager $appManager, - ImageManager $imageManager + ImageManager $imageManager, + ThemesService $themesService ) { parent::__construct($appName, $request); @@ -117,10 +95,10 @@ class ThemingController extends Controller { $this->config = $config; $this->tempManager = $tempManager; $this->appData = $appData; - $this->scssCacher = $scssCacher; $this->urlGenerator = $urlGenerator; $this->appManager = $appManager; $this->imageManager = $imageManager; + $this->themesService = $themesService; } /** @@ -185,19 +163,12 @@ class ThemingController extends Controller { $this->themingDefaults->set($setting, $value); - // reprocess server scss for preview - $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core'); - - return new DataResponse( - [ - 'data' => - [ - 'message' => $this->l10n->t('Saved'), - 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss')) - ], - 'status' => 'success' - ] - ); + return new DataResponse([ + 'data' => [ + 'message' => $this->l10n->t('Saved'), + ], + 'status' => 'success' + ]); } /** @@ -262,7 +233,6 @@ class ThemingController extends Controller { } $name = $image['name']; - $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core'); return new DataResponse( [ @@ -271,7 +241,6 @@ class ThemingController extends Controller { 'name' => $name, 'url' => $this->imageManager->getImageUrl($key), 'message' => $this->l10n->t('Saved'), - 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss')) ], 'status' => 'success' ] @@ -288,8 +257,6 @@ class ThemingController extends Controller { */ public function undo(string $setting): DataResponse { $value = $this->themingDefaults->undo($setting); - // reprocess server scss for preview - $cssCached = $this->scssCacher->process(\OC::$SERVERROOT, 'core/css/css-variables.scss', 'core'); return new DataResponse( [ @@ -297,7 +264,6 @@ class ThemingController extends Controller { [ 'value' => $value, 'message' => $this->l10n->t('Saved'), - 'serverCssUrl' => $this->urlGenerator->linkTo('', $this->scssCacher->getCachedSCSS('core', '/core/css/css-variables.scss')) ], 'status' => 'success' ] @@ -307,6 +273,7 @@ class ThemingController extends Controller { /** * @PublicPage * @NoCSRFRequired + * @NoSameSiteCookieRequired * * @param string $key * @param bool $useSvg @@ -339,27 +306,37 @@ class ThemingController extends Controller { * @NoCSRFRequired * @PublicPage * @NoSameSiteCookieRequired + * @NoTwoFactorRequired * - * @return FileDisplayResponse|NotFoundResponse - * @throws NotPermittedException - * @throws \Exception - * @throws \OCP\App\AppPathNotFoundException + * @return DataDisplayResponse|NotFoundResponse */ - public function getStylesheet() { - $appPath = $this->appManager->getAppPath('theming'); - - /* SCSSCacher is required here - * We cannot rely on automatic caching done by \OC_Util::addStyle, - * since we need to add the cacheBuster value to the url - */ - $cssCached = $this->scssCacher->process($appPath, 'css/theming.scss', 'theming'); - if (!$cssCached) { + public function getThemeStylesheet(string $themeId, bool $plain = false, bool $withCustomCss = false) { + $themes = $this->themesService->getThemes(); + if (!in_array($themeId, array_keys($themes))) { return new NotFoundResponse(); } + $theme = $themes[$themeId]; + $customCss = $theme->getCustomCss(); + + // Generate variables + $variables = ''; + foreach ($theme->getCSSVariables() as $variable => $value) { + $variables .= "$variable:$value; "; + }; + + // If plain is set, the browser decides of the css priority + if ($plain) { + $css = ":root { $variables } " . $customCss; + } else { + // If not set, we'll rely on the body class + $compiler = new Compiler(); + $compiledCss = $compiler->compileString("body[data-theme-$themeId] { $variables $customCss }"); + $css = $compiledCss->getCss();; + } + try { - $cssFile = $this->scssCacher->getCachedCSS('theming', 'theming.css'); - $response = new FileDisplayResponse($cssFile, Http::STATUS_OK, ['Content-Type' => 'text/css']); + $response = new DataDisplayResponse($css, Http::STATUS_OK, ['Content-Type' => 'text/css']); $response->cacheFor(86400); return $response; } catch (NotFoundException $e) { diff --git a/apps/theming/lib/Controller/UserThemeController.php b/apps/theming/lib/Controller/UserThemeController.php new file mode 100644 index 00000000000..ec379d2e6fa --- /dev/null +++ b/apps/theming/lib/Controller/UserThemeController.php @@ -0,0 +1,111 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2018 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> + * @copyright Copyright (c) 2019 Janis Köhr <janiskoehr@icloud.com> + * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Kesselberg <mail@danielkesselberg.de> + * @author Janis Köhr <janis.koehr@novatec-gmbh.de> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Controller; + +use OCA\Theming\Service\ThemesService; +use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCS\OCSBadRequestException; +use OCP\AppFramework\OCSController; +use OCP\IConfig; +use OCP\IRequest; +use OCP\IUserSession; +use OCP\PreConditionNotMetException; + +class UserThemeController extends OCSController { + + protected string $userId; + private IConfig $config; + private IUserSession $userSession; + private ThemesService $themesService; + + /** + * Config constructor. + */ + public function __construct(string $appName, + IRequest $request, + IConfig $config, + IUserSession $userSession, + ThemesService $themesService) { + parent::__construct($appName, $request); + $this->config = $config; + $this->userSession = $userSession; + $this->themesService = $themesService; + $this->userId = $userSession->getUser()->getUID(); + } + + /** + * @NoAdminRequired + * + * Enable theme + * + * @param string $themeId the theme ID + * @return DataResponse + * @throws OCSBadRequestException|PreConditionNotMetException + */ + public function enableTheme(string $themeId): DataResponse { + if ($themeId === '' || !$themeId) { + throw new OCSBadRequestException('Invalid theme id: ' . $themeId); + } + + $themes = $this->themesService->getThemes(); + if (!isset($themes[$themeId])) { + throw new OCSBadRequestException('Invalid theme id: ' . $themeId); + } + + // Enable selected theme + $this->themesService->enableTheme($themes[$themeId]); + return new DataResponse(); + } + + /** + * @NoAdminRequired + * + * Disable theme + * + * @param string $themeId the theme ID + * @return DataResponse + * @throws OCSBadRequestException|PreConditionNotMetException + */ + public function disableTheme(string $themeId): DataResponse { + if ($themeId === '' || !$themeId) { + throw new OCSBadRequestException('Invalid theme id: ' . $themeId); + } + + $themes = $this->themesService->getThemes(); + if (!isset($themes[$themeId])) { + throw new OCSBadRequestException('Invalid theme id: ' . $themeId); + } + + // Enable selected theme + $this->themesService->disableTheme($themes[$themeId]); + return new DataResponse(); + } +} diff --git a/apps/theming/lib/ITheme.php b/apps/theming/lib/ITheme.php new file mode 100644 index 00000000000..a5c9cdf26a6 --- /dev/null +++ b/apps/theming/lib/ITheme.php @@ -0,0 +1,99 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see <http://www.gnu.org/licenses/> + * + */ + +namespace OCA\Theming; + +/** + * Interface ITheme + * + * @since 25.0.0 + */ +interface ITheme { + + const TYPE_THEME = 1; + const TYPE_FONT = 2; + + /** + * Unique theme id + * Will be used to search for ID.png in the img folder + * + * @since 25.0.0 + */ + public function getId(): string; + + /** + * Theme type + * TYPE_THEME or TYPE_FONT + * + * @since 25.0.0 + */ + public function getType(): int; + + /** + * The theme translated title + * + * @since 25.0.0 + */ + public function getTitle(): string; + + /** + * The theme enable checkbox translated label + * + * @since 25.0.0 + */ + public function getEnableLabel(): string; + + /** + * The theme translated description + * + * @since 25.0.0 + */ + public function getDescription(): string; + + /** + * Get the media query triggering this theme + * Optional, ignored if falsy + * + * @return string + * @since 25.0.0 + */ + public function getMediaQuery(): string; + + /** + * Return the list of changed css variables + * + * @return array + * @since 25.0.0 + */ + public function getCSSVariables(): array; + + /** + * Return the custom css necessary for that app + * ⚠️ Warning, should be used slightly. + * Theoretically, editing the variables should be enough. + * + * @return string + * @since 25.0.0 + */ + public function getCustomCss(): string; +} diff --git a/apps/theming/lib/Listener/BeforeTemplateRenderedListener.php b/apps/theming/lib/Listener/BeforeTemplateRenderedListener.php index 10a9434835c..185289f6ff8 100644 --- a/apps/theming/lib/Listener/BeforeTemplateRenderedListener.php +++ b/apps/theming/lib/Listener/BeforeTemplateRenderedListener.php @@ -27,6 +27,8 @@ namespace OCA\Theming\Listener; use OCA\Theming\AppInfo\Application; use OCA\Theming\Service\JSDataService; +use OCA\Theming\Service\ThemeInjectionService; +use OCA\Theming\Service\ThemesService; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; use OCP\IConfig; @@ -36,25 +38,18 @@ use OCP\IURLGenerator; class BeforeTemplateRenderedListener implements IEventListener { - /** @var IInitialStateService */ - private $initialStateService; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var IConfig */ - private $config; - /** @var IServerContainer */ - private $serverContainer; + private IInitialStateService $initialStateService; + private IServerContainer $serverContainer; + private ThemeInjectionService $themeInjectionService; public function __construct( IInitialStateService $initialStateService, - IURLGenerator $urlGenerator, - IConfig $config, - IServerContainer $serverContainer + IServerContainer $serverContainer, + ThemeInjectionService $themeInjectionService ) { $this->initialStateService = $initialStateService; - $this->urlGenerator = $urlGenerator; - $this->config = $config; $this->serverContainer = $serverContainer; + $this->themeInjectionService = $themeInjectionService; } public function handle(Event $event): void { @@ -63,19 +58,7 @@ class BeforeTemplateRenderedListener implements IEventListener { return $serverContainer->query(JSDataService::class); }); - $linkToCSS = $this->urlGenerator->linkToRoute( - 'theming.Theming.getStylesheet', - [ - 'v' => $this->config->getAppValue('theming', 'cachebuster', '0'), - ] - ); - \OCP\Util::addHeader( - 'link', - [ - 'rel' => 'stylesheet', - 'href' => $linkToCSS, - ] - ); + $this->themeInjectionService->injectHeaders(); // Making sure to inject just after core \OCP\Util::addScript('theming', 'theming', 'core'); diff --git a/apps/theming/lib/Migration/MigrateUserConfig.php b/apps/theming/lib/Migration/MigrateUserConfig.php new file mode 100644 index 00000000000..0f8d982dfa7 --- /dev/null +++ b/apps/theming/lib/Migration/MigrateUserConfig.php @@ -0,0 +1,123 @@ +<?php + +declare(strict_types=1); + +/** + * @copyright Copyright (c) 2019 Janis Köhr <janiskoehr@icloud.com> + * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Janis Köhr <janis.koehr@novatec-gmbh.de> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Migration; + +use OCA\Theming\AppInfo\Application; +use OCA\Theming\Service\ThemesService; +use OCA\Theming\Themes\DarkHighContrastTheme; +use OCA\Theming\Themes\DarkTheme; +use OCA\Theming\Themes\DyslexiaFont; +use OCA\Theming\Themes\HighContrastTheme; +use OCP\IConfig; +use OCP\IUser; +use OCP\IUserManager; +use OCP\Migration\IOutput; +use OCP\Migration\IRepairStep; + +class MigrateUserConfig implements IRepairStep { + + protected IUserManager $userManager; + protected IConfig $config; + protected ThemesService $themesService; + protected DarkTheme $darkTheme; + protected DarkHighContrastTheme $darkHighContrastTheme; + protected HighContrastTheme $highContrastTheme; + protected DyslexiaFont $dyslexiaFont; + + /** + * MigrateUserConfig constructor. + */ + public function __construct(IConfig $config, + IUserManager $userManager, + ThemesService $themesService, + DarkTheme $darkTheme, + DarkHighContrastTheme $darkHighContrastTheme, + HighContrastTheme $highContrastTheme, + DyslexiaFont $dyslexiaFont) { + $this->config = $config; + $this->userManager = $userManager; + $this->themesService = $themesService; + + $this->darkTheme = $darkTheme; + $this->darkHighContrastTheme = $darkHighContrastTheme; + $this->highContrastTheme = $highContrastTheme; + $this->dyslexiaFont = $dyslexiaFont; + } + + /** + * Returns the step's name + * + * @return string + * @since 25.0.0 + */ + public function getName() { + return 'Migrate old user accessibility config'; + } + + /** + * Run repair step. + * Must throw exception on error. + * + * @param IOutput $output + * @throws \Exception in case of failure + * @since 25.0.0 + */ + public function run(IOutput $output) { + $output->startProgress(); + $this->userManager->callForSeenUsers(function (IUser $user) use ($output) { + $config = []; + + $font = $this->config->getUserValue($user->getUID(), 'accessibility', 'font', false); + $highcontrast = $this->config->getUserValue($user->getUID(), 'accessibility', 'highcontrast', false); + $theme = $this->config->getUserValue($user->getUID(), 'accessibility', 'theme', false); + + if ($highcontrast || $theme) { + if ($theme === 'dark' && $highcontrast === 'highcontrast') { + $config[] = $this->darkHighContrastTheme->getId(); + } else if ($theme === 'dark') { + $config[] = $this->darkTheme->getId(); + } else if ($highcontrast === 'highcontrast') { + $config[] = $this->highContrastTheme->getId(); + } + } + + if ($font === 'fontdyslexic') { + $config[] = $this->dyslexiaFont->getId(); + } + + if (!empty($config)) { + $this->config->setUserValue($user->getUID(), Application::APP_ID, 'enabled-themes', json_encode(array_unique($config))); + } + + $output->advance(); + }); + + $this->config->deleteAppFromAllUsers('accessibility'); + + $output->finishProgress(); + } +} diff --git a/apps/theming/lib/Service/JSDataService.php b/apps/theming/lib/Service/JSDataService.php index 1c4d138a764..fdc85ea445a 100644 --- a/apps/theming/lib/Service/JSDataService.php +++ b/apps/theming/lib/Service/JSDataService.php @@ -32,22 +32,21 @@ use OCA\Theming\Util; use OCP\IConfig; class JSDataService implements \JsonSerializable { - - /** @var ThemingDefaults */ - private $themingDefaults; - /** @var Util */ - private $util; - /** @var IConfig */ - private $appConfig; + private ThemingDefaults $themingDefaults; + private Util $util; + private IConfig $appConfig; + private ThemesService $themesService; public function __construct( ThemingDefaults $themingDefaults, Util $util, - IConfig $appConfig + IConfig $appConfig, + ThemesService $themesService ) { $this->themingDefaults = $themingDefaults; $this->util = $util; $this->appConfig = $appConfig; + $this->themesService = $themesService; } public function jsonSerialize(): array { @@ -60,6 +59,7 @@ class JSDataService implements \JsonSerializable { 'privacyUrl' => $this->themingDefaults->getPrivacyUrl(), 'inverted' => $this->util->invertTextColor($this->themingDefaults->getColorPrimary()), 'cacheBuster' => $this->appConfig->getAppValue(Application::APP_ID, 'cachebuster', '0'), + 'enabledThemes' => $this->themesService->getEnabledThemes(), ]; } } diff --git a/apps/theming/lib/Service/ThemeInjectionService.php b/apps/theming/lib/Service/ThemeInjectionService.php new file mode 100644 index 00000000000..fec14de96cf --- /dev/null +++ b/apps/theming/lib/Service/ThemeInjectionService.php @@ -0,0 +1,88 @@ +<?php +/** + * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Service; + +use OCA\Theming\Themes\DefaultTheme; +use OCP\IURLGenerator; +use OCP\Util; + +class ThemeInjectionService { + + private IURLGenerator $urlGenerator; + private ThemesService $themesService; + private DefaultTheme $defaultTheme; + + public function __construct(IURLGenerator $urlGenerator, + ThemesService $themesService, + DefaultTheme $defaultTheme) { + $this->urlGenerator = $urlGenerator; + $this->themesService = $themesService; + $this->defaultTheme = $defaultTheme; + } + + public function injectHeaders() { + $themes = $this->themesService->getThemes(); + $defaultTheme = $themes[$this->defaultTheme->getId()]; + $mediaThemes = array_filter($themes, function($theme) { + // Check if the theme provides a media query + return (bool)$theme->getMediaQuery(); + }); + + // Default theme fallback + $this->addThemeHeader($defaultTheme->getId()); + + // Themes applied by media queries + foreach($mediaThemes as $theme) { + $this->addThemeHeader($theme->getId(), true, $theme->getMediaQuery()); + } + + // Themes + foreach($this->themesService->getThemes() as $theme) { + // Ignore default theme as already processed first + if ($theme->getId() === $this->defaultTheme->getId()) { + continue; + } + $this->addThemeHeader($theme->getId(), false); + } + } + + /** + * Inject theme header into rendered page + * + * @param string $themeId the theme ID + * @param bool $plain request the :root syntax + * @param string $media media query to use in the <link> element + */ + private function addThemeHeader(string $themeId, bool $plain = true, string $media = null) { + $linkToCSS = $this->urlGenerator->linkToRoute('theming.Theming.getThemeStylesheet', [ + 'themeId' => $themeId, + 'plain' => $plain, + ]); + Util::addHeader('link', [ + 'rel' => 'stylesheet', + 'media' => $media, + 'href' => $linkToCSS, + 'class' => 'theme' + ]); + } +} diff --git a/apps/theming/lib/Service/ThemesService.php b/apps/theming/lib/Service/ThemesService.php new file mode 100644 index 00000000000..01ebc3fb504 --- /dev/null +++ b/apps/theming/lib/Service/ThemesService.php @@ -0,0 +1,172 @@ +<?php +/** + * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Service; + +use OCA\Theming\AppInfo\Application; +use OCA\Theming\ITheme; +use OCA\Theming\Themes\DarkHighContrastTheme; +use OCA\Theming\Themes\DarkTheme; +use OCA\Theming\Themes\DefaultTheme; +use OCA\Theming\Themes\DyslexiaFont; +use OCA\Theming\Themes\HighContrastTheme; +use OCP\IConfig; +use OCP\IUser; +use OCP\IUserSession; + +class ThemesService { + private IUserSession $userSession; + private IConfig $config; + + /** @var ITheme[] */ + private array $themesProviders; + + public function __construct(IUserSession $userSession, + IConfig $config, + DefaultTheme $defaultTheme, + DarkTheme $darkTheme, + HighContrastTheme $highContrastTheme, + DarkHighContrastTheme $darkHighContrastTheme, + DyslexiaFont $dyslexiaFont) { + $this->userSession = $userSession; + $this->config = $config; + + // Register themes + $this->themesProviders = [ + $defaultTheme->getId() => $defaultTheme, + $darkTheme->getId() => $darkTheme, + $highContrastTheme->getId() => $highContrastTheme, + $darkHighContrastTheme->getId() => $darkHighContrastTheme, + $dyslexiaFont->getId() => $dyslexiaFont, + ]; + } + + /** + * Get the list of all registered themes + * + * @return ITheme[] + */ + public function getThemes(): array { + return $this->themesProviders; + } + + /** + * Enable a theme for the logged-in user + * + * @param ITheme $theme the theme to enable + * @return string[] the enabled themes + */ + public function enableTheme(ITheme $theme): array { + $themesIds = $this->getEnabledThemes(); + + // If already enabled, ignore + if (in_array($theme->getId(), $themesIds)) { + return $themesIds; + } + + /** @var ITheme[] */ + $themes = array_map(function($themeId) { + return $this->getThemes()[$themeId]; + }, $themesIds); + + // Filtering all themes with the same type + $filteredThemes = array_filter($themes, function(ITheme $t) use ($theme) { + return $theme->getType() === $t->getType(); + }); + + // Retrieve IDs only + /** @var string[] */ + $filteredThemesIds = array_map(function(ITheme $t) { + return $t->getId(); + }, array_values($filteredThemes)); + + $enabledThemes = array_merge(array_diff($themesIds, $filteredThemesIds), [$theme->getId()]); + $this->setEnabledThemes($enabledThemes); + + return $enabledThemes; + } + + /** + * Disable a theme for the logged-in user + * + * @param ITheme $theme the theme to disable + * @return string[] the enabled themes + */ + public function disableTheme(ITheme $theme): array { + $themesIds = $this->getEnabledThemes(); + + // If enabled, removing it + if (in_array($theme->getId(), $themesIds)) { + $enabledThemes = array_diff($themesIds, [$theme->getId()]); + $this->setEnabledThemes($enabledThemes); + return $enabledThemes; + } + + return $themesIds; + } + + /** + * Check whether a theme is enabled or not + * for the logged-in user + * + * @return bool + */ + public function isEnabled(ITheme $theme): bool { + $user = $this->userSession->getUser(); + if ($user instanceof IUser) { + // Using keys as it's faster + $themes = $this->getEnabledThemes(); + return in_array($theme->getId(), $themes); + } + return false; + } + + /** + * Get the list of all enabled themes IDs + * for the logged-in user + * + * @return string[] + */ + public function getEnabledThemes(): array { + $user = $this->userSession->getUser(); + if ($user === null) { + return []; + } + + try { + return json_decode($this->config->getUserValue($user->getUID(), Application::APP_ID, 'enabled-themes', '[]')); + } catch (\Exception $e) { + return []; + } + } + + /** + * Set the list of enabled themes + * for the logged-in user + * + * @param string[] $themes the list of enabled themes IDs + */ + private function setEnabledThemes(array $themes): void { + $user = $this->userSession->getUser(); + $this->config->setUserValue($user->getUID(), Application::APP_ID, 'enabled-themes', json_encode(array_unique(array_values($themes)))); + } +} diff --git a/apps/theming/lib/Settings/Admin.php b/apps/theming/lib/Settings/Admin.php index 045f0b3fe77..6caa174d99b 100644 --- a/apps/theming/lib/Settings/Admin.php +++ b/apps/theming/lib/Settings/Admin.php @@ -36,22 +36,20 @@ use OCP\IURLGenerator; use OCP\Settings\IDelegatedSettings; class Admin implements IDelegatedSettings { - /** @var IConfig */ - private $config; - /** @var IL10N */ - private $l; - /** @var ThemingDefaults */ - private $themingDefaults; - /** @var IURLGenerator */ - private $urlGenerator; - /** @var ImageManager */ - private $imageManager; + private string $appName; + private IConfig $config; + private IL10N $l; + private ThemingDefaults $themingDefaults; + private IURLGenerator $urlGenerator; + private ImageManager $imageManager; - public function __construct(IConfig $config, + public function __construct(string $appName, + IConfig $config, IL10N $l, ThemingDefaults $themingDefaults, IURLGenerator $urlGenerator, ImageManager $imageManager) { + $this->appName = $appName; $this->config = $config; $this->l = $l; $this->themingDefaults = $themingDefaults; @@ -86,14 +84,14 @@ class Admin implements IDelegatedSettings { 'privacyUrl' => $this->themingDefaults->getPrivacyUrl(), ]; - return new TemplateResponse('theming', 'settings-admin', $parameters, ''); + return new TemplateResponse($this->appName, 'settings-admin', $parameters, ''); } /** * @return string the section ID, e.g. 'sharing' */ public function getSection(): string { - return 'theming'; + return $this->appName; } /** @@ -113,7 +111,7 @@ class Admin implements IDelegatedSettings { public function getAuthorizedAppConfig(): array { return [ - 'theming' => '/.*/', + $this->appName => '/.*/', ]; } } diff --git a/apps/theming/lib/Settings/Section.php b/apps/theming/lib/Settings/AdminSection.php index fe2cc9243bb..2fcc81a9279 100644 --- a/apps/theming/lib/Settings/Section.php +++ b/apps/theming/lib/Settings/AdminSection.php @@ -26,17 +26,13 @@ use OCP\IL10N; use OCP\IURLGenerator; use OCP\Settings\IIconSection; -class Section implements IIconSection { - /** @var IL10N */ - private $l; - /** @var IURLGenerator */ - private $url; +class AdminSection implements IIconSection { + private string $appName; + private IL10N $l; + private IURLGenerator $url; - /** - * @param IURLGenerator $url - * @param IL10N $l - */ - public function __construct(IURLGenerator $url, IL10N $l) { + public function __construct(string $appName, IURLGenerator $url, IL10N $l) { + $this->appName = $appName; $this->url = $url; $this->l = $l; } @@ -48,7 +44,7 @@ class Section implements IIconSection { * @returns string */ public function getID() { - return 'theming'; + return $this->appName; } /** @@ -76,6 +72,6 @@ class Section implements IIconSection { * {@inheritdoc} */ public function getIcon() { - return $this->url->imagePath('theming', 'app-dark.svg'); + return $this->url->imagePath($this->appName, 'app-dark.svg'); } } diff --git a/apps/theming/lib/Settings/Personal.php b/apps/theming/lib/Settings/Personal.php new file mode 100644 index 00000000000..6dd865b9cf6 --- /dev/null +++ b/apps/theming/lib/Settings/Personal.php @@ -0,0 +1,93 @@ +<?php +/** + * @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com> + * @copyright Copyright (c) 2019 Janis Köhr <janiskoehr@icloud.com> + * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Settings; + +use OCA\Theming\Service\ThemesService; +use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Services\IInitialState; +use OCP\IConfig; +use OCP\IUserSession; +use OCP\Settings\ISettings; +use OCP\Util; + +class Personal implements ISettings { + + protected string $appName; + private IConfig $config; + private IUserSession $userSession; + private ThemesService $themesService; + private IInitialState $initialStateService; + + public function __construct(string $appName, + IConfig $config, + IUserSession $userSession, + ThemesService $themesService, + IInitialState $initialStateService) { + $this->appName = $appName; + $this->config = $config; + $this->userSession = $userSession; + $this->themesService = $themesService; + $this->initialStateService = $initialStateService; + } + + public function getForm(): TemplateResponse { + $themes = array_map(function($theme) { + return [ + 'id' => $theme->getId(), + 'type' => $theme->getType(), + 'title' => $theme->getTitle(), + 'enableLabel' => $theme->getEnableLabel(), + 'description' => $theme->getDescription(), + 'enabled' => $this->themesService->isEnabled($theme), + ]; + }, $this->themesService->getThemes()); + + $this->initialStateService->provideInitialState('themes', array_values($themes)); + Util::addScript($this->appName, 'theming-settings'); + + return new TemplateResponse($this->appName, 'settings-personal'); + } + + /** + * @return string the section ID, e.g. 'sharing' + * @since 9.1 + */ + public function getSection(): string { + return $this->appName; + } + + /** + * @return int whether the form should be rather on the top or bottom of + * the admin section. The forms are arranged in ascending order of the + * priority values. It is required to return a value between 0 and 100. + * + * E.g.: 70 + * @since 9.1 + */ + public function getPriority(): int { + return 40; + } +} diff --git a/apps/theming/lib/Settings/PersonalSection.php b/apps/theming/lib/Settings/PersonalSection.php new file mode 100644 index 00000000000..821708e3970 --- /dev/null +++ b/apps/theming/lib/Settings/PersonalSection.php @@ -0,0 +1,100 @@ +<?php +/** + * @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Settings; + +use OCP\IL10N; +use OCP\IURLGenerator; +use OCP\Settings\IIconSection; + +class PersonalSection implements IIconSection { + + /** @var string */ + protected $appName; + + /** @var IURLGenerator */ + private $urlGenerator; + + /** @var IL10N */ + private $l; + + /** + * Personal Section constructor. + * + * @param string $appName + * @param IURLGenerator $urlGenerator + * @param IL10N $l + */ + public function __construct(string $appName, + IURLGenerator $urlGenerator, + IL10N $l) { + $this->appName = $appName; + $this->urlGenerator = $urlGenerator; + $this->l = $l; + } + + /** + * returns the relative path to an 16*16 icon describing the section. + * e.g. '/core/img/places/files.svg' + * + * @returns string + * @since 13.0.0 + */ + public function getIcon() { + return $this->urlGenerator->imagePath($this->appName, 'app-dark.svg'); + } + + /** + * returns the ID of the section. It is supposed to be a lower case string, + * e.g. 'ldap' + * + * @returns string + * @since 9.1 + */ + public function getID() { + return $this->appName; + } + + /** + * returns the translated name as it should be displayed, e.g. 'LDAP / AD + * integration'. Use the L10N service to translate it. + * + * @return string + * @since 9.1 + */ + public function getName() { + return $this->l->t('Appearance and accessibility'); + } + + /** + * @return int whether the form should be rather on the top or bottom of + * the settings navigation. The sections are arranged in ascending order of + * the priority values. It is required to return a value between 0 and 99. + * + * E.g.: 70 + * @since 9.1 + */ + public function getPriority() { + return 15; + } +} diff --git a/apps/theming/lib/Themes/DarkHighContrastTheme.php b/apps/theming/lib/Themes/DarkHighContrastTheme.php new file mode 100644 index 00000000000..62b7d4f6358 --- /dev/null +++ b/apps/theming/lib/Themes/DarkHighContrastTheme.php @@ -0,0 +1,98 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Themes; + +use OCA\Theming\ITheme; + +class DarkHighContrastTheme extends DarkTheme implements ITheme { + + public function getId(): string { + return 'dark-highcontrast'; + } + + public function getMediaQuery(): string { + return '(prefers-color-scheme: dark) and (prefers-contrast: more)'; + } + + public function getTitle(): string { + return $this->l->t('Dark theme with high contrast mode'); + } + + public function getEnableLabel(): string { + return $this->l->t('Enable dark high contrast mode'); + } + + public function getDescription(): string { + return $this->l->t('Similar to the high contrast mode, but with dark colours.'); + } + + /** + * Try to keep this consistent with HighContrastTheme + */ + public function getCSSVariables(): array { + $variables = parent::getCSSVariables(); + $colorMainText = '#ffffff'; + $colorMainBackground = '#000000'; + $colorBoxShadowRGB = join(',', $this->util->hexToRGB($colorMainText)); + + $variables['--color-main-background'] = $colorMainBackground; + $variables['--color-main-text'] = $colorMainText; + + $variables['--color-background-dark'] = $this->util->lighten($colorMainBackground, 30); + $variables['--color-background-darker'] = $this->util->lighten($colorMainBackground, 30); + + $variables['--color-placeholder-light'] = $this->util->lighten($colorMainBackground, 30); + $variables['--color-placeholder-dark'] = $this->util->lighten($colorMainBackground, 45); + + $variables['--color-text-maxcontrast'] = $colorMainText; + $variables['--color-text-light'] = $colorMainText; + $variables['--color-text-lighter'] = $colorMainText; + + // used for the icon loading animation + $variables['--color-loading-light'] = '#000000'; + $variables['--color-loading-dark'] = '#dddddd'; + + + $variables['--color-box-shadow-rgb'] = $colorBoxShadowRGB; + $variables['--color-box-shadow'] = $colorBoxShadowRGB; + + + $variables['--color-border'] = $this->util->lighten($colorMainBackground, 50); + $variables['--color-border-dark'] = $this->util->lighten($colorMainBackground, 50); + + return $variables; + } + + public function getCustomCss(): string { + return " + [class^='icon-'], [class*=' icon-'], + .action, + #appmenu li a, + .menutoggle { + opacity: 1 !important; + } + "; + } +} diff --git a/apps/theming/lib/Themes/DarkTheme.php b/apps/theming/lib/Themes/DarkTheme.php new file mode 100644 index 00000000000..f0cacfc1696 --- /dev/null +++ b/apps/theming/lib/Themes/DarkTheme.php @@ -0,0 +1,87 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Themes; + +use OCA\Theming\ITheme; + +class DarkTheme extends DefaultTheme implements ITheme { + + public function getId(): string { + return 'dark'; + } + + public function getMediaQuery(): string { + return '(prefers-color-scheme: dark)'; + } + + public function getTitle(): string { + return $this->l->t('Dark theme'); + } + + public function getEnableLabel(): string { + return $this->l->t('Enable dark theme'); + } + + public function getDescription(): string { + return $this->l->t('A dark theme to ease your eyes by reducing the overall luminosity and brightness. It is still under development, so please report any issues you may find.'); + } + + public function getCSSVariables(): array { + $defaultVariables = parent::getCSSVariables(); + + $colorMainText = '#D8D8D8'; + $colorMainBackground = '#171717'; + $colorMainBackgroundRGB = join(',', $this->util->hexToRGB($colorMainBackground)); + $colorBoxShadow = $this->util->darken($colorMainBackground, 70); + $colorBoxShadowRGB = join(',', $this->util->hexToRGB($colorBoxShadow)); + + return array_merge($defaultVariables, [ + '--color-main-text' => $colorMainText, + '--color-main-background' => $colorMainBackground, + '--color-main-background-rgb' => $colorMainBackgroundRGB, + + '--color-background-hover' => $this->util->lighten($colorMainBackground, 4), + '--color-background-dark' => $this->util->lighten($colorMainBackground, 7), + '--color-background-darker' => $this->util->lighten($colorMainBackground, 14), + + '--color-placeholder-light' => $this->util->lighten($colorMainBackground, 10), + '--color-placeholder-dark' => $this->util->lighten($colorMainBackground, 20), + + '--color-text-maxcontrast' => $this->util->darken($colorMainText, 30), + '--color-text-light' => $this->util->darken($colorMainText, 10), + '--color-text-lighter' => $this->util->darken($colorMainText, 20), + + '--color-loading-light' => '#777', + '--color-loading-dark' => '#CCC', + + '--color-box-shadow-rgb' => $colorBoxShadowRGB, + + '--color-border' => $this->util->lighten($colorMainBackground, 7), + '--color-border-dark' => $this->util->lighten($colorMainBackground, 14), + + '--background-invert-if-dark' => 'invert(100%)', + ]); + } +} diff --git a/apps/theming/lib/Themes/DefaultTheme.php b/apps/theming/lib/Themes/DefaultTheme.php new file mode 100644 index 00000000000..7efd8f133d7 --- /dev/null +++ b/apps/theming/lib/Themes/DefaultTheme.php @@ -0,0 +1,203 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Themes; + +use OCA\Theming\ImageManager; +use OCA\Theming\ThemingDefaults; +use OCA\Theming\Util; +use OCA\Theming\ITheme; +use OCP\IConfig; +use OCP\IL10N; +use OCP\IURLGenerator; + +class DefaultTheme implements ITheme { + public Util $util; + public ThemingDefaults $themingDefaults; + public IURLGenerator $urlGenerator; + public ImageManager $imageManager; + public IConfig $config; + public IL10N $l; + + public string $primaryColor; + + public function __construct(Util $util, + ThemingDefaults $themingDefaults, + IURLGenerator $urlGenerator, + ImageManager $imageManager, + IConfig $config, + IL10N $l) { + $this->util = $util; + $this->themingDefaults = $themingDefaults; + $this->urlGenerator = $urlGenerator; + $this->imageManager = $imageManager; + $this->config = $config; + $this->l = $l; + + $this->primaryColor = $this->themingDefaults->getColorPrimary(); + } + + public function getId(): string { + return 'default'; + } + + public function getType(): int { + return ITheme::TYPE_THEME; + } + + public function getTitle(): string { + return $this->l->t('Light theme'); + } + + public function getEnableLabel(): string { + return $this->l->t('Enable the default light theme'); + } + + public function getDescription(): string { + return $this->l->t('The default light appearance.'); + } + + public function getMediaQuery(): string { + return ''; + } + + public function getCSSVariables(): array { + $colorMainText = '#222222'; + $colorMainBackground = '#ffffff'; + $colorMainBackgroundRGB = join(',', $this->util->hexToRGB($colorMainBackground)); + $colorBoxShadow = $this->util->darken($colorMainBackground, 70); + $colorBoxShadowRGB = join(',', $this->util->hexToRGB($colorBoxShadow)); + + $variables = [ + '--color-main-background' => $colorMainBackground, + '--color-main-background-rgb' => $colorMainBackgroundRGB, + '--color-main-background-translucent' => 'rgba(var(--color-main-background-rgb), .97)', + + // to use like this: background-image: linear-gradient(0, var('--gradient-main-background)); + '--gradient-main-background' => 'var(--color-main-background) 0%, var(--color-main-background-translucent) 85%, transparent 100%', + + // used for different active/hover/focus/disabled states + '--color-background-hover' => $this->util->darken($colorMainBackground, 4), + '--color-background-dark' => $this->util->darken($colorMainBackground, 7), + '--color-background-darker' => $this->util->darken($colorMainBackground, 14), + + '--color-placeholder-light' => $this->util->darken($colorMainBackground, 10), + '--color-placeholder-dark' => $this->util->darken($colorMainBackground, 20), + + // primary related colours + '--color-primary' => $this->primaryColor, + '--color-primary-text' => $this->util->invertTextColor($this->primaryColor) ? '#000000' : '#ffffff', + '--color-primary-hover' => $this->util->mix($this->primaryColor, $colorMainBackground, 80), + '--color-primary-light' => $this->util->mix($this->primaryColor, $colorMainBackground, 10), + '--color-primary-light-text' => $this->primaryColor, + '--color-primary-light-hover' => $this->util->mix($this->primaryColor, $colorMainText, 10), + '--color-primary-text-dark' => $this->util->darken($this->util->invertTextColor($this->primaryColor) ? '#000000' : '#ffffff', 7), + // used for buttons, inputs... + '--color-primary-element' => $this->util->elementColor($this->primaryColor), + '--color-primary-element-hover' => $this->util->mix($this->util->elementColor($this->primaryColor), $colorMainBackground, 80), + '--color-primary-element-light' => $this->util->lighten($this->util->elementColor($this->primaryColor), 15), + '--color-primary-element-lighter' => $this->util->mix($this->util->elementColor($this->primaryColor), $colorMainBackground, 15), + + // max contrast for WCAG compliance + '--color-main-text' => $colorMainText, + '--color-text-maxcontrast' => $this->util->lighten($colorMainText, 33), + '--color-text-light' => $colorMainText, + '--color-text-lighter' => $this->util->lighten($colorMainText, 33), + + // info/warning/success feedback colours + '--color-error' => '#e9322d', + '--color-error-hover' => $this->util->mix('#e9322d', $colorMainBackground, 80), + '--color-warning' => '#eca700', + '--color-warning-hover' => $this->util->mix('#eca700', $colorMainBackground, 80), + '--color-success' => '#46ba61', + '--color-success-hover' => $this->util->mix('#46ba61', $colorMainBackground, 80), + + // used for the icon loading animation + '--color-loading-light' => '#cccccc', + '--color-loading-dark' => '#444444', + + '--color-box-shadow-rgb' => $colorBoxShadowRGB, + '--color-box-shadow' => "rgba(var(--color-box-shadow-rgb), 0.5)", + + '--color-border' => $this->util->darken($colorMainBackground, 7), + '--color-border-dark' => $this->util->darken($colorMainBackground, 14), + + '--font-face' => "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Cantarell, Ubuntu, 'Helvetica Neue', Arial, sans-serif, 'Noto Color Emoji', 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'", + '--default-font-size' => '15px', + + // TODO: support "(prefers-reduced-motion)" + '--animation-quick' => '100ms', + '--animation-slow' => '300ms', + + // Default variables -------------------------------------------- + '--border-radius' => '3px', + '--border-radius-large' => '10px', + // pill-style button, value is large so big buttons also have correct roundness + '--border-radius-pill' => '100px', + + '--default-line-height' => '24px', + + // various structure data + '--header-height' => '50px', + '--navigation-width' => '300px', + '--sidebar-min-width' => '300px', + '--sidebar-max-width' => '500px', + '--list-min-width' => '200px', + '--list-max-width' => '300px', + '--header-menu-item-height' => '44px', + '--header-menu-profile-item-height' => '66px', + + // mobile. Keep in sync with core/js/js.js + '--breakpoint-mobile' => '1024px', + + // invert filter if primary is too bright + // to be used for legacy reasons only. Use inline + // svg with proper css variable instead or material + // design icons. + '--primary-invert-if-bright' => $this->util->invertTextColor($this->primaryColor) ? 'invert(100%)' : 'unset', + '--background-invert-if-dark' => 'unset', + ]; + + // Register image variables only if custom-defined + $backgroundDeleted = $this->config->getAppValue('theming', 'backgroundMime', '') === 'backgroundColor'; + foreach(['logo', 'logoheader', 'favicon', 'background'] as $image) { + if ($this->imageManager->hasImage($image)) { + // If primary as background has been request, let's not define the background image + if ($image === 'background' && $backgroundDeleted) { + $variables["--image-background-plain"] = true; + continue; + } else if ($image === 'background') { + $variables['--image-background-size'] = 'cover'; + } + $variables["--image-$image"] = "url('".$this->imageManager->getImageUrl($image)."')"; + } + } + + return $variables; + } + + public function getCustomCss(): string { + return ''; + } +} diff --git a/apps/theming/lib/Themes/DyslexiaFont.php b/apps/theming/lib/Themes/DyslexiaFont.php new file mode 100644 index 00000000000..50284d33b9d --- /dev/null +++ b/apps/theming/lib/Themes/DyslexiaFont.php @@ -0,0 +1,84 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Themes; + +use OCA\Theming\ITheme; + +class DyslexiaFont extends DefaultTheme implements ITheme { + + public function getId(): string { + return 'opendyslexic'; + } + + public function getType(): int { + return ITheme::TYPE_FONT; + } + + public function getTitle(): string { + return $this->l->t('Dyslexia font'); + } + + public function getEnableLabel(): string { + return $this->l->t('Enable dyslexia font'); + } + + public function getDescription(): string { + return $this->l->t('OpenDyslexic is a free typeface/font designed to mitigate some of the common reading errors caused by dyslexia.'); + } + + public function getCSSVariables(): array { + $variables = parent::getCSSVariables(); + $originalFontFace = $variables['--font-face']; + + $variables = [ + '--font-face' => 'OpenDyslexic, ' . $originalFontFace + ]; + + return $variables; + } + + public function getCustomCss(): string { + return " + @font-face { + font-family: 'OpenDyslexic'; + font-style: normal; + font-weight: 400; + src: url('../fonts/OpenDyslexic-Regular.woff') format('woff'), + url('../fonts/OpenDyslexic-Regular.otf') format('opentype'), + url('../fonts/OpenDyslexic-Regular.ttf') format('truetype'); + } + + @font-face { + font-family: 'OpenDyslexic'; + font-style: normal; + font-weight: 700; + src: url('../fonts/OpenDyslexic-Bold.woff') format('woff'), + url('../fonts/OpenDyslexic-Bold.otf') format('opentype'), + url('../fonts/OpenDyslexic-Bold.ttf') format('truetype'); + } + "; + } +} + diff --git a/apps/theming/lib/Themes/HighContrastTheme.php b/apps/theming/lib/Themes/HighContrastTheme.php new file mode 100644 index 00000000000..77239f2076c --- /dev/null +++ b/apps/theming/lib/Themes/HighContrastTheme.php @@ -0,0 +1,91 @@ +<?php +declare(strict_types=1); +/** + * @copyright Copyright (c) 2022 Joas Schilling <coding@schilljs.com> + * + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Themes; + +use OCA\Theming\ITheme; + +class HighContrastTheme extends DefaultTheme implements ITheme { + + public function getId(): string { + return 'highcontrast'; + } + + public function getMediaQuery(): string { + return '(prefers-contrast: more)'; + } + + public function getTitle(): string { + return $this->l->t('High contrast mode'); + } + + public function getEnableLabel(): string { + return $this->l->t('Enable high contrast mode'); + } + + public function getDescription(): string { + return $this->l->t('A high contrast mode to ease your navigation. Visual quality will be reduced but clarity will be increased.'); + } + + public function getCSSVariables(): array { + $variables = parent::getCSSVariables(); + $colorMainText = '#000000'; + $colorMainBackground = '#ffffff'; + + $variables['--color-main-background'] = $colorMainBackground; + $variables['--color-main-text'] = $colorMainText; + + $variables['--color-background-dark'] = $this->util->darken($colorMainBackground, 30); + $variables['--color-background-darker'] = $this->util->darken($colorMainBackground, 30); + + $variables['--color-placeholder-light'] = $this->util->darken($colorMainBackground, 30); + $variables['--color-placeholder-dark'] = $this->util->darken($colorMainBackground, 45); + + $variables['--color-text-maxcontrast'] = 'var(--color-main-text)'; + $variables['--color-text-light'] = 'var(--color-main-text)'; + $variables['--color-text-lighter'] = 'var(--color-main-text)'; + + // used for the icon loading animation + $variables['--color-loading-light'] = '#dddddd'; + $variables['--color-loading-dark'] = '#000000'; + + $variables['--color-box-shadow'] = 'var(--color-main-text)'; + + $variables['--color-border'] = $this->util->darken($colorMainBackground, 50); + $variables['--color-border-dark'] = $this->util->darken($colorMainBackground, 50); + + return $variables; + } + + public function getCustomCss(): string { + return " + [class^='icon-'], [class*=' icon-'], + .action, + #appmenu li a, + .menutoggle { + opacity: 1 !important; + } + "; + } +} diff --git a/apps/theming/lib/Util.php b/apps/theming/lib/Util.php index 05b954d5059..9a00bd1d5b1 100644 --- a/apps/theming/lib/Util.php +++ b/apps/theming/lib/Util.php @@ -34,17 +34,13 @@ use OCP\Files\IAppData; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; use OCP\IConfig; +use Mexitek\PHPColors\Color; class Util { - /** @var IConfig */ - private $config; - - /** @var IAppManager */ - private $appManager; - - /** @var IAppData */ - private $appData; + private IConfig $config; + private IAppManager $appManager; + private IAppData $appData; /** * Util constructor. @@ -95,59 +91,52 @@ class Util { return $color; } + public function mix(string $color1, string $color2, int $factor): string { + $color = new Color($color1); + return '#' . $color->mix($color2, $factor); + } + + public function lighten(string $color, int $factor): string { + $color = new Color($color); + return '#' . $color->lighten($factor); + } + + public function darken(string $color, int $factor): string { + $color = new Color($color); + return '#' . $color->darken($factor); + } + /** * Convert RGB to HSL * * Copied from cssphp, copyright Leaf Corcoran, licensed under MIT * - * @param integer $red - * @param integer $green - * @param integer $blue + * @param int $red + * @param int $green + * @param int $blue * - * @return array + * @return float[] */ - public function toHSL($red, $green, $blue) { - $min = min($red, $green, $blue); - $max = max($red, $green, $blue); - $l = $min + $max; - $d = $max - $min; - - if ((int) $d === 0) { - $h = $s = 0; - } else { - if ($l < 255) { - $s = $d / $l; - } else { - $s = $d / (510 - $l); - } - - if ($red == $max) { - $h = 60 * ($green - $blue) / $d; - } elseif ($green == $max) { - $h = 60 * ($blue - $red) / $d + 120; - } else { - $h = 60 * ($red - $green) / $d + 240; - } - } - - return [fmod($h, 360), $s * 100, $l / 5.1]; + public function toHSL(int $red, int $green, int $blue): array { + $color = new Color(Color::rgbToHex(['R' => $red, 'G' => $green, 'B' => $blue])); + return array_values($color->getHsl()); } /** * @param string $color rgb color value * @return float */ - public function calculateLuminance($color) { + public function calculateLuminance(string $color): float { [$red, $green, $blue] = $this->hexToRGB($color); $hsl = $this->toHSL($red, $green, $blue); - return $hsl[2] / 100; + return $hsl[2]; } /** * @param string $color rgb color value * @return float */ - public function calculateLuma($color) { + public function calculateLuma(string $color): float { [$red, $green, $blue] = $this->hexToRGB($color); return (0.2126 * $red + 0.7152 * $green + 0.0722 * $blue) / 255; } @@ -157,19 +146,9 @@ class Util { * @return int[] * @psalm-return array{0: int, 1: int, 2: int} */ - public function hexToRGB($color) { - $hex = preg_replace("/[^0-9A-Fa-f]/", '', $color); - if (strlen($hex) === 3) { - $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; - } - if (strlen($hex) !== 6) { - return [0, 0, 0]; - } - return [ - hexdec(substr($hex, 0, 2)), - hexdec(substr($hex, 2, 2)), - hexdec(substr($hex, 4, 2)) - ]; + public function hexToRGB(string $color): array { + $color = new Color($color); + return array_values($color->getRgb()); } /** diff --git a/apps/theming/src/UserThemes.vue b/apps/theming/src/UserThemes.vue new file mode 100644 index 00000000000..1fd6cb20866 --- /dev/null +++ b/apps/theming/src/UserThemes.vue @@ -0,0 +1,186 @@ +<template> + <SettingsSection class="theming" :title="t('themes', 'Appearance and accessibility')"> + <p v-html="description" /> + <p v-html="descriptionDetail" /> + + <div class="theming__preview-list"> + <ItemPreview v-for="theme in themes" + :key="theme.id" + :theme="theme" + :selected="selectedTheme.id === theme.id" + :themes="themes" + type="theme" + @change="changeTheme" /> + <ItemPreview v-for="theme in fonts" + :key="theme.id" + :theme="theme" + :selected="theme.enabled" + :themes="fonts" + type="font" + @change="changeFont" /> + </div> + </SettingsSection> +</template> + +<script> +import { generateOcsUrl } from '@nextcloud/router' +import { loadState } from '@nextcloud/initial-state' +import axios from '@nextcloud/axios' +import SettingsSection from '@nextcloud/vue/dist/Components/SettingsSection' + +import ItemPreview from './components/ItemPreview' + +const availableThemes = loadState('theming', 'themes', []) + +console.debug('Available themes', availableThemes) + +export default { + name: 'UserThemes', + components: { + ItemPreview, + SettingsSection, + }, + + data() { + return { + availableThemes, + } + }, + + computed: { + themes() { + return this.availableThemes.filter(theme => theme.type === 1) + }, + fonts() { + return this.availableThemes.filter(theme => theme.type === 2) + }, + + // Selected theme, fallback on first (default) if none + selectedTheme() { + return this.themes.find(theme => theme.enabled === true) || this.themes[0] + }, + + description() { + // using the `t` replace method escape html, we have to do it manually :/ + return t( + 'theming', + 'Universal access is very important to us. We follow web standards and check to make everything usable also without mouse, and assistive software such as screenreaders. We aim to be compliant with the {guidelines}Web Content Accessibility Guidelines{linkend} 2.1 on AA level, with the high contrast theme even on AAA level.' + ) + .replace('{guidelines}', this.guidelinesLink) + .replace('{linkend}', '</a>') + }, + guidelinesLink() { + return '<a target="_blank" href="https://www.w3.org/WAI/standards-guidelines/wcag/" rel="noreferrer nofollow">' + }, + descriptionDetail() { + return t( + 'theming', + 'If you find any issues, don’t hesitate to report them on {issuetracker}our issue tracker{linkend}. And if you want to get involved, come join {designteam}our design team{linkend}!' + ) + .replace('{issuetracker}', this.issuetrackerLink) + .replace('{designteam}', this.designteamLink) + .replace(/\{linkend\}/g, '</a>') + }, + issuetrackerLink() { + return '<a target="_blank" href="https://github.com/nextcloud/server/issues/" rel="noreferrer nofollow">' + }, + designteamLink() { + return '<a target="_blank" href="https://nextcloud.com/design" rel="noreferrer nofollow">' + }, + }, + methods: { + changeTheme({ enabled, id }) { + // Reset selected and select new one + this.themes.forEach(theme => { + if (theme.id === id && enabled) { + theme.enabled = true + document.body.setAttribute(`data-theme-${theme.id}`, true) + return + } + theme.enabled = false + document.body.removeAttribute(`data-theme-${theme.id}`) + }) + + this.selectItem(enabled, id) + }, + changeFont({ enabled, id }) { + // Reset selected and select new one + this.fonts.forEach(font => { + if (font.id === id && enabled) { + font.enabled = true + document.body.setAttribute(`data-theme-${font.id}`, true) + return + } + font.enabled = false + document.body.removeAttribute(`data-theme-${font.id}`) + }) + + this.selectItem(enabled, id) + }, + + /** + * Commit a change and force reload css + * Fetching the file again will trigger the server update + * + * @param {boolean} enabled the theme state + * @param {string} themeId the theme ID to change + */ + async selectItem(enabled, themeId) { + try { + if (enabled) { + await axios({ + url: generateOcsUrl('apps/theming/api/v1/theme/{themeId}/enable', { themeId }), + method: 'PUT', + }) + } else { + await axios({ + url: generateOcsUrl('apps/theming/api/v1/theme/{themeId}', { themeId }), + method: 'DELETE', + }) + } + + } catch (err) { + console.error(err, err.response) + OC.Notification.showTemporary(t('theming', err.response.data.ocs.meta.message + '. Unable to apply the setting.')) + } + }, + }, +} +</script> +<style lang="scss" scoped> + +.theming { + // Limit width of settings sections for readability + p { + max-width: 800px; + } + + // Proper highlight for links and focus feedback + &::v-deep a { + font-weight: bold; + + &:hover, + &:focus { + text-decoration: underline; + } + } + + &__preview-list { + --gap: 30px; + + display: grid; + margin-top: var(--gap); + column-gap: var(--gap); + row-gap: var(--gap); + grid-template-columns: 1fr 1fr; + } +} + +@media (max-width: 1440px) { + .theming__preview-list { + display: flex; + flex-direction: column; + } +} + +</style> diff --git a/apps/theming/src/components/ItemPreview.vue b/apps/theming/src/components/ItemPreview.vue new file mode 100644 index 00000000000..82d588059a2 --- /dev/null +++ b/apps/theming/src/components/ItemPreview.vue @@ -0,0 +1,124 @@ +<template> + <div class="theming__preview"> + <div class="theming__preview-image" :style="{ backgroundImage: 'url(' + img + ')' }" /> + <div class="theming__preview-description"> + <h3>{{ theme.title }}</h3> + <p>{{ theme.description }}</p> + <CheckboxRadioSwitch class="theming__preview-toggle" + :checked.sync="checked" + :name="name" + :type="switchType"> + {{ theme.enableLabel }} + </CheckboxRadioSwitch> + </div> + </div> +</template> + +<script> +import { generateFilePath } from '@nextcloud/router' +import CheckboxRadioSwitch from '@nextcloud/vue/dist/Components/CheckboxRadioSwitch' + +export default { + name: 'ItemPreview', + components: { + CheckboxRadioSwitch, + }, + props: { + theme: { + type: Object, + required: true, + }, + selected: { + type: Boolean, + default: false, + }, + type: { + type: String, + default: '', + }, + themes: { + type: Array, + default: () => [], + }, + }, + computed: { + switchType() { + return this.themes.length === 1 ? 'switch' : 'radio' + }, + + name() { + return this.switchType === 'radio' ? this.type : null + }, + + img() { + return generateFilePath('theming', 'img', this.theme.id + '.jpg') + }, + + checked: { + get() { + return this.selected + }, + set(checked) { + console.debug('Selecting theme', this.theme, checked) + + // If this is a radio, we can only enable + if (this.switchType === 'radio') { + this.$emit('change', { enabled: true, id: this.theme.id }) + return + } + + // If this is a switch, we can disable the theme + this.$emit('change', { enabled: checked === true, id: this.theme.id }) + }, + }, + }, +} +</script> +<style lang="scss" scoped> +// We make previews on 16/10 screens +$ratio: 16; + +.theming__preview { + --ratio: 16; + position: relative; + display: flex; + justify-content: flex-start; + max-width: 800px; + + &, + * { + user-select: none; + } + + &-image { + flex-basis: calc(16px * var(--ratio)); + flex-shrink: 0; + height: calc(10px * var(--ratio)); + margin-right: var(--gap); + border-radius: var(--border-radius); + background-repeat: no-repeat; + background-position: top left; + background-size: cover; + } + + &-description { + display: flex; + flex-direction: column; + + label { + padding: 12px 0; + } + } +} + +@media (max-width: (1024px / 1.5)) { + .theming__preview { + flex-direction: column; + + &-image { + margin: 0; + } + } +} + +</style> diff --git a/apps/theming/src/settings.js b/apps/theming/src/settings.js new file mode 100644 index 00000000000..45a75e53ea5 --- /dev/null +++ b/apps/theming/src/settings.js @@ -0,0 +1,32 @@ +/** + * @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license AGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +import Vue from 'vue' +import App from './UserThemes.vue' + +// bind to window +Vue.prototype.OC = OC +Vue.prototype.t = t + +const View = Vue.extend(App) +const theming = new View() +theming.$mount('#theming') diff --git a/apps/theming/templates/settings-admin.php b/apps/theming/templates/settings-admin.php index d38ca0fc44c..6014f0e8579 100644 --- a/apps/theming/templates/settings-admin.php +++ b/apps/theming/templates/settings-admin.php @@ -116,7 +116,7 @@ style('theming', 'settings-admin'); <label for="upload-login-logoheader"><span><?php p($l->t('Header logo')) ?></span></label> <input id="upload-login-logoheader" class="fileupload" name="image" type="file"> <label for="upload-login-logoheader" class="button icon-upload svg" id="upload-login-logoheader" title="<?php p($l->t("Upload new header logo")) ?>"></label> - <div class="image-preview"></div> + <div id="theming-preview-logoheader" class="image-preview"></div> <div data-setting="logoheaderMime" data-toggle="tooltip" data-original-title="<?php p($l->t('Reset to default')); ?>" class="theme-undo icon icon-history"></div> </form> </div> @@ -127,7 +127,7 @@ style('theming', 'settings-admin'); <label for="upload-login-favicon"><span><?php p($l->t('Favicon')) ?></span></label> <input id="upload-login-favicon" class="fileupload" name="image" type="file"> <label for="upload-login-favicon" class="button icon-upload svg" id="upload-login-favicon" title="<?php p($l->t("Upload new favicon")) ?>"></label> - <div class="image-preview"></div> + <div id="theming-preview-favicon" class="image-preview"></div> <div data-setting="faviconMime" data-toggle="tooltip" data-original-title="<?php p($l->t('Reset to default')); ?>" class="theme-undo icon icon-history"></div> </form> </div> diff --git a/apps/theming/templates/settings-personal.php b/apps/theming/templates/settings-personal.php new file mode 100644 index 00000000000..4ba1aa47e6f --- /dev/null +++ b/apps/theming/templates/settings-personal.php @@ -0,0 +1,26 @@ +<?php +/** + * @copyright Copyright (c) 2018 John Molakvoæ <skjnldsv@protonmail.com> + * + * @author John Molakvoæ <skjnldsv@protonmail.com> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +?> + +<span id="theming"></span>
\ No newline at end of file diff --git a/apps/theming/tests/Controller/ThemingControllerTest.php b/apps/theming/tests/Controller/ThemingControllerTest.php index cff2028809d..511f7a6d528 100644 --- a/apps/theming/tests/Controller/ThemingControllerTest.php +++ b/apps/theming/tests/Controller/ThemingControllerTest.php @@ -34,8 +34,8 @@ namespace OCA\Theming\Tests\Controller; use OC\L10N\L10N; -use OC\Template\SCSSCacher; use OCA\Theming\Controller\ThemingController; +use OCA\Theming\Service\ThemesService; use OCA\Theming\ImageManager; use OCA\Theming\ThemingDefaults; use OCP\App\IAppManager; @@ -72,10 +72,10 @@ class ThemingControllerTest extends TestCase { private $appData; /** @var ImageManager|MockObject */ private $imageManager; - /** @var SCSSCacher */ - private $scssCacher; - /** @var IURLGenerator */ + /** @var IURLGenerator|MockObject */ private $urlGenerator; + /** @var ThemeService|MockObject */ + private $themesService; protected function setUp(): void { $this->request = $this->createMock(IRequest::class); @@ -85,9 +85,9 @@ class ThemingControllerTest extends TestCase { $this->appData = $this->createMock(IAppData::class); $this->appManager = $this->createMock(IAppManager::class); $this->tempManager = \OC::$server->getTempManager(); - $this->scssCacher = $this->createMock(SCSSCacher::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->imageManager = $this->createMock(ImageManager::class); + $this->themesService = $this->createMock(ThemesService::class); $timeFactory = $this->createMock(ITimeFactory::class); $timeFactory->expects($this->any()) @@ -104,10 +104,10 @@ class ThemingControllerTest extends TestCase { $this->l10n, $this->tempManager, $this->appData, - $this->scssCacher, $this->urlGenerator, $this->appManager, - $this->imageManager + $this->imageManager, + $this->themesService, ); parent::setUp(); @@ -144,23 +144,12 @@ class ThemingControllerTest extends TestCase { ->willReturnCallback(function ($str) { return $str; }); - $this->scssCacher - ->expects($this->once()) - ->method('getCachedSCSS') - ->with('core', '/core/css/css-variables.scss') - ->willReturn('/core/css/someHash-css-variables.scss'); - $this->urlGenerator - ->expects($this->once()) - ->method('linkTo') - ->with('', '/core/css/someHash-css-variables.scss') - ->willReturn('/nextcloudWebroot/core/css/someHash-css-variables.scss'); $expected = new DataResponse( [ 'data' => [ 'message' => $message, - 'serverCssUrl' => '/nextcloudWebroot/core/css/someHash-css-variables.scss', ], 'status' => 'success', ] @@ -382,9 +371,6 @@ class ThemingControllerTest extends TestCase { return $str; }); - $this->urlGenerator->expects($this->once()) - ->method('linkTo') - ->willReturn('serverCss'); $this->imageManager->expects($this->once()) ->method('getImageUrl') ->with('logo') @@ -400,7 +386,6 @@ class ThemingControllerTest extends TestCase { 'name' => 'logo.svg', 'message' => 'Saved', 'url' => 'imageUrl', - 'serverCssUrl' => 'serverCss' ], 'status' => 'success' ] @@ -440,9 +425,6 @@ class ThemingControllerTest extends TestCase { $this->imageManager->expects($this->once()) ->method('updateImage'); - $this->urlGenerator->expects($this->once()) - ->method('linkTo') - ->willReturn('serverCss'); $this->imageManager->expects($this->once()) ->method('getImageUrl') ->with('background') @@ -454,7 +436,6 @@ class ThemingControllerTest extends TestCase { 'name' => 'logo.svg', 'message' => 'Saved', 'url' => 'imageUrl', - 'serverCssUrl' => 'serverCss' ], 'status' => 'success' ] @@ -607,24 +588,13 @@ class ThemingControllerTest extends TestCase { ->method('undo') ->with('MySetting') ->willReturn('MyValue'); - $this->scssCacher - ->expects($this->once()) - ->method('getCachedSCSS') - ->with('core', '/core/css/css-variables.scss') - ->willReturn('/core/css/someHash-css-variables.scss'); - $this->urlGenerator - ->expects($this->once()) - ->method('linkTo') - ->with('', '/core/css/someHash-css-variables.scss') - ->willReturn('/nextcloudWebroot/core/css/someHash-css-variables.scss'); $expected = new DataResponse( [ 'data' => [ 'value' => 'MyValue', - 'message' => 'Saved', - 'serverCssUrl' => '/nextcloudWebroot/core/css/someHash-css-variables.scss', + 'message' => 'Saved' ], 'status' => 'success' ] @@ -651,16 +621,6 @@ class ThemingControllerTest extends TestCase { ->method('undo') ->with($value) ->willReturn($value); - $this->scssCacher - ->expects($this->once()) - ->method('getCachedSCSS') - ->with('core', '/core/css/css-variables.scss') - ->willReturn('/core/css/someHash-css-variables.scss'); - $this->urlGenerator - ->expects($this->once()) - ->method('linkTo') - ->with('', '/core/css/someHash-css-variables.scss') - ->willReturn('/nextcloudWebroot/core/css/someHash-css-variables.scss'); $expected = new DataResponse( [ @@ -668,7 +628,6 @@ class ThemingControllerTest extends TestCase { [ 'value' => $value, 'message' => 'Saved', - 'serverCssUrl' => '/nextcloudWebroot/core/css/someHash-css-variables.scss', ], 'status' => 'success' ] @@ -743,53 +702,6 @@ class ThemingControllerTest extends TestCase { @$this->assertEquals($expected, $this->themingController->getImage('background')); } - - public function testGetStylesheet() { - $this->appManager->expects($this->once())->method('getAppPath')->with('theming')->willReturn(\OC::$SERVERROOT . '/theming'); - $file = $this->createMock(ISimpleFile::class); - $file->expects($this->any())->method('getName')->willReturn('theming.css'); - $file->expects($this->any())->method('getMTime')->willReturn(42); - $file->expects($this->any())->method('getContent')->willReturn('compiled'); - $this->scssCacher->expects($this->once())->method('process')->willReturn(true); - $this->scssCacher->expects($this->once())->method('getCachedCSS')->willReturn($file); - - $response = new Http\FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => 'text/css']); - $response->cacheFor(86400); - - $actual = $this->themingController->getStylesheet(); - $this->assertEquals($response, $actual); - } - - public function testGetStylesheetFails() { - $this->appManager->expects($this->once())->method('getAppPath')->with('theming')->willReturn(\OC::$SERVERROOT . '/theming'); - $file = $this->createMock(ISimpleFile::class); - $file->expects($this->any())->method('getName')->willReturn('theming.css'); - $file->expects($this->any())->method('getMTime')->willReturn(42); - $file->expects($this->any())->method('getContent')->willReturn('compiled'); - $this->scssCacher->expects($this->once())->method('process')->willReturn(true); - $this->scssCacher->expects($this->once())->method('getCachedCSS')->willThrowException(new NotFoundException()); - $response = new Http\NotFoundResponse(); - - $actual = $this->themingController->getStylesheet(); - $this->assertEquals($response, $actual); - } - - public function testGetStylesheetOutsideServerroot() { - $this->appManager->expects($this->once())->method('getAppPath')->with('theming')->willReturn('/outside/serverroot/theming'); - $file = $this->createMock(ISimpleFile::class); - $file->expects($this->any())->method('getName')->willReturn('theming.css'); - $file->expects($this->any())->method('getMTime')->willReturn(42); - $file->expects($this->any())->method('getContent')->willReturn('compiled'); - $this->scssCacher->expects($this->once())->method('process')->with('/outside/serverroot/theming', 'css/theming.scss', 'theming')->willReturn(true); - $this->scssCacher->expects($this->once())->method('getCachedCSS')->willReturn($file); - - $response = new Http\FileDisplayResponse($file, Http::STATUS_OK, ['Content-Type' => 'text/css']); - $response->cacheFor(86400); - - $actual = $this->themingController->getStylesheet(); - $this->assertEquals($response, $actual); - } - public function testGetManifest() { $this->config ->expects($this->once()) diff --git a/apps/theming/tests/Controller/UserThemeControllerTest.php b/apps/theming/tests/Controller/UserThemeControllerTest.php new file mode 100644 index 00000000000..99e36938e74 --- /dev/null +++ b/apps/theming/tests/Controller/UserThemeControllerTest.php @@ -0,0 +1,153 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Bjoern Schiessle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Calviño Sánchez <danxuliu@gmail.com> + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * @author Julius Haertl <jus@bitgrid.net> + * @author Julius Härtl <jus@bitgrid.net> + * @author Kyle Fazzari <kyrofa@ubuntu.com> + * @author Lukas Reschke <lukas@statuscode.ch> + * @author Michael Weimann <mail@michael-weimann.eu> + * @author rakekniven <mark.ziegler@rakekniven.de> + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Tests\Controller; + +use OCA\Theming\Controller\UserThemeController; +use OCA\Theming\ITheme; +use OCA\Theming\Themes\DarkHighContrastTheme; +use OCA\Theming\Themes\DarkTheme; +use OCA\Theming\Themes\DefaultTheme; +use OCA\Theming\Themes\DyslexiaFont; +use OCA\Theming\Themes\HighContrastTheme; +use OCA\Theming\Service\ThemesService; +use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCS\OCSBadRequestException; +use OCP\IConfig; +use OCP\IRequest; +use OCP\IUser; +use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +class UserThemeControllerTest extends TestCase { + /** @var UserThemeController */ + private $userThemeController; + + /** @var IRequest|MockObject */ + private $request; + /** @var IConfig|MockObject */ + private $config; + /** @var IUserSession|MockObject */ + private $userSession; + /** @var ThemeService|MockObject */ + private $themesService; + + /** @var ITheme[] */ + private $themes; + + protected function setUp(): void { + $this->request = $this->createMock(IRequest::class); + $this->config = $this->createMock(IConfig::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->themesService = $this->createMock(ThemesService::class); + + $this->themes = [ + 'default' => $this->createMock(DefaultTheme::class), + 'dark' => $this->createMock(DarkTheme::class), + 'highcontrast' => $this->createMock(HighContrastTheme::class), + 'dark-highcontrast' => $this->createMock(DarkHighContrastTheme::class), + 'opendyslexic' => $this->createMock(DyslexiaFont::class), + ]; + + $user = $this->createMock(IUser::class); + $this->userSession->expects($this->any()) + ->method('getUser') + ->willReturn($user); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('user'); + + $this->userThemeController = new UserThemeController( + 'theming', + $this->request, + $this->config, + $this->userSession, + $this->themesService, + ); + + parent::setUp(); + } + + public function dataTestThemes() { + return [ + ['default'], + ['dark'], + ['highcontrast'], + ['dark-highcontrast'], + ['opendyslexic'], + ['', OCSBadRequestException::class], + ['badTheme', OCSBadRequestException::class], + ]; + } + + /** + * @dataProvider dataTestThemes + * + * @param string $themeId + * @param string $exception + */ + public function testEnableTheme($themeId, string $exception = null) { + $this->themesService + ->expects($this->any()) + ->method('getThemes') + ->willReturn($this->themes); + + if ($exception) { + $this->expectException($exception); + } + + $expected = new DataResponse(); + $this->assertEquals($expected, $this->userThemeController->enableTheme($themeId)); + } + + /** + * @dataProvider dataTestThemes + * + * @param string $themeId + * @param string $exception + */ + public function testDisableTheme($themeId, string $exception = null) { + $this->themesService + ->expects($this->any()) + ->method('getThemes') + ->willReturn($this->themes); + + if ($exception) { + $this->expectException($exception); + } + + $expected = new DataResponse(); + $this->assertEquals($expected, $this->userThemeController->disableTheme($themeId)); + } +} diff --git a/apps/theming/tests/Service/ThemesServiceTest.php b/apps/theming/tests/Service/ThemesServiceTest.php new file mode 100644 index 00000000000..2d0d313f9e4 --- /dev/null +++ b/apps/theming/tests/Service/ThemesServiceTest.php @@ -0,0 +1,255 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Bjoern Schiessle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Calviño Sánchez <danxuliu@gmail.com> + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * @author Julius Haertl <jus@bitgrid.net> + * @author Julius Härtl <jus@bitgrid.net> + * @author Kyle Fazzari <kyrofa@ubuntu.com> + * @author Lukas Reschke <lukas@statuscode.ch> + * @author Michael Weimann <mail@michael-weimann.eu> + * @author rakekniven <mark.ziegler@rakekniven.de> + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Tests\Service; + +use OCA\Theming\AppInfo\Application; +use OCA\Theming\ImageManager; +use OCA\Theming\ITheme; +use OCA\Theming\Themes\DarkHighContrastTheme; +use OCA\Theming\Themes\DarkTheme; +use OCA\Theming\Themes\DefaultTheme; +use OCA\Theming\Themes\DyslexiaFont; +use OCA\Theming\Themes\HighContrastTheme; +use OCA\Theming\Service\ThemesService; +use OCA\Theming\ThemingDefaults; +use OCA\Theming\Util; +use OCP\AppFramework\Http\DataResponse; +use OCP\AppFramework\OCS\OCSBadRequestException; +use OCP\IConfig; +use OCP\IL10N; +use OCP\IRequest; +use OCP\IURLGenerator; +use OCP\IUser; +use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +class ThemesServiceTest extends TestCase { + /** @var ThemesService */ + private $themesService; + + /** @var IUserSession|MockObject */ + private $userSession; + /** @var IConfig|MockObject */ + private $config; + /** @var ThemingDefaults|MockObject */ + private $themingDefaults; + + /** @var ITheme[] */ + private $themes; + + protected function setUp(): void { + $this->userSession = $this->createMock(IUserSession::class); + $this->config = $this->createMock(IConfig::class); + $this->themingDefaults = $this->createMock(ThemingDefaults::class); + + $this->themingDefaults->expects($this->any()) + ->method('getColorPrimary') + ->willReturn('#0082c9'); + + $this->initThemes(); + + $this->themesService = new ThemesService( + $this->userSession, + $this->config, + ...array_values($this->themes) + ); + + parent::setUp(); + } + + public function testGetThemes() { + $expected = [ + 'default', + 'dark', + 'highcontrast', + 'dark-highcontrast', + 'opendyslexic', + ]; + $this->assertEquals($expected, array_keys($this->themesService->getThemes())); + } + + + public function dataTestEnableTheme() { + return [ + ['dark', [], ['dark']], + ['dark', ['dark'], ['dark']], + ['opendyslexic', ['dark'], ['dark', 'opendyslexic']], + ['dark', ['highcontrast', 'opendyslexic'], ['opendyslexic', 'dark']], + ]; + } + + /** + * @dataProvider dataTestEnableTheme + * + * @param string $toEnable + * @param string[] $enabledThemes + * @param string[] $expectedEnabled + */ + public function testEnableTheme(string $toEnable, array $enabledThemes, array $expectedEnabled) { + $user = $this->createMock(IUser::class); + $this->userSession->expects($this->any()) + ->method('getUser') + ->willReturn($user); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('user'); + + $this->config->expects($this->once()) + ->method('getUserValue') + ->with('user', Application::APP_ID, 'enabled-themes', '[]') + ->willReturn(json_encode($enabledThemes)); + + $this->assertEquals($expectedEnabled, $this->themesService->enableTheme($this->themes[$toEnable])); + } + + + public function dataTestDisableTheme() { + return [ + ['dark', [], []], + ['dark', ['dark'], []], + ['opendyslexic', ['dark', 'opendyslexic'], ['dark'], ], + ['highcontrast', ['opendyslexic'], ['opendyslexic']], + ]; + } + + /** + * @dataProvider dataTestDisableTheme + * + * @param string $toEnable + * @param string[] $enabledThemes + * @param string[] $expectedEnabled + */ + public function testDisableTheme(string $toDisable, array $enabledThemes, array $expectedEnabled) { + $user = $this->createMock(IUser::class); + $this->userSession->expects($this->any()) + ->method('getUser') + ->willReturn($user); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('user'); + + $this->config->expects($this->once()) + ->method('getUserValue') + ->with('user', Application::APP_ID, 'enabled-themes', '[]') + ->willReturn(json_encode($enabledThemes)); + + + $this->assertEquals($expectedEnabled, $this->themesService->disableTheme($this->themes[$toDisable])); + } + + + public function dataTestIsEnabled() { + return [ + ['dark', [], false], + ['dark', ['dark'], true], + ['opendyslexic', ['dark', 'opendyslexic'], true], + ['highcontrast', ['opendyslexic'], false], + ]; + } + + /** + * @dataProvider dataTestIsEnabled + * + * @param string $toEnable + * @param string[] $enabledThemes + */ + public function testisEnabled(string $themeId, array $enabledThemes, $expected) { + $user = $this->createMock(IUser::class); + $this->userSession->expects($this->any()) + ->method('getUser') + ->willReturn($user); + $user->expects($this->any()) + ->method('getUID') + ->willReturn('user'); + + $this->config->expects($this->once()) + ->method('getUserValue') + ->with('user', Application::APP_ID, 'enabled-themes', '[]') + ->willReturn(json_encode($enabledThemes)); + + + $this->assertEquals($expected, $this->themesService->isEnabled($this->themes[$themeId])); + } + + private function initThemes() { + $util = $this->createMock(Util::class); + $urlGenerator = $this->createMock(IURLGenerator::class); + $imageManager = $this->createMock(ImageManager::class); + $l10n = $this->createMock(IL10N::class); + + $this->themes = [ + 'default' => new DefaultTheme( + $util, + $this->themingDefaults, + $urlGenerator, + $imageManager, + $this->config, + $l10n, + ), + 'dark' => new DarkTheme( + $util, + $this->themingDefaults, + $urlGenerator, + $imageManager, + $this->config, + $l10n, + ), + 'highcontrast' => new HighContrastTheme( + $util, + $this->themingDefaults, + $urlGenerator, + $imageManager, + $this->config, + $l10n, + ), + 'dark-highcontrast' => new DarkHighContrastTheme( + $util, + $this->themingDefaults, + $urlGenerator, + $imageManager, + $this->config, + $l10n, + ), + 'opendyslexic' => new DyslexiaFont( + $util, + $this->themingDefaults, + $urlGenerator, + $imageManager, + $this->config, + $l10n, + ), + ]; + } +} diff --git a/apps/theming/tests/ServicesTest.php b/apps/theming/tests/ServicesTest.php index fdd49deddd8..441e5d55044 100644 --- a/apps/theming/tests/ServicesTest.php +++ b/apps/theming/tests/ServicesTest.php @@ -28,7 +28,7 @@ namespace OCA\Theming\Tests; use OCA\Theming\Capabilities; use OCA\Theming\Controller\ThemingController; use OCA\Theming\Settings\Admin; -use OCA\Theming\Settings\Section; +use OCA\Theming\Settings\PersonalSection; use OCA\Theming\ThemingDefaults; use OCA\Theming\Util; use OCP\AppFramework\App; @@ -74,8 +74,8 @@ class ServicesTest extends TestCase { // Settings [Admin::class], [Admin::class, ISettings::class], - [Section::class], - [Section::class, IIconSection::class], + [PersonalSection::class], + [PersonalSection::class, IIconSection::class], ]; } diff --git a/apps/theming/tests/Settings/AdminTest.php b/apps/theming/tests/Settings/AdminTest.php index 50b95fe7e99..b10196a1ac5 100644 --- a/apps/theming/tests/Settings/AdminTest.php +++ b/apps/theming/tests/Settings/AdminTest.php @@ -27,6 +27,7 @@ */ namespace OCA\Theming\Tests\Settings; +use OCA\Theming\AppInfo\Application; use OCA\Theming\ImageManager; use OCA\Theming\Settings\Admin; use OCA\Theming\ThemingDefaults; @@ -59,6 +60,7 @@ class AdminTest extends TestCase { $this->imageManager = $this->createMock(ImageManager::class); $this->admin = new Admin( + Application::APP_ID, $this->config, $this->l10n, $this->themingDefaults, diff --git a/apps/theming/tests/Settings/SectionTest.php b/apps/theming/tests/Settings/SectionTest.php index 496c24b3e52..c168f13728d 100644 --- a/apps/theming/tests/Settings/SectionTest.php +++ b/apps/theming/tests/Settings/SectionTest.php @@ -23,7 +23,8 @@ */ namespace OCA\Theming\Tests\Settings; -use OCA\Theming\Settings\Section; +use OCA\Theming\AppInfo\Application; +use OCA\Theming\Settings\AdminSection; use OCP\IL10N; use OCP\IURLGenerator; use Test\TestCase; @@ -33,7 +34,7 @@ class SectionTest extends TestCase { private $url; /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ private $l; - /** @var Section */ + /** @var AdminSection */ private $section; protected function setUp(): void { @@ -41,7 +42,8 @@ class SectionTest extends TestCase { $this->url = $this->createMock(IURLGenerator::class); $this->l = $this->createMock(IL10N::class); - $this->section = new Section( + $this->section = new AdminSection( + Application::APP_ID, $this->url, $this->l ); diff --git a/apps/theming/tests/Themes/DefaultThemeTest.php b/apps/theming/tests/Themes/DefaultThemeTest.php new file mode 100644 index 00000000000..d3494b1c304 --- /dev/null +++ b/apps/theming/tests/Themes/DefaultThemeTest.php @@ -0,0 +1,146 @@ +<?php +/** + * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> + * + * @author Bjoern Schiessle <bjoern@schiessle.org> + * @author Christoph Wurst <christoph@winzerhof-wurst.at> + * @author Daniel Calviño Sánchez <danxuliu@gmail.com> + * @author Joas Schilling <coding@schilljs.com> + * @author John Molakvoæ <skjnldsv@protonmail.com> + * @author Julius Haertl <jus@bitgrid.net> + * @author Julius Härtl <jus@bitgrid.net> + * @author Kyle Fazzari <kyrofa@ubuntu.com> + * @author Lukas Reschke <lukas@statuscode.ch> + * @author Michael Weimann <mail@michael-weimann.eu> + * @author rakekniven <mark.ziegler@rakekniven.de> + * @author Roeland Jago Douma <roeland@famdouma.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ +namespace OCA\Theming\Tests\Service; + +use OC\App\AppManager; +use OCA\Theming\ImageManager; +use OCA\Theming\ITheme; +use OCA\Theming\Themes\DefaultTheme; +use OCA\Theming\ThemingDefaults; +use OCA\Theming\Util; +use OCP\Files\IAppData; +use OCP\IConfig; +use OCP\IL10N; +use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + + +class DefaultThemeTest extends TestCase { + /** @var ThemingDefaults|MockObject */ + private $themingDefaults; + /** @var IURLGenerator|MockObject */ + private $urlGenerator; + /** @var ImageManager|MockObject */ + private $imageManager; + /** @var IConfig|MockObject */ + private $config; + /** @var IL10N|MockObject */ + private $l10n; + + private DefaultTheme $defaultTheme; + + protected function setUp(): void { + $this->themingDefaults = $this->createMock(ThemingDefaults::class); + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->imageManager = $this->createMock(ImageManager::class); + $this->config = $this->createMock(IConfig::class); + $this->l10n = $this->createMock(IL10N::class); + + $util = new Util( + $this->config, + $this->createMock(AppManager::class), + $this->createMock(IAppData::class) + ); + + $this->themingDefaults + ->expects($this->any()) + ->method('getColorPrimary') + ->willReturn('#0082c9'); + + $this->l10n + ->expects($this->any()) + ->method('t') + ->willReturnCallback(function ($text, $parameters = []) { + return vsprintf($text, $parameters); + }); + + $this->defaultTheme = new DefaultTheme( + $util, + $this->themingDefaults, + $this->urlGenerator, + $this->imageManager, + $this->config, + $this->l10n, + ); + + parent::setUp(); + } + + + public function testGetId() { + $this->assertEquals('default', $this->defaultTheme->getId()); + } + + public function testGetType() { + $this->assertEquals(ITheme::TYPE_THEME, $this->defaultTheme->getType()); + } + + public function testGetTitle() { + $this->assertEquals('Light theme', $this->defaultTheme->getTitle()); + } + + public function testGetEnableLabel() { + $this->assertEquals('Enable the default light theme', $this->defaultTheme->getEnableLabel()); + } + + public function testGetDescription() { + $this->assertEquals('The default light appearance.', $this->defaultTheme->getDescription()); + } + + public function testGetMediaQuery() { + $this->assertEquals('', $this->defaultTheme->getMediaQuery()); + } + + public function testGetCustomCss() { + $this->assertEquals('', $this->defaultTheme->getCustomCss()); + } + + /** + * Ensure parity between the default theme and the static generated file + * @see ThemingController.php:313 + */ + public function testThemindDisabledFallbackCss() { + // Generate variables + $variables = ''; + foreach ($this->defaultTheme->getCSSVariables() as $variable => $value) { + $variables .= " $variable: $value;" . PHP_EOL; + }; + + $css = ":root { " . PHP_EOL . "$variables}" . PHP_EOL; + $fallbackCss = file_get_contents(__DIR__ . '/../../css/default.css'); + + $this->assertEquals($css, $fallbackCss); + } +} diff --git a/apps/theming/tests/UtilTest.php b/apps/theming/tests/UtilTest.php index f805d083e27..914ad8b073f 100644 --- a/apps/theming/tests/UtilTest.php +++ b/apps/theming/tests/UtilTest.php @@ -90,14 +90,15 @@ class UtilTest extends TestCase { $luminance = $this->util->calculateLuminance('#000'); $this->assertEquals(0, $luminance); } + public function testInvertTextColorInvalid() { - $invert = $this->util->invertTextColor('aaabbbcccddd123'); - $this->assertEquals(false, $invert); + $this->expectException(\Exception::class); + $this->util->invertTextColor('aaabbbcccddd123'); } public function testInvertTextColorEmpty() { - $invert = $this->util->invertTextColor(''); - $this->assertEquals(false, $invert); + $this->expectException(\Exception::class); + $this->util->invertTextColor(''); } public function testElementColorDefault() { |