Refactor to MediaHandler transform (#20)

Closes #6, Closes #18

This PR separates out 3 different classes: a distinct Hooks handling class, a MediaHandler class for models, and a MediaTransform class that handles all the actual model rendering.

Reviewed-on: #20
This commit is contained in:
2024-10-27 04:11:16 +00:00
parent 39329f5497
commit 3b5c2e993d
6 changed files with 395 additions and 269 deletions

View File

@@ -0,0 +1,77 @@
<?php
namespace MediaWiki\Extension\GlModelViewer;
use ImageHandler;
use Html;
class GlModelHandler extends ImageHandler {
/**
* Model cannot be displayed directly in a browser but can be rendered.
*
* @param File $file
* @return bool
*/
public function mustRender( $file ) {
return true;
}
/**
* Model can be rendered.
*
* @param File $file
* @return bool
*/
public function canRender( $file ) {
return true;
}
/**
* Get a MediaTransformOutput object representing the transformed output.
*
* @param File $image
* @param string $dstPath Filesystem destination path
* @param string $dstUrl Destination URL to use in output HTML
* @param array $params Arbitrary set of parameters validated by $this->validateParam()
* @param int $flags A bitfield, may contain self::TRANSFORM_LATER
* @return MediaTransformOutput
*/
public function doTransform($image, $dstPath, $dstUrl, $params, $flags = 0) {
return new GlModelTransformOutput($image, $params);
}
/**
* Check the incoming media parameters
*
* @param string $name
* @param string $value
* @return bool
*/
public function validateParam( $name, $value ) {
if (in_array($name, ['width', 'height'])) {
return $value > 0;
} else if (in_array($name, ['view', 'hsset'])) {
return true;
} else {
return false;
}
}
/**
* Small helper function to display information on the browser console
*
* Usage:
* echo '<script>';
* self::console_log('logged string');
* echo '</script>';
*
* @param $data information to display
* @param bool $add_script_tags true to put information is inside complete script tag
*/
public static function console_log($data, $add_script_tags = false) {
$command = 'console.log('. json_encode($data, JSON_HEX_TAG).');';
if ($add_script_tags) {
$command = '<script>'. $command . '</script>';
}
echo $command;
}
}

122
includes/GlModelHooks.php Normal file
View File

@@ -0,0 +1,122 @@
<?php
namespace MediaWiki\Extension\GlModelViewer;
use MediaWiki\MediaWikiServices;
use Html;
use ParserOutput;
class GlModelHooks {
/**
* MWHook: Add gltf mime types to MimeMagic
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/MimeMagicInit
*
* @param MimeAnalyzer $mime Instance of MW MimeAnalyzer object
*/
public static function onMimeMagicInit($mime) {
$mime->addExtraTypes('model/gltf-binary glb gltf');
$mime->addExtraInfo('model/gltf-binary [MULTIMEDIA]');
}
/**
* MWHook: Make sure that gltf files get the proper mime assignement on upload
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/MimeMagicImproveFromExtension
*
* @param MimeAnalyzer $mimeAnalyzer Instance of MW MimeAnalyzer object
* @param string $ext extention of upload file
* @param string &$mime current assigned mime type
*/
public static function onMimeMagicImproveFromExtension( $mimeAnalyzer, $ext, &$mime ) {
if ( $mime !== 'model/gltf-binary' && in_array( $ext, ['glb', 'gltf'] ) ) {
$mime = 'model/gltf-binary';
}
}
/**
* MWHook: Load the js and css modules if model-viewer element is found in the html output
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay
*
* @param OutputPage $out compiled page html and manipulation methods
*/
public static function onBeforePageDisplay($out) {
preg_match('/(<model-viewer src="\S*?\.(glb|gltf"))/',$out->getHTML(),$findGltf);
if ($findGltf[0]) {
$mvScriptAttr = array(
'src' => 'https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js',
'type' => 'module'
);
$out->addHeadItems(Html::rawElement('script',$mvScriptAttr));
$out->addModules('ext.glmv');
}
}
/**
* MWHook: Display model on file page
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/ImageOpenShowImageInlineBefore
*
* @param ImagePage $imagepage information regarding the page for the image file
* @param OutputPage $out compiled page html and manipulation methods
*/
public static function onImageOpenShowImageInlineBefore( $imagepage, $out ){
$file = $imagepage->getFile();
if ($file->getMimeType() == 'model/gltf-binary') {
$out->clearHTML();
$out->addWikiTextAsContent('[[' . $file->getTitle()->getFullText() . '|800x600px]]');
}
}
/**
* MWHook: Display model when model file page edits are previewed
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/AlternateEditPreview
*
* @param EditPage $editor access to information about the edit page itself
* @param Content $content access to the current content of the editor
* @param string &$previewHTML by reference access to the resultant compiled preview html
* @param ?ParserOutput &$parserOutput
* @return bool|void True to continue default processing or false to abort for custom processing
*/
public static function onAlternateEditPreview( $editor, $content, string &$previewHTML, ?ParserOutput &$parserOutput ) {
$file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($editor->getTitle());
if (!$file || $file->getMimeType() !== 'model/gltf-binary') {
return true;
}
$out = $editor->getContext()->getOutput();
$out->addModules('ext.glmv');
$mvTransform = $file->transform([ 'width' => '800', 'hight' => '600']);
$previewViewer = $mvTransform->toHtml();
$addButtonAttr = array(
'class' => 'AddHotspot',
'onclick' => 'readyAddHotspot()'
);
$addHsButton = Html::rawElement('button',$addButtonAttr,'Add a new hotspot');
$previewHTML = Html::rawElement('div',NULL,$previewViewer.$addHsButton);
return false;
}
/**
* Small helper function to display information on the browser console
*
* Usage:
* echo '<script>';
* self::console_log('logged string');
* echo '</script>';
*
* @param $data information to display
* @param bool $add_script_tags true to put information is inside complete script tag
*/
public static function console_log($data, $add_script_tags = false) {
$command = 'console.log('. json_encode($data, JSON_HEX_TAG).');';
if ($add_script_tags) {
$command = '<script>'. $command . '</script>';
}
echo $command;
}
}

View File

@@ -0,0 +1,167 @@
<?php
namespace MediaWiki\Extension\GlModelViewer;
use MediaTransformOutput;
use Html;
class GlModelTransformOutput extends MediaTransformOutput {
/**
* Main Constructor
*
* @access public
* @param File $file
* @param array $parameters Parameters for constructing HTML.
* @return void
*/
public function __construct($file, $parameters) {
$this->file = $file;
$this->parameters = $parameters;
$this->width = (isset($parameters['width'])) ? $parameters['width'] : '800';
$this->height = (isset($parameters['height'])) ? $parameters['height'] : (int)($this->width * .75);
$this->url = $file->getFullUrl();
$this->thumb = isset($parameters['isFilePageThumb']);
}
/**
* Fetch HTML for this transform output
*
* @access public
* @param array $options Associative array of options. Boolean options
* should be indicated with a value of true for true, and false or
* absent for false.
* alt Alternate text or caption
* desc-link Boolean, show a description link
* file-link Boolean, show a file download link
* custom-url-link Custom URL to link to
* custom-title-link Custom Title object to link to
* valign vertical-align property, if the output is an inline element
* img-class Class applied to the "<img>" tag, if there is such a tag
*
* @return string HTML
*/
public function toHtml($options = []) {
if ($this->thumb) {
return Html::rawElement('span',['class' => 'fake-thumbnail'],'Gltf model thumbnail');
}
//return Html::rawElement( 'div',[ 'class' => 'my-model-class'], $this->url . ' is a ' . $this->parameters['type'] . ' 3D model!' );
if (isset($options['img-class'])) {
$this->parameters['class'] = $options['img-class'];
}
return self::buildViewer($this->file->getDescriptionText(),$this->url,$this->parameters);
}
/**
* Build model-viewer and child elements
*
* This takes in the metadata text from the model page (or the current editor)
* and produces the html string for the model-viewer and all relevant child
* elements.
*
* @param string $inText The metadata text which must include a json formatted string inside a pre tag
* @param string $srcUrl The full url pointing to the model file
* @param array $frameParams The additional user defined parameters for the viewer such as hotspot and view classes
* @return string Html string of the complete model-viewer element inside a div container
*/
private function buildViewer($inText, $srcUrl, $viewParams) {
//Gather basic data
preg_match('/<pre>([\S\s]*?)<\/pre>/',$inText,$modelDescript);
$metadata = json_decode($modelDescript[1], true);
$viewClass = self::extractClassParams('view',$viewParams['class']);
$hsSetClass = self::extractClassParams('hsset',$viewParams['class']);
//Handle annotations and annotation sets
if (isset($metadata['annotations'])) {
$hotspots = [];
$annotations = [];
if ($hsSetClass != 'default' && isset($metadata['annotationSets'])) {
foreach($metadata['annotationSets'][$hsSetClass] as $includeAn) {
if (isset($metadata['annotations'][$includeAn])) {
$annotations[$includeAn] = $metadata['annotations'][$includeAn];
}
}
} else {
$annotations = $metadata['annotations'];
}
foreach($annotations as $label => $an) {
$elAnnot = Html::rawElement('div',['class' => 'HotspotAnnotation HiddenAnnotation'],$label);
$hsDefault = array(
'class' => 'Hotspot',
'slot' => 'hotspot-'.(count($hotspots) +1),
'onmousedown' => 'event.stopPropagation()',
'ontouchstart' => 'event.stopPropagation()',
'onclick' => 'onAnnotation(event)'
);
$attrHotspot = array_merge($hsDefault, $an);
$elHotspot = Html::rawElement('button',$attrHotspot,$elAnnot.(count($hotspots) +1));
array_push($hotspots, $elHotspot);
}
}
//Set viewer configurations or use basic default if none defined
if (isset($metadata['viewerConfig']) && isset($metadata['viewerConfig'][$viewClass])) {
$attrModelView = $metadata['viewerConfig'][$viewClass];
} else {
$attrModelView = array('camera-controls' => true);
}
//Add important additional attributes and render model-viewer with hotspots
$attrModelView = array_merge(['src' => $srcUrl, 'class' => 'mv-model', 'interpolation-decay' => '100'], $attrModelView);
$attrModelView['style'] = 'width: 100%; height: 100%;';
$hotspotHtml = (isset($hotspots)) ? implode($hotspots) : '';
$elModel = Html::rawElement('model-viewer', $attrModelView, $hotspotHtml);
//Render and return container element with model-viewer
$attrContainer = array(
'style' => 'width: ' . $this->width . 'px; height: ' . $this->height . 'px;',
'onmousedown' => 'clearAnnotations()',
'ontouchstart' => 'clearAnnotations()'
);
return Html::rawElement('div', $attrContainer, $elModel);
}
/**
* Detect and return model user params from link classes
*
* The best way to send information in a file link is by adding classes to the
* link. This function parses the array of those classes and returns the information
* or 'default'
*
* @param string $paramType the type of parameter to be extracted 'view'|'hsset'
* @param string $classList a string of class names
* @return string parameter name or 'default'
*/
private static function extractClassParams(string $paramType, ? string $classList) {
if (!in_array($paramType, ['view', 'hsset'])) {
return 'default';
}
if (!isset($classList)) {
return 'default';
}
$searchString = '/' . $paramType . '-(\S*)/';
preg_match($searchString,$classList,$extractInfo);
return ($extractInfo[1]) ? $extractInfo[1] : 'default';
}
/**
* Small helper function to display information on the browser console
*
* Usage:
* echo '<script>';
* self::console_log('logged string');
* echo '</script>';
*
* @param $data information to display
* @param bool $add_script_tags true to put information is inside complete script tag
*/
public static function console_log($data, $add_script_tags = false) {
$command = 'console.log('. json_encode($data, JSON_HEX_TAG).');';
if ($add_script_tags) {
$command = '<script>'. $command . '</script>';
}
echo $command;
}
}

View File

@@ -1,242 +0,0 @@
<?php
use MediaWiki\MediaWikiServices;
class GlModelViewer extends ImageHandler {
/**
* MWHook: Add gltf mime types to MimeMagic
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/MimeMagicInit
*
* @param MimeAnalyzer $mime Instance of MW MimeAnalyzer object
*/
public static function onMimeMagicInit(MimeAnalyzer $mime) {
$mime->addExtraTypes('model/gltf-binary glb gltf');
$mime->addExtraInfo('model/gltf-binary [DRAWING]');
}
/**
* MWHook: Make sure that gltf files get the proper mime assignement on upload
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/MimeMagicImproveFromExtension
*
* @param MimeAnalyzer $mimeAnalyzer Instance of MW MimeAnalyzer object
* @param string $ext extention of upload file
* @param string &$mime current assigned mime type
*/
public static function onMimeMagicImproveFromExtension( MimeAnalyzer $mimeAnalyzer, $ext, &$mime ) {
if ( $mime !== 'model/gltf-binary' && in_array( $ext, ['glb', 'gltf'] ) ) {
$mime = 'model/gltf-binary';
}
}
/**
* MWHook: Load the js and css modules if model-viewer element is found in the html output
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay
*
* @param OutputPage $out compiled page html and manipulation methods
*/
public static function onBeforePageDisplay(OutputPage $out) {
preg_match('/(<model-viewer src="\S*?\.(glb|gltf"))/',$out->getHTML(),$findGltf);
if ($findGltf[0]) {
$mvScriptAttr = array(
'src' => 'https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js',
'type' => 'module'
);
$out->addHeadItems(Html::rawElement('script',$mvScriptAttr));
$out->addModules('ext.glmv');
}
}
/**
* MWHook: Replace File link rendered image with model-viewer element
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/ImageBeforeProduceHTML
*
* @param DummyLinker &$linker
* @param Title &$title
* @param FileObject &$file object containing information regarding the actual file for the File page
* @param array &$frameParams any added parameters of the file link such as class etc.
* @param array &$handlerParams
* @param &$time
* @param &$result By reference access to the rendered html result of the image
* @param Parser $parser
* @param string &$query
* @param &$widthOption
* @return bool|void True to continue default processing or false to abort for custom processing
*/
public static function onImageBeforeProduceHTML( DummyLinker &$linker, Title &$title, &$file, array &$frameParams, array &$handlerParams, &$time, &$result, Parser $parser, string &$query, &$widthOption ) {
if ($file->getMimeType() !== 'model/gltf-binary') {
return true;
}
$result = self::buildViewer($file->getDescriptionText(), $file->getFullUrl(), $frameParams);
return false;
}
/**
* MWHook: Display model on file page
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/ImageOpenShowImageInlineBefore
*
* @param ImagePage $imagepage information regarding the page for the image file
* @param OutputPage $out compiled page html and manipulation methods
*/
public static function onImageOpenShowImageInlineBefore( $imagepage, $out ){
$file = $imagepage->getFile();
if ($file->getMimeType() == 'model/gltf-binary') {
$viewer = self::buildViewer($file->getDescriptionText(), $file->getFullUrl(), ['class' => 'view-default']);
$out->addHtml(Html::rawElement('div',['id' => 'file', 'class' => 'fullModelView'],$viewer));
}
}
/**
* MWHook: Display model when model file page edits are previewed
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/AlternateEditPreview
*
* @param EditPage $editor access to information about the edit page itself
* @param Content $content access to the current content of the editor
* @param string &$previewHTML by reference access to the resultant compiled preview html
* @param ?ParserOutput &$parserOutput
* @return bool|void True to continue default processing or false to abort for custom processing
*/
public static function onAlternateEditPreview( EditPage $editor, Content $content, string &$previewHTML, ?ParserOutput &$parserOutput ) {
$file = MediaWikiServices::getInstance()->getRepoGroup()->findFile($editor->getTitle());
if (!$file || $file->getMimeType() !== 'model/gltf-binary') {
return true;
}
$out = $editor->getContext()->getOutput();
$out->addModules('ext.glmv');
$previewViewer = self::buildViewer($content->getText(), $file->getFullUrl(), ['class' => 'view-default']);
$addButtonAttr = array(
'class' => 'AddHotspot',
'onclick' => 'readyAddHotspot()'
);
$addHsButton = Html::rawElement('button',$addButtonAttr,'Add a new hotspot');
$previewHTML = Html::rawElement('div',NULL,$previewViewer.$addHsButton);
return false;
}
/**
* Build model-viewer and child elements
*
* This takes in the metadata text from the model page (or the current editor)
* and produces the html string for the model-viewer and all relevant child
* elements.
*
* @param string $inText The metadata text which must include a json formatted string inside a pre tag
* @param string $srcUrl The full url pointing to the model file
* @param array $frameParams The additional user defined parameters for the viewer such as hotspot and view classes
* @return string Html string of the complete model-viewer element inside a div container
*/
private static function buildViewer($inText, $srcUrl, $frameParams) {
//Gather basic data
preg_match('/<pre>([\S\s]*?)<\/pre>/',$inText,$modelDescript);
$metadata = json_decode($modelDescript[1], true);
$viewClass = self::extractClassParams('view',$frameParams['class']);
$hsSetClass = self::extractClassParams('hsset',$frameParams['class']);
//Handle annotations and annotation sets
if (isset($metadata['annotations'])) {
$hotspots = [];
$annotations = [];
if ($hsSetClass != 'default' && isset($metadata['annotationSets'])) {
foreach($metadata['annotationSets'][$hsSetClass] as $includeAn) {
if (isset($metadata['annotations'][$includeAn])) {
$annotations[$includeAn] = $metadata['annotations'][$includeAn];
}
}
} else {
$annotations = $metadata['annotations'];
}
foreach($annotations as $label => $an) {
$elAnnot = Html::rawElement('div',['class' => 'HotspotAnnotation HiddenAnnotation'],$label);
$hsDefault = array(
'class' => 'Hotspot',
'slot' => 'hotspot-'.(count($hotspots) +1),
'onmousedown' => 'event.stopPropagation()',
'ontouchstart' => 'event.stopPropagation()',
'onclick' => 'onAnnotation(event)'
);
$attrHotspot = array_merge($hsDefault, $an);
$elHotspot = Html::rawElement('button',$attrHotspot,$elAnnot.(count($hotspots) +1));
array_push($hotspots, $elHotspot);
}
}
//Set viewer configurations or use basic default if none defined
if (isset($metadata['viewerConfig']) && isset($metadata['viewerConfig'][$viewClass])) {
$attrModelView = $metadata['viewerConfig'][$viewClass];
} else {
$attrModelView = array('camera-controls' => true);
}
//Add important additional attributes and render model-viewer with hotspots
$attrModelView = array_merge(['src' => $srcUrl, 'class' => 'mv-model', 'interpolation-decay' => '100'], $attrModelView);
$attrModelView['style'] = 'width: 100%; height: 100%; min-height: 400px;';
$elModel = Html::rawElement('model-viewer', $attrModelView, implode($hotspots));
//Render and return container element with model-viewer
$attrContainer = array(
'style' => "width: 800px; height: 600px;",
'onmousedown' => 'clearAnnotations()',
'ontouchstart' => 'clearAnnotations()'
);
return Html::rawElement('div', $attrContainer, $elModel);
}
/**
* Detect and return model user params from link classes
*
* The best way to send information in a file link is by adding classes to the
* link. This function parses the array of those classes and returns the information
* or 'default'
*
* @param string $paramType the type of parameter to be extracted 'view'|'hsset'
* @param string $classList the string of class names as returned in $frameParams or default construction
* @return string parameter name or 'default'
*/
private static function extractClassParams(string $paramType, string $classList) {
if (!in_array($paramType, ['view', 'hsset'])) {
return 'default';
}
if (!isset($classList)) {
return 'default';
}
$searchString = '/' . $paramType . '-(\S*)/';
preg_match($searchString,$classList,$extractInfo);
return ($extractInfo[1]) ? $extractInfo[1] : 'default';
}
/**
* Small helper function to display information on the browser console
*
* Usage:
* echo '<script>';
* self::console_log('logged string');
* echo '</script>';
*
* @param $data information to display
* @param bool $add_script_tags true to put information is inside complete script tag
*/
public static function console_log($data, $add_script_tags = false) {
$command = 'console.log('. json_encode($data, JSON_HEX_TAG).');';
if ($add_script_tags) {
$command = '<script>'. $command . '</script>';
}
echo $command;
}
/**
* ? But class won't work without it
*/
function doTransform($image, $dstPath, $dstUrl, $params, $flags = 0) {
}
}