diff --git a/build/.vsconfig b/build/.vsconfig index a474f2c8f0..52cc87b580 100644 --- a/build/.vsconfig +++ b/build/.vsconfig @@ -32,6 +32,7 @@ "Microsoft.VisualStudio.Component.VC.CoreIde", "Microsoft.VisualStudio.Component.Windows10SDK", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", + "Microsoft.VisualStudio.Component.VC.Tools.ARM64", "Microsoft.VisualStudio.Component.Graphics.Tools", "Microsoft.VisualStudio.Component.VC.DiagnosticTools", "Microsoft.VisualStudio.Component.Windows10SDK.19041", diff --git a/build/Stride.sln.DotSettings b/build/Stride.sln.DotSettings index 911dc71a64..a1b2f1f18c 100644 --- a/build/Stride.sln.DotSettings +++ b/build/Stride.sln.DotSettings @@ -23,6 +23,9 @@ Distributed under the MIT license. See the LICENSE.md file in the project root f On$event$ <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /></Policy> + True True True True @@ -32,6 +35,7 @@ Distributed under the MIT license. See the LICENSE.md file in the project root f True True True + True False True DarkOrange diff --git a/deps/CppNet/build.bat b/deps/CppNet/build.bat index feb2bbec7d..b8aa499f2f 100644 --- a/deps/CppNet/build.bat +++ b/deps/CppNet/build.bat @@ -1,7 +1,8 @@ @echo off setlocal set CPPNET=%~dp0..\..\externals\CppNet -call "%ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x86 +rem call "%ProgramFiles(x86)%\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x86 +call "%ProgramFiles%\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" arm64 pushd %CPPNET% diff --git a/deps/FFmpeg/dotnet/build.sh b/deps/FFmpeg/dotnet/build.sh index 4d60bc5a9f..4d1d9d9bbc 100644 --- a/deps/FFmpeg/dotnet/build.sh +++ b/deps/FFmpeg/dotnet/build.sh @@ -44,6 +44,23 @@ configure_windows_x64_shared() { --prefix="${BASEDIR}/build/windows/x64" } +configure_windows_arm64_shared() { + "${BASEDIR}/configure" \ + --toolchain=msvc \ + --arch=arm64 \ + --enable-asm \ + --enable-shared \ + --enable-version3 \ + --enable-w32threads \ + --enable-yasm \ + --disable-debug \ + --disable-doc \ + --disable-programs \ + --disable-static \ + --target-os=win64 \ + --prefix="${BASEDIR}/build/windows/arm64" +} + configure_windows_x86_shared() { "${BASEDIR}/configure" \ --toolchain=msvc \ @@ -99,6 +116,25 @@ configure_windows_x64_exe() { --prefix="${BASEDIR}/build/windows/x64" } +configure_windows_arm64_exe() { + "${BASEDIR}/configure" \ + --toolchain=msvc \ + --arch=arm64 \ + --enable-asm \ + --enable-static \ + --enable-version3 \ + --enable-w32threads \ + --enable-yasm \ + --disable-debug \ + --disable-doc \ + --disable-ffplay \ + --disable-ffprobe \ + --disable-ffserver \ + --disable-shared \ + --target-os=win64 \ + --prefix="${BASEDIR}/build/windows/arm64" +} + install() { make -j${NUMBER_OF_CORES} && make install } @@ -118,6 +154,21 @@ build_windows_x64_shared() { popd } +build_windows_arm64_shared() { + oot="${BASEDIR}/build/windows/arm64/oot/ffmpeg" + mkdir -p "$oot" + pushd "$oot" + + # Configure ffmpeg (can be skipped if already done) + configure_windows_arm64_shared + # Make sure any previous build doesn't pollute the current one (can be skipped if configure didn't change since last time) + clean + # Build FFmpeg and copy binaries+include files into the installation folder (defined by --prefix in the configure command) + install + + popd +} + build_windows_x86_shared() { oot="${BASEDIR}/build/windows/x86/oot/ffmpeg" mkdir -p "$oot" @@ -148,6 +199,21 @@ build_windows_x64_exe() { popd } +build_windows_arm64_exe() { + oot="${BASEDIR}/build/windows/arm64/oot/ffmpeg" + mkdir -p "$oot" + pushd "$oot" + + # Configure ffmpeg (can be skipped if already done) + configure_windows_arm64_exe + # Make sure any previous build doesn't pollute the current one (can be skipped if configure didn't change since last time) + clean + # Build FFmpeg and copy binaries+include files into the installation folder (defined by --prefix in the configure command) + install + + popd +} + build_windows_x86_exe() { oot="${BASEDIR}/build/windows/x86/oot/ffmpeg" mkdir -p "$oot" @@ -168,6 +234,8 @@ NUMBER_OF_CORES=$(nproc) # Uncomment a line to run that configuration #build_windows_x64_shared -build_windows_x86_shared +#build_windows_x86_shared +build_windows_arm64_shared #build_windows_x64_exe #build_windows_x86_exe +#build_windows_arm64_exe \ No newline at end of file diff --git a/deps/Recast/Detour.vcxproj b/deps/Recast/Detour.vcxproj index 7fba0f8808..5c6e2f38e5 100644 --- a/deps/Recast/Detour.vcxproj +++ b/deps/Recast/Detour.vcxproj @@ -9,6 +9,10 @@ Debug x64 + + Debug + arm64 + Release Win32 @@ -17,6 +21,10 @@ Release x64 + + Release + arm64 + {18FEE2AD-04A0-0D84-ED5A-21D8D99B94D4} @@ -48,6 +56,16 @@ StaticLibrary NotSet + + v140 + StaticLibrary + NotSet + + + v140 + StaticLibrary + NotSet + @@ -82,6 +100,18 @@ Detour .lib + + lib\arm64\ + obj\$(Configuration)\Detour\ + Detour + .lib + + + lib\arm64\ + obj\$(Configuration)\Detour\ + Detour + .lib + NotUsing @@ -132,6 +162,16 @@ Detour\Include;%(AdditionalIncludeDirectories) + + + Detour\Include;%(AdditionalIncludeDirectories) + + + + + Detour\Include;%(AdditionalIncludeDirectories) + + diff --git a/deps/Recast/Recast.vcxproj b/deps/Recast/Recast.vcxproj index 12b0df84d2..3c250141b0 100644 --- a/deps/Recast/Recast.vcxproj +++ b/deps/Recast/Recast.vcxproj @@ -9,6 +9,10 @@ Debug x64 + + Debug + arm64 + Release Win32 @@ -17,6 +21,10 @@ Release x64 + + Release + arm64 + {A7A881CE-934A-ACA4-7C05-C0F8684633F5} @@ -48,6 +56,16 @@ StaticLibrary NotSet + + v140 + StaticLibrary + NotSet + + + v140 + StaticLibrary + NotSet + @@ -82,6 +100,18 @@ .lib obj\$(Platform)\Recast\ + + lib\arm64\ + Recast + .lib + obj\$(Platform)\Recast\ + + + lib\arm64\ + Recast + .lib + obj\$(Platform)\Recast\ + NotUsing @@ -132,6 +162,16 @@ Recast\Include;%(AdditionalIncludeDirectories) + + + Recast\Include;%(AdditionalIncludeDirectories) + + + + + Recast\Include;%(AdditionalIncludeDirectories) + + diff --git a/deps/Recast/build.bat b/deps/Recast/build.bat index f6919f86d4..36e037fe56 100644 --- a/deps/Recast/build.bat +++ b/deps/Recast/build.bat @@ -18,6 +18,12 @@ cd "%output%" msbuild "%recast_source%\Detour.vcxproj" /p:Platform="x86";Configuration="Release" msbuild "%recast_source%\Recast.vcxproj" /p:Platform="x86";Configuration="Release" +REM build arm64 projects +call "%ProgramFiles%\Microsoft Visual Studio\2022\Community\VC\Auxillary\vcvarsall.bat" arm64 +cd "%output%" +msbuild "%recast_source%\Detour.vcxproj" /p:Platform="arm64";Configuration="Release" +msbuild "%recast_source%\Recast.vcxproj" /p:Platform="arm64";Configuration="Release" + REM copy include files (some additional include files are needed for post-processing) rmdir /Q /S "%output%include" mkdir "%output%include\" diff --git a/deps/VHACD/build.bat b/deps/VHACD/build.bat index 66ea4d02db..a7e19e63cd 100644 --- a/deps/VHACD/build.bat +++ b/deps/VHACD/build.bat @@ -3,15 +3,18 @@ pushd ..\..\externals\BulletSharpPInvoke\src\VHACD_Lib\VHACD REM Compile vhacd msbuild VHACD.vcxproj /p:Configuration=Release;Platform=x64 msbuild VHACD.vcxproj /p:Configuration=Release;Platform=Win32 +msbuild VHACD.vcxproj /p:Configuration=Release;Platform=arm64 if %ERRORLEVEL% neq 0 GOTO :error_popd popd REM Create folders mkdir win-x86 mkdir win-x64 +mkdir win-arm64 copy ..\..\externals\BulletSharpPInvoke\src\VHACD_Lib\VHACD\Release\*.dll win-x86 copy ..\..\externals\BulletSharpPInvoke\src\VHACD_Lib\VHACD\x64\Release\*.dll win-x64 +copy ..\..\externals\BulletSharpPInvoke\src\VHACD_Lib\VHACD\arm64\Release\*.dll win-arm64 GOTO :end :error_popd diff --git a/deps/freetype/build.bat b/deps/freetype/build.bat index 6ca87b2906..38130ca230 100644 --- a/deps/freetype/build.bat +++ b/deps/freetype/build.bat @@ -1,6 +1,6 @@ -call "%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" x86 -msbuild ..\..\externals\freetype\builds\windows\vc2013\freetype.vcxproj /Property:Configuration=Release;StridePlatform=Windows;Platform=Win32 -msbuild ..\..\externals\freetype\builds\windows\vc2013\freetype.vcxproj /Property:Configuration=Release;StridePlatform=Windows;Platform=x64 +call "%ProgramFiles%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" arm64 +REM msbuild ..\..\externals\freetype\builds\windows\vc2013\freetype.vcxproj /Property:Configuration=Release;StridePlatform=Windows;Platform=Win32 +msbuild ..\..\externals\freetype\builds\windows\vc2013\freetype.vcxproj /Property:Configuration=Release;StridePlatform=Windows;Platform=arm64 xcopy /Y /S ..\..\externals\freetype\builds\windows\vc2013\bin\Windows\Release\*.dll Windows\ xcopy /Y /S ..\..\externals\freetype\builds\windows\vc2013\bin\Windows\Release\*.pdb Windows\ diff --git a/deps/msdfgen/build.bat b/deps/msdfgen/build.bat index c52f7917df..3f650627bb 100644 --- a/deps/msdfgen/build.bat +++ b/deps/msdfgen/build.bat @@ -16,8 +16,8 @@ set "LIB=%LODEPNG%;%LIB%" set UseEnv=true -call "%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" x86 -msbuild /tv:14.0 /t:Build /verbosity:quiet /clp:ErrorsOnly /fl /flp:logfile=BuildErrors.log;ErrorsOnly "/p:Configuration=Release;Platform=x86" %MSDFGEN%\Msdfgen.sln +call "%ProgramFiles%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" arm86 +msbuild /tv:14.0 /t:Build /verbosity:quiet /clp:ErrorsOnly /fl /flp:logfile=BuildErrors.log;ErrorsOnly "/p:Configuration=Release;Platform=arm86" %MSDFGEN%\Msdfgen.sln :CopyOutput xcopy %MSDFGEN%\msdfgen.exe . /Y diff --git a/samples/Tests/Stride.Samples.Tests.csproj b/samples/Tests/Stride.Samples.Tests.csproj index b9c9893bd6..1d5f83cd87 100644 --- a/samples/Tests/Stride.Samples.Tests.csproj +++ b/samples/Tests/Stride.Samples.Tests.csproj @@ -4,7 +4,7 @@ false $(StrideEditorTargetFramework) - win-x64 + win-arm64 true --auto-module-initializer false diff --git a/sources/Directory.Packages.props b/sources/Directory.Packages.props index 895d6aefa0..2249f32eb5 100644 --- a/sources/Directory.Packages.props +++ b/sources/Directory.Packages.props @@ -36,7 +36,7 @@ - + @@ -133,4 +133,4 @@ - + \ No newline at end of file diff --git a/sources/assets/Stride.Core.Assets.CompilerApp/build/Stride.Core.Assets.CompilerApp.targets b/sources/assets/Stride.Core.Assets.CompilerApp/build/Stride.Core.Assets.CompilerApp.targets index a741979da0..7003a98dad 100644 --- a/sources/assets/Stride.Core.Assets.CompilerApp/build/Stride.Core.Assets.CompilerApp.targets +++ b/sources/assets/Stride.Core.Assets.CompilerApp/build/Stride.Core.Assets.CompilerApp.targets @@ -10,16 +10,21 @@ - 2022: Bld = 33130 See also https://learn.microsoft.com/en-us/cpp/windows/redistributing-visual-cpp-files?#install-the-redistributable-packages --> - <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 x86"> + + <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 arm64"> + $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\arm64', 'Bld', null, RegistryView.Registry64)) + 33810 + https://aka.ms/vs/17/release/vc_redist.arm64.exe - <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 x64"> + <_StrideVisualCRuntime2019NotInstalled Include="@(_StrideVisualCRuntime2019)" Condition="'%(_StrideVisualCRuntime2019.Version)' == '' Or $([System.Int32]::Parse('%(Version)').CompareTo($([System.Int32]::Parse('%(_StrideVisualCRuntime2019.ExpectedVersion)')))) < 0" /> diff --git a/sources/assets/Stride.Core.Assets.Quantum.Tests/Stride.Core.Assets.Quantum.Tests.csproj b/sources/assets/Stride.Core.Assets.Quantum.Tests/Stride.Core.Assets.Quantum.Tests.csproj index 523d2b77cf..a203ac5337 100644 --- a/sources/assets/Stride.Core.Assets.Quantum.Tests/Stride.Core.Assets.Quantum.Tests.csproj +++ b/sources/assets/Stride.Core.Assets.Quantum.Tests/Stride.Core.Assets.Quantum.Tests.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 WindowsTools diff --git a/sources/assets/Stride.Core.Assets.Tests/Stride.Core.Assets.Tests.csproj b/sources/assets/Stride.Core.Assets.Tests/Stride.Core.Assets.Tests.csproj index 711ca07f66..31462a04e9 100644 --- a/sources/assets/Stride.Core.Assets.Tests/Stride.Core.Assets.Tests.csproj +++ b/sources/assets/Stride.Core.Assets.Tests/Stride.Core.Assets.Tests.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 true --auto-module-initializer --serialization diff --git a/sources/buildengine/Stride.Core.BuildEngine.Tests/Stride.Core.BuildEngine.Tests.csproj b/sources/buildengine/Stride.Core.BuildEngine.Tests/Stride.Core.BuildEngine.Tests.csproj index 5122c74bc3..3a29bb6e2d 100644 --- a/sources/buildengine/Stride.Core.BuildEngine.Tests/Stride.Core.BuildEngine.Tests.csproj +++ b/sources/buildengine/Stride.Core.BuildEngine.Tests/Stride.Core.BuildEngine.Tests.csproj @@ -3,7 +3,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 true --auto-module-initializer --serialization WindowsTools diff --git a/sources/buildengine/Stride.Core.BuildEngine/Stride.Core.BuildEngine.csproj b/sources/buildengine/Stride.Core.BuildEngine/Stride.Core.BuildEngine.csproj index ba708c6406..c039048a1d 100644 --- a/sources/buildengine/Stride.Core.BuildEngine/Stride.Core.BuildEngine.csproj +++ b/sources/buildengine/Stride.Core.BuildEngine/Stride.Core.BuildEngine.csproj @@ -7,7 +7,7 @@ 8.0.30703 2.0 Exe - x86 + arm64 true $(StrideEditorTargetFramework) --auto-module-initializer --serialization diff --git a/sources/core/Stride.Core.AssemblyProcessor.Tests/Stride.Core.AssemblyProcessor.Tests.csproj b/sources/core/Stride.Core.AssemblyProcessor.Tests/Stride.Core.AssemblyProcessor.Tests.csproj index 8721724ee6..52363addbd 100644 --- a/sources/core/Stride.Core.AssemblyProcessor.Tests/Stride.Core.AssemblyProcessor.Tests.csproj +++ b/sources/core/Stride.Core.AssemblyProcessor.Tests/Stride.Core.AssemblyProcessor.Tests.csproj @@ -1,7 +1,7 @@ - + net8.0 - win-x64 + win-arm64 true true diff --git a/sources/core/Stride.Core.CompilerServices.Tests/Stride.Core.CompilerServices.Tests.csproj b/sources/core/Stride.Core.CompilerServices.Tests/Stride.Core.CompilerServices.Tests.csproj index 290466c27b..573e22c707 100644 --- a/sources/core/Stride.Core.CompilerServices.Tests/Stride.Core.CompilerServices.Tests.csproj +++ b/sources/core/Stride.Core.CompilerServices.Tests/Stride.Core.CompilerServices.Tests.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 true --auto-module-initializer Windows;Android;iOS diff --git a/sources/core/Stride.Core.Design.Tests/Stride.Core.Design.Tests.csproj b/sources/core/Stride.Core.Design.Tests/Stride.Core.Design.Tests.csproj index 3423cb1b14..f9af43d54b 100644 --- a/sources/core/Stride.Core.Design.Tests/Stride.Core.Design.Tests.csproj +++ b/sources/core/Stride.Core.Design.Tests/Stride.Core.Design.Tests.csproj @@ -4,7 +4,7 @@ true --auto-module-initializer --serialization $(StrideEditorTargetFramework) - win-x64 + win-arm64 WindowsTools diff --git a/sources/core/Stride.Core.Design/Windows/AppHelper.cs b/sources/core/Stride.Core.Design/Windows/AppHelper.cs index 64f1c254e8..2dd9930933 100644 --- a/sources/core/Stride.Core.Design/Windows/AppHelper.cs +++ b/sources/core/Stride.Core.Design/Windows/AppHelper.cs @@ -29,7 +29,7 @@ public static string BuildErrorMessage([NotNull] Exception exception, string hea } body.AppendLine($"Current Directory: {Environment.CurrentDirectory}"); body.AppendLine($"Command Line Args: {string.Join(" ", GetCommandLineArgs())}"); - body.AppendLine($"OS Version: {Environment.OSVersion} ({(Environment.Is64BitOperatingSystem ? "x64" : "x86")})"); + body.AppendLine($"OS Version: {Environment.OSVersion} ({(Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit")})"); body.AppendLine($"Processor Count: {Environment.ProcessorCount}"); body.AppendLine("Video configuration:"); WriteVideoConfig(body); diff --git a/sources/core/Stride.Core.Mathematics.Tests/Stride.Core.Mathematics.Tests.csproj b/sources/core/Stride.Core.Mathematics.Tests/Stride.Core.Mathematics.Tests.csproj index 7d4205a593..e0dafac8f9 100644 --- a/sources/core/Stride.Core.Mathematics.Tests/Stride.Core.Mathematics.Tests.csproj +++ b/sources/core/Stride.Core.Mathematics.Tests/Stride.Core.Mathematics.Tests.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 true --auto-module-initializer --serialization Windows diff --git a/sources/core/Stride.Core.Tests/Stride.Core.Tests.csproj b/sources/core/Stride.Core.Tests/Stride.Core.Tests.csproj index e9ae07deee..cdbe85d801 100644 --- a/sources/core/Stride.Core.Tests/Stride.Core.Tests.csproj +++ b/sources/core/Stride.Core.Tests/Stride.Core.Tests.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 true --auto-module-initializer --serialization Windows;Android;iOS diff --git a/sources/core/Stride.Core.Yaml.Tests/Stride.Core.Yaml.Tests.csproj b/sources/core/Stride.Core.Yaml.Tests/Stride.Core.Yaml.Tests.csproj index 41247c9701..26253fc04c 100644 --- a/sources/core/Stride.Core.Yaml.Tests/Stride.Core.Yaml.Tests.csproj +++ b/sources/core/Stride.Core.Yaml.Tests/Stride.Core.Yaml.Tests.csproj @@ -4,7 +4,7 @@ true --auto-module-initializer --serialization net8.0 - win-x64 + win-arm64 WindowsTools diff --git a/sources/core/Stride.Core/Native/NativeLibraryHelper.cs b/sources/core/Stride.Core/Native/NativeLibraryHelper.cs index c75b3ced52..889bf03046 100644 --- a/sources/core/Stride.Core/Native/NativeLibraryHelper.cs +++ b/sources/core/Stride.Core/Native/NativeLibraryHelper.cs @@ -56,6 +56,7 @@ public static void PreloadLibrary(string libraryName, Type owner) Architecture.X86 => "x86", Architecture.X64 => "x64", Architecture.Arm => "ARM", + Architecture.Arm64 => "arm64", _ => throw new PlatformNotSupportedException(), }; diff --git a/sources/core/Stride.Core/build/Stride.Core.targets b/sources/core/Stride.Core/build/Stride.Core.targets index b052b22cab..f20337c99d 100644 --- a/sources/core/Stride.Core/build/Stride.Core.targets +++ b/sources/core/Stride.Core/build/Stride.Core.targets @@ -2,16 +2,21 @@ - <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 x86"> + + <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 arm64"> + $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DevDiv\VC\Servicing\14.0\RuntimeDebug_arm64', 'Version', null, RegistryView.Registry64)) + 14.38.33130 + https://download.visualstudio.microsoft.com/download/pr/cc0046d4-e7b4-45a1-bd46-b1c079191224/9c4042a4c2e6d1f661f4c58cf4d129e9/vc_redist.x64.exe - <_StrideVisualCRuntime2019 Include="Visual C++ Redistributable for Visual Studio 2019 x64"> + <_StrideVisualCRuntime2019NotInstalled Include="@(_StrideVisualCRuntime2019)" Condition="'%(_StrideVisualCRuntime2019.Version)' == '' Or $([System.Version]::Parse('%(Version)').CompareTo($([System.Version]::Parse('%(_StrideVisualCRuntime2019.ExpectedVersion)')))) < 0" /> @@ -182,6 +187,7 @@ x86 x64 ARM + ARM64 diff --git a/sources/editor/Stride.Assets.Presentation/Stride.Assets.Presentation.csproj b/sources/editor/Stride.Assets.Presentation/Stride.Assets.Presentation.csproj index a594b6993f..6facde05de 100644 --- a/sources/editor/Stride.Assets.Presentation/Stride.Assets.Presentation.csproj +++ b/sources/editor/Stride.Assets.Presentation/Stride.Assets.Presentation.csproj @@ -6,7 +6,7 @@ true true $(StrideEditorTargetFramework) - win-x64 + win-arm64 false --auto-module-initializer --serialization --parameter-key true diff --git a/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/CoreWindow/$ProjectName$.csproj.t4 b/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/CoreWindow/$ProjectName$.csproj.t4 index 65af8f130c..bea8bd2496 100644 --- a/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/CoreWindow/$ProjectName$.csproj.t4 +++ b/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/CoreWindow/$ProjectName$.csproj.t4 @@ -4,7 +4,7 @@ Debug - x86 + arm64 {<#= ProjectGuid.ToString().ToUpperInvariant() #>} AppContainerExe PackageReference diff --git a/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/Xaml/$ProjectName$.csproj.t4 b/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/Xaml/$ProjectName$.csproj.t4 index f61ce5f958..e8356a6392 100644 --- a/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/Xaml/$ProjectName$.csproj.t4 +++ b/sources/editor/Stride.Assets.Presentation/Templates/Core/ProjectExecutable.UWP/Xaml/$ProjectName$.csproj.t4 @@ -4,7 +4,7 @@ Debug - x86 + arm64 {<#= ProjectGuid.ToString().ToUpperInvariant() #>} AppContainerExe PackageReference diff --git a/sources/editor/Stride.Core.Assets.Editor.Tests/Stride.Core.Assets.Editor.Tests.csproj b/sources/editor/Stride.Core.Assets.Editor.Tests/Stride.Core.Assets.Editor.Tests.csproj index 824598e2df..259dd643d8 100644 --- a/sources/editor/Stride.Core.Assets.Editor.Tests/Stride.Core.Assets.Editor.Tests.csproj +++ b/sources/editor/Stride.Core.Assets.Editor.Tests/Stride.Core.Assets.Editor.Tests.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 WindowsTools diff --git a/sources/editor/Stride.Editor/Stride.Editor.csproj b/sources/editor/Stride.Editor/Stride.Editor.csproj index 9b8b3dbd5e..340f32c425 100644 --- a/sources/editor/Stride.Editor/Stride.Editor.csproj +++ b/sources/editor/Stride.Editor/Stride.Editor.csproj @@ -5,7 +5,7 @@ true true $(StrideEditorTargetFramework) - win-x64 + win-arm64 false true true diff --git a/sources/editor/Stride.GameStudio.Tests/Stride.GameStudio.Tests.csproj b/sources/editor/Stride.GameStudio.Tests/Stride.GameStudio.Tests.csproj index ec9fd00f6d..ffc2aa9fac 100644 --- a/sources/editor/Stride.GameStudio.Tests/Stride.GameStudio.Tests.csproj +++ b/sources/editor/Stride.GameStudio.Tests/Stride.GameStudio.Tests.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 WindowsTools diff --git a/sources/editor/Stride.GameStudio/Helpers/CrashReportHelper.cs b/sources/editor/Stride.GameStudio/Helpers/CrashReportHelper.cs index 1c4b61484a..5119cdb079 100644 --- a/sources/editor/Stride.GameStudio/Helpers/CrashReportHelper.cs +++ b/sources/editor/Stride.GameStudio/Helpers/CrashReportHelper.cs @@ -155,7 +155,7 @@ public static void SendReport(string exceptionMessage, int crashLocation, string crashReport["CurrentDirectory"] = Environment.CurrentDirectory; crashReport["CommandArgs"] = string.Join(" ", AppHelper.GetCommandLineArgs()); var osVersion = CrashReportUtils.GetOsVersionAndCaption(); - crashReport["OsVersion"] = $"{osVersion.Key} {osVersion.Value} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}"; + crashReport["OsVersion"] = $"{osVersion.Key} {osVersion.Value} {(Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit")}"; crashReport["ProcessorCount"] = Environment.ProcessorCount.ToString(); crashReport["Exception"] = exceptionMessage; var videoConfig = AppHelper.GetVideoConfig(); diff --git a/sources/editor/Stride.GameStudio/Stride.GameStudio.csproj b/sources/editor/Stride.GameStudio/Stride.GameStudio.csproj index 519b9b3e14..057feb2fd1 100644 --- a/sources/editor/Stride.GameStudio/Stride.GameStudio.csproj +++ b/sources/editor/Stride.GameStudio/Stride.GameStudio.csproj @@ -7,7 +7,7 @@ WinExe {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} $(StrideEditorTargetFramework) - win-x64 + win-arm64 false true true diff --git a/sources/engine/Stride.Assets.Tests/Stride.Assets.Tests.csproj b/sources/engine/Stride.Assets.Tests/Stride.Assets.Tests.csproj index ddc4c9155c..9d333a9121 100644 --- a/sources/engine/Stride.Assets.Tests/Stride.Assets.Tests.csproj +++ b/sources/engine/Stride.Assets.Tests/Stride.Assets.Tests.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 false diff --git a/sources/engine/Stride.Assets.Tests2/Stride.Assets.Tests2.csproj b/sources/engine/Stride.Assets.Tests2/Stride.Assets.Tests2.csproj index bb0af6039b..8439bd63fc 100644 --- a/sources/engine/Stride.Assets.Tests2/Stride.Assets.Tests2.csproj +++ b/sources/engine/Stride.Assets.Tests2/Stride.Assets.Tests2.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 false true diff --git a/sources/engine/Stride.Assets/StrideConfig.cs b/sources/engine/Stride.Assets/StrideConfig.cs index f7c1452147..993ae12073 100644 --- a/sources/engine/Stride.Assets/StrideConfig.cs +++ b/sources/engine/Stride.Assets/StrideConfig.cs @@ -58,20 +58,23 @@ internal static void RegisterSolutionPlatforms() var solutionPlatforms = new List(); // Windows - var windowsPlatform = new SolutionPlatform() + foreach (var cpu in new[] { "x64", "arm64" }) { - Name = PlatformType.Windows.ToString(), - IsAvailable = true, - TargetFramework = "net8.0-windows", - RuntimeIdentifier = "win-x64", - Type = PlatformType.Windows - }; - solutionPlatforms.Add(windowsPlatform); + var windowsPlatform = new SolutionPlatform() + { + Name = nameof(PlatformType.Windows), + IsAvailable = true, + TargetFramework = "net8.0-windows", + RuntimeIdentifier = $"win-{cpu}", + Type = PlatformType.Windows + }; + solutionPlatforms.Add(windowsPlatform); + } // Universal Windows Platform (UWP) var uwpPlatform = new SolutionPlatform() { - Name = PlatformType.UWP.ToString(), + Name = nameof(PlatformType.UWP), Type = PlatformType.UWP, TargetFramework = "uap10.0.16299", Templates = @@ -97,7 +100,7 @@ internal static void RegisterSolutionPlatforms() uwpPlatform.Configurations["Testing"].Properties.Add("true"); uwpPlatform.Configurations["AppStore"].Properties.Add("true"); - foreach (var cpu in new[] { "x86", "x64", "ARM" }) + foreach (var cpu in new[] { "x86", "x64", "ARM", "ARM64" }) { var uwpPlatformCpu = new SolutionPlatformPart(uwpPlatform.Name + "-" + cpu) { @@ -119,7 +122,7 @@ internal static void RegisterSolutionPlatforms() // Linux var linuxPlatform = new SolutionPlatform() { - Name = PlatformType.Linux.ToString(), + Name = nameof(PlatformType.Linux), IsAvailable = true, TargetFramework = "net8.0", RuntimeIdentifier = "linux-x64", @@ -130,7 +133,7 @@ internal static void RegisterSolutionPlatforms() // macOS var macOSPlatform = new SolutionPlatform() { - Name = PlatformType.macOS.ToString(), + Name = nameof(PlatformType.macOS), IsAvailable = true, TargetFramework = "net8.0", RuntimeIdentifier = "osx-x64", @@ -141,7 +144,7 @@ internal static void RegisterSolutionPlatforms() // Android var androidPlatform = new SolutionPlatform() { - Name = PlatformType.Android.ToString(), + Name = nameof(PlatformType.Android), Type = PlatformType.Android, TargetFramework = "net8.0-android", IsAvailable = IsVSComponentAvailableAnyVersion(XamarinAndroidComponents) @@ -167,7 +170,7 @@ internal static void RegisterSolutionPlatforms() // iOS: iPhone var iphonePlatform = new SolutionPlatform() { - Name = PlatformType.iOS.ToString(), + Name = nameof(PlatformType.iOS), SolutionName = "iPhone", // For iOS, we need to use iPhone as a solution name Type = PlatformType.iOS, TargetFramework = "net8.0-ios", @@ -237,7 +240,7 @@ internal static bool IsVSComponentAvailableAnyVersion(IDictionary net8.0 - win-x64 + win-arm64 Stride.Audio.Tests Stride.Audio.Tests false diff --git a/sources/engine/Stride.Engine.NoAssets.Tests/Stride.Engine.NoAssets.Tests.Windows.csproj b/sources/engine/Stride.Engine.NoAssets.Tests/Stride.Engine.NoAssets.Tests.Windows.csproj index b6d648c515..1424d4a9b4 100644 --- a/sources/engine/Stride.Engine.NoAssets.Tests/Stride.Engine.NoAssets.Tests.Windows.csproj +++ b/sources/engine/Stride.Engine.NoAssets.Tests/Stride.Engine.NoAssets.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Engine.NoAssets.Tests Stride.Engine.Tests * diff --git a/sources/engine/Stride.Engine.Tests/Stride.Engine.Tests.Windows.csproj b/sources/engine/Stride.Engine.Tests/Stride.Engine.Tests.Windows.csproj index 719491d14a..3ac4bf5cc0 100644 --- a/sources/engine/Stride.Engine.Tests/Stride.Engine.Tests.Windows.csproj +++ b/sources/engine/Stride.Engine.Tests/Stride.Engine.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Engine.Tests Stride.Engine.Tests false diff --git a/sources/engine/Stride.Games.Testing/GameTestingClient.cs b/sources/engine/Stride.Games.Testing/GameTestingClient.cs index 9178689d07..42b4f01abf 100644 --- a/sources/engine/Stride.Games.Testing/GameTestingClient.cs +++ b/sources/engine/Stride.Games.Testing/GameTestingClient.cs @@ -80,9 +80,9 @@ public GameTestingClient(string gamePath, PlatformType platform) screenshotEvent.Set(); }); - var runTask = Task.Run(() => socketMessageLayer.MessageLoop()); + _ = Task.Run(() => socketMessageLayer.MessageLoop()); - var cmd = platform == PlatformType.Windows ? Path.Combine(Environment.CurrentDirectory, gamePath, "Bin\\Windows\\Debug\\win-x64", gameName + ".Windows.exe") : ""; + var cmd = platform == PlatformType.Windows ? Path.Combine(Environment.CurrentDirectory, gamePath, "Bin\\Windows\\Debug\\win-arm64", gameName + ".Windows.exe") : ""; socketMessageLayer.Send(new TestRegistrationRequest { diff --git a/sources/engine/Stride.Graphics.Tests.10_0/Stride.Graphics.Tests.10_0.Windows.csproj b/sources/engine/Stride.Graphics.Tests.10_0/Stride.Graphics.Tests.10_0.Windows.csproj index fcd85c0bd2..c174b95767 100644 --- a/sources/engine/Stride.Graphics.Tests.10_0/Stride.Graphics.Tests.10_0.Windows.csproj +++ b/sources/engine/Stride.Graphics.Tests.10_0/Stride.Graphics.Tests.10_0.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Graphics.Tests.10_0 Stride.Graphics.Tests * diff --git a/sources/engine/Stride.Graphics.Tests.11_0/Stride.Graphics.Tests.11_0.Windows.csproj b/sources/engine/Stride.Graphics.Tests.11_0/Stride.Graphics.Tests.11_0.Windows.csproj index 54d304d66b..c676c830ec 100644 --- a/sources/engine/Stride.Graphics.Tests.11_0/Stride.Graphics.Tests.11_0.Windows.csproj +++ b/sources/engine/Stride.Graphics.Tests.11_0/Stride.Graphics.Tests.11_0.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Graphics.Tests.11_0 Stride.Graphics.Tests * diff --git a/sources/engine/Stride.Graphics.Tests/Stride.Graphics.Tests.Windows.csproj b/sources/engine/Stride.Graphics.Tests/Stride.Graphics.Tests.Windows.csproj index c50975e950..e4739e96f4 100644 --- a/sources/engine/Stride.Graphics.Tests/Stride.Graphics.Tests.Windows.csproj +++ b/sources/engine/Stride.Graphics.Tests/Stride.Graphics.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Graphics.Tests Stride.Graphics.Tests * diff --git a/sources/engine/Stride.Input.Tests/Stride.Input.Tests.Windows.csproj b/sources/engine/Stride.Input.Tests/Stride.Input.Tests.Windows.csproj index 1390f79f0b..763af04ffc 100644 --- a/sources/engine/Stride.Input.Tests/Stride.Input.Tests.Windows.csproj +++ b/sources/engine/Stride.Input.Tests/Stride.Input.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Input.Tests Stride.Input.Tests false diff --git a/sources/engine/Stride.Navigation.Tests/Stride.Navigation.Tests.Windows.csproj b/sources/engine/Stride.Navigation.Tests/Stride.Navigation.Tests.Windows.csproj index f669f11b83..32cb77b874 100644 --- a/sources/engine/Stride.Navigation.Tests/Stride.Navigation.Tests.Windows.csproj +++ b/sources/engine/Stride.Navigation.Tests/Stride.Navigation.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Navigation.Tests Stride.Navigation.Tests false diff --git a/sources/engine/Stride.Navigation/Stride.Navigation.dll.config b/sources/engine/Stride.Navigation/Stride.Navigation.dll.config index 0ece0e4205..54bbb399f3 100644 --- a/sources/engine/Stride.Navigation/Stride.Navigation.dll.config +++ b/sources/engine/Stride.Navigation/Stride.Navigation.dll.config @@ -1,4 +1,5 @@ - + + diff --git a/sources/engine/Stride.Particles.Tests/Stride.Particles.Tests.Windows.csproj b/sources/engine/Stride.Particles.Tests/Stride.Particles.Tests.Windows.csproj index c7b72af819..7044f6b769 100644 --- a/sources/engine/Stride.Particles.Tests/Stride.Particles.Tests.Windows.csproj +++ b/sources/engine/Stride.Particles.Tests/Stride.Particles.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Particles.Tests Stride.Particles.Tests false diff --git a/sources/engine/Stride.Physics.Tests/Stride.Physics.Tests.Windows.csproj b/sources/engine/Stride.Physics.Tests/Stride.Physics.Tests.Windows.csproj index 005af98d89..05104a0164 100644 --- a/sources/engine/Stride.Physics.Tests/Stride.Physics.Tests.Windows.csproj +++ b/sources/engine/Stride.Physics.Tests/Stride.Physics.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.Physics.Tests Stride.Physics.Tests false diff --git a/sources/engine/Stride.Shaders.Tests/Stride.Shaders.Tests.Windows.csproj b/sources/engine/Stride.Shaders.Tests/Stride.Shaders.Tests.Windows.csproj index 53052129d3..f2c7d0ecf3 100644 --- a/sources/engine/Stride.Shaders.Tests/Stride.Shaders.Tests.Windows.csproj +++ b/sources/engine/Stride.Shaders.Tests/Stride.Shaders.Tests.Windows.csproj @@ -2,7 +2,7 @@ $(StrideEditorTargetFramework) - win-x64 + win-arm64 Stride.Shaders.Tests Stride.Shaders.Tests * diff --git a/sources/engine/Stride.UI.Tests/Stride.UI.Tests.Windows.csproj b/sources/engine/Stride.UI.Tests/Stride.UI.Tests.Windows.csproj index 92b9980c82..b495581a1d 100644 --- a/sources/engine/Stride.UI.Tests/Stride.UI.Tests.Windows.csproj +++ b/sources/engine/Stride.UI.Tests/Stride.UI.Tests.Windows.csproj @@ -2,7 +2,7 @@ net8.0 - win-x64 + win-arm64 Stride.UI.Tests Stride.UI.Tests false diff --git a/sources/engine/Stride.VirtualReality/Stride.VirtualReality.csproj b/sources/engine/Stride.VirtualReality/Stride.VirtualReality.csproj index 66feffb7ac..826e279dd6 100644 --- a/sources/engine/Stride.VirtualReality/Stride.VirtualReality.csproj +++ b/sources/engine/Stride.VirtualReality/Stride.VirtualReality.csproj @@ -23,8 +23,8 @@ PreserveNewest - runtimes\win-x64\native\%(RecursiveDir)%(Filename)%(Extension) - runtimes\win-x64\native\%(RecursiveDir)%(Filename)%(Extension) + runtimes\win-arm64\native\%(RecursiveDir)%(Filename)%(Extension) + runtimes\win-arm64\native\%(RecursiveDir)%(Filename)%(Extension) PreserveNewest diff --git a/sources/launcher/Stride.Launcher/CrashReport/CrashReportHelper.cs b/sources/launcher/Stride.Launcher/CrashReport/CrashReportHelper.cs index 996fb09af5..6b7eba9a0b 100644 --- a/sources/launcher/Stride.Launcher/CrashReport/CrashReportHelper.cs +++ b/sources/launcher/Stride.Launcher/CrashReport/CrashReportHelper.cs @@ -54,7 +54,7 @@ private static void SendReport(string exceptionMessage) ["UserMessage"] = "", ["CurrentDirectory"] = Environment.CurrentDirectory, ["CommandArgs"] = string.Join(" ", AppHelper.GetCommandLineArgs()), - ["OsVersion"] = $"{Environment.OSVersion} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}", + ["OsVersion"] = $"{Environment.OSVersion} {(Environment.Is64BitOperatingSystem ? "64 bit" : "32 bit")}", ["ProcessorCount"] = Environment.ProcessorCount.ToString(), ["Exception"] = exceptionMessage }; diff --git a/sources/launcher/Stride.Launcher/Properties/PublishProfiles/FolderProfile.pubxml b/sources/launcher/Stride.Launcher/Properties/PublishProfiles/FolderProfile.pubxml index 9560a92708..910ab94aa6 100644 --- a/sources/launcher/Stride.Launcher/Properties/PublishProfiles/FolderProfile.pubxml +++ b/sources/launcher/Stride.Launcher/Properties/PublishProfiles/FolderProfile.pubxml @@ -10,7 +10,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. FileSystem net8.0-windows7.0 true - win-x64 + win-arm64 true false true diff --git a/sources/launcher/Stride.Launcher/Stride.Launcher.csproj b/sources/launcher/Stride.Launcher/Stride.Launcher.csproj index d8d7cf5ecf..c9e0c81552 100644 --- a/sources/launcher/Stride.Launcher/Stride.Launcher.csproj +++ b/sources/launcher/Stride.Launcher/Stride.Launcher.csproj @@ -2,7 +2,7 @@ WinExe net8.0-windows7.0 - win-x64 + win-arm64 false false true diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ApiDescriptionExtensions.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ApiDescriptionExtensions.cs new file mode 100644 index 0000000000..61c4886f52 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ApiDescriptionExtensions.cs @@ -0,0 +1,39 @@ +using System; +using System.Text; +using System.Web; +using System.Web.Http.Description; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + public static class ApiDescriptionExtensions + { + /// + /// Generates an URI-friendly ID for the . E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" + /// + /// The . + /// The ID as a string. + public static string GetFriendlyId(this ApiDescription description) + { + string path = description.RelativePath; + string[] urlParts = path.Split('?'); + string localPath = urlParts[0]; + string queryKeyString = null; + if (urlParts.Length > 1) + { + string query = urlParts[1]; + string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; + queryKeyString = String.Join("_", queryKeys); + } + + StringBuilder friendlyPath = new StringBuilder(); + friendlyPath.AppendFormat("{0}-{1}", + description.HttpMethod.Method, + localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); + if (queryKeyString != null) + { + friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); + } + return friendlyPath.ToString(); + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/App_Start/HelpPageConfig.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/App_Start/HelpPageConfig.cs new file mode 100644 index 0000000000..fd0cb37e81 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/App_Start/HelpPageConfig.cs @@ -0,0 +1,113 @@ +// Uncomment the following to provide samples for PageResult. Must also add the Microsoft.AspNet.WebApi.OData +// package to your project. +////#define Handle_PageResultOfT + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net.Http.Headers; +using System.Reflection; +using System.Web; +using System.Web.Http; +#if Handle_PageResultOfT +using System.Web.Http.OData; +#endif + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// Use this class to customize the Help Page. + /// For example you can set a custom to supply the documentation + /// or you can provide the samples for the requests/responses. + /// + public static class HelpPageConfig + { + [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", + MessageId = "Stride.Metrics.ServerApp.Areas.HelpPage.TextSample.#ctor(System.String)", + Justification = "End users may choose to merge this string with existing localized resources.")] + [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", + MessageId = "bsonspec", + Justification = "Part of a URI.")] + public static void Register(HttpConfiguration config) + { + //// Uncomment the following to use the documentation from XML documentation file. + //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); + + //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. + //// Also, the string arrays will be used for IEnumerable. The sample objects will be serialized into different media type + //// formats by the available formatters. + //config.SetSampleObjects(new Dictionary + //{ + // {typeof(string), "sample string"}, + // {typeof(IEnumerable), new string[]{"sample 1", "sample 2"}} + //}); + + // Extend the following to provide factories for types not handled automatically (those lacking parameterless + // constructors) or for which you prefer to use non-default property values. Line below provides a fallback + // since automatic handling will fail and GeneratePageResult handles only a single type. +#if Handle_PageResultOfT + config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); +#endif + + // Extend the following to use a preset object directly as the sample for all actions that support a media + // type, regardless of the body parameter or return type. The lines below avoid display of binary content. + // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. + config.SetSampleForMediaType( + new TextSample("Binary JSON content. See http://bsonspec.org for details."), + new MediaTypeHeaderValue("application/bson")); + + //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format + //// and have IEnumerable as the body parameter or return type. + //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable)); + + //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" + //// and action named "Put". + //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); + + //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" + //// on the controller named "Values" and action named "Get" with parameter "id". + //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); + + //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent. + //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. + //config.SetActualRequestType(typeof(string), "Values", "Get"); + + //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent. + //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. + //config.SetActualResponseType(typeof(string), "Values", "Post"); + } + +#if Handle_PageResultOfT + private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) + { + if (type.IsGenericType) + { + Type openGenericType = type.GetGenericTypeDefinition(); + if (openGenericType == typeof(PageResult<>)) + { + // Get the T in PageResult + Type[] typeParameters = type.GetGenericArguments(); + Debug.Assert(typeParameters.Length == 1); + + // Create an enumeration to pass as the first parameter to the PageResult constuctor + Type itemsType = typeof(List<>).MakeGenericType(typeParameters); + object items = sampleGenerator.GetSampleObject(itemsType); + + // Fill in the other information needed to invoke the PageResult constuctor + Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; + object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; + + // Call PageResult(IEnumerable items, Uri nextPageLink, long? count) constructor + ConstructorInfo constructor = type.GetConstructor(parameterTypes); + return constructor.Invoke(parameters); + } + } + + return null; + } +#endif + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Controllers/HelpController.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Controllers/HelpController.cs new file mode 100644 index 0000000000..cc3c0bcd41 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Controllers/HelpController.cs @@ -0,0 +1,63 @@ +using System; +using System.Web.Http; +using System.Web.Mvc; +using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions; +using Stride.Metrics.ServerApp.Areas.HelpPage.Models; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.Controllers +{ + /// + /// The controller that will handle requests for the help page. + /// + public class HelpController : Controller + { + private const string ErrorViewName = "Error"; + + public HelpController() + : this(GlobalConfiguration.Configuration) + { + } + + public HelpController(HttpConfiguration config) + { + Configuration = config; + } + + public HttpConfiguration Configuration { get; private set; } + + public ActionResult Index() + { + ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); + return View(Configuration.Services.GetApiExplorer().ApiDescriptions); + } + + public ActionResult Api(string apiId) + { + if (!String.IsNullOrEmpty(apiId)) + { + HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); + if (apiModel != null) + { + return View(apiModel); + } + } + + return View(ErrorViewName); + } + + public ActionResult ResourceModel(string modelName) + { + if (!String.IsNullOrEmpty(modelName)) + { + ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); + ModelDescription modelDescription; + if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) + { + return View(modelDescription); + } + } + + return View(ErrorViewName); + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPage.css b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPage.css new file mode 100644 index 0000000000..aff223033d --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPage.css @@ -0,0 +1,134 @@ +.help-page h1, +.help-page .h1, +.help-page h2, +.help-page .h2, +.help-page h3, +.help-page .h3, +#body.help-page, +.help-page-table th, +.help-page-table pre, +.help-page-table p { + font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; +} + +.help-page pre.wrapped { + white-space: -moz-pre-wrap; + white-space: -pre-wrap; + white-space: -o-pre-wrap; + white-space: pre-wrap; +} + +.help-page .warning-message-container { + margin-top: 20px; + padding: 0 10px; + color: #525252; + background: #EFDCA9; + border: 1px solid #CCCCCC; +} + +.help-page-table { + width: 100%; + border-collapse: collapse; + text-align: left; + margin: 0px 0px 20px 0px; + border-top: 1px solid #D4D4D4; +} + +.help-page-table th { + text-align: left; + font-weight: bold; + border-bottom: 1px solid #D4D4D4; + padding: 5px 6px 5px 6px; +} + +.help-page-table td { + border-bottom: 1px solid #D4D4D4; + padding: 10px 8px 10px 8px; + vertical-align: top; +} + +.help-page-table pre, +.help-page-table p { + margin: 0px; + padding: 0px; + font-family: inherit; + font-size: 100%; +} + +.help-page-table tbody tr:hover td { + background-color: #F3F3F3; +} + +.help-page a:hover { + background-color: transparent; +} + +.help-page .sample-header { + border: 2px solid #D4D4D4; + background: #00497E; + color: #FFFFFF; + padding: 8px 15px; + border-bottom: none; + display: inline-block; + margin: 10px 0px 0px 0px; +} + +.help-page .sample-content { + display: block; + border-width: 0; + padding: 15px 20px; + background: #FFFFFF; + border: 2px solid #D4D4D4; + margin: 0px 0px 10px 0px; +} + +.help-page .api-name { + width: 40%; +} + +.help-page .api-documentation { + width: 60%; +} + +.help-page .parameter-name { + width: 20%; +} + +.help-page .parameter-documentation { + width: 40%; +} + +.help-page .parameter-type { + width: 20%; +} + +.help-page .parameter-annotations { + width: 20%; +} + +.help-page h1, +.help-page .h1 { + font-size: 36px; + line-height: normal; +} + +.help-page h2, +.help-page .h2 { + font-size: 24px; +} + +.help-page h3, +.help-page .h3 { + font-size: 20px; +} + +#body.help-page { + font-size: 14px; + line-height: 143%; + color: #333; +} + +.help-page a { + color: #0000EE; + text-decoration: none; +} diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageAreaRegistration.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageAreaRegistration.cs new file mode 100644 index 0000000000..a39464cfcb --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageAreaRegistration.cs @@ -0,0 +1,26 @@ +using System.Web.Http; +using System.Web.Mvc; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + public class HelpPageAreaRegistration : AreaRegistration + { + public override string AreaName + { + get + { + return "HelpPage"; + } + } + + public override void RegisterArea(AreaRegistrationContext context) + { + context.MapRoute( + "HelpPage_Default", + "Help/{action}/{apiId}", + new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); + + HelpPageConfig.Register(GlobalConfiguration.Configuration); + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageConfigurationExtensions.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageConfigurationExtensions.cs new file mode 100644 index 0000000000..5f2836030b --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/HelpPageConfigurationExtensions.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Web.Http; +using System.Web.Http.Controllers; +using System.Web.Http.Description; +using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions; +using Stride.Metrics.ServerApp.Areas.HelpPage.Models; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + public static class HelpPageConfigurationExtensions + { + private const string ApiModelPrefix = "MS_HelpPageApiModel_"; + + /// + /// Sets the documentation provider for help page. + /// + /// The . + /// The documentation provider. + public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) + { + config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); + } + + /// + /// Sets the objects that will be used by the formatters to produce sample requests/responses. + /// + /// The . + /// The sample objects. + public static void SetSampleObjects(this HttpConfiguration config, IDictionary sampleObjects) + { + config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; + } + + /// + /// Sets the sample request directly for the specified media type and action. + /// + /// The . + /// The sample request. + /// The media type. + /// Name of the controller. + /// Name of the action. + public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); + } + + /// + /// Sets the sample request directly for the specified media type and action with parameters. + /// + /// The . + /// The sample request. + /// The media type. + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); + } + + /// + /// Sets the sample request directly for the specified media type of the action. + /// + /// The . + /// The sample response. + /// The media type. + /// Name of the controller. + /// Name of the action. + public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); + } + + /// + /// Sets the sample response directly for the specified media type of the action with specific parameters. + /// + /// The . + /// The sample response. + /// The media type. + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); + } + + /// + /// Sets the sample directly for all actions with the specified media type. + /// + /// The . + /// The sample. + /// The media type. + public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); + } + + /// + /// Sets the sample directly for all actions with the specified type and media type. + /// + /// The . + /// The sample. + /// The media type. + /// The parameter type or return type of an action. + public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) + { + config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); + } + + /// + /// Specifies the actual type of passed to the in an action. + /// The help page will use this information to produce more accurate request samples. + /// + /// The . + /// The type. + /// Name of the controller. + /// Name of the action. + public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) + { + config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); + } + + /// + /// Specifies the actual type of passed to the in an action. + /// The help page will use this information to produce more accurate request samples. + /// + /// The . + /// The type. + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) + { + config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); + } + + /// + /// Specifies the actual type of returned as part of the in an action. + /// The help page will use this information to produce more accurate response samples. + /// + /// The . + /// The type. + /// Name of the controller. + /// Name of the action. + public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) + { + config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); + } + + /// + /// Specifies the actual type of returned as part of the in an action. + /// The help page will use this information to produce more accurate response samples. + /// + /// The . + /// The type. + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) + { + config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); + } + + /// + /// Gets the help page sample generator. + /// + /// The . + /// The help page sample generator. + public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) + { + return (HelpPageSampleGenerator)config.Properties.GetOrAdd( + typeof(HelpPageSampleGenerator), + k => new HelpPageSampleGenerator()); + } + + /// + /// Sets the help page sample generator. + /// + /// The . + /// The help page sample generator. + public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) + { + config.Properties.AddOrUpdate( + typeof(HelpPageSampleGenerator), + k => sampleGenerator, + (k, o) => sampleGenerator); + } + + /// + /// Gets the model description generator. + /// + /// The configuration. + /// The + public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) + { + return (ModelDescriptionGenerator)config.Properties.GetOrAdd( + typeof(ModelDescriptionGenerator), + k => InitializeModelDescriptionGenerator(config)); + } + + /// + /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. + /// + /// The . + /// The ID. + /// + /// An + /// + public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) + { + object model; + string modelId = ApiModelPrefix + apiDescriptionId; + if (!config.Properties.TryGetValue(modelId, out model)) + { + Collection apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; + ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); + if (apiDescription != null) + { + model = GenerateApiModel(apiDescription, config); + config.Properties.TryAdd(modelId, model); + } + } + + return (HelpPageApiModel)model; + } + + private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) + { + HelpPageApiModel apiModel = new HelpPageApiModel() + { + ApiDescription = apiDescription, + }; + + ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); + HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); + GenerateUriParameters(apiModel, modelGenerator); + GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); + GenerateResourceDescription(apiModel, modelGenerator); + GenerateSamples(apiModel, sampleGenerator); + + return apiModel; + } + + private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) + { + ApiDescription apiDescription = apiModel.ApiDescription; + foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) + { + if (apiParameter.Source == ApiParameterSource.FromUri) + { + HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; + Type parameterType = null; + ModelDescription typeDescription = null; + ComplexTypeModelDescription complexTypeDescription = null; + if (parameterDescriptor != null) + { + parameterType = parameterDescriptor.ParameterType; + typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); + complexTypeDescription = typeDescription as ComplexTypeModelDescription; + } + + // Example: + // [TypeConverter(typeof(PointConverter))] + // public class Point + // { + // public Point(int x, int y) + // { + // X = x; + // Y = y; + // } + // public int X { get; set; } + // public int Y { get; set; } + // } + // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. + // + // public class Point + // { + // public int X { get; set; } + // public int Y { get; set; } + // } + // Regular complex class Point will have properties X and Y added to UriParameters collection. + if (complexTypeDescription != null + && !IsBindableWithTypeConverter(parameterType)) + { + foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) + { + apiModel.UriParameters.Add(uriParameter); + } + } + else if (parameterDescriptor != null) + { + ParameterDescription uriParameter = + AddParameterDescription(apiModel, apiParameter, typeDescription); + + if (!parameterDescriptor.IsOptional) + { + uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); + } + + object defaultValue = parameterDescriptor.DefaultValue; + if (defaultValue != null) + { + uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); + } + } + else + { + Debug.Assert(parameterDescriptor == null); + + // If parameterDescriptor is null, this is an undeclared route parameter which only occurs + // when source is FromUri. Ignored in request model and among resource parameters but listed + // as a simple string here. + ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); + AddParameterDescription(apiModel, apiParameter, modelDescription); + } + } + } + } + + private static bool IsBindableWithTypeConverter(Type parameterType) + { + if (parameterType == null) + { + return false; + } + + return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); + } + + private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, + ApiParameterDescription apiParameter, ModelDescription typeDescription) + { + ParameterDescription parameterDescription = new ParameterDescription + { + Name = apiParameter.Name, + Documentation = apiParameter.Documentation, + TypeDescription = typeDescription, + }; + + apiModel.UriParameters.Add(parameterDescription); + return parameterDescription; + } + + private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) + { + ApiDescription apiDescription = apiModel.ApiDescription; + foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) + { + if (apiParameter.Source == ApiParameterSource.FromBody) + { + Type parameterType = apiParameter.ParameterDescriptor.ParameterType; + apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); + apiModel.RequestDocumentation = apiParameter.Documentation; + } + else if (apiParameter.ParameterDescriptor != null && + apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) + { + Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); + + if (parameterType != null) + { + apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); + } + } + } + } + + private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) + { + ResponseDescription response = apiModel.ApiDescription.ResponseDescription; + Type responseType = response.ResponseType ?? response.DeclaredType; + if (responseType != null && responseType != typeof(void)) + { + apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); + } + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] + private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) + { + try + { + foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) + { + apiModel.SampleRequests.Add(item.Key, item.Value); + LogInvalidSampleAsError(apiModel, item.Value); + } + + foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) + { + apiModel.SampleResponses.Add(item.Key, item.Value); + LogInvalidSampleAsError(apiModel, item.Value); + } + } + catch (Exception e) + { + apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, + "An exception has occurred while generating the sample. Exception message: {0}", + HelpPageSampleGenerator.UnwrapException(e).Message)); + } + } + + private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) + { + parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( + p => p.Source == ApiParameterSource.FromBody || + (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); + + if (parameterDescription == null) + { + resourceType = null; + return false; + } + + resourceType = parameterDescription.ParameterDescriptor.ParameterType; + + if (resourceType == typeof(HttpRequestMessage)) + { + HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); + resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); + } + + if (resourceType == null) + { + parameterDescription = null; + return false; + } + + return true; + } + + private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) + { + ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); + Collection apis = config.Services.GetApiExplorer().ApiDescriptions; + foreach (ApiDescription api in apis) + { + ApiParameterDescription parameterDescription; + Type parameterType; + if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) + { + modelGenerator.GetOrCreateModelDescription(parameterType); + } + } + return modelGenerator; + } + + private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) + { + InvalidSample invalidSample = sample as InvalidSample; + if (invalidSample != null) + { + apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); + } + } + } +} diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs new file mode 100644 index 0000000000..86efb604c1 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs @@ -0,0 +1,7 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class CollectionModelDescription : ModelDescription + { + public ModelDescription ElementDescription { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs new file mode 100644 index 0000000000..08c928a990 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs @@ -0,0 +1,14 @@ +using System.Collections.ObjectModel; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class ComplexTypeModelDescription : ModelDescription + { + public ComplexTypeModelDescription() + { + Properties = new Collection(); + } + + public Collection Properties { get; private set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs new file mode 100644 index 0000000000..287f6d18dd --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs @@ -0,0 +1,6 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class DictionaryModelDescription : KeyValuePairModelDescription + { + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs new file mode 100644 index 0000000000..4f2129254c --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class EnumTypeModelDescription : ModelDescription + { + public EnumTypeModelDescription() + { + Values = new Collection(); + } + + public Collection Values { get; private set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs new file mode 100644 index 0000000000..0c3df4f839 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs @@ -0,0 +1,11 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class EnumValueDescription + { + public string Documentation { get; set; } + + public string Name { get; set; } + + public string Value { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs new file mode 100644 index 0000000000..9d8797da68 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs @@ -0,0 +1,12 @@ +using System; +using System.Reflection; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public interface IModelDocumentationProvider + { + string GetDocumentation(MemberInfo member); + + string GetDocumentation(Type type); + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs new file mode 100644 index 0000000000..07dc094044 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs @@ -0,0 +1,9 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class KeyValuePairModelDescription : ModelDescription + { + public ModelDescription KeyModelDescription { get; set; } + + public ModelDescription ValueModelDescription { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescription.cs new file mode 100644 index 0000000000..050da4256c --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescription.cs @@ -0,0 +1,16 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + /// + /// Describes a type model. + /// + public abstract class ModelDescription + { + public string Documentation { get; set; } + + public Type ModelType { get; set; } + + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs new file mode 100644 index 0000000000..fad2bbca69 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs @@ -0,0 +1,451 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel.DataAnnotations; +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +using System.Web.Http; +using System.Web.Http.Description; +using System.Xml.Serialization; +using Newtonsoft.Json; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + /// + /// Generates model descriptions for given types. + /// + public class ModelDescriptionGenerator + { + // Modify this to support more data annotation attributes. + private readonly IDictionary> AnnotationTextGenerator = new Dictionary> + { + { typeof(RequiredAttribute), a => "Required" }, + { typeof(RangeAttribute), a => + { + RangeAttribute range = (RangeAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); + } + }, + { typeof(MaxLengthAttribute), a => + { + MaxLengthAttribute maxLength = (MaxLengthAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); + } + }, + { typeof(MinLengthAttribute), a => + { + MinLengthAttribute minLength = (MinLengthAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); + } + }, + { typeof(StringLengthAttribute), a => + { + StringLengthAttribute strLength = (StringLengthAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); + } + }, + { typeof(DataTypeAttribute), a => + { + DataTypeAttribute dataType = (DataTypeAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); + } + }, + { typeof(RegularExpressionAttribute), a => + { + RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; + return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); + } + }, + }; + + // Modify this to add more default documentations. + private readonly IDictionary DefaultTypeDocumentation = new Dictionary + { + { typeof(Int16), "integer" }, + { typeof(Int32), "integer" }, + { typeof(Int64), "integer" }, + { typeof(UInt16), "unsigned integer" }, + { typeof(UInt32), "unsigned integer" }, + { typeof(UInt64), "unsigned integer" }, + { typeof(Byte), "byte" }, + { typeof(Char), "character" }, + { typeof(SByte), "signed byte" }, + { typeof(Uri), "URI" }, + { typeof(Single), "decimal number" }, + { typeof(Double), "decimal number" }, + { typeof(Decimal), "decimal number" }, + { typeof(String), "string" }, + { typeof(Guid), "globally unique identifier" }, + { typeof(TimeSpan), "time interval" }, + { typeof(DateTime), "date" }, + { typeof(DateTimeOffset), "date" }, + { typeof(Boolean), "boolean" }, + }; + + private Lazy _documentationProvider; + + public ModelDescriptionGenerator(HttpConfiguration config) + { + if (config == null) + { + throw new ArgumentNullException("config"); + } + + _documentationProvider = new Lazy(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); + GeneratedModels = new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + public Dictionary GeneratedModels { get; private set; } + + private IModelDocumentationProvider DocumentationProvider + { + get + { + return _documentationProvider.Value; + } + } + + public ModelDescription GetOrCreateModelDescription(Type modelType) + { + if (modelType == null) + { + throw new ArgumentNullException("modelType"); + } + + Type underlyingType = Nullable.GetUnderlyingType(modelType); + if (underlyingType != null) + { + modelType = underlyingType; + } + + ModelDescription modelDescription; + string modelName = ModelNameHelper.GetModelName(modelType); + if (GeneratedModels.TryGetValue(modelName, out modelDescription)) + { + if (modelType != modelDescription.ModelType) + { + throw new InvalidOperationException( + String.Format( + CultureInfo.CurrentCulture, + "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", + modelName, + modelDescription.ModelType.FullName, + modelType.FullName)); + } + + return modelDescription; + } + + if (DefaultTypeDocumentation.ContainsKey(modelType)) + { + return GenerateSimpleTypeModelDescription(modelType); + } + + if (modelType.IsEnum) + { + return GenerateEnumTypeModelDescription(modelType); + } + + if (modelType.IsGenericType) + { + Type[] genericArguments = modelType.GetGenericArguments(); + + if (genericArguments.Length == 1) + { + Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); + if (enumerableType.IsAssignableFrom(modelType)) + { + return GenerateCollectionModelDescription(modelType, genericArguments[0]); + } + } + if (genericArguments.Length == 2) + { + Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); + if (dictionaryType.IsAssignableFrom(modelType)) + { + return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); + } + + Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); + if (keyValuePairType.IsAssignableFrom(modelType)) + { + return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); + } + } + } + + if (modelType.IsArray) + { + Type elementType = modelType.GetElementType(); + return GenerateCollectionModelDescription(modelType, elementType); + } + + if (modelType == typeof(NameValueCollection)) + { + return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); + } + + if (typeof(IDictionary).IsAssignableFrom(modelType)) + { + return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); + } + + if (typeof(IEnumerable).IsAssignableFrom(modelType)) + { + return GenerateCollectionModelDescription(modelType, typeof(object)); + } + + return GenerateComplexTypeModelDescription(modelType); + } + + // Change this to provide different name for the member. + private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) + { + JsonPropertyAttribute jsonProperty = member.GetCustomAttribute(); + if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) + { + return jsonProperty.PropertyName; + } + + if (hasDataContractAttribute) + { + DataMemberAttribute dataMember = member.GetCustomAttribute(); + if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) + { + return dataMember.Name; + } + } + + return member.Name; + } + + private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) + { + JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute(); + XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute(); + IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute(); + NonSerializedAttribute nonSerialized = member.GetCustomAttribute(); + ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute(); + + bool hasMemberAttribute = member.DeclaringType.IsEnum ? + member.GetCustomAttribute() != null : + member.GetCustomAttribute() != null; + + // Display member only if all the followings are true: + // no JsonIgnoreAttribute + // no XmlIgnoreAttribute + // no IgnoreDataMemberAttribute + // no NonSerializedAttribute + // no ApiExplorerSettingsAttribute with IgnoreApi set to true + // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute + return jsonIgnore == null && + xmlIgnore == null && + ignoreDataMember == null && + nonSerialized == null && + (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && + (!hasDataContractAttribute || hasMemberAttribute); + } + + private string CreateDefaultDocumentation(Type type) + { + string documentation; + if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) + { + return documentation; + } + if (DocumentationProvider != null) + { + documentation = DocumentationProvider.GetDocumentation(type); + } + + return documentation; + } + + private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) + { + List annotations = new List(); + + IEnumerable attributes = property.GetCustomAttributes(); + foreach (Attribute attribute in attributes) + { + Func textGenerator; + if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) + { + annotations.Add( + new ParameterAnnotation + { + AnnotationAttribute = attribute, + Documentation = textGenerator(attribute) + }); + } + } + + // Rearrange the annotations + annotations.Sort((x, y) => + { + // Special-case RequiredAttribute so that it shows up on top + if (x.AnnotationAttribute is RequiredAttribute) + { + return -1; + } + if (y.AnnotationAttribute is RequiredAttribute) + { + return 1; + } + + // Sort the rest based on alphabetic order of the documentation + return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); + }); + + foreach (ParameterAnnotation annotation in annotations) + { + propertyModel.Annotations.Add(annotation); + } + } + + private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) + { + ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); + if (collectionModelDescription != null) + { + return new CollectionModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + ElementDescription = collectionModelDescription + }; + } + + return null; + } + + private ModelDescription GenerateComplexTypeModelDescription(Type modelType) + { + ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + Documentation = CreateDefaultDocumentation(modelType) + }; + + GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); + bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; + PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); + foreach (PropertyInfo property in properties) + { + if (ShouldDisplayMember(property, hasDataContractAttribute)) + { + ParameterDescription propertyModel = new ParameterDescription + { + Name = GetMemberName(property, hasDataContractAttribute) + }; + + if (DocumentationProvider != null) + { + propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); + } + + GenerateAnnotations(property, propertyModel); + complexModelDescription.Properties.Add(propertyModel); + propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); + } + } + + FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); + foreach (FieldInfo field in fields) + { + if (ShouldDisplayMember(field, hasDataContractAttribute)) + { + ParameterDescription propertyModel = new ParameterDescription + { + Name = GetMemberName(field, hasDataContractAttribute) + }; + + if (DocumentationProvider != null) + { + propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); + } + + complexModelDescription.Properties.Add(propertyModel); + propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); + } + } + + return complexModelDescription; + } + + private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) + { + ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); + ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); + + return new DictionaryModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + KeyModelDescription = keyModelDescription, + ValueModelDescription = valueModelDescription + }; + } + + private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) + { + EnumTypeModelDescription enumDescription = new EnumTypeModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + Documentation = CreateDefaultDocumentation(modelType) + }; + bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; + foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) + { + if (ShouldDisplayMember(field, hasDataContractAttribute)) + { + EnumValueDescription enumValue = new EnumValueDescription + { + Name = field.Name, + Value = field.GetRawConstantValue().ToString() + }; + if (DocumentationProvider != null) + { + enumValue.Documentation = DocumentationProvider.GetDocumentation(field); + } + enumDescription.Values.Add(enumValue); + } + } + GeneratedModels.Add(enumDescription.Name, enumDescription); + + return enumDescription; + } + + private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) + { + ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); + ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); + + return new KeyValuePairModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + KeyModelDescription = keyModelDescription, + ValueModelDescription = valueModelDescription + }; + } + + private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) + { + SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription + { + Name = ModelNameHelper.GetModelName(modelType), + ModelType = modelType, + Documentation = CreateDefaultDocumentation(modelType) + }; + GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); + + return simpleModelDescription; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs new file mode 100644 index 0000000000..cc06c113f9 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs @@ -0,0 +1,18 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + /// + /// Use this attribute to change the name of the generated for a type. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] + public sealed class ModelNameAttribute : Attribute + { + public ModelNameAttribute(string name) + { + Name = name; + } + + public string Name { get; private set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs new file mode 100644 index 0000000000..3d054b2244 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs @@ -0,0 +1,36 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Reflection; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + internal static class ModelNameHelper + { + // Modify this to provide custom model name mapping. + public static string GetModelName(Type type) + { + ModelNameAttribute modelNameAttribute = type.GetCustomAttribute(); + if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) + { + return modelNameAttribute.Name; + } + + string modelName = type.Name; + if (type.IsGenericType) + { + // Format the generic type name to something like: GenericOfAgurment1AndArgument2 + Type genericType = type.GetGenericTypeDefinition(); + Type[] genericArguments = type.GetGenericArguments(); + string genericTypeName = genericType.Name; + + // Trim the generic parameter counts from the name + genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); + string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); + modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); + } + + return modelName; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs new file mode 100644 index 0000000000..3e2b0b6744 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs @@ -0,0 +1,11 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class ParameterAnnotation + { + public Attribute AnnotationAttribute { get; set; } + + public string Documentation { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs new file mode 100644 index 0000000000..7c772d71eb --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class ParameterDescription + { + public ParameterDescription() + { + Annotations = new Collection(); + } + + public Collection Annotations { get; private set; } + + public string Documentation { get; set; } + + public string Name { get; set; } + + public ModelDescription TypeDescription { get; set; } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs new file mode 100644 index 0000000000..a6707d07c0 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs @@ -0,0 +1,6 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +{ + public class SimpleTypeModelDescription : ModelDescription + { + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Models/HelpPageApiModel.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Models/HelpPageApiModel.cs new file mode 100644 index 0000000000..7038e8bcd8 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Models/HelpPageApiModel.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Net.Http.Headers; +using System.Web.Http.Description; +using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage.Models +{ + /// + /// The model that represents an API displayed on the help page. + /// + public class HelpPageApiModel + { + /// + /// Initializes a new instance of the class. + /// + public HelpPageApiModel() + { + UriParameters = new Collection(); + SampleRequests = new Dictionary(); + SampleResponses = new Dictionary(); + ErrorMessages = new Collection(); + } + + /// + /// Gets or sets the that describes the API. + /// + public ApiDescription ApiDescription { get; set; } + + /// + /// Gets or sets the collection that describes the URI parameters for the API. + /// + public Collection UriParameters { get; private set; } + + /// + /// Gets or sets the documentation for the request. + /// + public string RequestDocumentation { get; set; } + + /// + /// Gets or sets the that describes the request body. + /// + public ModelDescription RequestModelDescription { get; set; } + + /// + /// Gets the request body parameter descriptions. + /// + public IList RequestBodyParameters + { + get + { + return GetParameterDescriptions(RequestModelDescription); + } + } + + /// + /// Gets or sets the that describes the resource. + /// + public ModelDescription ResourceDescription { get; set; } + + /// + /// Gets the resource property descriptions. + /// + public IList ResourceProperties + { + get + { + return GetParameterDescriptions(ResourceDescription); + } + } + + /// + /// Gets the sample requests associated with the API. + /// + public IDictionary SampleRequests { get; private set; } + + /// + /// Gets the sample responses associated with the API. + /// + public IDictionary SampleResponses { get; private set; } + + /// + /// Gets the error messages associated with this model. + /// + public Collection ErrorMessages { get; private set; } + + private static IList GetParameterDescriptions(ModelDescription modelDescription) + { + ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; + if (complexTypeModelDescription != null) + { + return complexTypeModelDescription.Properties; + } + + CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; + if (collectionModelDescription != null) + { + complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; + if (complexTypeModelDescription != null) + { + return complexTypeModelDescription.Properties; + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs new file mode 100644 index 0000000000..4c65209489 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs @@ -0,0 +1,444 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Formatting; +using System.Net.Http.Headers; +using System.Web.Http.Description; +using System.Xml.Linq; +using Newtonsoft.Json; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This class will generate the samples for the help page. + /// + public class HelpPageSampleGenerator + { + /// + /// Initializes a new instance of the class. + /// + public HelpPageSampleGenerator() + { + ActualHttpMessageTypes = new Dictionary(); + ActionSamples = new Dictionary(); + SampleObjects = new Dictionary(); + SampleObjectFactories = new List> + { + DefaultSampleObjectFactory, + }; + } + + /// + /// Gets CLR types that are used as the content of or . + /// + public IDictionary ActualHttpMessageTypes { get; internal set; } + + /// + /// Gets the objects that are used directly as samples for certain actions. + /// + public IDictionary ActionSamples { get; internal set; } + + /// + /// Gets the objects that are serialized as samples by the supported formatters. + /// + public IDictionary SampleObjects { get; internal set; } + + /// + /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, + /// stopping when the factory successfully returns a non- object. + /// + /// + /// Collection includes just initially. Use + /// SampleObjectFactories.Insert(0, func) to provide an override and + /// SampleObjectFactories.Add(func) to provide a fallback. + [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", + Justification = "This is an appropriate nesting of generic types")] + public IList> SampleObjectFactories { get; private set; } + + /// + /// Gets the request body samples for a given . + /// + /// The . + /// The samples keyed by media type. + public IDictionary GetSampleRequests(ApiDescription api) + { + return GetSample(api, SampleDirection.Request); + } + + /// + /// Gets the response body samples for a given . + /// + /// The . + /// The samples keyed by media type. + public IDictionary GetSampleResponses(ApiDescription api) + { + return GetSample(api, SampleDirection.Response); + } + + /// + /// Gets the request or response body samples. + /// + /// The . + /// The value indicating whether the sample is for a request or for a response. + /// The samples keyed by media type. + public virtual IDictionary GetSample(ApiDescription api, SampleDirection sampleDirection) + { + if (api == null) + { + throw new ArgumentNullException("api"); + } + string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; + string actionName = api.ActionDescriptor.ActionName; + IEnumerable parameterNames = api.ParameterDescriptions.Select(p => p.Name); + Collection formatters; + Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); + var samples = new Dictionary(); + + // Use the samples provided directly for actions + var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); + foreach (var actionSample in actionSamples) + { + samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); + } + + // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. + // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. + if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) + { + object sampleObject = GetSampleObject(type); + foreach (var formatter in formatters) + { + foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) + { + if (!samples.ContainsKey(mediaType)) + { + object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); + + // If no sample found, try generate sample using formatter and sample object + if (sample == null && sampleObject != null) + { + sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); + } + + samples.Add(mediaType, WrapSampleIfString(sample)); + } + } + } + } + + return samples; + } + + /// + /// Search for samples that are provided directly through . + /// + /// Name of the controller. + /// Name of the action. + /// The parameter names. + /// The CLR type. + /// The formatter. + /// The media type. + /// The value indicating whether the sample is for a request or for a response. + /// The sample that matches the parameters. + public virtual object GetActionSample(string controllerName, string actionName, IEnumerable parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) + { + object sample; + + // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. + // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. + // If still not found, try to get the sample provided for the specified mediaType and type. + // Finally, try to get the sample provided for the specified mediaType. + if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || + ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || + ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || + ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) + { + return sample; + } + + return null; + } + + /// + /// Gets the sample object that will be serialized by the formatters. + /// First, it will look at the . If no sample object is found, it will try to create + /// one using (which wraps an ) and other + /// factories in . + /// + /// The type. + /// The sample object. + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", + Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] + public virtual object GetSampleObject(Type type) + { + object sampleObject; + + if (!SampleObjects.TryGetValue(type, out sampleObject)) + { + // No specific object available, try our factories. + foreach (Func factory in SampleObjectFactories) + { + if (factory == null) + { + continue; + } + + try + { + sampleObject = factory(this, type); + if (sampleObject != null) + { + break; + } + } + catch + { + // Ignore any problems encountered in the factory; go on to the next one (if any). + } + } + } + + return sampleObject; + } + + /// + /// Resolves the actual type of passed to the in an action. + /// + /// The . + /// The type. + public virtual Type ResolveHttpRequestMessageType(ApiDescription api) + { + string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; + string actionName = api.ActionDescriptor.ActionName; + IEnumerable parameterNames = api.ParameterDescriptions.Select(p => p.Name); + Collection formatters; + return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); + } + + /// + /// Resolves the type of the action parameter or return value when or is used. + /// + /// The . + /// Name of the controller. + /// Name of the action. + /// The parameter names. + /// The value indicating whether the sample is for a request or a response. + /// The formatters. + [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] + public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable parameterNames, SampleDirection sampleDirection, out Collection formatters) + { + if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) + { + throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); + } + if (api == null) + { + throw new ArgumentNullException("api"); + } + Type type; + if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || + ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) + { + // Re-compute the supported formatters based on type + Collection newFormatters = new Collection(); + foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) + { + if (IsFormatSupported(sampleDirection, formatter, type)) + { + newFormatters.Add(formatter); + } + } + formatters = newFormatters; + } + else + { + switch (sampleDirection) + { + case SampleDirection.Request: + ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); + type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; + formatters = api.SupportedRequestBodyFormatters; + break; + case SampleDirection.Response: + default: + type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; + formatters = api.SupportedResponseFormatters; + break; + } + } + + return type; + } + + /// + /// Writes the sample object using formatter. + /// + /// The formatter. + /// The value. + /// The type. + /// Type of the media. + /// + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] + public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) + { + if (formatter == null) + { + throw new ArgumentNullException("formatter"); + } + if (mediaType == null) + { + throw new ArgumentNullException("mediaType"); + } + + object sample = String.Empty; + MemoryStream ms = null; + HttpContent content = null; + try + { + if (formatter.CanWriteType(type)) + { + ms = new MemoryStream(); + content = new ObjectContent(type, value, formatter, mediaType); + formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); + ms.Position = 0; + StreamReader reader = new StreamReader(ms); + string serializedSampleString = reader.ReadToEnd(); + if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) + { + serializedSampleString = TryFormatXml(serializedSampleString); + } + else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) + { + serializedSampleString = TryFormatJson(serializedSampleString); + } + + sample = new TextSample(serializedSampleString); + } + else + { + sample = new InvalidSample(String.Format( + CultureInfo.CurrentCulture, + "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", + mediaType, + formatter.GetType().Name, + type.Name)); + } + } + catch (Exception e) + { + sample = new InvalidSample(String.Format( + CultureInfo.CurrentCulture, + "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", + formatter.GetType().Name, + mediaType.MediaType, + UnwrapException(e).Message)); + } + finally + { + if (ms != null) + { + ms.Dispose(); + } + if (content != null) + { + content.Dispose(); + } + } + + return sample; + } + + internal static Exception UnwrapException(Exception exception) + { + AggregateException aggregateException = exception as AggregateException; + if (aggregateException != null) + { + return aggregateException.Flatten().InnerException; + } + return exception; + } + + // Default factory for sample objects + private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) + { + // Try to create a default sample object + ObjectGenerator objectGenerator = new ObjectGenerator(); + return objectGenerator.GenerateObject(type); + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] + private static string TryFormatJson(string str) + { + try + { + object parsedJson = JsonConvert.DeserializeObject(str); + return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); + } + catch + { + // can't parse JSON, return the original string + return str; + } + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] + private static string TryFormatXml(string str) + { + try + { + XDocument xml = XDocument.Parse(str); + return xml.ToString(); + } + catch + { + // can't parse XML, return the original string + return str; + } + } + + private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) + { + switch (sampleDirection) + { + case SampleDirection.Request: + return formatter.CanReadType(type); + case SampleDirection.Response: + return formatter.CanWriteType(type); + } + return false; + } + + private IEnumerable> GetAllActionSamples(string controllerName, string actionName, IEnumerable parameterNames, SampleDirection sampleDirection) + { + HashSet parameterNamesSet = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); + foreach (var sample in ActionSamples) + { + HelpPageSampleKey sampleKey = sample.Key; + if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && + String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && + (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && + sampleDirection == sampleKey.SampleDirection) + { + yield return sample; + } + } + } + + private static object WrapSampleIfString(object sample) + { + string stringSample = sample as string; + if (stringSample != null) + { + return new TextSample(stringSample); + } + + return sample; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs new file mode 100644 index 0000000000..7a7147493a --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Net.Http.Headers; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This is used to identify the place where the sample should be applied. + /// + public class HelpPageSampleKey + { + /// + /// Creates a new based on media type. + /// + /// The media type. + public HelpPageSampleKey(MediaTypeHeaderValue mediaType) + { + if (mediaType == null) + { + throw new ArgumentNullException("mediaType"); + } + + ActionName = String.Empty; + ControllerName = String.Empty; + MediaType = mediaType; + ParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); + } + + /// + /// Creates a new based on media type and CLR type. + /// + /// The media type. + /// The CLR type. + public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) + : this(mediaType) + { + if (type == null) + { + throw new ArgumentNullException("type"); + } + + ParameterType = type; + } + + /// + /// Creates a new based on , controller name, action name and parameter names. + /// + /// The . + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) + { + if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) + { + throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); + } + if (controllerName == null) + { + throw new ArgumentNullException("controllerName"); + } + if (actionName == null) + { + throw new ArgumentNullException("actionName"); + } + if (parameterNames == null) + { + throw new ArgumentNullException("parameterNames"); + } + + ControllerName = controllerName; + ActionName = actionName; + ParameterNames = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); + SampleDirection = sampleDirection; + } + + /// + /// Creates a new based on media type, , controller name, action name and parameter names. + /// + /// The media type. + /// The . + /// Name of the controller. + /// Name of the action. + /// The parameter names. + public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) + : this(sampleDirection, controllerName, actionName, parameterNames) + { + if (mediaType == null) + { + throw new ArgumentNullException("mediaType"); + } + + MediaType = mediaType; + } + + /// + /// Gets the name of the controller. + /// + /// + /// The name of the controller. + /// + public string ControllerName { get; private set; } + + /// + /// Gets the name of the action. + /// + /// + /// The name of the action. + /// + public string ActionName { get; private set; } + + /// + /// Gets the media type. + /// + /// + /// The media type. + /// + public MediaTypeHeaderValue MediaType { get; private set; } + + /// + /// Gets the parameter names. + /// + public HashSet ParameterNames { get; private set; } + + public Type ParameterType { get; private set; } + + /// + /// Gets the . + /// + public SampleDirection? SampleDirection { get; private set; } + + public override bool Equals(object obj) + { + HelpPageSampleKey otherKey = obj as HelpPageSampleKey; + if (otherKey == null) + { + return false; + } + + return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && + String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && + (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && + ParameterType == otherKey.ParameterType && + SampleDirection == otherKey.SampleDirection && + ParameterNames.SetEquals(otherKey.ParameterNames); + } + + public override int GetHashCode() + { + int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); + if (MediaType != null) + { + hashCode ^= MediaType.GetHashCode(); + } + if (SampleDirection != null) + { + hashCode ^= SampleDirection.GetHashCode(); + } + if (ParameterType != null) + { + hashCode ^= ParameterType.GetHashCode(); + } + foreach (string parameterName in ParameterNames) + { + hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); + } + + return hashCode; + } + } +} diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ImageSample.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ImageSample.cs new file mode 100644 index 0000000000..9176abf9e6 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ImageSample.cs @@ -0,0 +1,41 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. + /// + public class ImageSample + { + /// + /// Initializes a new instance of the class. + /// + /// The URL of an image. + public ImageSample(string src) + { + if (src == null) + { + throw new ArgumentNullException("src"); + } + Src = src; + } + + public string Src { get; private set; } + + public override bool Equals(object obj) + { + ImageSample other = obj as ImageSample; + return other != null && Src == other.Src; + } + + public override int GetHashCode() + { + return Src.GetHashCode(); + } + + public override string ToString() + { + return Src; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/InvalidSample.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/InvalidSample.cs new file mode 100644 index 0000000000..9f0434d4d5 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/InvalidSample.cs @@ -0,0 +1,37 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. + /// + public class InvalidSample + { + public InvalidSample(string errorMessage) + { + if (errorMessage == null) + { + throw new ArgumentNullException("errorMessage"); + } + ErrorMessage = errorMessage; + } + + public string ErrorMessage { get; private set; } + + public override bool Equals(object obj) + { + InvalidSample other = obj as InvalidSample; + return other != null && ErrorMessage == other.ErrorMessage; + } + + public override int GetHashCode() + { + return ErrorMessage.GetHashCode(); + } + + public override string ToString() + { + return ErrorMessage; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs new file mode 100644 index 0000000000..f121e93ec0 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs @@ -0,0 +1,456 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; +using System.Reflection; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This class will create an object of a given type and populate it with sample data. + /// + public class ObjectGenerator + { + internal const int DefaultCollectionSize = 2; + private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); + + /// + /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: + /// Simple types: , , , , , etc. + /// Complex types: POCO types. + /// Nullables: . + /// Arrays: arrays of simple types or complex types. + /// Key value pairs: + /// Tuples: , , etc + /// Dictionaries: or anything deriving from . + /// Collections: , , , , , or anything deriving from or . + /// Queryables: , . + /// + /// The type. + /// An object of the given type. + public object GenerateObject(Type type) + { + return GenerateObject(type, new Dictionary()); + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] + private object GenerateObject(Type type, Dictionary createdObjectReferences) + { + try + { + if (SimpleTypeObjectGenerator.CanGenerateObject(type)) + { + return SimpleObjectGenerator.GenerateObject(type); + } + + if (type.IsArray) + { + return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); + } + + if (type.IsGenericType) + { + return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); + } + + if (type == typeof(IDictionary)) + { + return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); + } + + if (typeof(IDictionary).IsAssignableFrom(type)) + { + return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); + } + + if (type == typeof(IList) || + type == typeof(IEnumerable) || + type == typeof(ICollection)) + { + return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); + } + + if (typeof(IList).IsAssignableFrom(type)) + { + return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); + } + + if (type == typeof(IQueryable)) + { + return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); + } + + if (type.IsEnum) + { + return GenerateEnum(type); + } + + if (type.IsPublic || type.IsNestedPublic) + { + return GenerateComplexObject(type, createdObjectReferences); + } + } + catch + { + // Returns null if anything fails + return null; + } + + return null; + } + + private static object GenerateGenericType(Type type, int collectionSize, Dictionary createdObjectReferences) + { + Type genericTypeDefinition = type.GetGenericTypeDefinition(); + if (genericTypeDefinition == typeof(Nullable<>)) + { + return GenerateNullable(type, createdObjectReferences); + } + + if (genericTypeDefinition == typeof(KeyValuePair<,>)) + { + return GenerateKeyValuePair(type, createdObjectReferences); + } + + if (IsTuple(genericTypeDefinition)) + { + return GenerateTuple(type, createdObjectReferences); + } + + Type[] genericArguments = type.GetGenericArguments(); + if (genericArguments.Length == 1) + { + if (genericTypeDefinition == typeof(IList<>) || + genericTypeDefinition == typeof(IEnumerable<>) || + genericTypeDefinition == typeof(ICollection<>)) + { + Type collectionType = typeof(List<>).MakeGenericType(genericArguments); + return GenerateCollection(collectionType, collectionSize, createdObjectReferences); + } + + if (genericTypeDefinition == typeof(IQueryable<>)) + { + return GenerateQueryable(type, collectionSize, createdObjectReferences); + } + + Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); + if (closedCollectionType.IsAssignableFrom(type)) + { + return GenerateCollection(type, collectionSize, createdObjectReferences); + } + } + + if (genericArguments.Length == 2) + { + if (genericTypeDefinition == typeof(IDictionary<,>)) + { + Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); + return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); + } + + Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); + if (closedDictionaryType.IsAssignableFrom(type)) + { + return GenerateDictionary(type, collectionSize, createdObjectReferences); + } + } + + if (type.IsPublic || type.IsNestedPublic) + { + return GenerateComplexObject(type, createdObjectReferences); + } + + return null; + } + + private static object GenerateTuple(Type type, Dictionary createdObjectReferences) + { + Type[] genericArgs = type.GetGenericArguments(); + object[] parameterValues = new object[genericArgs.Length]; + bool failedToCreateTuple = true; + ObjectGenerator objectGenerator = new ObjectGenerator(); + for (int i = 0; i < genericArgs.Length; i++) + { + parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); + failedToCreateTuple &= parameterValues[i] == null; + } + if (failedToCreateTuple) + { + return null; + } + object result = Activator.CreateInstance(type, parameterValues); + return result; + } + + private static bool IsTuple(Type genericTypeDefinition) + { + return genericTypeDefinition == typeof(Tuple<>) || + genericTypeDefinition == typeof(Tuple<,>) || + genericTypeDefinition == typeof(Tuple<,,>) || + genericTypeDefinition == typeof(Tuple<,,,>) || + genericTypeDefinition == typeof(Tuple<,,,,>) || + genericTypeDefinition == typeof(Tuple<,,,,,>) || + genericTypeDefinition == typeof(Tuple<,,,,,,>) || + genericTypeDefinition == typeof(Tuple<,,,,,,,>); + } + + private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary createdObjectReferences) + { + Type[] genericArgs = keyValuePairType.GetGenericArguments(); + Type typeK = genericArgs[0]; + Type typeV = genericArgs[1]; + ObjectGenerator objectGenerator = new ObjectGenerator(); + object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); + object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); + if (keyObject == null && valueObject == null) + { + // Failed to create key and values + return null; + } + object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); + return result; + } + + private static object GenerateArray(Type arrayType, int size, Dictionary createdObjectReferences) + { + Type type = arrayType.GetElementType(); + Array result = Array.CreateInstance(type, size); + bool areAllElementsNull = true; + ObjectGenerator objectGenerator = new ObjectGenerator(); + for (int i = 0; i < size; i++) + { + object element = objectGenerator.GenerateObject(type, createdObjectReferences); + result.SetValue(element, i); + areAllElementsNull &= element == null; + } + + if (areAllElementsNull) + { + return null; + } + + return result; + } + + private static object GenerateDictionary(Type dictionaryType, int size, Dictionary createdObjectReferences) + { + Type typeK = typeof(object); + Type typeV = typeof(object); + if (dictionaryType.IsGenericType) + { + Type[] genericArgs = dictionaryType.GetGenericArguments(); + typeK = genericArgs[0]; + typeV = genericArgs[1]; + } + + object result = Activator.CreateInstance(dictionaryType); + MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); + MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); + ObjectGenerator objectGenerator = new ObjectGenerator(); + for (int i = 0; i < size; i++) + { + object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); + if (newKey == null) + { + // Cannot generate a valid key + return null; + } + + bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); + if (!containsKey) + { + object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); + addMethod.Invoke(result, new object[] { newKey, newValue }); + } + } + + return result; + } + + private static object GenerateEnum(Type enumType) + { + Array possibleValues = Enum.GetValues(enumType); + if (possibleValues.Length > 0) + { + return possibleValues.GetValue(0); + } + return null; + } + + private static object GenerateQueryable(Type queryableType, int size, Dictionary createdObjectReferences) + { + bool isGeneric = queryableType.IsGenericType; + object list; + if (isGeneric) + { + Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); + list = GenerateCollection(listType, size, createdObjectReferences); + } + else + { + list = GenerateArray(typeof(object[]), size, createdObjectReferences); + } + if (list == null) + { + return null; + } + if (isGeneric) + { + Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); + MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); + return asQueryableMethod.Invoke(null, new[] { list }); + } + + return Queryable.AsQueryable((IEnumerable)list); + } + + private static object GenerateCollection(Type collectionType, int size, Dictionary createdObjectReferences) + { + Type type = collectionType.IsGenericType ? + collectionType.GetGenericArguments()[0] : + typeof(object); + object result = Activator.CreateInstance(collectionType); + MethodInfo addMethod = collectionType.GetMethod("Add"); + bool areAllElementsNull = true; + ObjectGenerator objectGenerator = new ObjectGenerator(); + for (int i = 0; i < size; i++) + { + object element = objectGenerator.GenerateObject(type, createdObjectReferences); + addMethod.Invoke(result, new object[] { element }); + areAllElementsNull &= element == null; + } + + if (areAllElementsNull) + { + return null; + } + + return result; + } + + private static object GenerateNullable(Type nullableType, Dictionary createdObjectReferences) + { + Type type = nullableType.GetGenericArguments()[0]; + ObjectGenerator objectGenerator = new ObjectGenerator(); + return objectGenerator.GenerateObject(type, createdObjectReferences); + } + + private static object GenerateComplexObject(Type type, Dictionary createdObjectReferences) + { + object result = null; + + if (createdObjectReferences.TryGetValue(type, out result)) + { + // The object has been created already, just return it. This will handle the circular reference case. + return result; + } + + if (type.IsValueType) + { + result = Activator.CreateInstance(type); + } + else + { + ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); + if (defaultCtor == null) + { + // Cannot instantiate the type because it doesn't have a default constructor + return null; + } + + result = defaultCtor.Invoke(new object[0]); + } + createdObjectReferences.Add(type, result); + SetPublicProperties(type, result, createdObjectReferences); + SetPublicFields(type, result, createdObjectReferences); + return result; + } + + private static void SetPublicProperties(Type type, object obj, Dictionary createdObjectReferences) + { + PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); + ObjectGenerator objectGenerator = new ObjectGenerator(); + foreach (PropertyInfo property in properties) + { + if (property.CanWrite) + { + object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); + property.SetValue(obj, propertyValue, null); + } + } + } + + private static void SetPublicFields(Type type, object obj, Dictionary createdObjectReferences) + { + FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); + ObjectGenerator objectGenerator = new ObjectGenerator(); + foreach (FieldInfo field in fields) + { + object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); + field.SetValue(obj, fieldValue); + } + } + + private class SimpleTypeObjectGenerator + { + private long _index = 0; + private static readonly Dictionary> DefaultGenerators = InitializeGenerators(); + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] + private static Dictionary> InitializeGenerators() + { + return new Dictionary> + { + { typeof(Boolean), index => true }, + { typeof(Byte), index => (Byte)64 }, + { typeof(Char), index => (Char)65 }, + { typeof(DateTime), index => DateTime.Now }, + { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, + { typeof(DBNull), index => DBNull.Value }, + { typeof(Decimal), index => (Decimal)index }, + { typeof(Double), index => (Double)(index + 0.1) }, + { typeof(Guid), index => Guid.NewGuid() }, + { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, + { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, + { typeof(Int64), index => (Int64)index }, + { typeof(Object), index => new object() }, + { typeof(SByte), index => (SByte)64 }, + { typeof(Single), index => (Single)(index + 0.1) }, + { + typeof(String), index => + { + return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); + } + }, + { + typeof(TimeSpan), index => + { + return TimeSpan.FromTicks(1234567); + } + }, + { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, + { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, + { typeof(UInt64), index => (UInt64)index }, + { + typeof(Uri), index => + { + return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); + } + }, + }; + } + + public static bool CanGenerateObject(Type type) + { + return DefaultGenerators.ContainsKey(type); + } + + public object GenerateObject(Type type) + { + return DefaultGenerators[type](++_index); + } + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/SampleDirection.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/SampleDirection.cs new file mode 100644 index 0000000000..4dcab7c652 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/SampleDirection.cs @@ -0,0 +1,11 @@ +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// Indicates whether the sample is used for request or response + /// + public enum SampleDirection + { + Request = 0, + Response + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/TextSample.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/TextSample.cs new file mode 100644 index 0000000000..7fc791d809 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/SampleGeneration/TextSample.cs @@ -0,0 +1,37 @@ +using System; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. + /// + public class TextSample + { + public TextSample(string text) + { + if (text == null) + { + throw new ArgumentNullException("text"); + } + Text = text; + } + + public string Text { get; private set; } + + public override bool Equals(object obj) + { + TextSample other = obj as TextSample; + return other != null && Text == other.Text; + } + + public override int GetHashCode() + { + return Text.GetHashCode(); + } + + public override string ToString() + { + return Text; + } + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Api.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Api.cshtml new file mode 100644 index 0000000000..277154a65f --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Api.cshtml @@ -0,0 +1,22 @@ +@using System.Web.Http +@using Stride.Metrics.ServerApp.Areas.HelpPage.Models +@model HelpPageApiModel + +@{ + var description = Model.ApiDescription; + ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; +} + + +
+ +
+ @Html.DisplayForModel() +
+
diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml new file mode 100644 index 0000000000..74b645f182 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml @@ -0,0 +1,41 @@ +@using System.Web.Http +@using System.Web.Http.Controllers +@using System.Web.Http.Description +@using Stride.Metrics.ServerApp.Areas.HelpPage +@using Stride.Metrics.ServerApp.Areas.HelpPage.Models +@model IGrouping + +@{ + var controllerDocumentation = ViewBag.DocumentationProvider != null ? + ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : + null; +} + +

@Model.Key.ControllerName

+@if (!String.IsNullOrEmpty(controllerDocumentation)) +{ +

@controllerDocumentation

+} + + + + + + @foreach (var api in Model) + { + + + + + } + +
APIDescription
@api.HttpMethod.Method @api.RelativePath + @if (api.Documentation != null) + { +

@api.Documentation

+ } + else + { +

No documentation available.

+ } +
\ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml new file mode 100644 index 0000000000..8a72319ccb --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml @@ -0,0 +1,6 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model CollectionModelDescription +@if (Model.ElementDescription is ComplexTypeModelDescription) +{ + @Html.DisplayFor(m => m.ElementDescription) +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml new file mode 100644 index 0000000000..c21a5e6ec1 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml @@ -0,0 +1,3 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model ComplexTypeModelDescription +@Html.DisplayFor(m => m.Properties, "Parameters") \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml new file mode 100644 index 0000000000..0ac14e222a --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml @@ -0,0 +1,4 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model DictionaryModelDescription +Dictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] +and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml new file mode 100644 index 0000000000..c79068bf8b --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml @@ -0,0 +1,24 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model EnumTypeModelDescription + +

Possible enumeration values:

+ + + + + + + @foreach (EnumValueDescription value in Model.Values) + { + + + + + + } + +
NameValueDescription
@value.Name +

@value.Value

+
+

@value.Documentation

+
\ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml new file mode 100644 index 0000000000..01486a5c9a --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml @@ -0,0 +1,67 @@ +@using System.Web.Http +@using System.Web.Http.Description +@using Stride.Metrics.ServerApp.Areas.HelpPage.Models +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model HelpPageApiModel + +@{ + ApiDescription description = Model.ApiDescription; +} +

@description.HttpMethod.Method @description.RelativePath

+
+

@description.Documentation

+ +

Request Information

+ +

URI Parameters

+ @Html.DisplayFor(m => m.UriParameters, "Parameters") + +

Body Parameters

+ +

@Model.RequestDocumentation

+ + @if (Model.RequestModelDescription != null) + { + @Html.DisplayFor(m => m.RequestModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.RequestModelDescription }) + if (Model.RequestBodyParameters != null) + { + @Html.DisplayFor(m => m.RequestBodyParameters, "Parameters") + } + } + else + { +

None.

+ } + + @if (Model.SampleRequests.Count > 0) + { +

Request Formats

+ @Html.DisplayFor(m => m.SampleRequests, "Samples") + } + +

Response Information

+ +

Resource Description

+ +

@description.ResponseDescription.Documentation

+ + @if (Model.ResourceDescription != null) + { + @Html.DisplayFor(m => m.ResourceDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ResourceDescription }) + if (Model.ResourceProperties != null) + { + @Html.DisplayFor(m => m.ResourceProperties, "Parameters") + } + } + else + { +

None.

+ } + + @if (Model.SampleResponses.Count > 0) + { +

Response Formats

+ @Html.DisplayFor(m => m.SampleResponses, "Samples") + } + +
\ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml new file mode 100644 index 0000000000..33347cbfaa --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml @@ -0,0 +1,4 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage +@model ImageSample + + \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml new file mode 100644 index 0000000000..96adc7e51f --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml @@ -0,0 +1,13 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage +@model InvalidSample + +@if (HttpContext.Current.IsDebuggingEnabled) +{ +
+

@Model.ErrorMessage

+
+} +else +{ +

Sample not available.

+} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml new file mode 100644 index 0000000000..1601594f66 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml @@ -0,0 +1,4 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model KeyValuePairModelDescription +Pair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] +and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml new file mode 100644 index 0000000000..60c3a5d22a --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml @@ -0,0 +1,26 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model Type +@{ + ModelDescription modelDescription = ViewBag.modelDescription; + if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription) + { + if (Model == typeof(Object)) + { + @:Object + } + else + { + @Html.ActionLink(modelDescription.Name, "ResourceModel", "Help", new { modelName = modelDescription.Name }, null) + } + } + else if (modelDescription is CollectionModelDescription) + { + var collectionDescription = modelDescription as CollectionModelDescription; + var elementDescription = collectionDescription.ElementDescription; + @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, "ModelDescriptionLink", new { modelDescription = elementDescription }) + } + else + { + @Html.DisplayFor(m => modelDescription) + } +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml new file mode 100644 index 0000000000..0a3f95dd3b --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml @@ -0,0 +1,48 @@ +@using System.Collections.Generic +@using System.Collections.ObjectModel +@using System.Web.Http.Description +@using System.Threading +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model IList + +@if (Model.Count > 0) +{ + + + + + + @foreach (ParameterDescription parameter in Model) + { + ModelDescription modelDescription = parameter.TypeDescription; + + + + + + + } + +
NameDescriptionTypeAdditional information
@parameter.Name +

@parameter.Documentation

+
+ @Html.DisplayFor(m => modelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = modelDescription }) + + @if (parameter.Annotations.Count > 0) + { + foreach (var annotation in parameter.Annotations) + { +

@annotation.Documentation

+ } + } + else + { +

None.

+ } +
+} +else +{ +

None.

+} + diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml new file mode 100644 index 0000000000..c19596fb12 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml @@ -0,0 +1,30 @@ +@using System.Net.Http.Headers +@model Dictionary + +@{ + // Group the samples into a single tab if they are the same. + Dictionary samples = Model.GroupBy(pair => pair.Value).ToDictionary( + pair => String.Join(", ", pair.Select(m => m.Key.ToString()).ToArray()), + pair => pair.Key); + var mediaTypes = samples.Keys; +} +
+ @foreach (var mediaType in mediaTypes) + { +

@mediaType

+
+ Sample: + @{ + var sample = samples[mediaType]; + if (sample == null) + { +

Sample not available.

+ } + else + { + @Html.DisplayFor(s => sample); + } + } +
+ } +
\ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml new file mode 100644 index 0000000000..641578e9f2 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml @@ -0,0 +1,3 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model SimpleTypeModelDescription +@Model.Documentation \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml new file mode 100644 index 0000000000..f17a4586bd --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml @@ -0,0 +1,6 @@ +@using Stride.Metrics.ServerApp.Areas.HelpPage +@model TextSample + +
+@Model.Text
+
\ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Index.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Index.cshtml new file mode 100644 index 0000000000..e023e182ef --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/Index.cshtml @@ -0,0 +1,38 @@ +@using System.Web.Http +@using System.Web.Http.Controllers +@using System.Web.Http.Description +@using System.Collections.ObjectModel +@using Stride.Metrics.ServerApp.Areas.HelpPage.Models +@model Collection + +@{ + ViewBag.Title = "ASP.NET Web API Help Page"; + + // Group APIs by controller + ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor); +} + + +
+
+
+

@ViewBag.Title

+
+
+
+
+ +
+ @foreach (var group in apiGroups) + { + @Html.DisplayFor(m => group, "ApiGroup") + } +
+
diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/ResourceModel.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/ResourceModel.cshtml new file mode 100644 index 0000000000..c874dc7968 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Help/ResourceModel.cshtml @@ -0,0 +1,19 @@ +@using System.Web.Http +@using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions +@model ModelDescription + + +
+ +

@Model.Name

+

@Model.Documentation

+
+ @Html.DisplayFor(m => Model) +
+
diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Shared/_Layout.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Shared/_Layout.cshtml new file mode 100644 index 0000000000..896c833a03 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Shared/_Layout.cshtml @@ -0,0 +1,12 @@ + + + + + + @ViewBag.Title + @RenderSection("scripts", required: false) + + + @RenderBody() + + \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Web.config b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Web.config new file mode 100644 index 0000000000..5ce411ea87 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/Web.config @@ -0,0 +1,41 @@ + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/_ViewStart.cshtml b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/_ViewStart.cshtml new file mode 100644 index 0000000000..a925950837 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/Views/_ViewStart.cshtml @@ -0,0 +1,4 @@ +@{ + // Change the Layout path below to blend the look and feel of the help page with your existing web pages. + Layout = "~/Areas/HelpPage/Views/Shared/_Layout.cshtml"; +} \ No newline at end of file diff --git a/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/XmlDocumentationProvider.cs b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/XmlDocumentationProvider.cs new file mode 100644 index 0000000000..d3d3562ea7 --- /dev/null +++ b/sources/metrics/Stride.Metrics.ServerApp/Areas/HelpPage/XmlDocumentationProvider.cs @@ -0,0 +1,161 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Web.Http.Controllers; +using System.Web.Http.Description; +using System.Xml.XPath; +using Stride.Metrics.ServerApp.Areas.HelpPage.ModelDescriptions; + +namespace Stride.Metrics.ServerApp.Areas.HelpPage +{ + /// + /// A custom that reads the API documentation from an XML documentation file. + /// + public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider + { + private XPathNavigator _documentNavigator; + private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; + private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; + private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; + private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; + private const string ParameterExpression = "param[@name='{0}']"; + + /// + /// Initializes a new instance of the class. + /// + /// The physical path to XML document. + public XmlDocumentationProvider(string documentPath) + { + if (documentPath == null) + { + throw new ArgumentNullException("documentPath"); + } + XPathDocument xpath = new XPathDocument(documentPath); + _documentNavigator = xpath.CreateNavigator(); + } + + public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) + { + XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); + return GetTagValue(typeNode, "summary"); + } + + public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) + { + XPathNavigator methodNode = GetMethodNode(actionDescriptor); + return GetTagValue(methodNode, "summary"); + } + + public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) + { + ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; + if (reflectedParameterDescriptor != null) + { + XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); + if (methodNode != null) + { + string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; + XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); + if (parameterNode != null) + { + return parameterNode.Value.Trim(); + } + } + } + + return null; + } + + public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) + { + XPathNavigator methodNode = GetMethodNode(actionDescriptor); + return GetTagValue(methodNode, "returns"); + } + + public string GetDocumentation(MemberInfo member) + { + string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); + string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; + string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); + XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); + return GetTagValue(propertyNode, "summary"); + } + + public string GetDocumentation(Type type) + { + XPathNavigator typeNode = GetTypeNode(type); + return GetTagValue(typeNode, "summary"); + } + + private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) + { + ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; + if (reflectedActionDescriptor != null) + { + string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); + return _documentNavigator.SelectSingleNode(selectExpression); + } + + return null; + } + + private static string GetMemberName(MethodInfo method) + { + string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); + ParameterInfo[] parameters = method.GetParameters(); + if (parameters.Length != 0) + { + string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); + name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); + } + + return name; + } + + private static string GetTagValue(XPathNavigator parentNode, string tagName) + { + if (parentNode != null) + { + XPathNavigator node = parentNode.SelectSingleNode(tagName); + if (node != null) + { + return node.Value.Trim(); + } + } + + return null; + } + + private XPathNavigator GetTypeNode(Type type) + { + string controllerTypeName = GetTypeName(type); + string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); + return _documentNavigator.SelectSingleNode(selectExpression); + } + + private static string GetTypeName(Type type) + { + string name = type.FullName; + if (type.IsGenericType) + { + // Format the generic type name to something like: Generic{System.Int32,System.String} + Type genericType = type.GetGenericTypeDefinition(); + Type[] genericArguments = type.GetGenericArguments(); + string genericTypeName = genericType.FullName; + + // Trim the generic parameter counts from the name + genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); + string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); + name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); + } + if (type.IsNested) + { + // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. + name = name.Replace("+", "."); + } + + return name; + } + } +} diff --git a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-32.dll b/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-32.dll deleted file mode 100644 index d4ccccf503..0000000000 --- a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-32.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3741446b0ce92e3c066b6825a1d8e777b13c1af0485751dae0b3e99adb84ced6 -size 289792 diff --git a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-64.dll b/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-64.dll deleted file mode 100644 index f6b108f310..0000000000 --- a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/ClearScriptV8-64.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8aad6fca8da8273decda494b149f3aede35e28a9b60f972060bcd7731d077f40 -size 326144 diff --git a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-ia32.dll b/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-ia32.dll deleted file mode 100644 index 80fee80a40..0000000000 --- a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-ia32.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b987252ff38151d40dc6a13a0da1361fc24cc470562a0dd147510a93a888068d -size 4195328 diff --git a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-x64.dll b/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-x64.dll deleted file mode 100644 index 8fe9d2c350..0000000000 --- a/sources/metrics/Stride.Metrics.ServerApp/ClearScript.V8/v8-x64.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:403d24de4adcaab807ae7e2da28f97e4c010aeb4d720732b31df78eaf8db9f9e -size 5370368 diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/alerts.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/alerts.less index 5618bfcec7..bdd0df2025 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/alerts.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/alerts.less @@ -15,10 +15,9 @@ // Headings for larger alerts h4 { margin-top: 0; - // Specified for the h4 to prevent conflicts of changing @headings-color - color: inherit; + color: inherit; // Specified for the h4 to prevent conflicts of changing @headings-color } - + // Provide class for links that match alerts .alert-link { font-weight: @alert-link-font-weight; @@ -29,7 +28,7 @@ > ul { margin-bottom: 0; } - + > p + p { margin-top: 5px; } @@ -39,7 +38,8 @@ // // Expand the right padding and account for the close button's positioning. -.alert-dismissable, // The misspelled .alert-dismissable was deprecated in 3.2.0. +// The misspelled .alert-dismissable was deprecated in 3.2.0. +.alert-dismissable, .alert-dismissible { padding-right: (@alert-padding + 20); diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/badges.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/badges.less index c70bb939eb..be7f8d0cc6 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/badges.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/badges.less @@ -10,11 +10,11 @@ padding: 3px 7px; font-size: @font-size-small; font-weight: @badge-font-weight; - color: @badge-color; line-height: @badge-line-height; - vertical-align: baseline; - white-space: nowrap; + color: @badge-color; text-align: center; + white-space: nowrap; + vertical-align: middle; background-color: @badge-bg; border-radius: @badge-border-radius; diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/bootstrap.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/bootstrap.less index fc07bed9d3..d6161eb2e5 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/bootstrap.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/bootstrap.less @@ -1,3 +1,9 @@ +/*! + * Bootstrap v3.4.1 (https://getbootstrap.com/) + * Copyright 2011-2019 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ + // Core variables and mixins @import "variables.less"; @import "mixins.less"; @@ -5,6 +11,7 @@ // Reset and dependencies @import "normalize.less"; @import "print.less"; +@import "glyphicons.less"; // Core CSS @import "scaffolding.less"; diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/breadcrumbs.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/breadcrumbs.less index cb01d503fb..e4e53961ad 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/breadcrumbs.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/breadcrumbs.less @@ -14,9 +14,9 @@ display: inline-block; + li:before { - content: "@{breadcrumb-separator}\00a0"; // Unicode space added since inline-block means non-collapsing white-space padding: 0 5px; color: @breadcrumb-color; + content: "@{breadcrumb-separator}\00a0"; // Unicode space added since inline-block means non-collapsing white-space } } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/button-groups.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/button-groups.less index 13c1800dea..0472800f16 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/button-groups.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/button-groups.less @@ -1,3 +1,5 @@ +// stylelint-disable selector-no-qualifying-type */ + // // Button groups // -------------------------------------------------- @@ -36,6 +38,7 @@ margin-left: -5px; // Offset the first child's margin &:extend(.clearfix all); + .btn, .btn-group, .input-group { float: left; @@ -58,7 +61,7 @@ .border-right-radius(0); } } -// Need .dropdown-toggle since :last-child doesn't apply given a .dropdown-menu immediately after it +// Need .dropdown-toggle since :last-child doesn't apply, given that a .dropdown-menu is used immediately after it .btn-group > .btn:last-child:not(:first-child), .btn-group > .dropdown-toggle:not(:first-child) { .border-left-radius(0); @@ -102,18 +105,18 @@ // Give the line between buttons some depth .btn-group > .btn + .dropdown-toggle { - padding-left: 8px; padding-right: 8px; + padding-left: 8px; } .btn-group > .btn-lg + .dropdown-toggle { - padding-left: 12px; padding-right: 12px; + padding-left: 12px; } // The clickable button for toggling the menu // Remove the gradient and set the same inset shadow as the :active state .btn-group.open .dropdown-toggle { - .box-shadow(inset 0 3px 5px rgba(0,0,0,.125)); + .box-shadow(inset 0 3px 5px rgba(0, 0, 0, .125)); // Show no shadow for `.btn-link` since it has no other button styles. &.btn-link { @@ -172,12 +175,12 @@ border-radius: 0; } &:first-child:not(:last-child) { - border-top-right-radius: @border-radius-base; + .border-top-radius(@btn-border-radius-base); .border-bottom-radius(0); } &:last-child:not(:first-child) { - border-bottom-left-radius: @border-radius-base; .border-top-radius(0); + .border-bottom-radius(@btn-border-radius-base); } } .btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { @@ -204,8 +207,8 @@ border-collapse: separate; > .btn, > .btn-group { - float: none; display: table-cell; + float: none; width: 1%; } > .btn-group .btn { @@ -236,7 +239,7 @@ input[type="radio"], input[type="checkbox"] { position: absolute; - clip: rect(0,0,0,0); + clip: rect(0, 0, 0, 0); pointer-events: none; } } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/buttons.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/buttons.less index 5a746049e3..17f076bcfb 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/buttons.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/buttons.less @@ -1,3 +1,5 @@ +// stylelint-disable selector-no-qualifying-type + // // Buttons // -------------------------------------------------- @@ -11,13 +13,13 @@ margin-bottom: 0; // For input.btn font-weight: @btn-font-weight; text-align: center; + white-space: nowrap; vertical-align: middle; touch-action: manipulation; cursor: pointer; background-image: none; // Reset unusual Firefox-on-Android default style; see https://github.com/necolas/normalize.css/issues/214 border: 1px solid transparent; - white-space: nowrap; - .button-size(@padding-base-vertical; @padding-base-horizontal; @font-size-base; @line-height-base; @border-radius-base); + .button-size(@padding-base-vertical; @padding-base-horizontal; @font-size-base; @line-height-base; @btn-border-radius-base); .user-select(none); &, @@ -38,19 +40,25 @@ &:active, &.active { - outline: 0; background-image: none; - .box-shadow(inset 0 3px 5px rgba(0,0,0,.125)); + outline: 0; + .box-shadow(inset 0 3px 5px rgba(0, 0, 0, .125)); } &.disabled, &[disabled], fieldset[disabled] & { cursor: @cursor-disabled; - pointer-events: none; // Future-proof disabling of clicks .opacity(.65); .box-shadow(none); } + + a& { + &.disabled, + fieldset[disabled] & { + pointer-events: none; // Future-proof disabling of clicks on `` elements + } + } } @@ -86,8 +94,8 @@ // Make a button look and behave like a link .btn-link { + font-weight: 400; color: @link-color; - font-weight: normal; border-radius: 0; &, @@ -126,14 +134,14 @@ .btn-lg { // line-height: ensure even-numbered height of button next to large input - .button-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @border-radius-large); + .button-size(@padding-large-vertical; @padding-large-horizontal; @font-size-large; @line-height-large; @btn-border-radius-large); } .btn-sm { // line-height: ensure proper height of button next to small input - .button-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @border-radius-small); + .button-size(@padding-small-vertical; @padding-small-horizontal; @font-size-small; @line-height-small; @btn-border-radius-small); } .btn-xs { - .button-size(@padding-xs-vertical; @padding-xs-horizontal; @font-size-small; @line-height-small; @border-radius-small); + .button-size(@padding-xs-vertical; @padding-xs-horizontal; @font-size-small; @line-height-small; @btn-border-radius-small); } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/carousel.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/carousel.less index 4bbe946d3a..1a247958cc 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/carousel.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/carousel.less @@ -1,3 +1,5 @@ +// stylelint-disable media-feature-name-no-unknown + // // Carousel // -------------------------------------------------- @@ -10,12 +12,12 @@ .carousel-inner { position: relative; - overflow: hidden; width: 100%; + overflow: hidden; > .item { - display: none; position: relative; + display: none; .transition(.6s ease-in-out left); // Account for jankitude on images @@ -27,9 +29,9 @@ // WebKit CSS3 transforms for supported devices @media all and (transform-3d), (-webkit-transform-3d) { - .transition-transform(~'0.6s ease-in-out'); - .backface-visibility(~'hidden'); - .perspective(1000); + .transition-transform(~"0.6s ease-in-out"); + .backface-visibility(~"hidden"); + .perspective(1000px); &.next, &.active.right { @@ -93,33 +95,34 @@ .carousel-control { position: absolute; top: 0; - left: 0; bottom: 0; + left: 0; width: @carousel-control-width; - .opacity(@carousel-control-opacity); font-size: @carousel-control-font-size; color: @carousel-control-color; text-align: center; text-shadow: @carousel-text-shadow; + background-color: rgba(0, 0, 0, 0); // Fix IE9 click-thru bug + .opacity(@carousel-control-opacity); // We can't have this transition here because WebKit cancels the carousel // animation if you trip this while in the middle of another animation. // Set gradients for backgrounds &.left { - #gradient > .horizontal(@start-color: rgba(0,0,0,.5); @end-color: rgba(0,0,0,.0001)); + #gradient > .horizontal(@start-color: rgba(0, 0, 0, .5); @end-color: rgba(0, 0, 0, .0001)); } &.right { - left: auto; right: 0; - #gradient > .horizontal(@start-color: rgba(0,0,0,.0001); @end-color: rgba(0,0,0,.5)); + left: auto; + #gradient > .horizontal(@start-color: rgba(0, 0, 0, .0001); @end-color: rgba(0, 0, 0, .5)); } // Hover/focus state &:hover, &:focus { - outline: 0; color: @carousel-control-color; text-decoration: none; + outline: 0; .opacity(.9); } @@ -132,6 +135,7 @@ top: 50%; z-index: 5; display: inline-block; + margin-top: -10px; } .icon-prev, .glyphicon-chevron-left { @@ -145,22 +149,20 @@ } .icon-prev, .icon-next { - width: 20px; + width: 20px; height: 20px; - margin-top: -10px; - line-height: 1; font-family: serif; + line-height: 1; } - .icon-prev { &:before { - content: '\2039';// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039) + content: "\2039";// SINGLE LEFT-POINTING ANGLE QUOTATION MARK (U+2039) } } .icon-next { &:before { - content: '\203a';// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A) + content: "\203a";// SINGLE RIGHT-POINTING ANGLE QUOTATION MARK (U+203A) } } } @@ -176,21 +178,18 @@ left: 50%; z-index: 15; width: 60%; - margin-left: -30%; padding-left: 0; - list-style: none; + margin-left: -30%; text-align: center; + list-style: none; li { display: inline-block; - width: 10px; + width: 10px; height: 10px; margin: 1px; text-indent: -999px; - border: 1px solid @carousel-indicator-border-color; - border-radius: 10px; cursor: pointer; - // IE8-9 hack for event handling // // Internet Explorer 8-9 does not support clicks on elements without a set @@ -201,12 +200,16 @@ // For IE8, we set solid black as it doesn't support `rgba()`. For IE9, we // set alpha transparency for the best results possible. background-color: #000 \9; // IE8 - background-color: rgba(0,0,0,0); // IE9 + background-color: rgba(0, 0, 0, 0); // IE9 + + border: 1px solid @carousel-indicator-border-color; + border-radius: 10px; } + .active { - margin: 0; - width: 12px; + width: 12px; height: 12px; + margin: 0; background-color: @carousel-indicator-active-bg; } } @@ -216,15 +219,16 @@ // Hidden by default for smaller viewports .carousel-caption { position: absolute; - left: 15%; right: 15%; bottom: 20px; + left: 15%; z-index: 10; padding-top: 20px; padding-bottom: 20px; color: @carousel-caption-color; text-align: center; text-shadow: @carousel-text-shadow; + & .btn { text-shadow: none; // No shadow for button elements in carousel-caption } @@ -240,25 +244,25 @@ .glyphicon-chevron-right, .icon-prev, .icon-next { - width: 30px; - height: 30px; - margin-top: -15px; - font-size: 30px; + width: (@carousel-control-font-size * 1.5); + height: (@carousel-control-font-size * 1.5); + margin-top: (@carousel-control-font-size / -2); + font-size: (@carousel-control-font-size * 1.5); } .glyphicon-chevron-left, .icon-prev { - margin-left: -15px; + margin-left: (@carousel-control-font-size / -2); } .glyphicon-chevron-right, .icon-next { - margin-right: -15px; + margin-right: (@carousel-control-font-size / -2); } } // Show and left align the captions .carousel-caption { - left: 20%; right: 20%; + left: 20%; padding-bottom: 30px; } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/close.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/close.less index 6d5bfe087a..48baf355fd 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/close.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/close.less @@ -1,3 +1,5 @@ +// stylelint-disable property-no-vendor-prefix + // // Close icons // -------------------------------------------------- @@ -30,5 +32,6 @@ background: transparent; border: 0; -webkit-appearance: none; + appearance: none; } } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/code.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/code.less index a08b4d48c4..4e07976d54 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/code.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/code.less @@ -27,12 +27,12 @@ kbd { color: @kbd-color; background-color: @kbd-bg; border-radius: @border-radius-small; - box-shadow: inset 0 -1px 0 rgba(0,0,0,.25); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); kbd { padding: 0; font-size: 100%; - font-weight: bold; + font-weight: 700; box-shadow: none; } } @@ -44,9 +44,9 @@ pre { margin: 0 0 (@line-height-computed / 2); font-size: (@font-size-base - 1); // 14px to 13px line-height: @line-height-base; + color: @pre-color; word-break: break-all; word-wrap: break-word; - color: @pre-color; background-color: @pre-bg; border: 1px solid @pre-border-color; border-radius: @border-radius-base; diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/component-animations.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/component-animations.less index 0bcee910ac..4e7cfd0b55 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/component-animations.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/component-animations.less @@ -1,3 +1,5 @@ +// stylelint-disable selector-no-qualifying-type + // // Component animations // -------------------------------------------------- @@ -10,6 +12,7 @@ .fade { opacity: 0; .transition(opacity .15s linear); + &.in { opacity: 1; } diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/dropdowns.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/dropdowns.less index af344607bd..542c00461a 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/dropdowns.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/dropdowns.less @@ -10,9 +10,10 @@ height: 0; margin-left: 2px; vertical-align: middle; - border-top: @caret-width-base dashed; + border-top: @caret-width-base dashed; + border-top: @caret-width-base solid ~"\9"; // IE8 border-right: @caret-width-base solid transparent; - border-left: @caret-width-base solid transparent; + border-left: @caret-width-base solid transparent; } // The dropdown wrapper (div) @@ -37,15 +38,15 @@ min-width: 160px; padding: 5px 0; margin: 2px 0 0; // override default ul - list-style: none; font-size: @font-size-base; text-align: left; // Ensures proper alignment if parent has it changed (e.g., modal footer) + list-style: none; background-color: @dropdown-bg; + background-clip: padding-box; border: 1px solid @dropdown-fallback-border; // IE8 fallback border: 1px solid @dropdown-border; border-radius: @border-radius-base; - .box-shadow(0 6px 12px rgba(0,0,0,.175)); - background-clip: padding-box; + .box-shadow(0 6px 12px rgba(0, 0, 0, .175)); // Aligns the dropdown menu to right // @@ -65,20 +66,17 @@ display: block; padding: 3px 20px; clear: both; - font-weight: normal; + font-weight: 400; line-height: @line-height-base; color: @dropdown-link-color; white-space: nowrap; // prevent links from randomly breaking onto new lines - } -} -// Hover/Focus state -.dropdown-menu > li > a { - &:hover, - &:focus { - text-decoration: none; - color: @dropdown-link-hover-color; - background-color: @dropdown-link-hover-bg; + &:hover, + &:focus { + color: @dropdown-link-hover-color; + text-decoration: none; + background-color: @dropdown-link-hover-bg; + } } } @@ -89,8 +87,8 @@ &:focus { color: @dropdown-link-active-color; text-decoration: none; - outline: 0; background-color: @dropdown-link-active-bg; + outline: 0; } } @@ -109,10 +107,10 @@ &:hover, &:focus { text-decoration: none; + cursor: @cursor-disabled; background-color: transparent; background-image: none; // Remove CSS gradient .reset-filter(); - cursor: @cursor-disabled; } } @@ -134,8 +132,8 @@ // Add extra class to `.dropdown-menu` to flip the alignment of the dropdown // menu with the parent. .dropdown-menu-right { - left: auto; // Reset the default from `.dropdown-menu` right: 0; + left: auto; // Reset the default from `.dropdown-menu` } // With v3, we enabled auto-flipping if you have a dropdown within a right // aligned nav component. To enable the undoing of that, we provide an override @@ -144,8 +142,8 @@ // This is only for left-aligning a dropdown menu within a `.navbar-right` or // `.pull-right` nav component. .dropdown-menu-left { - left: 0; right: auto; + left: 0; } // Dropdown section headers @@ -161,10 +159,10 @@ // Backdrop to catch body clicks on mobile, etc. .dropdown-backdrop { position: fixed; - left: 0; + top: 0; right: 0; bottom: 0; - top: 0; + left: 0; z-index: (@zindex-dropdown - 10); } @@ -183,9 +181,10 @@ .navbar-fixed-bottom .dropdown { // Reverse the caret .caret { - border-top: 0; - border-bottom: @caret-width-base solid; content: ""; + border-top: 0; + border-bottom: @caret-width-base dashed; + border-bottom: @caret-width-base solid ~"\9"; // IE8 } // Different positioning for bottom up menu .dropdown-menu { diff --git a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/forms.less b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/forms.less index e4b50629e9..edf19bfb6d 100644 --- a/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/forms.less +++ b/sources/metrics/Stride.Metrics.ServerApp/Content/bootstrap/forms.less @@ -1,3 +1,5 @@ +// stylelint-disable selector-no-qualifying-type, property-no-vendor-prefix, media-feature-name-no-vendor-prefix + // // Forms // -------------------------------------------------- @@ -8,13 +10,13 @@ // Restyle and baseline non-control form elements. fieldset { - padding: 0; - margin: 0; - border: 0; // Chrome and Firefox set a `min-width: min-content;` on fieldsets, // so we reset that to ensure it behaves more like a standard block element. // See https://github.com/twbs/bootstrap/issues/12359. min-width: 0; + padding: 0; + margin: 0; + border: 0; } legend { @@ -33,7 +35,7 @@ label { display: inline-block; max-width: 100%; // Force IE8 to wrap long content (see https://github.com/twbs/bootstrap/issues/13141) margin-bottom: 5px; - font-weight: bold; + font-weight: 700; } @@ -43,9 +45,18 @@ label { // is required to ensure optimum display with or without those classes to better // address browser inconsistencies. -// Override content-box in Normalize (* isn't specific enough) input[type="search"] { + // Override content-box in Normalize (* isn't specific enough) .box-sizing(border-box); + + // Search inputs in iOS + // + // This overrides the extra rounded corners on search inputs in iOS so that our + // `.form-control` class can properly style them. Note that this cannot simply + // be added to `.form-control` as it's not specific enough. For details, see + // https://github.com/twbs/bootstrap/issues/11586. + -webkit-appearance: none; + appearance: none; } // Position radios and checkboxes better @@ -54,9 +65,18 @@ input[type="checkbox"] { margin: 4px 0 0; margin-top: 1px \9; // IE8-9 line-height: normal; + + // Apply same disabled cursor tweak as for inputs + // Some special care is needed because "; - return div.firstChild.getAttribute("href") === "#" ; -}) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; -}) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( div ) { - return div.getAttribute("disabled") == null; -}) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); -} - -return Sizzle; - -})( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - - -var rneedsContext = jQuery.expr.match.needsContext; - -var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); - - - -var risSimple = /^.[^:#\[\.,]*$/; - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - }); - - } - - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - }); - - } - - if ( typeof qualifier === "string" ) { - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - qualifier = jQuery.filter( qualifier, elements ); - } - - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; - }); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - })); -}; - -jQuery.fn.extend({ - find: function( selector ) { - var i, - len = this.length, - ret = [], - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); - } - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, - filter: function( selector ) { - return this.pushStack( winnow(this, selector || [], false) ); - }, - not: function( selector ) { - return this.pushStack( winnow(this, selector || [], true) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -}); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - init = jQuery.fn.init = function( selector, context ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Support: Blackberry 4.6 - // gEBID returns nodes no longer in the document (#6963) - if ( elem && elem.parentNode ) { - // Inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return typeof rootjQuery.ready !== "undefined" ? - rootjQuery.ready( selector ) : - // Execute immediately if ready is not present - selector( jQuery ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.extend({ - dir: function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; - }, - - sibling: function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; - } -}); - -jQuery.fn.extend({ - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter(function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { - // Always skip document fragments - if ( cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors)) ) { - - matched.push( cur ); - break; - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.unique( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } -}); - -function sibling( cur, dir ) { - while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return elem.contentDocument || jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.unique( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -}); -var rnotwhite = (/\S+/g); - - - -// String to Object options format cache -var optionsCache = {}; - -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( list && ( !fired || stack ) ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -jQuery.extend({ - - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // Add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } - } - } - - // If we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -}); - - -// The deferred used on DOM ready -var readyList; - -jQuery.fn.ready = function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; -}; - -jQuery.extend({ - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.triggerHandler ) { - jQuery( document ).triggerHandler( "ready" ); - jQuery( document ).off( "ready" ); - } - } -}); - -/** - * The ready event handler and self cleanup method - */ -function completed() { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - jQuery.ready(); -} - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // We once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - } - } - return readyList.promise( obj ); -}; - -// Kick off the DOM ready check even if the user does not -jQuery.ready.promise(); - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - len ? fn( elems[0], key ) : emptyGet; -}; - - -/** - * Determines whether an object can have data - */ -jQuery.acceptData = function( owner ) { - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - /* jshint -W018 */ - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - -function Data() { - // Support: Android<4, - // Old WebKit does not have Object.preventExtensions/freeze method, - // return new empty object instead with no [[set]] accessor - Object.defineProperty( this.cache = {}, 0, { - get: function() { - return {}; - } - }); - - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; -Data.accepts = jQuery.acceptData; - -Data.prototype = { - key: function( owner ) { - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return the key for a frozen object. - if ( !Data.accepts( owner ) ) { - return 0; - } - - var descriptor = {}, - // Check if the owner object already has a cache key - unlock = owner[ this.expando ]; - - // If not, create one - if ( !unlock ) { - unlock = Data.uid++; - - // Secure it in a non-enumerable, non-writable property - try { - descriptor[ this.expando ] = { value: unlock }; - Object.defineProperties( owner, descriptor ); - - // Support: Android<4 - // Fallback to a less secure definition - } catch ( e ) { - descriptor[ this.expando ] = unlock; - jQuery.extend( owner, descriptor ); - } - } - - // Ensure the cache object - if ( !this.cache[ unlock ] ) { - this.cache[ unlock ] = {}; - } - - return unlock; - }, - set: function( owner, data, value ) { - var prop, - // There may be an unlock assigned to this node, - // if there is no entry for this "owner", create one inline - // and set the unlock as though an owner entry had always existed - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - // Handle: [ owner, key, value ] args - if ( typeof data === "string" ) { - cache[ data ] = value; - - // Handle: [ owner, { properties } ] args - } else { - // Fresh assignments by object are shallow copied - if ( jQuery.isEmptyObject( cache ) ) { - jQuery.extend( this.cache[ unlock ], data ); - // Otherwise, copy the properties one-by-one to the cache object - } else { - for ( prop in data ) { - cache[ prop ] = data[ prop ]; - } - } - } - return cache; - }, - get: function( owner, key ) { - // Either a valid cache is found, or will be created. - // New caches will be created and the unlock returned, - // allowing direct access to the newly created - // empty data object. A valid owner object must be provided. - var cache = this.cache[ this.key( owner ) ]; - - return key === undefined ? - cache : cache[ key ]; - }, - access: function( owner, key, value ) { - var stored; - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ((key && typeof key === "string") && value === undefined) ) { - - stored = this.get( owner, key ); - - return stored !== undefined ? - stored : this.get( owner, jQuery.camelCase(key) ); - } - - // [*]When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, name, camel, - unlock = this.key( owner ), - cache = this.cache[ unlock ]; - - if ( key === undefined ) { - this.cache[ unlock ] = {}; - - } else { - // Support array or space separated string of keys - if ( jQuery.isArray( key ) ) { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = key.concat( key.map( jQuery.camelCase ) ); - } else { - camel = jQuery.camelCase( key ); - // Try the string as a key before any manipulation - if ( key in cache ) { - name = [ key, camel ]; - } else { - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - name = camel; - name = name in cache ? - [ name ] : ( name.match( rnotwhite ) || [] ); - } - } - - i = name.length; - while ( i-- ) { - delete cache[ name[ i ] ]; - } - } - }, - hasData: function( owner ) { - return !jQuery.isEmptyObject( - this.cache[ owner[ this.expando ] ] || {} - ); - }, - discard: function( owner ) { - if ( owner[ this.expando ] ) { - delete this.cache[ owner[ this.expando ] ]; - } - } -}; -var data_priv = new Data(); - -var data_user = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /([A-Z])/g; - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - data_user.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend({ - hasData: function( elem ) { - return data_user.hasData( elem ) || data_priv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return data_user.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - data_user.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to data_priv methods, these can be deprecated. - _data: function( elem, name, data ) { - return data_priv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - data_priv.remove( elem, name ); - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = data_user.get( elem ); - - if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE11+ - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice(5) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - data_priv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - data_user.set( this, key ); - }); - } - - return access( this, function( value ) { - var data, - camelKey = jQuery.camelCase( key ); - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - // Attempt to get data from the cache - // with the key as-is - data = data_user.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to get data from the cache - // with the key camelized - data = data_user.get( elem, camelKey ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, camelKey, undefined ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each(function() { - // First, attempt to store a copy or reference of any - // data that might've been store with a camelCased key. - var data = data_user.get( this, camelKey ); - - // For HTML5 data-* attribute interop, we have to - // store property names with dashes in a camelCase form. - // This might not apply to all properties...* - data_user.set( this, camelKey, value ); - - // *... In the case of properties that might _actually_ - // have dashes, we need to also store a copy of that - // unchanged property. - if ( key.indexOf("-") !== -1 && data !== undefined ) { - data_user.set( this, key, value ); - } - }); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each(function() { - data_user.remove( this, key ); - }); - } -}); - - -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = data_priv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray( data ) ) { - queue = data_priv.access( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return data_priv.get( elem, key ) || data_priv.access( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - data_priv.remove( elem, [ type + "queue", key ] ); - }) - }); - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = data_priv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -}); -var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var isHidden = function( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); - }; - -var rcheckableType = (/^(?:checkbox|radio)$/i); - - - -(function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Safari<=5.1 - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Safari<=5.1, Android<4.2 - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE<=11+ - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; -})(); -var strundefined = typeof undefined; - - - -support.focusinBubbles = "onfocusin" in window; - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = data_priv.hasData( elem ) && data_priv.get( elem ); - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - data_priv.remove( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && jQuery.acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && - jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, j, ret, matched, handleObj, - handlerQueue = [], - args = slice.call( arguments ), - handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, matches, sel, handleObj, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.disabled !== true || event.type !== "click" ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); - } - - return handlerQueue; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: Cordova 2.5 (WebKit) (#13255) - // All events should have a target; Cordova deviceready doesn't - if ( !event.target ) { - event.target = document; - } - - // Support: Safari 6.0+, Chrome<28 - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } -}; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - // Support: Android<4.0 - src.returnValue === false ? - returnTrue : - returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && e.preventDefault ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && e.stopPropagation ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && e.stopImmediatePropagation ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -// Support: Chrome 15+ -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// Support: Firefox, Chrome, Safari -// Create "bubbling" focus and blur events -if ( !support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = data_priv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = data_priv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - data_priv.remove( doc, fix ); - - } else { - data_priv.access( doc, fix, attaches ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -}); - - -var - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rhtml = /<|&#?\w+;/, - rnoInnerhtml = /<(?:script|style|link)/i, - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /^$|\/(?:java|ecma)script/i, - rscriptTypeMasked = /^true\/(.*)/, - rcleanScript = /^\s*\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - - // Support: IE9 - option: [ 1, "" ], - - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] - }; - -// Support: IE9 -wrapMap.optgroup = wrapMap.option; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// Support: 1.x compatibility -// Manipulating tables requires a tbody -function manipulationTarget( elem, content ) { - return jQuery.nodeName( elem, "table" ) && - jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? - - elem.getElementsByTagName("tbody")[0] || - elem.appendChild( elem.ownerDocument.createElement("tbody") ) : - elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; - } else { - elem.removeAttribute("type"); - } - - return elem; -} - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - data_priv.set( - elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) - ); - } -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( data_priv.hasData( src ) ) { - pdataOld = data_priv.access( src ); - pdataCur = data_priv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( data_user.hasData( src ) ) { - udataOld = data_user.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - data_user.set( dest, udataCur ); - } -} - -function getAll( context, tag ) { - var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : - context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : - []; - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], ret ) : - ret; -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - buildFragment: function( elems, context, scripts, selection ) { - var elem, tmp, tag, wrap, contains, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - // Support: QtWebKit, PhantomJS - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement("div") ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: QtWebKit, PhantomJS - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( (elem = nodes[ i++ ]) ) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; - }, - - cleanData: function( elems ) { - var data, elem, type, key, - special = jQuery.event.special, - i = 0; - - for ( ; (elem = elems[ i ]) !== undefined; i++ ) { - if ( jQuery.acceptData( elem ) ) { - key = elem[ data_priv.expando ]; - - if ( key && (data = data_priv.cache[ key ]) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - if ( data_priv.cache[ key ] ) { - // Discard any remaining `private` data - delete data_priv.cache[ key ]; - } - } - } - // Discard any remaining `user` data - delete data_user.cache[ elem[ data_user.expando ] ]; - } - } -}); - -jQuery.fn.extend({ - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each(function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - }); - }, null, value, arguments.length ); - }, - - append: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip( arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - remove: function( selector, keepData /* Internal Use Only */ ) { - var elem, - elems = selector ? jQuery.filter( selector, this ) : this, - i = 0; - - for ( ; (elem = elems[i]) != null; i++ ) { - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - - return this; - }, - - empty: function() { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map(function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1>" ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var arg = arguments[ 0 ]; - - // Make the changes, replacing each context element with the new content - this.domManip( arguments, function( elem ) { - arg = this.parentNode; - - jQuery.cleanData( getAll( this ) ); - - if ( arg ) { - arg.replaceChild( elem, this ); - } - }); - - // Force removal if there was no new content (e.g., from empty arguments) - return arg && (arg.length || arg.nodeType) ? this : this.remove(); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, - - domManip: function( args, callback ) { - - // Flatten any nested arrays - args = concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[ 0 ], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - self.domManip( args, callback ); - }); - } - - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - if ( first ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - // Support: QtWebKit - // jQuery.merge because push.apply(_, arraylike) throws - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( this[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - - if ( node.src ) { - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); - } - } else { - jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); - } - } - } - } - } - } - - return this; - } -}); - -jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: QtWebKit - // .get() because push.apply(_, arraylike) throws - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -}); - - -var iframe, - elemdisplay = {}; - -/** - * Retrieve the actual display of a element - * @param {String} name nodeName of the element - * @param {Object} doc Document object - */ -// Called only from within defaultDisplay -function actualDisplay( name, doc ) { - var style, - elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), - - // getDefaultComputedStyle might be reliably used only on attached element - display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? - - // Use of this method is a temporary fix (more like optimization) until something better comes along, - // since it was removed from specification and supported only in FF - style.display : jQuery.css( elem[ 0 ], "display" ); - - // We don't have any data stored on the element, - // so use "detach" method as fast way to get rid of the element - elem.detach(); - - return display; -} - -/** - * Try to determine the default display value of an element - * @param {String} nodeName - */ -function defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - - // Use the already-created iframe if possible - iframe = (iframe || jQuery( "