before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37 values | quality_score float32 0.07 1 | comment_type stringclasses 9 values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2 classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533 values | repo_stars int64 321 419k | repo_language stringclasses 27 values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bool isAnyBehaviorMissing = false;
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), instrInfos.parameters,
[this, &isAnyBehaviorMissing,
&instrInfos](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
if (ParameterMetadata::IsBehavior(parameterMetadata.GetType())) {
const gd::String &behaviorName = parameterValue.GetPlainString();
const gd::String &actualBehaviorType =
GetObjectsContainersList().GetTypeOfBehaviorInObjectOrGroup(
lastObjectName, behaviorName);
const gd::String &expectedBehaviorType =
parameterMetadata.GetExtraInfo();
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
const auto &objectParameterMetadata =
instrInfos.GetParameter(lastObjectIndex);
// Event-functions crashes if behaviors are missing on some object
// of a group because they lose sight of the original objects.
// Missing behaviors are only "fatal" for ObjectList parameters to
// reduce side effects on built-in functions.
if (objectParameterMetadata.GetType() == "objectList") {
isAnyBehaviorMissing = true;
}
gd::ProjectDiagnostic projectDiagnostic(
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
actualBehaviorType, expectedBehaviorType, lastObjectName);
if (diagnosticReport)
diagnosticReport->Add(projectDiagnostic);
}
}
});
return isAnyBehaviorMissing;
}
/**
* Generate code for an action.
*/
gd::String EventsCodeGenerator::GenerateActionCode(
gd::Instruction& action,
EventsCodeGenerationContext& context,
const gd::String& optionalAsyncCallbackName) {
gd::String actionCode;
const gd::InstructionMetadata& instrInfos =
MetadataProvider::GetActionMetadata(platform, action.GetType());
if (MetadataProvider::IsBadInstructionMetadata(instrInfos)) {
return "/* Unknown instruction - skipped. */";
}
| I think it's safe to stop generating the instruction in this case because:
- the only built-in functions which has an `objectList` and a `behavior` are Physics collision conditions
- the diagnostic report bullied users to make them fix their groups
- the events-functions crashed so it was not usable for them | bool isAnyBehaviorMissing = false;
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), instrInfos.parameters,
[this, &isAnyBehaviorMissing,
&instrInfos](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
if (ParameterMetadata::IsBehavior(parameterMetadata.GetType())) {
const gd::String &behaviorName = parameterValue.GetPlainString();
const gd::String &actualBehaviorType =
GetObjectsContainersList().GetTypeOfBehaviorInObjectOrGroup(
lastObjectName, behaviorName);
const gd::String &expectedBehaviorType =
parameterMetadata.GetExtraInfo();
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
const auto &objectParameterMetadata =
instrInfos.GetParameter(lastObjectIndex);
// Event functions crash if some objects in a group are missing
// the required behaviors, since they lose reference to the original
// objects. Missing behaviors are considered "fatal" only for
// ObjectList parameters, in order to minimize side effects on
// built-in functions.
if (objectParameterMetadata.GetType() == "objectList") {
isAnyBehaviorMissing = true;
}
gd::ProjectDiagnostic projectDiagnostic(
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
actualBehaviorType, expectedBehaviorType, lastObjectName);
if (diagnosticReport)
diagnosticReport->Add(projectDiagnostic);
}
}
});
return isAnyBehaviorMissing;
}
/**
* Generate code for an action.
*/
gd::String EventsCodeGenerator::GenerateActionCode(
gd::Instruction& action,
EventsCodeGenerationContext& context,
const gd::String& optionalAsyncCallbackName) {
gd::String actionCode;
const gd::InstructionMetadata& instrInfos =
MetadataProvider::GetActionMetadata(platform, action.GetType());
if (MetadataProvider::IsBadInstructionMetadata(instrInfos)) {
return "/* Unknown instruction - skipped. */";
| @@ -506,13 +512,24 @@ void EventsCodeGenerator::CheckBehaviorParameters(
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
+ const auto &objectParameterMetadata =
+ instrInfos.GetParameter(lastObjectIndex);
+ // Event-functions crashes if behaviors are missing on some object
+ // of a group because they lose sight of the original objects.
+ // Missing behaviors are only "fatal" for ObjectList parameters to
+ // reduce side effects on built-in functions.
+ if (objectParameterMetadata.GetType() == "objectList") {
+ isAnyBehaviorMissing = true;
+ }
| Core/GDCore/Events/CodeGeneration/EventsCodeGenerator.cpp | 26 | C++ | 0.643 | bug | 312 | 51 | 51 | false | Fix a crash at runtime when behaviors are missing in functions | 7,830 | 4ian/GDevelop | 10,154 | JavaScript | D8H | D8H |
bool EventsCodeGenerator::CheckBehaviorParameters(
const gd::Instruction &instruction,
const gd::InstructionMetadata &instrInfos) {
bool isAnyBehaviorMissing = false;
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), instrInfos.parameters,
[this, &isAnyBehaviorMissing,
&instrInfos](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
if (ParameterMetadata::IsBehavior(parameterMetadata.GetType())) {
const gd::String &behaviorName = parameterValue.GetPlainString();
const gd::String &actualBehaviorType =
GetObjectsContainersList().GetTypeOfBehaviorInObjectOrGroup(
lastObjectName, behaviorName);
const gd::String &expectedBehaviorType =
parameterMetadata.GetExtraInfo();
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
const auto &objectParameterMetadata =
instrInfos.GetParameter(lastObjectIndex);
// Event-functions crashes if behaviors are missing on some object
// of a group because they lose sight of the original objects.
// Missing behaviors are only "fatal" for ObjectList parameters to
// reduce side effects on built-in functions.
if (objectParameterMetadata.GetType() == "objectList") {
isAnyBehaviorMissing = true;
}
gd::ProjectDiagnostic projectDiagnostic(
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
actualBehaviorType, expectedBehaviorType, lastObjectName);
if (diagnosticReport)
diagnosticReport->Add(projectDiagnostic);
}
}
});
return isAnyBehaviorMissing;
}
/**
* Generate code for an action.
*/
gd::String EventsCodeGenerator::GenerateActionCode(
gd::Instruction& action,
EventsCodeGenerationContext& context,
const gd::String& optionalAsyncCallbackName) {
gd::String actionCode;
const gd::InstructionMetadata& instrInfos =
MetadataProvider::GetActionMetadata(platform, action.GetType());
| "Lose sight" is not super clear. Maybe:
```suggestion
// Event functions crash if some objects in a group are missing
// the required behaviors, since they lose reference to the original objects.
// Missing behaviors are considered "fatal" only for ObjectList parameters,
// in order to minimize side effects on built-in functions.
``` | bool EventsCodeGenerator::CheckBehaviorParameters(
const gd::Instruction &instruction,
const gd::InstructionMetadata &instrInfos) {
bool isAnyBehaviorMissing = false;
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), instrInfos.parameters,
[this, &isAnyBehaviorMissing,
&instrInfos](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
if (ParameterMetadata::IsBehavior(parameterMetadata.GetType())) {
const gd::String &behaviorName = parameterValue.GetPlainString();
const gd::String &actualBehaviorType =
GetObjectsContainersList().GetTypeOfBehaviorInObjectOrGroup(
lastObjectName, behaviorName);
const gd::String &expectedBehaviorType =
parameterMetadata.GetExtraInfo();
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
const auto &objectParameterMetadata =
instrInfos.GetParameter(lastObjectIndex);
// Event functions crash if some objects in a group are missing
// the required behaviors, since they lose reference to the original
// objects. Missing behaviors are considered "fatal" only for
// ObjectList parameters, in order to minimize side effects on
// built-in functions.
if (objectParameterMetadata.GetType() == "objectList") {
isAnyBehaviorMissing = true;
}
gd::ProjectDiagnostic projectDiagnostic(
gd::ProjectDiagnostic::ErrorType::MissingBehavior, "",
actualBehaviorType, expectedBehaviorType, lastObjectName);
if (diagnosticReport)
diagnosticReport->Add(projectDiagnostic);
}
}
});
return isAnyBehaviorMissing;
}
/**
* Generate code for an action.
*/
gd::String EventsCodeGenerator::GenerateActionCode(
gd::Instruction& action,
EventsCodeGenerationContext& context,
const gd::String& optionalAsyncCallbackName) {
gd::String actionCode;
const gd::InstructionMetadata& instrInfos =
| @@ -506,13 +512,24 @@ void EventsCodeGenerator::CheckBehaviorParameters(
if (!expectedBehaviorType.empty() &&
actualBehaviorType != expectedBehaviorType) {
+ const auto &objectParameterMetadata =
+ instrInfos.GetParameter(lastObjectIndex);
+ // Event-functions crashes if behaviors are missing on some object
+ // of a group because they lose sight of the original objects.
+ // Missing behaviors are only "fatal" for ObjectList parameters to
+ // reduce side effects on built-in functions.
| Core/GDCore/Events/CodeGeneration/EventsCodeGenerator.cpp | 26 | C++ | 0.857 | bug | 384 | 51 | 51 | false | Fix a crash at runtime when behaviors are missing in functions | 7,830 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
.getOrCreate('top')
.setValue('Z+')
.setLabel(_('3D world top'))
.setType('choice')
.addExtraInfo('Z+')
.addExtraInfo('Y-')
.setGroup(_('Orientation'));
properties
.getOrCreate('elevation')
.setValue('90')
.setLabel(_('Elevation (in degrees)'))
.setType('number')
.setGroup(_('Orientation'))
.setDescription(_('Maximal elevation is reached at 90°.'));
properties
.getOrCreate('rotation')
.setValue('0')
.setLabel(_('Rotation (in degrees)'))
.setType('number')
.setGroup(_('Orientation'));
}
{
const effect = extension
.addEffect('Skybox')
.setFullName(_('Skybox'))
.setDescription(_('A background cube which surrounds the scene.'))
.markAsNotWorkingForObjects()
.markAsOnlyWorkingFor3D()
.addIncludeFile('Extensions/3D/Skybox.js');
const properties = effect.getProperties();
properties
.getOrCreate('xPositive')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Left face (X+)'));
properties
.getOrCreate('xNegative')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Right face (X-)'));
properties
.getOrCreate('yPositive')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Front face (Y+)'));
properties
.getOrCreate('yNegative')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Back face (Y-)'));
properties | See if chatgpt can give you a more user friendly description? | .getOrCreate('top')
.setValue('Z+')
.setLabel(_('3D world top'))
.setType('choice')
.addExtraInfo('Z+')
.addExtraInfo('Y-')
.setGroup(_('Orientation'));
properties
.getOrCreate('elevation')
.setValue('90')
.setLabel(_('Elevation (in degrees)'))
.setType('number')
.setGroup(_('Orientation'))
.setDescription(_('Maximal elevation is reached at 90°.'));
properties
.getOrCreate('rotation')
.setValue('0')
.setLabel(_('Rotation (in degrees)'))
.setType('number')
.setGroup(_('Orientation'));
}
{
const effect = extension
.addEffect('Skybox')
.setFullName(_('Skybox'))
.setDescription(
_('Display a background on a cube surrounding the scene.')
)
.markAsNotWorkingForObjects()
.markAsOnlyWorkingFor3D()
.addIncludeFile('Extensions/3D/Skybox.js');
const properties = effect.getProperties();
properties
.getOrCreate('rightFaceResourceName')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Right face (X+)'));
properties
.getOrCreate('leftFaceResourceName')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Left face (X-)'));
properties
.getOrCreate('bottomFaceResourceName')
.setType('resource')
.addExtraInfo('image')
.setLabel(_('Bottom face (Y+)'));
properties
.getOrCreate('topFaceResourceName')
.setType('resource')
.addExtraInfo('image') | @@ -2063,6 +2063,46 @@ module.exports = {
.setType('number')
.setGroup(_('Orientation'));
}
+ {
+ const effect = extension
+ .addEffect('Skybox')
+ .setFullName(_('Skybox'))
+ .setDescription(_('A background cube which surrounds the scene.')) | Extensions/3D/JsExtension.js | 26 | JavaScript | 0.286 | question | 61 | 51 | 51 | false | Add a skybox filter | 7,843 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
eventsFunctionsExtension={eventsFunctionsExtension}
eventsBasedObject={eventsBasedObject}
eventsBasedObjectVariant={eventsBasedObjectVariant}
layersContainer={this.props.layersContainer}
globalObjectsContainer={this.props.globalObjectsContainer}
objectsContainer={this.props.objectsContainer}
projectScopedContainersAccessor={
projectScopedContainersAccessor
}
initialInstances={initialInstances}
instancesSelection={this.instancesSelection}
onSelectInstances={this._onSelectInstances}
onAddObjectInstance={this.addInstanceOnTheScene}
selectedLayer={this.state.selectedLayer}
editLayer={this.editLayer}
editLayerEffects={this.editLayerEffects}
editInstanceVariables={this.editInstanceVariables}
editObjectByName={this.editObjectByName}
editObjectInPropertiesPanel={this.editObjectInPropertiesPanel}
selectedObjectFolderOrObjectsWithContext={
selectedObjectFolderOrObjectsWithContext
}
onLayerRenamed={this._onLayerRenamed}
onRemoveLayer={this._onRemoveLayer}
onSelectLayer={(layer: string) =>
this.setState({
selectedLayer: layer,
instancesEditorSettings: {
...this.state.instancesEditorSettings,
selectedLayer: layer,
},
})
}
tileMapTileSelection={this.state.tileMapTileSelection}
onSelectTileMapTile={this.onSelectTileMapTile}
onExportAssets={this.openObjectExporterDialog}
onDeleteObjects={this._onDeleteObjects}
getValidatedObjectOrGroupName={
this._getValidatedObjectOrGroupName
}
onCreateObjectGroup={this._createObjectGroup}
onEditObjectGroup={this._editObjectGroup}
onDeleteObjectGroup={this._onDeleteObjectGroup}
onRenameObjectGroup={this._onRenameObjectGroup}
canObjectOrGroupBeGlobal={this.canObjectOrGroupBeGlobal}
updateBehaviorsSharedData={this.updateBehaviorsSharedData}
onEditObject={this.editObject}
onOpenEventBasedObjectEditor={
this.props.onOpenEventBasedObjectEditor
}
onOpenEventBasedObjectVariantEditor={ | you can probably create a method `this._onSelectLayer` that does this logic | onOpenSceneProperties={this.openSceneProperties}
onEditObjectGroup={this._editObjectGroup}
onEditLayerEffects={this.editLayerEffects}
onEditLayer={this.editLayer}
/>
<EditorsDisplay
ref={ref => (this.editorDisplay = ref)}
project={project}
layout={layout}
eventsFunctionsExtension={eventsFunctionsExtension}
eventsBasedObject={eventsBasedObject}
eventsBasedObjectVariant={eventsBasedObjectVariant}
layersContainer={this.props.layersContainer}
globalObjectsContainer={this.props.globalObjectsContainer}
objectsContainer={this.props.objectsContainer}
projectScopedContainersAccessor={
projectScopedContainersAccessor
}
initialInstances={initialInstances}
instancesSelection={this.instancesSelection}
onSelectInstances={this._onSelectInstances}
onAddObjectInstance={this.addInstanceOnTheScene}
selectedLayer={this.state.selectedLayer}
editLayer={this.editLayer}
editLayerEffects={this.editLayerEffects}
editInstanceVariables={this.editInstanceVariables}
editObjectByName={this.editObjectByName}
editObjectInPropertiesPanel={this.editObjectInPropertiesPanel}
selectedObjectFolderOrObjectsWithContext={
selectedObjectFolderOrObjectsWithContext
}
onLayerRenamed={this._onLayerRenamed}
onRemoveLayer={this._onRemoveLayer}
onSelectLayer={this._onSelectLayer}
tileMapTileSelection={this.state.tileMapTileSelection}
onSelectTileMapTile={this.onSelectTileMapTile}
onExportAssets={this.openObjectExporterDialog}
onDeleteObjects={this._onDeleteObjects}
getValidatedObjectOrGroupName={
this._getValidatedObjectOrGroupName
}
onCreateObjectGroup={this._createObjectGroup}
onEditObjectGroup={this._editObjectGroup}
onDeleteObjectGroup={this._onDeleteObjectGroup}
onRenameObjectGroup={this._onRenameObjectGroup}
canObjectOrGroupBeGlobal={this.canObjectOrGroupBeGlobal}
updateBehaviorsSharedData={this.updateBehaviorsSharedData}
onEditObject={this.editObject}
onOpenEventBasedObjectEditor={
this.props.onOpenEventBasedObjectEditor
} | @@ -2044,7 +2049,13 @@ export default class SceneEditor extends React.Component<Props, State> {
onLayerRenamed={this._onLayerRenamed}
onRemoveLayer={this._onRemoveLayer}
onSelectLayer={(layer: string) =>
- this.setState({ selectedLayer: layer })
+ this.setState({ | newIDE/app/src/SceneEditor/index.js | 26 | JavaScript | 0.357 | suggestion | 75 | 51 | 51 | false | fix(instances-editor): persist selected layer across sessions | 7,879 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | Digvijay-x1 |
selectedLayer: string,
tileMapTileSelection: ?TileMapTileSelection,
lastSelectionType: 'instance' | 'object',
|};
type CopyCutPasteOptions = {|
useLastCursorPosition?: boolean,
pasteInTheForeground?: boolean,
|};
const editSceneIconReactNode = <EditSceneIcon />;
export default class SceneEditor extends React.Component<Props, State> {
instancesSelection: InstancesSelection;
contextMenu: ?ContextMenuInterface;
editorDisplay: ?SceneEditorsDisplayInterface;
resourceExternallyChangedCallbackId: ?string;
constructor(props: Props) {
super(props);
this.instancesSelection = new InstancesSelection();
const initialInstancesEditorSettings = props.getInitialInstancesEditorSettings
? props.getInitialInstancesEditorSettings()
: {};
this.state = {
setupGridOpen: false,
scenePropertiesDialogOpen: false,
layersListOpen: false,
onCloseLayerRemoveDialog: null,
layerRemoved: null,
editedLayer: null,
editedLayerInitialTab: 'properties',
isAssetExporterDialogOpen: false,
editedObjectWithContext: null,
editedObjectInitialTab: 'properties',
variablesEditedInstance: null,
newObjectInstanceSceneCoordinates: null,
editedGroup: null,
isCreatingNewGroup: false,
extractAsExternalLayoutDialogOpen: false,
extractAsCustomObjectDialogOpen: false,
instancesEditorSettings: initialInstancesEditorSettings,
history: getHistoryInitialState(props.initialInstances, {
historyMaxSize: 50,
}), | props.getInitialInstancesEditorSettings is guaranteed to be always passed, no need to check for its existence. | selectedLayer: string,
tileMapTileSelection: ?TileMapTileSelection,
lastSelectionType: 'instance' | 'object',
|};
type CopyCutPasteOptions = {|
useLastCursorPosition?: boolean,
pasteInTheForeground?: boolean,
|};
const editSceneIconReactNode = <EditSceneIcon />;
export default class SceneEditor extends React.Component<Props, State> {
instancesSelection: InstancesSelection;
contextMenu: ?ContextMenuInterface;
editorDisplay: ?SceneEditorsDisplayInterface;
resourceExternallyChangedCallbackId: ?string;
constructor(props: Props) {
super(props);
this.instancesSelection = new InstancesSelection();
const initialInstancesEditorSettings = props.getInitialInstancesEditorSettings();
this.state = {
setupGridOpen: false,
scenePropertiesDialogOpen: false,
layersListOpen: false,
onCloseLayerRemoveDialog: null,
layerRemoved: null,
editedLayer: null,
editedLayerInitialTab: 'properties',
isAssetExporterDialogOpen: false,
editedObjectWithContext: null,
editedObjectInitialTab: 'properties',
variablesEditedInstance: null,
newObjectInstanceSceneCoordinates: null,
editedGroup: null,
isCreatingNewGroup: false,
extractAsExternalLayoutDialogOpen: false,
extractAsCustomObjectDialogOpen: false,
instancesEditorSettings: initialInstancesEditorSettings,
history: getHistoryInitialState(props.initialInstances, {
historyMaxSize: 50,
}),
layoutVariablesDialogOpen: false, | @@ -208,6 +208,11 @@ export default class SceneEditor extends React.Component<Props, State> {
super(props);
this.instancesSelection = new InstancesSelection();
+
+ const initialInstancesEditorSettings = props.getInitialInstancesEditorSettings | newIDE/app/src/SceneEditor/index.js | 26 | JavaScript | 0.357 | suggestion | 110 | 51 | 51 | false | fix(instances-editor): persist selected layer across sessions | 7,879 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Digvijay-x1 |
.MarkAsAdvanced();
extension
.AddAction(
"AjoutHasard",
_("Pick a random object"),
_("Pick one object from all the specified objects. When an object "
"is picked, the next conditions and actions of this event work "
"only on that object."),
_("Pick a random _PARAM1_"),
_("Objects"),
"res/actions/ajouthasard24.png",
"res/actions/ajouthasard.png")
.AddCodeOnlyParameter("objectsContext", "")
.AddParameter("objectList", _("Object"))
.MarkAsSimple();
extension
.AddAction(
"PickNearest",
_("Pick nearest object"),
_("Pick the object of this type that is nearest to the specified "
"position. If the condition is inverted, the object farthest from "
"the specified position is picked instead."),
_("Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
_("Objects"),
"res/conditions/distance24.png",
"res/conditions/distance.png")
.AddParameter("objectList", _("Object"))
.AddParameter("expression", _("X position"))
.AddParameter("expression", _("Y position"))
.AddCodeOnlyParameter("conditionInverted", "")
.MarkAsSimple();
extension
.AddAction(
"MoveObjects",
_("Apply movement to all objects"),
_("Moves all objects according to the forces they have. GDevelop "
"calls this action at the end of the events by default."),
_("Apply movement to all objects"),
_("Movement using forces"),
"res/actions/doMove24.png",
"res/actions/doMove.png")
.AddCodeOnlyParameter("currentScene", "")
.SetHelpPath("/tutorials/how-to-move-objects/")
.MarkAsAdvanced();
extension
.AddCondition("SeDirige",
_("An object is moving toward another (using forces)"), | **AddAction**, but the description is about **condition**. | .MarkAsAdvanced();
extension
.AddAction("AjoutHasard",
_("Pick a random object"),
_("Pick one instance from all the specified objects. When an "
"instance is picked, the next conditions and actions of "
"this event work only on that object instance."),
_("Pick a random _PARAM1_"),
_("Objects"),
"res/actions/ajouthasard24.png",
"res/actions/ajouthasard.png")
.AddCodeOnlyParameter("objectsContext", "")
.AddParameter("objectList", _("Object"))
.MarkAsSimple();
extension
.AddAction(
"PickNearest",
_("Pick nearest object"),
_("Pick the instance of this object that is nearest to the specified "
"position."),
_("Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
_("Objects"),
"res/conditions/distance24.png",
"res/conditions/distance.png")
.AddParameter("objectList", _("Object"))
.AddParameter("expression", _("X position"))
.AddParameter("expression", _("Y position"))
.MarkAsSimple();
extension
.AddAction(
"MoveObjects",
_("Apply movement to all objects"),
_("Moves all objects according to the forces they have. GDevelop "
"calls this action at the end of the events by default."),
_("Apply movement to all objects"),
_("Movement using forces"),
"res/actions/doMove24.png",
"res/actions/doMove.png")
.AddCodeOnlyParameter("currentScene", "")
.SetHelpPath("/tutorials/how-to-move-objects/")
.MarkAsAdvanced();
extension
.AddCondition("SeDirige",
_("An object is moving toward another (using forces)"),
_("Check if an object moves toward another.\nThe first "
"object must move."),
_("_PARAM0_ is moving toward _PARAM1_"), | @@ -1645,6 +1664,23 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsBaseObjectExtension(
.AddParameter("objectList", _("Object"))
.MarkAsSimple();
+ extension
+ .AddAction(
+ "PickNearest",
+ _("Pick nearest object"),
+ _("Pick the object of this type that is nearest to the specified "
+ "position. If the condition is inverted, the object farthest from "
+ "the specified position is picked instead."),
+ _("Pick the _PARAM0_ that is nearest to _PARAM1_;_PARAM2_"),
+ _("Objects"),
+ "res/conditions/distance24.png",
+ "res/conditions/distance.png") | Core/GDCore/Extensions/Builtin/BaseObjectExtension.cpp | 26 | C++ | 0.214 | suggestion | 58 | 51 | 51 | false | Add "Pick Nearest" and "Rotate toward object" action | 7,883 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | 4ian |
}
return makeGenericFailure(
`Could not find an object in the asset store to replace "${object_name}" in scene "${scene_name}". Instead, inspect properties of the object and modify it until it matches what you want it to be.`
);
};
const duplicateExistingObject = (duplicatedObjectName: string) => {
const object = objectsContainer.getObject(object_name);
const serializedObject = serializeToJSObject(object);
const duplicatedObject = objectsContainer.insertNewObject(
project,
object.getType(),
duplicatedObjectName,
objectsContainer.getObjectsCount()
);
unserializeFromJSObject(
duplicatedObject,
serializedObject,
'unserializeFrom',
project
);
duplicatedObject.setName(duplicatedObjectName); // Unserialization has overwritten the name.
return makeGenericSuccess(
`Duplicated object "${object.getName()}" as "${duplicatedObject.getName()}".`
);
};
if (shouldReplaceExistingObject) {
// Replace an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(object_name)) {
return createNewObject();
}
return replaceExistingObject();
} else if (duplicatedObjectName) {
// Duplicate an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(object_name)) {
return makeGenericFailure(
`Object with name "${object_name}" does not exist in scene "${scene_name}", cannot duplicate it.`
);
}
return duplicateExistingObject(duplicatedObjectName);
} else {
// Add a new object.
if (objectsContainer.hasObjectNamed(object_name)) {
if (objectsContainer.getObject(object_name).getType() !== object_type) {
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").` | As discussed, reverse this (duplicated_object_name is the source object that will be copied and used as the source for the new one. The new one name is "object_name") | }
return makeGenericFailure(
`Could not find an object in the asset store to replace "${object_name}" in scene "${scene_name}". Instead, inspect properties of the object and modify it until it matches what you want it to be.`
);
};
const duplicateExistingObject = (duplicatedObjectName: string) => {
const object = objectsContainer.getObject(duplicatedObjectName);
const serializedObject = serializeToJSObject(object);
const newObject = objectsContainer.insertNewObject(
project,
object.getType(),
object_name,
objectsContainer.getObjectsCount()
);
unserializeFromJSObject(
newObject,
serializedObject,
'unserializeFrom',
project
);
newObject.setName(object_name); // Unserialization has overwritten the name.
return makeGenericSuccess(
`Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}". The new object "${newObject.getName()}" has the same type, behaviors, properties and effects as the one it was duplicated from.`
);
};
if (shouldReplaceExistingObject) {
// Replace an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(object_name)) {
return createNewObject();
}
return replaceExistingObject();
} else if (duplicatedObjectName) {
// Duplicate an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(duplicatedObjectName)) {
return makeGenericFailure(
`Object with name "${duplicatedObjectName}" does not exist in scene "${scene_name}", cannot duplicate it into ${object_name}.`
);
}
return duplicateExistingObject(duplicatedObjectName);
} else {
// Add a new object.
if (objectsContainer.hasObjectNamed(object_name)) {
if (objectsContainer.getObject(object_name).getType() !== object_type) {
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").` | @@ -662,7 +691,45 @@ const createOrReplaceObject: EditorFunction = {
);
};
- if (!shouldReplaceExistingObject) {
+ const duplicateExistingObject = (duplicatedObjectName: string) => {
+ const object = objectsContainer.getObject(object_name);
+ const serializedObject = serializeToJSObject(object);
+ const duplicatedObject = objectsContainer.insertNewObject(
+ project,
+ object.getType(),
+ duplicatedObjectName,
+ objectsContainer.getObjectsCount()
+ );
+ unserializeFromJSObject(
+ duplicatedObject,
+ serializedObject,
+ 'unserializeFrom',
+ project
+ );
+ duplicatedObject.setName(duplicatedObjectName); // Unserialization has overwritten the name.
+
+ return makeGenericSuccess(
+ `Duplicated object "${object.getName()}" as "${duplicatedObject.getName()}".` | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.429 | refactor | 167 | 51 | 51 | false | Adapt editor function to duplicate object | 7,889 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
}
return makeGenericFailure(
`Could not find an object in the asset store to replace "${object_name}" in scene "${scene_name}". Instead, inspect properties of the object and modify it until it matches what you want it to be.`
);
};
const duplicateExistingObject = (duplicatedObjectName: string) => {
const object = objectsContainer.getObject(duplicatedObjectName);
const serializedObject = serializeToJSObject(object);
const newObject = objectsContainer.insertNewObject(
project,
object.getType(),
object_name,
objectsContainer.getObjectsCount()
);
unserializeFromJSObject(
newObject,
serializedObject,
'unserializeFrom',
project
);
newObject.setName(object_name); // Unserialization has overwritten the name.
return makeGenericSuccess(
`Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}".`
);
};
if (shouldReplaceExistingObject) {
// Replace an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(object_name)) {
return createNewObject();
}
return replaceExistingObject();
} else if (duplicatedObjectName) {
// Duplicate an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(duplicatedObjectName)) {
return makeGenericFailure(
`Object with name "${duplicatedObjectName}" does not exist in scene "${scene_name}", cannot duplicate it into ${object_name}.`
);
}
return duplicateExistingObject(duplicatedObjectName);
} else {
// Add a new object.
if (objectsContainer.hasObjectNamed(object_name)) {
if (objectsContainer.getObject(object_name).getType() !== object_type) {
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").` | ```suggestion
`Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}". The new object "{newObject.getName()}" has the same type, behaviors, properties and effects as the one it was duplicated from.`
``` | }
return makeGenericFailure(
`Could not find an object in the asset store to replace "${object_name}" in scene "${scene_name}". Instead, inspect properties of the object and modify it until it matches what you want it to be.`
);
};
const duplicateExistingObject = (duplicatedObjectName: string) => {
const object = objectsContainer.getObject(duplicatedObjectName);
const serializedObject = serializeToJSObject(object);
const newObject = objectsContainer.insertNewObject(
project,
object.getType(),
object_name,
objectsContainer.getObjectsCount()
);
unserializeFromJSObject(
newObject,
serializedObject,
'unserializeFrom',
project
);
newObject.setName(object_name); // Unserialization has overwritten the name.
return makeGenericSuccess(
`Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}". The new object "${newObject.getName()}" has the same type, behaviors, properties and effects as the one it was duplicated from.`
);
};
if (shouldReplaceExistingObject) {
// Replace an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(object_name)) {
return createNewObject();
}
return replaceExistingObject();
} else if (duplicatedObjectName) {
// Duplicate an existing object, if there is one existing.
if (!objectsContainer.hasObjectNamed(duplicatedObjectName)) {
return makeGenericFailure(
`Object with name "${duplicatedObjectName}" does not exist in scene "${scene_name}", cannot duplicate it into ${object_name}.`
);
}
return duplicateExistingObject(duplicatedObjectName);
} else {
// Add a new object.
if (objectsContainer.hasObjectNamed(object_name)) {
if (objectsContainer.getObject(object_name).getType() !== object_type) {
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").` | @@ -662,7 +691,45 @@ const createOrReplaceObject: EditorFunction = {
);
};
- if (!shouldReplaceExistingObject) {
+ const duplicateExistingObject = (duplicatedObjectName: string) => {
+ const object = objectsContainer.getObject(duplicatedObjectName);
+ const serializedObject = serializeToJSObject(object);
+ const newObject = objectsContainer.insertNewObject(
+ project,
+ object.getType(),
+ object_name,
+ objectsContainer.getObjectsCount()
+ );
+ unserializeFromJSObject(
+ newObject,
+ serializedObject,
+ 'unserializeFrom',
+ project
+ );
+ newObject.setName(object_name); // Unserialization has overwritten the name.
+
+ return makeGenericSuccess(
+ `Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}".` | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.929 | refactor | 227 | 51 | 51 | false | Adapt editor function to duplicate object | 7,889 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
logger.warn(
'Unable to find bitmap font for resource "' + resourceName + '".'
);
return;
}
if (this._loadedFontsData.get(resource)) {
return;
}
try {
const response = await fetch(
this._resourceLoader.getFullUrl(resource.file),
{
credentials: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? // Any resource stored on the GDevelop Cloud buckets needs the "credentials" of the user,
// i.e: its gdevelop.io cookie, to be passed.
'include'
: // For other resources, use "same-origin" as done by default by fetch.
'same-origin',
}
);
const fontDataRaw = await response.text();
// Sanitize : remove the lines staring with #
const sanitizedFontData = fontDataRaw
.split('\n')
.filter((line) => !line.trim().startsWith('#'))
.join('\n');
this._loadedFontsData.set(resource, sanitizedFontData);
} catch (error) {
logger.error(
"Can't fetch the bitmap font file " +
resource.file +
', error: ' +
error
);
}
}
/**
* To be called when the game is disposed.
* Uninstall all the fonts from memory and clear cache of loaded fonts.
*/
dispose(): void {
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
| ```suggestion
// Sanitize: remove lines starting with # (acting as comments)
``` | logger.warn(
'Unable to find bitmap font for resource "' + resourceName + '".'
);
return;
}
if (this._loadedFontsData.get(resource)) {
return;
}
try {
const response = await fetch(
this._resourceLoader.getFullUrl(resource.file),
{
credentials: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? // Any resource stored on the GDevelop Cloud buckets needs the "credentials" of the user,
// i.e: its gdevelop.io cookie, to be passed.
'include'
: // For other resources, use "same-origin" as done by default by fetch.
'same-origin',
}
);
const fontDataRaw = await response.text();
// Sanitize: remove lines starting with # (acting as comments)
const sanitizedFontData = fontDataRaw
.split('\n')
.filter((line) => !line.trim().startsWith('#'))
.join('\n');
this._loadedFontsData.set(resource, sanitizedFontData);
} catch (error) {
logger.error(
"Can't fetch the bitmap font file " +
resource.file +
', error: ' +
error
);
}
}
/**
* To be called when the game is disposed.
* Uninstall all the fonts from memory and clear cache of loaded fonts.
*/
dispose(): void {
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
| @@ -278,8 +278,15 @@ namespace gdjs {
'same-origin',
}
);
- const fontData = await response.text();
- this._loadedFontsData.set(resource, fontData);
+ const fontDataRaw = await response.text();
+
+ // Sanitize : remove the lines staring with # | GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts | 26 | TypeScript | 0.643 | security | 88 | 51 | 51 | false | Sanitize the .fnt before loading in PixiJS | 7,909 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
);
const deleteThisGroup = SafeExtractor.extractBooleanProperty(
changed_group,
'delete_this_group'
);
const objects = SafeExtractor.extractArrayProperty(
changed_group,
'objects'
);
if (groupName === null) {
warnings.push(
`Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
);
return;
}
let foundGroup: gdObjectGroup;
if (!groups.has(groupName)) {
// Create the group if it does not exist yet.
foundGroup = groups.insertNew(groupName, groups.count());
} else {
foundGroup = groups.get(groupName);
}
if (deleteThisGroup) {
foundGroup.delete();
changes.push(
`Deleted group "${groupName}" from scene "${scene_name}".`
);
} else {
if (newGroupName) {
foundGroup.setName(newGroupName);
changes.push(
`Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
);
}
if (objects) {
const newObjectNames = objects
.map(object =>
SafeExtractor.extractStringProperty(object, 'object_name')
)
.filter(Boolean);
// Remove objects that are not in the list, and add new objects.
const currentObjectNames = foundGroup
.getAllObjectsNames()
.toJSArray();
currentObjectNames.forEach(objectName => {
if (!newObjectNames.includes(objectName)) {
foundGroup.removeObject(objectName);
}
}); | This will probably crash the app/mess up the memory because you release an object that is still owned by the list of groups. You need to call `remove` on the ObjectGroupsContainer | }
changes.push(
`Modified "${propertyName}" property of the "${effectName}" effect to "${newValue}".`
);
});
}
if (newlyCreatedEffect) {
const effectMetadata = gd.MetadataProvider.getEffectMetadata(
project.getCurrentPlatform(),
newlyCreatedEffect.getEffectType()
);
if (gd.MetadataProvider.isBadEffectMetadata(effectMetadata)) {
// Should not happen.
} else {
changes.push(
`Created new "${newlyCreatedEffect.getName()}" effect on layer "${layerName}" at position ${new_effect_position ||
0}. It properties are: ${serializeEffectProperties(
newlyCreatedEffect,
effectMetadata
)
// This stringify might not give the prettiest output, this could be improved.
.map(serializedProperty => JSON.stringify(serializedProperty))
.join(', ')}.`
);
}
}
});
}
if (changed_groups) {
const groups = scene.getObjects().getObjectGroups();
changed_groups.forEach(changed_group => {
const groupName = SafeExtractor.extractStringProperty(
changed_group,
'group_name'
);
const newGroupName = SafeExtractor.extractStringProperty(
changed_group,
'new_group_name'
);
const deleteThisGroup = SafeExtractor.extractBooleanProperty(
changed_group,
'delete_this_group'
);
const objects = SafeExtractor.extractArrayProperty(
changed_group,
'objects'
);
if (groupName === null) { | @@ -3891,6 +3934,94 @@ const changeScenePropertiesLayersEffects: EditorFunction = {
});
}
+ if (changed_groups) {
+ const groups = project
+ .getLayout(scene_name)
+ .getObjects()
+ .getObjectGroups();
+ changed_groups.forEach(changed_group => {
+ const groupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'group_name'
+ );
+ const newGroupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'new_group_name'
+ );
+ const deleteThisGroup = SafeExtractor.extractBooleanProperty(
+ changed_group,
+ 'delete_this_group'
+ );
+ const objects = SafeExtractor.extractArrayProperty(
+ changed_group,
+ 'objects'
+ );
+ if (groupName === null) {
+ warnings.push(
+ `Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
+ );
+ return;
+ }
+
+ let foundGroup: gdObjectGroup;
+ if (!groups.has(groupName)) {
+ // Create the group if it does not exist yet.
+ foundGroup = groups.insertNew(groupName, groups.count());
+ } else {
+ foundGroup = groups.get(groupName);
+ }
+
+ if (deleteThisGroup) {
+ foundGroup.delete(); | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.714 | bug | 179 | 51 | 51 | false | New Editor function to update scene groups | 7,910 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
project
.getLayout(scene_name)
.getObjects()
.hasObjectNamed(objectName)
) {
foundGroup.addObject(objectName);
} else {
warnings.push(
`Object "${objectName}" not found in scene "${scene_name}", so it was not added to group "${groupName}".`
);
}
}
});
changes.push(
`Modified objects of group "${groupName}" in scene "${scene_name}".`
);
}
}
});
}
if (changes.length === 0 && warnings.length === 0) {
return {
success: false,
message: 'No changes were made.',
};
} else if (changes.length === 0 && warnings.length > 0) {
return {
success: false,
message:
'No changes were made because of the issues listed in the warnings.',
warnings: warnings.join('\n'),
};
} else if (changes.length > 0 && warnings.length === 0) {
return {
success: true,
message: ['Successfully done the changes.', ...changes].join('\n'),
};
} else {
return {
success: true,
message: [
'Successfully done some changes but some issues were found - see the warnings.',
...changes,
].join('\n'),
warnings: warnings.join('\n'),
};
}
},
};
| Need to do a whole project refactoring, check how it's done for objects. | return;
}
let foundGroup: gdObjectGroup;
if (!groups.has(groupName)) {
// Create the group if it does not exist yet.
foundGroup = groups.insertNew(groupName, groups.count());
} else {
foundGroup = groups.get(groupName);
}
if (deleteThisGroup) {
groups.remove(groupName);
changes.push(
`Deleted group "${groupName}" from scene "${scene_name}".`
);
} else {
if (newGroupName) {
gd.WholeProjectRefactorer.objectOrGroupRenamedInScene(
project,
scene,
foundGroup.getName(),
newGroupName,
/* isObjectGroup=*/ true
);
foundGroup.setName(newGroupName);
changes.push(
`Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
);
}
if (objects) {
const newObjectNames = objects
.map(object =>
SafeExtractor.extractStringProperty(object, 'object_name')
)
.filter(Boolean);
// Remove objects that are not in the list, and add new objects.
const currentObjectNames = foundGroup
.getAllObjectsNames()
.toJSArray();
currentObjectNames.forEach(objectName => {
if (!newObjectNames.includes(objectName)) {
foundGroup.removeObject(objectName);
}
});
const globalObjects = project.getObjects();
const sceneObjects = scene.getObjects();
newObjectNames.forEach(objectName => {
if (!currentObjectNames.includes(objectName)) {
if (
sceneObjects.hasObjectNamed(objectName) || | @@ -3891,6 +3934,94 @@ const changeScenePropertiesLayersEffects: EditorFunction = {
});
}
+ if (changed_groups) {
+ const groups = project
+ .getLayout(scene_name)
+ .getObjects()
+ .getObjectGroups();
+ changed_groups.forEach(changed_group => {
+ const groupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'group_name'
+ );
+ const newGroupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'new_group_name'
+ );
+ const deleteThisGroup = SafeExtractor.extractBooleanProperty(
+ changed_group,
+ 'delete_this_group'
+ );
+ const objects = SafeExtractor.extractArrayProperty(
+ changed_group,
+ 'objects'
+ );
+ if (groupName === null) {
+ warnings.push(
+ `Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
+ );
+ return;
+ }
+
+ let foundGroup: gdObjectGroup;
+ if (!groups.has(groupName)) {
+ // Create the group if it does not exist yet.
+ foundGroup = groups.insertNew(groupName, groups.count());
+ } else {
+ foundGroup = groups.get(groupName);
+ }
+
+ if (deleteThisGroup) {
+ foundGroup.delete();
+ changes.push(
+ `Deleted group "${groupName}" from scene "${scene_name}".`
+ );
+ } else {
+ if (newGroupName) {
+ foundGroup.setName(newGroupName); | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.286 | refactor | 72 | 51 | 51 | false | New Editor function to update scene groups | 7,910 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
} else {
if (newGroupName) {
foundGroup.setName(newGroupName);
changes.push(
`Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
);
}
if (objects) {
const newObjectNames = objects
.map(object =>
SafeExtractor.extractStringProperty(object, 'object_name')
)
.filter(Boolean);
// Remove objects that are not in the list, and add new objects.
const currentObjectNames = foundGroup
.getAllObjectsNames()
.toJSArray();
currentObjectNames.forEach(objectName => {
if (!newObjectNames.includes(objectName)) {
foundGroup.removeObject(objectName);
}
});
newObjectNames.forEach(objectName => {
if (!currentObjectNames.includes(objectName)) {
if (
project
.getLayout(scene_name)
.getObjects()
.hasObjectNamed(objectName)
) {
foundGroup.addObject(objectName);
} else {
warnings.push(
`Object "${objectName}" not found in scene "${scene_name}", so it was not added to group "${groupName}".`
);
}
}
});
changes.push(
`Modified objects of group "${groupName}" in scene "${scene_name}".`
);
}
}
});
}
if (changes.length === 0 && warnings.length === 0) {
return {
success: false,
message: 'No changes were made.',
}; | Let's also handle global objects, which are exposed to the AI. | }
if (changed_groups) {
const groups = scene.getObjects().getObjectGroups();
changed_groups.forEach(changed_group => {
const groupName = SafeExtractor.extractStringProperty(
changed_group,
'group_name'
);
const newGroupName = SafeExtractor.extractStringProperty(
changed_group,
'new_group_name'
);
const deleteThisGroup = SafeExtractor.extractBooleanProperty(
changed_group,
'delete_this_group'
);
const objects = SafeExtractor.extractArrayProperty(
changed_group,
'objects'
);
if (groupName === null) {
warnings.push(
`Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
);
return;
}
let foundGroup: gdObjectGroup;
if (!groups.has(groupName)) {
// Create the group if it does not exist yet.
foundGroup = groups.insertNew(groupName, groups.count());
} else {
foundGroup = groups.get(groupName);
}
if (deleteThisGroup) {
groups.remove(groupName);
changes.push(
`Deleted group "${groupName}" from scene "${scene_name}".`
);
} else {
if (newGroupName) {
gd.WholeProjectRefactorer.objectOrGroupRenamedInScene(
project,
scene,
foundGroup.getName(),
newGroupName,
/* isObjectGroup=*/ true
);
foundGroup.setName(newGroupName); | @@ -3891,6 +3934,94 @@ const changeScenePropertiesLayersEffects: EditorFunction = {
});
}
+ if (changed_groups) {
+ const groups = project
+ .getLayout(scene_name)
+ .getObjects()
+ .getObjectGroups();
+ changed_groups.forEach(changed_group => {
+ const groupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'group_name'
+ );
+ const newGroupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'new_group_name'
+ );
+ const deleteThisGroup = SafeExtractor.extractBooleanProperty(
+ changed_group,
+ 'delete_this_group'
+ );
+ const objects = SafeExtractor.extractArrayProperty(
+ changed_group,
+ 'objects'
+ );
+ if (groupName === null) {
+ warnings.push(
+ `Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
+ );
+ return;
+ }
+
+ let foundGroup: gdObjectGroup;
+ if (!groups.has(groupName)) {
+ // Create the group if it does not exist yet.
+ foundGroup = groups.insertNew(groupName, groups.count());
+ } else {
+ foundGroup = groups.get(groupName);
+ }
+
+ if (deleteThisGroup) {
+ foundGroup.delete();
+ changes.push(
+ `Deleted group "${groupName}" from scene "${scene_name}".`
+ );
+ } else {
+ if (newGroupName) {
+ foundGroup.setName(newGroupName);
+ changes.push(
+ `Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
+ );
+ }
+ if (objects) {
+ const newObjectNames = objects
+ .map(object =>
+ SafeExtractor.extractStringProperty(object, 'object_name')
+ )
+ .filter(Boolean);
+ // Remove objects that are not in the list, and add new objects.
+ const currentObjectNames = foundGroup
+ .getAllObjectsNames()
+ .toJSArray();
+ currentObjectNames.forEach(objectName => {
+ if (!newObjectNames.includes(objectName)) {
+ foundGroup.removeObject(objectName);
+ }
+ });
+ newObjectNames.forEach(objectName => {
+ if (!currentObjectNames.includes(objectName)) {
+ if (
+ project | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.357 | suggestion | 62 | 51 | 51 | false | New Editor function to update scene groups | 7,910 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
foundGroup.getName(),
newGroupName,
/* isObjectGroup=*/ true
);
foundGroup.setName(newGroupName);
changes.push(
`Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
);
}
if (objects) {
const newObjectNames = objects
.map(object =>
SafeExtractor.extractStringProperty(object, 'object_name')
)
.filter(Boolean);
// Remove objects that are not in the list, and add new objects.
const currentObjectNames = foundGroup
.getAllObjectsNames()
.toJSArray();
currentObjectNames.forEach(objectName => {
if (!newObjectNames.includes(objectName)) {
foundGroup.removeObject(objectName);
}
});
const globalObjects = project.getObjects();
const sceneObjects = project.getLayout(scene_name).getObjects();
newObjectNames.forEach(objectName => {
if (!currentObjectNames.includes(objectName)) {
if (
sceneObjects.hasObjectNamed(objectName) ||
globalObjects.hasObjectNamed(objectName)
) {
foundGroup.addObject(objectName);
} else {
warnings.push(
`Object "${objectName}" not found in scene "${scene_name}", so it was not added to group "${groupName}".`
);
}
}
});
changes.push(
`Modified objects of group "${groupName}" in scene "${scene_name}".`
);
}
}
});
// Notify the editor that object groups have been modified
onObjectGroupsModifiedOutsideEditor({
scene,
}); | You already have it?
```suggestion
const sceneObjects = scene.getObjects();
```
I see any get as suspicious if I don't see a check before for existence. | foundGroup.getName(),
newGroupName,
/* isObjectGroup=*/ true
);
foundGroup.setName(newGroupName);
changes.push(
`Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
);
}
if (objects) {
const newObjectNames = objects
.map(object =>
SafeExtractor.extractStringProperty(object, 'object_name')
)
.filter(Boolean);
// Remove objects that are not in the list, and add new objects.
const currentObjectNames = foundGroup
.getAllObjectsNames()
.toJSArray();
currentObjectNames.forEach(objectName => {
if (!newObjectNames.includes(objectName)) {
foundGroup.removeObject(objectName);
}
});
const globalObjects = project.getObjects();
const sceneObjects = scene.getObjects();
newObjectNames.forEach(objectName => {
if (!currentObjectNames.includes(objectName)) {
if (
sceneObjects.hasObjectNamed(objectName) ||
globalObjects.hasObjectNamed(objectName)
) {
foundGroup.addObject(objectName);
} else {
warnings.push(
`Object "${objectName}" not found in scene "${scene_name}", so it was not added to group "${groupName}".`
);
}
}
});
changes.push(
`Modified objects of group "${groupName}" in scene "${scene_name}".`
);
}
}
});
// Notify the editor that object groups have been modified
onObjectGroupsModifiedOutsideEditor({
scene,
}); | @@ -3891,6 +3978,103 @@ const changeScenePropertiesLayersEffects: EditorFunction = {
});
}
+ if (changed_groups) {
+ const groups = scene.getObjects().getObjectGroups();
+ changed_groups.forEach(changed_group => {
+ const groupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'group_name'
+ );
+ const newGroupName = SafeExtractor.extractStringProperty(
+ changed_group,
+ 'new_group_name'
+ );
+ const deleteThisGroup = SafeExtractor.extractBooleanProperty(
+ changed_group,
+ 'delete_this_group'
+ );
+ const objects = SafeExtractor.extractArrayProperty(
+ changed_group,
+ 'objects'
+ );
+ if (groupName === null) {
+ warnings.push(
+ `Missing "group_name" in an item of \`changed_groups\`. It was ignored and not changed. Make sure you follow the exact format for changing group properties.`
+ );
+ return;
+ }
+
+ let foundGroup: gdObjectGroup;
+ if (!groups.has(groupName)) {
+ // Create the group if it does not exist yet.
+ foundGroup = groups.insertNew(groupName, groups.count());
+ } else {
+ foundGroup = groups.get(groupName);
+ }
+
+ if (deleteThisGroup) {
+ groups.remove(groupName);
+ changes.push(
+ `Deleted group "${groupName}" from scene "${scene_name}".`
+ );
+ } else {
+ if (newGroupName) {
+ gd.WholeProjectRefactorer.objectOrGroupRenamedInScene(
+ project,
+ scene,
+ foundGroup.getName(),
+ newGroupName,
+ /* isObjectGroup=*/ true
+ );
+ foundGroup.setName(newGroupName);
+ changes.push(
+ `Renamed group "${groupName}" to "${newGroupName}" in scene "${scene_name}".`
+ );
+ }
+ if (objects) {
+ const newObjectNames = objects
+ .map(object =>
+ SafeExtractor.extractStringProperty(object, 'object_name')
+ )
+ .filter(Boolean);
+ // Remove objects that are not in the list, and add new objects.
+ const currentObjectNames = foundGroup
+ .getAllObjectsNames()
+ .toJSArray();
+ currentObjectNames.forEach(objectName => {
+ if (!newObjectNames.includes(objectName)) {
+ foundGroup.removeObject(objectName);
+ }
+ });
+ const globalObjects = project.getObjects();
+ const sceneObjects = project.getLayout(scene_name).getObjects(); | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.714 | suggestion | 165 | 51 | 51 | false | New Editor function to update scene groups | 7,910 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
ResourcesLoader,
objectConfiguration
);
else if (project.hasEventsBasedObject(objectType)) {
return RenderedCustomObjectInstance.getThumbnail(
project,
ResourcesLoader,
objectConfiguration
);
} else {
return this.renderers['unknownObjectType'].getThumbnail(
project,
ResourcesLoader,
objectConfiguration
);
}
},
createNewUnknownInstanceRenderer: function(
project: gdProject,
instance: gdInitialInstance,
pixiContainer: PIXI.Container
): RenderedInstance | Rendered3DInstance {
return new this.renderers['unknownObjectType'](
project,
instance,
//$FlowFixMe It's ok because RenderedUnknownInstance don't use it.
null,
pixiContainer,
PixiResourcesLoader
);
},
createNewInstanceRenderer: function(
project: gdProject,
instance: gdInitialInstance,
associatedObjectConfiguration: gdObjectConfiguration,
pixiContainer: PIXI.Container,
threeGroup: THREE.Group | null,
getPropertyOverridings: (() => Map<string, string>) | null = null
): RenderedInstance | Rendered3DInstance {
const objectType = associatedObjectConfiguration.getType();
if (threeGroup && this.renderers3D.hasOwnProperty(objectType)) {
return new this.renderers3D[objectType](
project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
} else if (this.renderers.hasOwnProperty(objectType))
return new this.renderers[objectType]( | Might be worth a comment in RenderedUnknownInstance that this thing is null? | ResourcesLoader,
objectConfiguration
);
else if (project.hasEventsBasedObject(objectType)) {
return RenderedCustomObjectInstance.getThumbnail(
project,
ResourcesLoader,
objectConfiguration
);
} else {
return this.renderers['unknownObjectType'].getThumbnail(
project,
ResourcesLoader,
objectConfiguration
);
}
},
createNewUnknownInstanceRenderer: function(
project: gdProject,
instance: gdInitialInstance,
pixiContainer: PIXI.Container
): RenderedInstance | Rendered3DInstance {
return new this.renderers['unknownObjectType'](
project,
instance,
null,
pixiContainer,
PixiResourcesLoader
);
},
createNewInstanceRenderer: function(
project: gdProject,
instance: gdInitialInstance,
associatedObjectConfiguration: gdObjectConfiguration,
pixiContainer: PIXI.Container,
threeGroup: THREE.Group | null,
getPropertyOverridings: (() => Map<string, string>) | null = null
): RenderedInstance | Rendered3DInstance {
const objectType = associatedObjectConfiguration.getType();
if (threeGroup && this.renderers3D.hasOwnProperty(objectType)) {
return new this.renderers3D[objectType](
project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
} else if (this.renderers.hasOwnProperty(objectType))
return new this.renderers[objectType](
project, | @@ -78,6 +78,20 @@ const ObjectsRenderingService = {
);
}
},
+ createNewUnknownInstanceRenderer: function(
+ project: gdProject,
+ instance: gdInitialInstance,
+ pixiContainer: PIXI.Container
+ ): RenderedInstance | Rendered3DInstance {
+ return new this.renderers['unknownObjectType'](
+ project,
+ instance,
+ //$FlowFixMe It's ok because RenderedUnknownInstance don't use it. | newIDE/app/src/ObjectsRendering/ObjectsRenderingService.js | 26 | JavaScript | 0.357 | question | 76 | 51 | 51 | false | Display a placeholder for instances with unknown objects in the editor | 7,933 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").`
);
}
// /!\ Tell the editor that some objects have potentially been modified (and even removed).
// This will force the objects panel to refresh.
onObjectsModifiedOutsideEditor({
scene: layout,
});
return makeGenericSuccess(
`Object with name "${object_name}" already exists, no need to re-create it.`
);
}
return createNewObject();
}
},
};
/**
* Retrieves the properties of a specific object (global or in a scene)
*/
const inspectObjectProperties: EditorFunction = {
renderForEditor: ({ args, editorCallbacks }) => {
const scope = extractRequiredString(args, 'scope');
const scene_name = extractRequiredString(args, 'scene_name');
const object_name = extractRequiredString(args, 'object_name');
const isGlobalObject = scope === 'global';
return {
text: isGlobalObject ? (
<Trans>
Inspecting properties of global object <b>{object_name}</b>.
</Trans>
) : (
<Trans>
Inspecting properties of object <b>{object_name}</b> in scene{' '}
<Link
href="#"
onClick={() =>
editorCallbacks.onOpenLayout(scene_name, {
openEventsEditor: true,
openSceneEditor: true,
focusWhenOpened: 'scene',
})
}
>
{scene_name}
</Link> | For me, this scope should not be needed here: the function itself should do the work of searching the object wherever it is.
This is similar to events btw, you search in scene then in global objects. |
if (!existingObject) {
// No existing object to duplicate, create a new one.
return createNewObject();
}
const objectsContainerWhereObjectWasFound = isGlobalObject
? globalObjects
: layoutObjects;
const targetObjectsContainer =
target_object_scope === 'global'
? globalObjects
: objectsContainerWhereObjectWasFound;
const serializedObject = serializeToJSObject(existingObject);
const newObject = targetObjectsContainer.insertNewObject(
project,
existingObject.getType(),
object_name,
targetObjectsContainer.getObjectsCount()
);
unserializeFromJSObject(
newObject,
serializedObject,
'unserializeFrom',
project
);
newObject.setName(object_name); // Unserialization has overwritten the name.
// /!\ Tell the editor that some objects have potentially been modified (and even removed).
// This will force the objects panel to refresh.
onObjectsModifiedOutsideEditor({
scene: layout,
});
return makeGenericSuccess(
`Duplicated object "${duplicatedObjectName}" as "${newObject.getName()}". The new object "${newObject.getName()}" has the same type, behaviors, properties and effects as the one it was duplicated from.`
);
};
if (shouldReplaceExistingObject) {
return replaceExistingObject();
} else if (duplicatedObjectName) {
return duplicateExistingObject(duplicatedObjectName);
} else {
return createNewObject();
}
},
};
/**
* Retrieves the properties of a specific object (global or in a scene) | @@ -790,15 +817,22 @@ const createOrReplaceObject: EditorFunction = {
};
/**
- * Retrieves the properties of a specific object in a scene
+ * Retrieves the properties of a specific object (global or in a scene)
*/
const inspectObjectProperties: EditorFunction = {
renderForEditor: ({ args, editorCallbacks }) => {
+ const scope = extractRequiredString(args, 'scope'); | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.5 | suggestion | 201 | 51 | 51 | false | Object Editor Functions handle global scope | 7,959 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
!objectConfiguration.updateProperty(
foundPropertyName,
sanitizePropertyNewValue(foundProperty, newValue)
)
) {
warnings.push(
`Could not change property "${foundPropertyName}" of object "${object_name}". The value might be invalid, of the wrong type or not allowed.`
);
return;
}
changes.push(
`Changed property "${foundPropertyName}" of object "${object_name}" to "${newValue}".`
);
});
return makeMultipleChangesOutput(changes, warnings);
},
};
/**
* Adds a behavior to an object in a scene
*/
const addBehavior: EditorFunction = {
renderForEditor: ({ project, args, editorCallbacks }) => {
const scope = extractRequiredString(args, 'scope');
const scene_name = extractRequiredString(args, 'scene_name');
const object_name = extractRequiredString(args, 'object_name');
const behavior_type = extractRequiredString(args, 'behavior_type');
const optionalBehaviorName = SafeExtractor.extractStringProperty(
args,
'behavior_name'
);
const isGlobalObject = scope === 'global';
const makeText = (behaviorTypeLabel: string) => {
return {
text: isGlobalObject ? (
<Trans>
Add behavior {behaviorName} (<b>{behaviorTypeLabel}</b>) on global
object <b>{object_name}</b>.
</Trans>
) : (
<Trans>
Add behavior {behaviorName} (<b>{behaviorTypeLabel}</b>) on object{' '}
<b>{object_name}</b> in scene{' '}
<Link
href="#"
onClick={() =>
editorCallbacks.onOpenLayout(scene_name, { | Same as the other, the name should be enough | const objectConfiguration = object.getConfiguration();
const objectProperties = objectConfiguration.getProperties();
const { foundPropertyName, foundProperty } = findPropertyByName({
properties: objectProperties,
name: propertyName,
});
if (!foundPropertyName) {
warnings.push(
`Property not found: ${propertyName} on object ${object_name}.`
);
return;
}
if (
!objectConfiguration.updateProperty(
foundPropertyName,
sanitizePropertyNewValue(foundProperty, newValue)
)
) {
warnings.push(
`Could not change property "${foundPropertyName}" of object "${object_name}". The value might be invalid, of the wrong type or not allowed.`
);
return;
}
changes.push(
`Changed property "${foundPropertyName}" of object "${object_name}" to "${newValue}".`
);
});
return makeMultipleChangesOutput(changes, warnings);
},
};
/**
* Adds a behavior to an object in a scene
*/
const addBehavior: EditorFunction = {
renderForEditor: ({ project, args, editorCallbacks }) => {
const scene_name = extractRequiredString(args, 'scene_name');
const object_name = extractRequiredString(args, 'object_name');
const behavior_type = extractRequiredString(args, 'behavior_type');
const optionalBehaviorName = SafeExtractor.extractStringProperty(
args,
'behavior_name'
);
const makeText = (behaviorTypeLabel: string) => {
return { | @@ -1150,6 +1212,7 @@ const changeObjectProperty: EditorFunction = {
*/
const addBehavior: EditorFunction = {
renderForEditor: ({ project, args, editorCallbacks }) => {
+ const scope = extractRequiredString(args, 'scope'); | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.143 | suggestion | 44 | 51 | 51 | false | Object Editor Functions handle global scope | 7,959 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
return renderChanges(changes);
},
launchFunction: async ({ project, args }) => {
const scene_name = extractRequiredString(args, 'scene_name');
const object_name = extractRequiredString(args, 'object_name');
const changed_properties =
SafeExtractor.extractArrayProperty(args, 'changed_properties') || [];
if (!project.hasLayoutNamed(scene_name)) {
return makeGenericFailure(`Scene not found: "${scene_name}".`);
}
const layout = project.getLayout(scene_name);
const layoutObjects = layout.getObjects();
const globalObjects = project.getObjects();
let object: gdObject | null = null;
let isGlobalObject = false;
if (layoutObjects.hasObjectNamed(object_name)) {
object = layoutObjects.getObject(object_name);
} else if (globalObjects.hasObjectNamed(object_name)) {
object = globalObjects.getObject(object_name);
}
if (!object) {
return makeGenericFailure(
`Object not found: "${object_name}" in scene "${scene_name}", nor in the global objects.`
);
}
const warnings = [];
const changes = [];
changed_properties.forEach(changed_property => {
if (!object) return;
const propertyName = SafeExtractor.extractStringProperty(
changed_property,
'property_name'
);
const newValue = SafeExtractor.extractStringProperty(
changed_property,
'new_value'
);
if (propertyName === null || newValue === null) {
warnings.push(
`Missing "property_name" or "new_value" in an item of \`changed_properties\`: ${JSON.stringify(
changed_property
)}. It was ignored and not changed.`
); | This seems to be always left at false and so will break when trying to refactor the project for a global object? |
return {
label: foundProperty ? foundProperty.getLabel() : propertyName,
newValue: newValue,
};
})
.filter(Boolean);
return renderChanges(changes);
},
launchFunction: async ({ project, args }) => {
const scene_name = extractRequiredString(args, 'scene_name');
const object_name = extractRequiredString(args, 'object_name');
const changed_properties =
SafeExtractor.extractArrayProperty(args, 'changed_properties') || [];
if (!project.hasLayoutNamed(scene_name)) {
return makeGenericFailure(`Scene not found: "${scene_name}".`);
}
const layout = project.getLayout(scene_name);
const layoutObjects = layout.getObjects();
const globalObjects = project.getObjects();
let object: gdObject | null = null;
let isGlobalObject = false;
if (layoutObjects.hasObjectNamed(object_name)) {
object = layoutObjects.getObject(object_name);
} else if (globalObjects.hasObjectNamed(object_name)) {
object = globalObjects.getObject(object_name);
isGlobalObject = true;
}
if (!object) {
return makeGenericFailure(
`Object not found: "${object_name}" in scene "${scene_name}", nor in the global objects.`
);
}
const warnings = [];
const changes = [];
changed_properties.forEach(changed_property => {
if (!object) return;
const propertyName = SafeExtractor.extractStringProperty(
changed_property,
'property_name'
);
const newValue = SafeExtractor.extractStringProperty( | @@ -1019,15 +1087,16 @@ const changeObjectProperty: EditorFunction = {
}
const layout = project.getLayout(scene_name);
+ const layoutObjects = layout.getObjects();
+ const globalObjects = project.getObjects();
- let isGlobalObject = false;
let object: gdObject | null = null;
+ let isGlobalObject = false; | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.429 | refactor | 112 | 51 | 51 | false | Object Editor Functions handle global scope | 7,959 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
', '
)}.`;
return propertiesText;
};
const createNewObject = async () => {
// Check if object already exists.
let existingObject: gdObject | null = null;
if (layoutObjects.hasObjectNamed(object_name)) {
existingObject = layoutObjects.getObject(object_name);
} else if (globalObjects.hasObjectNamed(object_name)) {
existingObject = globalObjects.getObject(object_name);
}
if (existingObject) {
if (existingObject.getType() !== object_type) {
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").`
);
}
// /!\ Tell the editor that some objects have potentially been modified (and even removed).
// This will force the objects panel to refresh.
onObjectsModifiedOutsideEditor({
scene: layout,
});
return makeGenericSuccess(
`Object with name "${object_name}" already exists, no need to re-create it.`
);
}
const targetObjectsContainer =
target_object_scope === 'global' ? globalObjects : layoutObjects;
// First try to search and install an object from the asset store.
try {
const { status, message, createdObjects } = await searchAndInstallAsset(
{
objectsContainer: targetObjectsContainer,
objectName: object_name,
objectType: object_type,
searchTerms: search_terms || '',
description: description || '',
twoDimensionalViewKind: two_dimensional_view_kind || '',
}
);
if (status === 'error') {
return makeGenericFailure(
`Unable to search and install object (${message}).`
); | Might be worth writing something like
```suggestion
`Object with name "${object_name}" already exists globally but with a different type ("${object_type}").`
```
(needs a boolean to remember or check where it's coming from, but worth it I think for a LLM that is freaking out) | ', '
)}.`;
return propertiesText;
};
const createNewObject = async () => {
// Check if object already exists.
let existingObject: gdObject | null = null;
let isGlobalObject = false;
if (layoutObjects.hasObjectNamed(object_name)) {
existingObject = layoutObjects.getObject(object_name);
} else if (globalObjects.hasObjectNamed(object_name)) {
existingObject = globalObjects.getObject(object_name);
isGlobalObject = true;
}
if (existingObject) {
if (existingObject.getType() !== object_type) {
if (isGlobalObject) {
return makeGenericFailure(
`Object with name "${object_name}" already exists globally but with a different type ("${object_type}").`
);
}
return makeGenericFailure(
`Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").`
);
}
// /!\ Tell the editor that some objects have potentially been modified (and even removed).
// This will force the objects panel to refresh.
onObjectsModifiedOutsideEditor({
scene: layout,
});
return makeGenericSuccess(
`Object with name "${object_name}" already exists, no need to re-create it.`
);
}
const targetObjectsContainer =
target_object_scope === 'global' ? globalObjects : layoutObjects;
// First try to search and install an object from the asset store.
try {
const { status, message, createdObjects } = await searchAndInstallAsset(
{
objectsContainer: targetObjectsContainer,
objectName: object_name,
objectType: object_type,
searchTerms: search_terms || '',
description: description || '', | @@ -553,11 +558,39 @@ const createOrReplaceObject: EditorFunction = {
};
const createNewObject = async () => {
+ // Check if object already exists.
+ let existingObject: gdObject | null = null;
+
+ if (layoutObjects.hasObjectNamed(object_name)) {
+ existingObject = layoutObjects.getObject(object_name);
+ } else if (globalObjects.hasObjectNamed(object_name)) {
+ existingObject = globalObjects.getObject(object_name);
+ }
+ if (existingObject) {
+ if (existingObject.getType() !== object_type) {
+ return makeGenericFailure(
+ `Object with name "${object_name}" already exists in scene "${scene_name}" but with a different type ("${object_type}").` | newIDE/app/src/EditorFunctions/index.js | 26 | JavaScript | 0.929 | suggestion | 289 | 51 | 51 | false | Object Editor Functions handle global scope | 7,959 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
}
}
/**
* To be called when the game is disposed.
* Uninstall all the fonts from memory and clear cache of loaded fonts.
*/
dispose(): void {
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
this._pixiBitmapFontsInUse = {};
this._pixiBitmapFontsToUninstall.length = 0;
this._loadedFontsData.clear();
}
unloadResource(resourceData: ResourceData): void {
this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
if (bitmapFontInstallKey.startsWith(resourceData.name)) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
delete this._pixiBitmapFontsInUse[bitmapFontInstallKey];
}
}
for (
let index = 0;
index < this._pixiBitmapFontsToUninstall.length;
index++
) {
const bitmapFontInstallKey = this._pixiBitmapFontsToUninstall[index];
if (bitmapFontInstallKey.startsWith(resourceData.name)) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
this._pixiBitmapFontsToUninstall.splice(index, 1);
index--;
}
}
}
}
// Register the class to let the engine use it.
export const BitmapFontManager = gdjs.PixiBitmapFontManager;
export type BitmapFontManager = gdjs.PixiBitmapFontManager;
} | I think that should be
```suggestion
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
```
to avoid issues when a resource name is a prefix of another (not that unlikely, it can happen if a resource name is "MyBitmapText" and another is "MyBitmapTextSpecial" or "MyBitmapText2", etc...) | }
}
/**
* To be called when the game is disposed.
* Uninstall all the fonts from memory and clear cache of loaded fonts.
*/
dispose(): void {
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
this._pixiBitmapFontsInUse = {};
this._pixiBitmapFontsToUninstall.length = 0;
this._loadedFontsData.clear();
}
unloadResource(resourceData: ResourceData): void {
this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
delete this._pixiBitmapFontsInUse[bitmapFontInstallKey];
}
}
for (
let index = 0;
index < this._pixiBitmapFontsToUninstall.length;
index++
) {
const bitmapFontInstallKey = this._pixiBitmapFontsToUninstall[index];
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
this._pixiBitmapFontsToUninstall.splice(index, 1);
index--;
}
}
}
}
// Register the class to let the engine use it.
export const BitmapFontManager = gdjs.PixiBitmapFontManager;
export type BitmapFontManager = gdjs.PixiBitmapFontManager;
} | @@ -316,19 +316,27 @@ namespace gdjs {
}
unloadResource(resourceData: ResourceData): void {
- const loadedFont = this._loadedFontsData.getFromName(resourceData.name);
- if (loadedFont) {
- this._loadedFontsData.delete(resourceData);
- }
+ this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
- if (bitmapFontInstallKey.endsWith(resourceData.file))
+ if (bitmapFontInstallKey.startsWith(resourceData.name)) { | GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts | 26 | TypeScript | 0.857 | suggestion | 310 | 51 | 51 | false | Fix Bitmap text not being displayed after a 1st unload | 7,977 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
this._pixiBitmapFontsInUse = {};
this._pixiBitmapFontsToUninstall.length = 0;
this._loadedFontsData.clear();
}
unloadResource(resourceData: ResourceData): void {
this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
if (bitmapFontInstallKey.startsWith(resourceData.name)) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
delete this._pixiBitmapFontsInUse[bitmapFontInstallKey];
}
}
for (
let index = 0;
index < this._pixiBitmapFontsToUninstall.length;
index++
) {
const bitmapFontInstallKey = this._pixiBitmapFontsToUninstall[index];
if (bitmapFontInstallKey.startsWith(resourceData.name)) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
this._pixiBitmapFontsToUninstall.splice(index, 1);
index--;
}
}
}
}
// Register the class to let the engine use it.
export const BitmapFontManager = gdjs.PixiBitmapFontManager;
export type BitmapFontManager = gdjs.PixiBitmapFontManager;
}
| Same, probably safer to add the delimiter:
```suggestion
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
``` | PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
}
this._pixiBitmapFontsInUse = {};
this._pixiBitmapFontsToUninstall.length = 0;
this._loadedFontsData.clear();
}
unloadResource(resourceData: ResourceData): void {
this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
delete this._pixiBitmapFontsInUse[bitmapFontInstallKey];
}
}
for (
let index = 0;
index < this._pixiBitmapFontsToUninstall.length;
index++
) {
const bitmapFontInstallKey = this._pixiBitmapFontsToUninstall[index];
if (bitmapFontInstallKey.startsWith(resourceData.name + '@')) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
this._pixiBitmapFontsToUninstall.splice(index, 1);
index--;
}
}
}
}
// Register the class to let the engine use it.
export const BitmapFontManager = gdjs.PixiBitmapFontManager;
export type BitmapFontManager = gdjs.PixiBitmapFontManager;
}
| @@ -316,19 +316,27 @@ namespace gdjs {
}
unloadResource(resourceData: ResourceData): void {
- const loadedFont = this._loadedFontsData.getFromName(resourceData.name);
- if (loadedFont) {
- this._loadedFontsData.delete(resourceData);
- }
+ this._loadedFontsData.delete(resourceData);
for (const bitmapFontInstallKey in this._pixiBitmapFontsInUse) {
- if (bitmapFontInstallKey.endsWith(resourceData.file))
+ if (bitmapFontInstallKey.startsWith(resourceData.name)) {
PIXI.BitmapFont.uninstall(bitmapFontInstallKey);
+ delete this._pixiBitmapFontsInUse[bitmapFontInstallKey];
+ }
}
- for (const bitmapFontInstallKey of this._pixiBitmapFontsToUninstall) {
- if (bitmapFontInstallKey.endsWith(resourceData.file))
+ for (
+ let index = 0;
+ index < this._pixiBitmapFontsToUninstall.length;
+ index++
+ ) {
+ const bitmapFontInstallKey = this._pixiBitmapFontsToUninstall[index];
+
+ if (bitmapFontInstallKey.startsWith(resourceData.name)) { | GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts | 26 | TypeScript | 0.714 | suggestion | 132 | 39 | 39 | false | Fix Bitmap text not being displayed after a 1st unload | 7,977 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
const selectedInstanceObjectName = this.instancesSelection
.getSelectedInstances()[0]
.getObjectName();
this.editObjectByName(selectedInstanceObjectName);
};
editLayerEffects = (layer: ?gdLayer) => {
this.setState({ editedLayer: layer, editedLayerInitialTab: 'effects' });
};
editLayer = (layer: ?gdLayer) => {
this.setState({ editedLayer: layer, editedLayerInitialTab: 'properties' });
};
editInstanceVariables = (instance: ?gdInitialInstance) => {
this.setState({ variablesEditedInstance: instance });
};
editLayoutVariables = (open: boolean = true) => {
this.setState({ layoutVariablesDialogOpen: open });
};
editObject = (
editedObject: ?gdObject,
initialTab: ?ObjectEditorTab,
callback?: () => mixed
) => {
const { project } = this.props;
if (editedObject) {
this.setState(
{
editedObjectWithContext: {
object: editedObject,
global: project.getObjects().hasObjectNamed(editedObject.getName()),
},
editedObjectInitialTab: initialTab || 'properties',
},
callback
);
} else {
this.setState(
{
editedObjectWithContext: null,
editedObjectInitialTab: 'properties',
},
callback
);
}
};
isEditingObject = (): boolean => { | ```suggestion
callback?: () => void
``` | const selectedInstanceObjectName = this.instancesSelection
.getSelectedInstances()[0]
.getObjectName();
this.editObjectByName(selectedInstanceObjectName);
};
editLayerEffects = (layer: ?gdLayer) => {
this.setState({ editedLayer: layer, editedLayerInitialTab: 'effects' });
};
editLayer = (layer: ?gdLayer) => {
this.setState({ editedLayer: layer, editedLayerInitialTab: 'properties' });
};
editInstanceVariables = (instance: ?gdInitialInstance) => {
this.setState({ variablesEditedInstance: instance });
};
editLayoutVariables = (open: boolean = true) => {
this.setState({ layoutVariablesDialogOpen: open });
};
editObject = (
editedObject: ?gdObject,
initialTab: ?ObjectEditorTab,
callback?: () => void
) => {
const { project } = this.props;
if (editedObject) {
this.setState(
{
editedObjectWithContext: {
object: editedObject,
global: project.getObjects().hasObjectNamed(editedObject.getName()),
},
editedObjectInitialTab: initialTab || 'properties',
},
callback
);
} else {
this.setState(
{
editedObjectWithContext: null,
editedObjectInitialTab: 'properties',
},
callback
);
}
};
isEditingObject = (): boolean => { | @@ -809,21 +809,31 @@ export default class SceneEditor extends React.Component<Props, State> {
this.setState({ layoutVariablesDialogOpen: open });
};
- editObject = (editedObject: ?gdObject, initialTab: ?ObjectEditorTab) => {
+ editObject = (
+ editedObject: ?gdObject,
+ initialTab: ?ObjectEditorTab,
+ callback?: () => mixed | newIDE/app/src/SceneEditor/index.js | 26 | JavaScript | 0.429 | suggestion | 43 | 51 | 51 | false | Fix object editor dialog not hot-reloading the editor | 7,991 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/Platform.h"
#include "GDCore/IDE/Events/ExpressionValidator.h"
#include "GDCore/IDE/VariableInstructionSwitcher.h"
#include "GDCore/Project/InitialInstancesContainer.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/ObjectGroup.h"
#include "GDCore/Project/ObjectsContainer.h"
#include "GDCore/Project/ObjectsContainersList.h"
#include "GDCore/Project/ProjectScopedContainers.h"
#include "GDCore/Project/Variable.h"
#include "GDCore/Project/VariablesContainer.h"
#include "GDCore/String.h"
namespace gd {
bool InstructionValidator::IsParameterValid(
const gd::Platform &platform,
const gd::ProjectScopedContainers projectScopedContainers,
const gd::Instruction &instruction, const InstructionMetadata &metadata,
std::size_t parameterIndex, const gd::String &value) {
auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when any parameter declaration uses
// "number" instead of "expression".
auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don"t.
// This is why it"s done here instead of in the parser directly.
if (parameterType == "objectvar" && | GetParameter does not do any bound checking nor return a "null object", so let's check the bound to avoid a crash in case a wrong parameterIndex is passed. Better be safe. |
#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/Platform.h"
#include "GDCore/IDE/Events/ExpressionValidator.h"
#include "GDCore/IDE/VariableInstructionSwitcher.h"
#include "GDCore/Project/InitialInstancesContainer.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/ObjectGroup.h"
#include "GDCore/Project/ObjectsContainer.h"
#include "GDCore/Project/ObjectsContainersList.h"
#include "GDCore/Project/ProjectScopedContainers.h"
#include "GDCore/Project/Variable.h"
#include "GDCore/Project/VariablesContainer.h"
#include "GDCore/String.h"
namespace gd {
bool InstructionValidator::IsParameterValid(
const gd::Platform &platform,
const gd::ProjectScopedContainers projectScopedContainers,
const gd::Instruction &instruction, const InstructionMetadata &metadata,
std::size_t parameterIndex, const gd::String &value) {
if (parameterIndex >= instruction.GetParametersCount() ||
parameterIndex >= metadata.GetParametersCount()) {
return false;
}
const auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when all parameter declarations use
// "number" instead of "expression".
const auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
} | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex); | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.571 | bug | 171 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/Platform.h"
#include "GDCore/IDE/Events/ExpressionValidator.h"
#include "GDCore/IDE/VariableInstructionSwitcher.h"
#include "GDCore/Project/InitialInstancesContainer.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/ObjectGroup.h"
#include "GDCore/Project/ObjectsContainer.h"
#include "GDCore/Project/ObjectsContainersList.h"
#include "GDCore/Project/ProjectScopedContainers.h"
#include "GDCore/Project/Variable.h"
#include "GDCore/Project/VariablesContainer.h"
#include "GDCore/String.h"
namespace gd {
bool InstructionValidator::IsParameterValid(
const gd::Platform &platform,
const gd::ProjectScopedContainers projectScopedContainers,
const gd::Instruction &instruction, const InstructionMetadata &metadata,
std::size_t parameterIndex, const gd::String &value) {
auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when any parameter declaration uses
// "number" instead of "expression".
auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don"t.
// This is why it"s done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction( | ```suggestion
// TODO Remove the ternary when all parameter declarations use
``` | #include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/Platform.h"
#include "GDCore/IDE/Events/ExpressionValidator.h"
#include "GDCore/IDE/VariableInstructionSwitcher.h"
#include "GDCore/Project/InitialInstancesContainer.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/ObjectGroup.h"
#include "GDCore/Project/ObjectsContainer.h"
#include "GDCore/Project/ObjectsContainersList.h"
#include "GDCore/Project/ProjectScopedContainers.h"
#include "GDCore/Project/Variable.h"
#include "GDCore/Project/VariablesContainer.h"
#include "GDCore/String.h"
namespace gd {
bool InstructionValidator::IsParameterValid(
const gd::Platform &platform,
const gd::ProjectScopedContainers projectScopedContainers,
const gd::Instruction &instruction, const InstructionMetadata &metadata,
std::size_t parameterIndex, const gd::String &value) {
if (parameterIndex >= instruction.GetParametersCount() ||
parameterIndex >= metadata.GetParametersCount()) {
return false;
}
const auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when all parameter declarations use
// "number" instead of "expression".
const auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
+ // TODO Remove the ternary when any parameter declaration uses | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.643 | suggestion | 82 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
std::size_t parameterIndex, const gd::String &value) {
auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when any parameter declaration uses
// "number" instead of "expression".
auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don"t.
// This is why it"s done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it"s the best we can
// do.
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
auto &objectName = instruction.GetParameter(0).GetPlainString();
auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
(parameterMetadata.GetExtraInfo().empty() ||
objectsContainersList.GetTypeOfObject(objectOrGroupName) == | ```suggestion
// declared while legacy ones don't.
// This is why it's done here instead of in the parser directly.
``` | std::size_t parameterIndex, const gd::String &value) {
if (parameterIndex >= instruction.GetParametersCount() ||
parameterIndex >= metadata.GetParametersCount()) {
return false;
}
const auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when all parameter declarations use
// "number" instead of "expression".
const auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don't.
// This is why it's done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it's the best we can
// do.
const auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
const auto &objectName = instruction.GetParameter(0).GetPlainString();
const auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
const auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
const auto &objectsContainersList = | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
+ // TODO Remove the ternary when any parameter declaration uses
+ // "number" instead of "expression".
+ auto ¶meterType = parameterMetadata.GetType() == "expression"
+ ? "number"
+ : parameterMetadata.GetType();
+ bool shouldNotBeValidated = parameterType == "layer" && value.empty();
+ if (shouldNotBeValidated) {
+ return true;
+ }
+ if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
+ gd::ParameterMetadata::IsExpression("string", parameterType) ||
+ gd::ParameterMetadata::IsExpression("variable", parameterType)) {
+ auto &expressionNode =
+ *instruction.GetParameter(parameterIndex).GetRootNode();
+ ExpressionValidator expressionValidator(platform, projectScopedContainers,
+ parameterType,
+ parameterMetadata.GetExtraInfo());
+ expressionNode.Visit(expressionValidator);
+ if (!expressionValidator.GetAllErrors().empty()) {
+ return false;
+ }
+ // New object variable instructions require the variable to be
+ // declared while legacy ones don"t.
+ // This is why it"s done here instead of in the parser directly. | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.786 | suggestion | 127 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don"t.
// This is why it"s done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it"s the best we can
// do.
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
auto &objectName = instruction.GetParameter(0).GetPlainString();
auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
(parameterMetadata.GetExtraInfo().empty() ||
objectsContainersList.GetTypeOfObject(objectOrGroupName) ==
parameterMetadata.GetExtraInfo()) &&
InstructionValidator::HasRequiredBehaviors(
instruction, metadata, parameterIndex, objectsContainersList);
} else if (gd::ParameterMetadata::IsExpression("resource", parameterType)) { | ```suggestion
// Check at least the name of the root variable, it's the best we can
``` | }
const auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
// TODO Remove the ternary when all parameter declarations use
// "number" instead of "expression".
const auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don't.
// This is why it's done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it's the best we can
// do.
const auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
const auto &objectName = instruction.GetParameter(0).GetPlainString();
const auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
const auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
const auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
(parameterMetadata.GetExtraInfo().empty() ||
objectsContainersList.GetTypeOfObject(objectOrGroupName) == | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
+ // TODO Remove the ternary when any parameter declaration uses
+ // "number" instead of "expression".
+ auto ¶meterType = parameterMetadata.GetType() == "expression"
+ ? "number"
+ : parameterMetadata.GetType();
+ bool shouldNotBeValidated = parameterType == "layer" && value.empty();
+ if (shouldNotBeValidated) {
+ return true;
+ }
+ if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
+ gd::ParameterMetadata::IsExpression("string", parameterType) ||
+ gd::ParameterMetadata::IsExpression("variable", parameterType)) {
+ auto &expressionNode =
+ *instruction.GetParameter(parameterIndex).GetRootNode();
+ ExpressionValidator expressionValidator(platform, projectScopedContainers,
+ parameterType,
+ parameterMetadata.GetExtraInfo());
+ expressionNode.Visit(expressionValidator);
+ if (!expressionValidator.GetAllErrors().empty()) {
+ return false;
+ }
+ // New object variable instructions require the variable to be
+ // declared while legacy ones don"t.
+ // This is why it"s done here instead of in the parser directly.
+ if (parameterType == "objectvar" &&
+ gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
+ instruction.GetType())) {
+ // Check at least the name of the root variable, it"s the best we can | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.571 | suggestion | 93 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don"t.
// This is why it"s done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it"s the best we can
// do.
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
auto &objectName = instruction.GetParameter(0).GetPlainString();
auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
(parameterMetadata.GetExtraInfo().empty() ||
objectsContainersList.GetTypeOfObject(objectOrGroupName) ==
parameterMetadata.GetExtraInfo()) &&
InstructionValidator::HasRequiredBehaviors(
instruction, metadata, parameterIndex, objectsContainersList);
} else if (gd::ParameterMetadata::IsExpression("resource", parameterType)) {
auto &resourceName =
instruction.GetParameter(parameterIndex).GetPlainString(); | Try to use `const auto&` as possible, better to ensure we don't mutate these things. | // TODO Remove the ternary when all parameter declarations use
// "number" instead of "expression".
const auto ¶meterType = parameterMetadata.GetType() == "expression"
? "number"
: parameterMetadata.GetType();
bool shouldNotBeValidated = parameterType == "layer" && value.empty();
if (shouldNotBeValidated) {
return true;
}
if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
gd::ParameterMetadata::IsExpression("string", parameterType) ||
gd::ParameterMetadata::IsExpression("variable", parameterType)) {
auto &expressionNode =
*instruction.GetParameter(parameterIndex).GetRootNode();
ExpressionValidator expressionValidator(platform, projectScopedContainers,
parameterType,
parameterMetadata.GetExtraInfo());
expressionNode.Visit(expressionValidator);
if (!expressionValidator.GetAllErrors().empty()) {
return false;
}
// New object variable instructions require the variable to be
// declared while legacy ones don't.
// This is why it's done here instead of in the parser directly.
if (parameterType == "objectvar" &&
gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
// Check at least the name of the root variable, it's the best we can
// do.
const auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
const auto &objectName = instruction.GetParameter(0).GetPlainString();
const auto &variableName =
instruction.GetParameter(parameterIndex).GetPlainString();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
objectName,
gd::InstructionValidator::GetRootVariableName(variableName)) ==
gd::ObjectsContainersList::DoesNotExist) {
return false;
}
}
} else if (gd::ParameterMetadata::IsObject(parameterType)) {
const auto &objectOrGroupName =
instruction.GetParameter(parameterIndex).GetPlainString();
const auto &objectsContainersList =
projectScopedContainers.GetObjectsContainersList();
return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
(parameterMetadata.GetExtraInfo().empty() ||
objectsContainersList.GetTypeOfObject(objectOrGroupName) ==
parameterMetadata.GetExtraInfo()) &&
InstructionValidator::HasRequiredBehaviors( | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
+ // TODO Remove the ternary when any parameter declaration uses
+ // "number" instead of "expression".
+ auto ¶meterType = parameterMetadata.GetType() == "expression"
+ ? "number"
+ : parameterMetadata.GetType();
+ bool shouldNotBeValidated = parameterType == "layer" && value.empty();
+ if (shouldNotBeValidated) {
+ return true;
+ }
+ if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
+ gd::ParameterMetadata::IsExpression("string", parameterType) ||
+ gd::ParameterMetadata::IsExpression("variable", parameterType)) {
+ auto &expressionNode =
+ *instruction.GetParameter(parameterIndex).GetRootNode();
+ ExpressionValidator expressionValidator(platform, projectScopedContainers,
+ parameterType,
+ parameterMetadata.GetExtraInfo());
+ expressionNode.Visit(expressionValidator);
+ if (!expressionValidator.GetAllErrors().empty()) {
+ return false;
+ }
+ // New object variable instructions require the variable to be
+ // declared while legacy ones don"t.
+ // This is why it"s done here instead of in the parser directly.
+ if (parameterType == "objectvar" &&
+ gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
+ instruction.GetType())) {
+ // Check at least the name of the root variable, it"s the best we can
+ // do.
+ auto &objectsContainersList = | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.429 | suggestion | 84 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
}
return true;
}
gd::String InstructionValidator::GetRootVariableName(const gd::String &name) {
auto dotPosition = name.find('.');
auto squareBracketPosition = name.find('[');
if (dotPosition == gd::String::npos &&
squareBracketPosition == gd::String::npos) {
return name;
}
return name.substr(0, dotPosition < squareBracketPosition
? dotPosition
: squareBracketPosition);
};
bool InstructionValidator::HasRequiredBehaviors(
const gd::Instruction &instruction,
const gd::InstructionMetadata &instructionMetadata,
std::size_t objectParameterIndex,
const gd::ObjectsContainersList &objectsContainersList) {
auto &objectOrGroupName =
instruction.GetParameter(objectParameterIndex).GetPlainString();
for (size_t index = objectParameterIndex + 1;
index < instructionMetadata.GetParametersCount(); index++) {
auto &behaviorParameter = instructionMetadata.GetParameter(index);
auto ¶meterType = behaviorParameter.GetValueTypeMetadata();
if (parameterType.IsObject()) {
return true;
}
if (!parameterType.IsBehavior()) {
continue;
}
auto &behaviorType = behaviorParameter.GetExtraInfo();
if (behaviorType.empty()) {
continue;
}
if (index >= instruction.GetParametersCount()) {
return false;
}
auto &behaviorName = instruction.GetParameter(index).GetPlainString();
if (objectsContainersList.GetTypeOfBehaviorInObjectOrGroup(
objectOrGroupName, behaviorName,
/** searchInGroups = */ true) != behaviorType) {
return false;
}
}
return true;
};
| Here and below, try to const everything:
```suggestion
const auto &behaviorParameter = instructionMetadata.GetParameter(index);
``` | const auto &resourceName =
instruction.GetParameter(parameterIndex).GetPlainString();
return projectScopedContainers.GetResourcesContainersList()
.HasResourceNamed(resourceName);
}
return true;
}
gd::String InstructionValidator::GetRootVariableName(const gd::String &name) {
const auto dotPosition = name.find('.');
const auto squareBracketPosition = name.find('[');
if (dotPosition == gd::String::npos &&
squareBracketPosition == gd::String::npos) {
return name;
}
return name.substr(0, dotPosition < squareBracketPosition
? dotPosition
: squareBracketPosition);
};
bool InstructionValidator::HasRequiredBehaviors(
const gd::Instruction &instruction,
const gd::InstructionMetadata &instructionMetadata,
std::size_t objectParameterIndex,
const gd::ObjectsContainersList &objectsContainersList) {
if (objectParameterIndex >= instruction.GetParametersCount()) {
return false;
}
const auto &objectOrGroupName =
instruction.GetParameter(objectParameterIndex).GetPlainString();
for (size_t index = objectParameterIndex + 1;
index < instructionMetadata.GetParametersCount(); index++) {
const auto &behaviorParameter = instructionMetadata.GetParameter(index);
const auto ¶meterType = behaviorParameter.GetValueTypeMetadata();
if (parameterType.IsObject()) {
return true;
}
if (!parameterType.IsBehavior()) {
continue;
}
const auto &behaviorType = behaviorParameter.GetExtraInfo();
if (behaviorType.empty()) {
continue;
}
if (index >= instruction.GetParametersCount()) {
return false;
}
const auto &behaviorName = instruction.GetParameter(index).GetPlainString();
if (objectsContainersList.GetTypeOfBehaviorInObjectOrGroup(
objectOrGroupName, behaviorName, | @@ -0,0 +1,141 @@
+/*
+ * GDevelop Core
+ * Copyright 2008-2025 Florian Rival (Florian.Rival@gmail.com). All rights
+ * reserved. This project is released under the MIT License.
+ */
+#include "InstructionValidator.h"
+
+#include "GDCore/Extensions/Metadata/AbstractFunctionMetadata.h"
+#include "GDCore/Extensions/Metadata/BehaviorMetadata.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/Platform.h"
+#include "GDCore/IDE/Events/ExpressionValidator.h"
+#include "GDCore/IDE/VariableInstructionSwitcher.h"
+#include "GDCore/Project/InitialInstancesContainer.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/ObjectGroup.h"
+#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/ObjectsContainersList.h"
+#include "GDCore/Project/ProjectScopedContainers.h"
+#include "GDCore/Project/Variable.h"
+#include "GDCore/Project/VariablesContainer.h"
+#include "GDCore/String.h"
+
+namespace gd {
+
+bool InstructionValidator::IsParameterValid(
+ const gd::Platform &platform,
+ const gd::ProjectScopedContainers projectScopedContainers,
+ const gd::Instruction &instruction, const InstructionMetadata &metadata,
+ std::size_t parameterIndex, const gd::String &value) {
+ auto ¶meterMetadata = metadata.GetParameter(parameterIndex);
+ // TODO Remove the ternary when any parameter declaration uses
+ // "number" instead of "expression".
+ auto ¶meterType = parameterMetadata.GetType() == "expression"
+ ? "number"
+ : parameterMetadata.GetType();
+ bool shouldNotBeValidated = parameterType == "layer" && value.empty();
+ if (shouldNotBeValidated) {
+ return true;
+ }
+ if (gd::ParameterMetadata::IsExpression("number", parameterType) ||
+ gd::ParameterMetadata::IsExpression("string", parameterType) ||
+ gd::ParameterMetadata::IsExpression("variable", parameterType)) {
+ auto &expressionNode =
+ *instruction.GetParameter(parameterIndex).GetRootNode();
+ ExpressionValidator expressionValidator(platform, projectScopedContainers,
+ parameterType,
+ parameterMetadata.GetExtraInfo());
+ expressionNode.Visit(expressionValidator);
+ if (!expressionValidator.GetAllErrors().empty()) {
+ return false;
+ }
+ // New object variable instructions require the variable to be
+ // declared while legacy ones don"t.
+ // This is why it"s done here instead of in the parser directly.
+ if (parameterType == "objectvar" &&
+ gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
+ instruction.GetType())) {
+ // Check at least the name of the root variable, it"s the best we can
+ // do.
+ auto &objectsContainersList =
+ projectScopedContainers.GetObjectsContainersList();
+ auto &objectName = instruction.GetParameter(0).GetPlainString();
+ auto &variableName =
+ instruction.GetParameter(parameterIndex).GetPlainString();
+ if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
+ objectName,
+ gd::InstructionValidator::GetRootVariableName(variableName)) ==
+ gd::ObjectsContainersList::DoesNotExist) {
+ return false;
+ }
+ }
+ } else if (gd::ParameterMetadata::IsObject(parameterType)) {
+ auto &objectOrGroupName =
+ instruction.GetParameter(parameterIndex).GetPlainString();
+ auto &objectsContainersList =
+ projectScopedContainers.GetObjectsContainersList();
+ return objectsContainersList.HasObjectOrGroupNamed(objectOrGroupName) &&
+ (parameterMetadata.GetExtraInfo().empty() ||
+ objectsContainersList.GetTypeOfObject(objectOrGroupName) ==
+ parameterMetadata.GetExtraInfo()) &&
+ InstructionValidator::HasRequiredBehaviors(
+ instruction, metadata, parameterIndex, objectsContainersList);
+ } else if (gd::ParameterMetadata::IsExpression("resource", parameterType)) {
+ auto &resourceName =
+ instruction.GetParameter(parameterIndex).GetPlainString();
+ return projectScopedContainers.GetResourcesContainersList()
+ .HasResourceNamed(resourceName);
+ }
+ return true;
+}
+
+gd::String InstructionValidator::GetRootVariableName(const gd::String &name) {
+ auto dotPosition = name.find('.');
+ auto squareBracketPosition = name.find('[');
+ if (dotPosition == gd::String::npos &&
+ squareBracketPosition == gd::String::npos) {
+ return name;
+ }
+ return name.substr(0, dotPosition < squareBracketPosition
+ ? dotPosition
+ : squareBracketPosition);
+};
+
+bool InstructionValidator::HasRequiredBehaviors(
+ const gd::Instruction &instruction,
+ const gd::InstructionMetadata &instructionMetadata,
+ std::size_t objectParameterIndex,
+ const gd::ObjectsContainersList &objectsContainersList) {
+ auto &objectOrGroupName =
+ instruction.GetParameter(objectParameterIndex).GetPlainString();
+ for (size_t index = objectParameterIndex + 1;
+ index < instructionMetadata.GetParametersCount(); index++) {
+ auto &behaviorParameter = instructionMetadata.GetParameter(index); | Core/GDCore/IDE/InstructionValidator.cpp | 26 | C++ | 0.714 | suggestion | 136 | 51 | 51 | false | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
<SelectOption
key={effectMetadata.type}
value={effectMetadata.type}
label={effectMetadata.fullName}
disabled={
target === 'object' &&
effectMetadata.isMarkedAsNotWorkingForObjects
}
/>
))}
</SelectField>
<InlineCheckbox
id="layer-visibility"
paddingSize="small"
checkedIcon={<VisibilityIcon />}
uncheckedIcon={<VisibilityOffIcon />}
checked={!effect.isInitiallyDisabled()}
onCheck={(e, checked) => {
effect.setInitiallyDisabled(!checked);
forceUpdate();
}}
tooltipOrHelperText={
!effect.isInitiallyDisabled() ? (
<Trans>Disable from the start</Trans>
) : (
<Trans>Enable from the start</Trans>
)
}
/>
</Line>
</ResponsiveLineStackLayout>
<ElementWithMenu
element={
<IconButton size="small">
<ThreeDotsMenu />
</IconButton>
}
buildMenuTemplate={(i18n: I18nType) => [
{
label: i18n._(t`Delete`),
click: () => removeEffect(effect),
},
{
label: i18n._(t`Copy`),
click: () => copyEffect(effect),
},
{
label: i18n._(t`Paste`),
click: () => pasteEffectsBefore(effect),
enabled: isClipboardContainingEffects,
}, | Maybe I should have kept "Hide" and "Show" like for layers | <SelectOption
key={effectMetadata.type}
value={effectMetadata.type}
label={effectMetadata.fullName}
disabled={
target === 'object' &&
effectMetadata.isMarkedAsNotWorkingForObjects
}
/>
))}
</SelectField>
</Line>
</ResponsiveLineStackLayout>
<InlineCheckbox
id="effect-visibility"
paddingSize="small"
checkedIcon={<VisibilityIcon />}
uncheckedIcon={<VisibilityOffIcon />}
checked={effect.isEnabled()}
onCheck={(e, checked) => {
effect.setEnabled(checked);
forceUpdate();
}}
tooltipOrHelperText={
effect.isEnabled() ? (
<Trans>Hide effect</Trans>
) : (
<Trans>Show effect</Trans>
)
}
/>
<ElementWithMenu
element={
<IconButton size="small">
<ThreeDotsMenu />
</IconButton>
}
buildMenuTemplate={(i18n: I18nType) => [
{
label: i18n._(t`Delete`),
click: () => removeEffect(effect),
},
{
label: i18n._(t`Copy`),
click: () => copyEffect(effect),
},
{
label: i18n._(t`Paste`),
click: () => pasteEffectsBefore(effect),
enabled: isClipboardContainingEffects,
}, | @@ -300,6 +303,24 @@ const Effect = React.forwardRef(
/>
))}
</SelectField>
+ <InlineCheckbox
+ id="layer-visibility"
+ paddingSize="small"
+ checkedIcon={<VisibilityIcon />}
+ uncheckedIcon={<VisibilityOffIcon />}
+ checked={!effect.isInitiallyDisabled()}
+ onCheck={(e, checked) => {
+ effect.setInitiallyDisabled(!checked);
+ forceUpdate();
+ }}
+ tooltipOrHelperText={
+ !effect.isInitiallyDisabled() ? (
+ <Trans>Disable from the start</Trans>
+ ) : (
+ <Trans>Enable from the start</Trans> | newIDE/app/src/EffectsList/index.js | 26 | JavaScript | 0.286 | suggestion | 58 | 51 | 51 | false | Allow to set effects as initially disabled | 8,002 | 4ian/GDevelop | 10,154 | JavaScript | D8H | D8H |
/*
* GDevelop Core
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#include "GDCore/Project/Effect.h"
#include "GDCore/CommonTools.h"
#include "GDCore/Serialization/SerializerElement.h"
namespace gd {
gd::String Effect::badStringParameterValue;
void Effect::SerializeTo(SerializerElement& element) const {
element.SetAttribute("name", GetName());
element.SetAttribute("effectType", GetEffectType());
if (IsFolded()) element.SetBoolAttribute("folded", true);
if (!IsEnabled()) {
element.SetBoolAttribute("isDisabled", true);
}
SerializerElement& doubleParametersElement =
element.AddChild("doubleParameters");
for (auto& parameter : doubleParameters)
doubleParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
SerializerElement& stringParametersElement =
element.AddChild("stringParameters");
for (auto& parameter : stringParameters)
stringParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
SerializerElement& booleanParametersElement =
element.AddChild("booleanParameters");
for (auto& parameter : booleanParameters)
booleanParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
}
void Effect::UnserializeFrom(const SerializerElement& element) {
SetName(element.GetStringAttribute("name"));
SetEffectType(element.GetStringAttribute(
"effectType",
"", | could that be:
```suggestion
element.SetBoolAttribute("disabled", true);
```
? | /*
* GDevelop Core
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#include "GDCore/Project/Effect.h"
#include "GDCore/CommonTools.h"
#include "GDCore/Serialization/SerializerElement.h"
namespace gd {
gd::String Effect::badStringParameterValue;
void Effect::SerializeTo(SerializerElement& element) const {
element.SetAttribute("name", GetName());
element.SetAttribute("effectType", GetEffectType());
if (IsFolded()) element.SetBoolAttribute("folded", true);
if (!IsEnabled()) {
element.SetBoolAttribute("disabled", true);
}
SerializerElement& doubleParametersElement =
element.AddChild("doubleParameters");
for (auto& parameter : doubleParameters)
doubleParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
SerializerElement& stringParametersElement =
element.AddChild("stringParameters");
for (auto& parameter : stringParameters)
stringParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
SerializerElement& booleanParametersElement =
element.AddChild("booleanParameters");
for (auto& parameter : booleanParameters)
booleanParametersElement.AddChild(parameter.first)
.SetValue(parameter.second);
}
void Effect::UnserializeFrom(const SerializerElement& element) {
SetName(element.GetStringAttribute("name"));
SetEffectType(element.GetStringAttribute(
"effectType",
"", | @@ -15,7 +15,9 @@ void Effect::SerializeTo(SerializerElement& element) const {
element.SetAttribute("name", GetName());
element.SetAttribute("effectType", GetEffectType());
if (IsFolded()) element.SetBoolAttribute("folded", true);
-
+ if (!IsEnabled()) {
+ element.SetBoolAttribute("isDisabled", true); | Core/GDCore/Project/Effect.cpp | 19 | C++ | 0.643 | question | 82 | 44 | 44 | false | Allow to set effects as initially disabled | 8,002 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
extensionName,
onWillInstallExtension,
onExtensionInstalled,
onOpenEventsFunctionsExtension,
}: Props) {
const [isInstalling, setIsInstalling] = React.useState<boolean>(false);
const installExtension = useInstallExtension();
const {
translatedExtensionShortHeadersByName: extensionShortHeadersByName,
} = React.useContext(ExtensionStoreContext);
const installOrUpdateExtension = async (i18n: I18nType) => {
setIsInstalling(true);
try {
const extensionShortHeaders: Array<ExtensionShortHeader> = [
extensionShortHeader,
];
const requiredExtensionInstallation = await checkRequiredExtensionsUpdate(
{
requiredExtensions: getRequiredExtensions(extensionShortHeaders),
project,
extensionShortHeadersByName,
}
);
await installExtension({
project,
requiredExtensionInstallation,
userSelectedExtensionNames: [],
importedSerializedExtensions: [],
onWillInstallExtension,
onExtensionInstalled,
updateMode: 'all',
reason: 'extension',
});
} finally {
setIsInstalling(false);
}
};
return (
<I18n>
{({ i18n }) => (
<ExtensionInstallDialog
project={project}
isInstalling={isInstalling}
onClose={onClose}
onInstall={() => installOrUpdateExtension(i18n)}
extensionShortHeader={extensionShortHeader}
onEdit={() => {
onOpenEventsFunctionsExtension(extensionName);
onClose(); | why is the array `missingExtensionShortHeaders` not returning the assetShortHeader when it has been installed before? should it always return it instead of pushing it afterwards? | extensionName,
onWillInstallExtension,
onExtensionInstalled,
onOpenEventsFunctionsExtension,
}: Props) {
const [isInstalling, setIsInstalling] = React.useState<boolean>(false);
const installExtension = useInstallExtension();
const {
translatedExtensionShortHeadersByName: extensionShortHeadersByName,
} = React.useContext(ExtensionStoreContext);
const installOrUpdateExtension = async (i18n: I18nType) => {
setIsInstalling(true);
try {
const extensionShortHeaders: Array<ExtensionShortHeader> = [
extensionShortHeader,
];
const requiredExtensionInstallation = await checkRequiredExtensionsUpdate(
{
requiredExtensions: getRequiredExtensions(extensionShortHeaders),
project,
extensionShortHeadersByName,
}
);
if (
!requiredExtensionInstallation.missingExtensionShortHeaders.includes(
extensionShortHeader
)
) {
// Allow to reinstall the extension even if the versions match.
requiredExtensionInstallation.missingExtensionShortHeaders.push(
extensionShortHeader
);
}
await installExtension({
project,
requiredExtensionInstallation,
userSelectedExtensionNames: [],
importedSerializedExtensions: [],
onWillInstallExtension,
onExtensionInstalled,
updateMode: 'all',
reason: 'extension',
});
} finally {
setIsInstalling(false);
}
};
return (
<I18n> | @@ -51,6 +51,16 @@ function InstalledExtensionDetails({
extensionShortHeadersByName,
}
);
+ if (
+ !requiredExtensionInstallation.missingExtensionShortHeaders.includes( | newIDE/app/src/ProjectManager/InstalledExtensionDetails.js | 26 | JavaScript | 0.571 | question | 178 | 51 | 51 | false | Fix extension reinstall wasn't doing anything | 8,017 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | D8H |
>
{props.firstIndex + index + 1}
</Button>
))}
</ButtonGroup>
</div>
);
};
const isBitEnabled = (bitsValue: number, pos: number) => {
return !!(bitsValue & (1 << pos));
};
const enableBit = (bitsValue: number, pos: number, enable: boolean) => {
if (enable) bitsValue |= 1 << pos;
else bitsValue &= ~(1 << pos);
return bitsValue;
};
const Physics3DEditor = (props: Props) => {
const { behavior, onBehaviorUpdated } = props;
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return areAdvancedPropertiesModified(
behavior.getProperties(),
propertyName =>
behaviorMetadata
.getProperties()
.get(propertyName)
.getValue()
);
},
[behavior]
);
const updateBehaviorProperty = React.useCallback(
(property, value) => {
behavior.updateProperty(property, value);
forceUpdate();
onBehaviorUpdated();
},
[behavior, forceUpdate, onBehaviorUpdated]
);
const properties = behavior.getProperties(); | Is there a risk these are "bad metadata"? Should we protect against this? | >
{props.firstIndex + index + 1}
</Button>
))}
</ButtonGroup>
</div>
);
};
const isBitEnabled = (bitsValue: number, pos: number) => {
return !!(bitsValue & (1 << pos));
};
const enableBit = (bitsValue: number, pos: number, enable: boolean) => {
if (enable) bitsValue |= 1 << pos;
else bitsValue &= ~(1 << pos);
return bitsValue;
};
const Physics3DEditor = (props: Props) => {
const { behavior, onBehaviorUpdated } = props;
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return areAdvancedPropertiesModified(
behavior.getProperties(),
propertyName => {
const properties = behaviorMetadata.getProperties();
return properties.has(propertyName)
? properties.get(propertyName).getValue()
: '';
}
);
},
[behavior]
);
const updateBehaviorProperty = React.useCallback(
(property, value) => {
behavior.updateProperty(property, value);
forceUpdate();
onBehaviorUpdated();
},
[behavior, forceUpdate, onBehaviorUpdated]
);
| @@ -64,7 +66,20 @@ const Physics3DEditor = (props: Props) => {
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
- () => areAdvancedPropertiesModified(behavior),
+ () => {
+ const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata( | newIDE/app/src/BehaviorsEditor/Editors/Physics3DEditor/index.js | 26 | JavaScript | 0.286 | question | 73 | 51 | 51 | false | Collapse advanced properties in the object editor | 8,028 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
<ColumnStackLayout noMargin>
{renderObjectNameField && renderObjectNameField()}
{tutorialIds.map(tutorialId => (
<DismissableTutorialMessage
key={tutorialId}
tutorialId={tutorialId}
/>
))}
{
<React.Fragment>
{extraInformation ? (
<Line>
<ColumnStackLayout noMargin>
{extraInformation.map(({ kind, message }, index) => (
<AlertMessage kind={kind} key={index}>
{i18n._(message)}
</AlertMessage>
))}
</ColumnStackLayout>
</Line>
) : null}
<PropertiesEditorByVisibility
project={project}
object={object}
propertiesValues={customObjectConfiguration.getProperties()}
getPropertyDefaultValue={propertyName =>
customObjectEventsBasedObject
? customObjectEventsBasedObject
.getPropertyDescriptors()
.get(propertyName)
.getValue()
: ''
}
instances={[customObjectConfiguration]}
unsavedChanges={unsavedChanges}
resourceManagementProps={resourceManagementProps}
projectScopedContainersAccessor={
projectScopedContainersAccessor
}
placeholder={
customObjectEventsBasedObject &&
(customObjectEventsBasedObject
.getObjects()
.getObjectsCount() === 0 &&
!customObjectEventsBasedObject.isAnimatable()) ? (
<Trans>
There is nothing to configure for this object. You can
still use events to interact with the object.
</Trans>
) : null
} | Let's protect against propertyName not being present in the map of properties. | <ColumnStackLayout noMargin>
{renderObjectNameField && renderObjectNameField()}
{tutorialIds.map(tutorialId => (
<DismissableTutorialMessage
key={tutorialId}
tutorialId={tutorialId}
/>
))}
{
<React.Fragment>
{extraInformation ? (
<Line>
<ColumnStackLayout noMargin>
{extraInformation.map(({ kind, message }, index) => (
<AlertMessage kind={kind} key={index}>
{i18n._(message)}
</AlertMessage>
))}
</ColumnStackLayout>
</Line>
) : null}
<PropertiesEditorByVisibility
project={project}
object={object}
propertiesValues={customObjectConfiguration.getProperties()}
getPropertyDefaultValue={propertyName => {
if (!customObjectEventsBasedObject) {
return '';
}
const properties = customObjectEventsBasedObject.getPropertyDescriptors();
return properties.has(propertyName)
? properties.get(propertyName).getValue()
: '';
}}
instances={[customObjectConfiguration]}
unsavedChanges={unsavedChanges}
resourceManagementProps={resourceManagementProps}
projectScopedContainersAccessor={
projectScopedContainersAccessor
}
placeholder={
customObjectEventsBasedObject &&
(customObjectEventsBasedObject
.getObjects()
.getObjectsCount() === 0 &&
!customObjectEventsBasedObject.isAnimatable()) ? (
<Trans>
There is nothing to configure for this object. You can
still use events to interact with the object.
</Trans>
) : null | @@ -469,15 +457,36 @@ const CustomObjectPropertiesEditor = (props: Props) => {
</ColumnStackLayout>
</Line>
) : null}
- <PropertiesEditor
- unsavedChanges={unsavedChanges}
- schema={propertiesSchema}
- instances={[customObjectConfiguration]}
+ <PropertiesEditorByVisibility
project={project}
+ object={object}
+ propertiesValues={customObjectConfiguration.getProperties()}
+ getPropertyDefaultValue={propertyName => | newIDE/app/src/ObjectEditor/Editors/CustomObjectPropertiesEditor/index.js | 26 | JavaScript | 0.214 | suggestion | 78 | 51 | 51 | false | Collapse advanced properties in the object editor | 8,028 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
import { type BehaviorEditorProps } from './BehaviorEditorProps.flow';
import { Column } from '../../UI/Grid';
const gd: libGDevelop = global.gd;
type Props = BehaviorEditorProps;
const BehaviorPropertiesEditor = ({
project,
behavior,
object,
onBehaviorUpdated,
resourceManagementProps,
projectScopedContainersAccessor,
}: Props) => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return (
<Column expand>
<PropertiesEditorByVisibility
project={project}
object={object}
propertiesValues={behavior.getProperties()}
getPropertyDefaultValue={propertyName =>
behaviorMetadata
.getProperties()
.get(propertyName)
.getValue()
}
instances={[behavior]}
onInstancesModified={onBehaviorUpdated}
resourceManagementProps={resourceManagementProps}
projectScopedContainersAccessor={projectScopedContainersAccessor}
placeholder={
<Trans>
There is nothing to configure for this behavior. You can still use
events to interact with the object and this behavior.
</Trans>
}
/>
</Column>
);
};
export default BehaviorPropertiesEditor;
| Let's protect against propertyName not being present in the map of properties. | import { type BehaviorEditorProps } from './BehaviorEditorProps.flow';
import { Column } from '../../UI/Grid';
const gd: libGDevelop = global.gd;
type Props = BehaviorEditorProps;
const BehaviorPropertiesEditor = ({
project,
behavior,
object,
onBehaviorUpdated,
resourceManagementProps,
projectScopedContainersAccessor,
}: Props) => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return (
<Column expand>
<PropertiesEditorByVisibility
project={project}
object={object}
propertiesValues={behavior.getProperties()}
getPropertyDefaultValue={propertyName => {
const properties = behaviorMetadata.getProperties();
return properties.has(propertyName)
? properties.get(propertyName).getValue()
: '';
}}
instances={[behavior]}
onInstancesModified={onBehaviorUpdated}
resourceManagementProps={resourceManagementProps}
projectScopedContainersAccessor={projectScopedContainersAccessor}
placeholder={
<Trans>
There is nothing to configure for this behavior. You can still use
events to interact with the object and this behavior.
</Trans>
}
/>
</Column>
);
};
export default BehaviorPropertiesEditor;
| @@ -52,131 +18,33 @@ const BehaviorPropertiesEditor = ({
resourceManagementProps,
projectScopedContainersAccessor,
}: Props) => {
- const [
- shouldShowDeprecatedProperties,
- setShouldShowDeprecatedProperties,
- ] = React.useState<boolean>(false);
-
- const basicPropertiesSchema = React.useMemo(
- () =>
- propertiesMapToSchema(
- behavior.getProperties(),
- behavior => behavior.getProperties(),
- (behavior, name, value) => {
- behavior.updateProperty(name, value);
- },
- object,
- 'Basic'
- ),
- [behavior, object]
- );
-
- const areAdvancedPropertiesExpandedByDefault = React.useMemo(
- () => areAdvancedPropertiesModified(behavior),
- [behavior]
- );
-
- const advancedPropertiesSchema = React.useMemo(
- () =>
- propertiesMapToSchema(
- behavior.getProperties(),
- behavior => behavior.getProperties(),
- (behavior, name, value) => {
- behavior.updateProperty(name, value);
- },
- object,
- 'Advanced'
- ),
- [behavior, object]
- );
-
- const deprecatedPropertiesSchema = React.useMemo(
- () =>
- propertiesMapToSchema(
- behavior.getProperties(),
- behavior => behavior.getProperties(),
- (behavior, name, value) => {
- behavior.updateProperty(name, value);
- },
- object,
- 'Deprecated'
- ),
- [behavior, object]
+ const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
+ gd.JsPlatform.get(),
+ behavior.getTypeName()
);
-
return (
<Column expand>
- {basicPropertiesSchema.length > 0 ||
- advancedPropertiesSchema.length > 0 ||
- deprecatedPropertiesSchema.length > 0 ? (
- <ColumnStackLayout expand noMargin>
- <PropertiesEditor
- project={project}
- schema={basicPropertiesSchema}
- instances={[behavior]}
- onInstancesModified={onBehaviorUpdated}
- resourceManagementProps={resourceManagementProps}
- projectScopedContainersAccessor={projectScopedContainersAccessor}
- />
- {(advancedPropertiesSchema.length > 0 ||
- deprecatedPropertiesSchema.length > 0) && (
- <Accordion
- defaultExpanded={areAdvancedPropertiesExpandedByDefault}
- noMargin
- >
- <AccordionHeader noMargin>
- <Text size="sub-title">
- <Trans>Advanced properties</Trans>
- </Text>
- </AccordionHeader>
- <AccordionBody disableGutters>
- <Column expand noMargin>
- <PropertiesEditor
- project={project}
- schema={advancedPropertiesSchema}
- instances={[behavior]}
- onInstancesModified={onBehaviorUpdated}
- resourceManagementProps={resourceManagementProps}
- projectScopedContainersAccessor={
- projectScopedContainersAccessor
- }
- />
- {deprecatedPropertiesSchema.length > 0 &&
- (shouldShowDeprecatedProperties ? (
- <PropertiesEditor
- project={project}
- schema={deprecatedPropertiesSchema}
- instances={[behavior]}
- onInstancesModified={onBehaviorUpdated}
- resourceManagementProps={resourceManagementProps}
- projectScopedContainersAccessor={
- projectScopedContainersAccessor
- }
- />
- ) : (
- <Line justifyContent="center">
- <FlatButton
- key="show-deprecated"
- label={<Trans>Show deprecated options</Trans>}
- onClick={() =>
- setShouldShowDeprecatedProperties(true)
- }
- />
- </Line>
- ))}
- </Column>
- </AccordionBody>
- </Accordion>
- )}
- </ColumnStackLayout>
- ) : (
- <EmptyMessage>
+ <PropertiesEditorByVisibility
+ project={project}
+ object={object}
+ propertiesValues={behavior.getProperties()}
+ getPropertyDefaultValue={propertyName => | newIDE/app/src/BehaviorsEditor/Editors/BehaviorPropertiesEditor.js | 26 | JavaScript | 0.214 | suggestion | 78 | 48 | 48 | false | Collapse advanced properties in the object editor | 8,028 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
};
const isBitEnabled = (bitsValue: number, pos: number) => {
return !!(bitsValue & (1 << pos));
};
const enableBit = (bitsValue: number, pos: number, enable: boolean) => {
if (enable) bitsValue |= 1 << pos;
else bitsValue &= ~(1 << pos);
return bitsValue;
};
const Physics3DEditor = (props: Props) => {
const { behavior, onBehaviorUpdated } = props;
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return areAdvancedPropertiesModified(
behavior.getProperties(),
propertyName =>
behaviorMetadata
.getProperties()
.get(propertyName)
.getValue()
);
},
[behavior]
);
const updateBehaviorProperty = React.useCallback(
(property, value) => {
behavior.updateProperty(property, value);
forceUpdate();
onBehaviorUpdated();
},
[behavior, forceUpdate, onBehaviorUpdated]
);
const properties = behavior.getProperties();
const staticBits = Array(4).fill(null);
const dynamicBits = Array(4).fill(null);
const shape = properties.get('shape').getValue();
const layersValues = parseInt(properties.get('layers').getValue(), 10);
const masksValues = parseInt(properties.get('masks').getValue(), 10);
const isStatic = properties.get('bodyType').getValue() === 'Static'; | As for the rest, probably check if propertyName exists? | };
const isBitEnabled = (bitsValue: number, pos: number) => {
return !!(bitsValue & (1 << pos));
};
const enableBit = (bitsValue: number, pos: number, enable: boolean) => {
if (enable) bitsValue |= 1 << pos;
else bitsValue &= ~(1 << pos);
return bitsValue;
};
const Physics3DEditor = (props: Props) => {
const { behavior, onBehaviorUpdated } = props;
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() => {
const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
gd.JsPlatform.get(),
behavior.getTypeName()
);
return areAdvancedPropertiesModified(
behavior.getProperties(),
propertyName => {
const properties = behaviorMetadata.getProperties();
return properties.has(propertyName)
? properties.get(propertyName).getValue()
: '';
}
);
},
[behavior]
);
const updateBehaviorProperty = React.useCallback(
(property, value) => {
behavior.updateProperty(property, value);
forceUpdate();
onBehaviorUpdated();
},
[behavior, forceUpdate, onBehaviorUpdated]
);
const properties = behavior.getProperties();
const staticBits = Array(4).fill(null);
const dynamicBits = Array(4).fill(null);
const shape = properties.get('shape').getValue();
const layersValues = parseInt(properties.get('layers').getValue(), 10);
const masksValues = parseInt(properties.get('masks').getValue(), 10);
| @@ -64,7 +66,20 @@ const Physics3DEditor = (props: Props) => {
const forceUpdate = useForceUpdate();
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
- () => areAdvancedPropertiesModified(behavior),
+ () => {
+ const behaviorMetadata = gd.MetadataProvider.getBehaviorMetadata(
+ gd.JsPlatform.get(),
+ behavior.getTypeName()
+ );
+ return areAdvancedPropertiesModified(
+ behavior.getProperties(),
+ propertyName =>
+ behaviorMetadata | newIDE/app/src/BehaviorsEditor/Editors/Physics3DEditor/index.js | 26 | JavaScript | 0.214 | question | 55 | 51 | 51 | false | Collapse advanced properties in the object editor | 8,028 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
// Notifications on Microsoft Windows platforms show the app user model id.
// If not set, defaults to `electron.app.{app.name}`.
if (process.platform === 'win32') {
app.setAppUserModelId('gdevelop.ide');
}
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
const isIntegrated = args.mode === 'integrated';
const devTools = !!args['dev-tools'];
if (isIntegrated && app.dock) {
app.dock.hide();
}
registerGdideProtocol({ isDev });
// Create the browser window.
const options = { width: args.width || 800, height: args.height || 600, x: args.x, y: args.y, titleBarStyle: 'hidden', titleBarOverlay: { color: '#000000', symbolColor: '#ffffff' }, trafficLightPosition: { x: 12, y: 12 }, webPreferences: { webSecurity: false, // Allow Node.js API access in renderer process, as long // Allow to access to local files,
// as we've not removed dependency on it and on "@electron/remote".
nodeIntegration: true, contextIsolation: false }, enableLargerThanScreen: true, backgroundColor: '#000', frame: false, titleBarStyle: 'hiddenInset' }; // свой заголовок // чтоб красиво на macOS
if (isIntegrated) {
options.acceptFirstMouse = true;
options.skipTaskbar = true;
options.hasShadow = false;
options.frame = false;
options.minimizable = false;
options.movable = false;
options.resizable = false;
options.fullscreenable = false;
options.show = false;
}
mainWindow = new BrowserWindow(options);
if (!isIntegrated) mainWindow.maximize();
// Enable `@electron/remote` module for renderer process
require('@electron/remote/main').enable(mainWindow.webContents);
if (isDev)
mainWindow.webContents.session.loadExtension(
path.join(__dirname, 'extensions/ReactDeveloperTools/4.24.3_0/')
); | Could you run Prettier on this file (if you use VS Code, use the "Format document" command in the command palette)?
|
// Notifications on Microsoft Windows platforms show the app user model id.
// If not set, defaults to `electron.app.{app.name}`.
if (process.platform === 'win32') {
app.setAppUserModelId('gdevelop.ide');
}
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
const isIntegrated = args.mode === 'integrated';
const devTools = !!args['dev-tools'];
if (isIntegrated && app.dock) {
app.dock.hide();
}
registerGdideProtocol({ isDev });
// Create the browser window.
const options = {
width: args.width || 800,
height: args.height || 600,
x: args.x,
y: args.y,
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#000000',
symbolColor: '#ffffff',
},
trafficLightPosition: { x: 12, y: 12 },
webPreferences: {
webSecurity: false, // Allow to access to local files,
// Allow Node.js API access in renderer process, as long
// as we've not removed dependency on it and on "@electron/remote".
nodeIntegration: true,
contextIsolation: false,
},
enableLargerThanScreen: true,
backgroundColor: '#000',
};
if (isIntegrated) {
options.acceptFirstMouse = true;
options.skipTaskbar = true;
options.hasShadow = false; | @@ -94,27 +94,9 @@ app.on('ready', function() {
registerGdideProtocol({ isDev });
// Create the browser window.
- const options = {
- width: args.width || 800,
- height: args.height || 600,
- x: args.x,
- y: args.y,
- titleBarStyle: 'hidden',
- titleBarOverlay: {
- color: '#000000',
- symbolColor: '#ffffff',
- },
- trafficLightPosition: { x: 12, y: 12 },
- webPreferences: {
- webSecurity: false, // Allow to access to local files,
- // Allow Node.js API access in renderer process, as long
+ const options = { width: args.width || 800, height: args.height || 600, x: args.x, y: args.y, titleBarStyle: 'hidden', titleBarOverlay: { color: '#000000', symbolColor: '#ffffff' }, trafficLightPosition: { x: 12, y: 12 }, webPreferences: { webSecurity: false, // Allow Node.js API access in renderer process, as long // Allow to access to local files, | newIDE/electron-app/app/main.js | 26 | JavaScript | 0.429 | question | 116 | 51 | 51 | false | feat: Add "window-maximize-toggle" for macOS | 8,053 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
private _loadingSpineAtlases = new gdjs.ResourceCache<
Promise<pixi_spine.TextureAtlas>
>();
/**
* @param resourceLoader The resources loader of the game.
* @param imageManager The image manager of the game.
*/
constructor(
resourceLoader: gdjs.ResourceLoader,
imageManager: ImageManager
) {
this._resourceLoader = resourceLoader;
this._imageManager = imageManager;
}
getResourceKinds(): ResourceKind[] {
return atlasKinds;
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because pixi-spine parses resources by itself.
}
async loadResource(resourceName: string): Promise<void> {
try {
await this.getOrLoad(resourceName);
} catch (error) {
throw error;
}
}
/**
* Returns promisified loaded atlas resource if it is available, loads it otherwise.
*
* @param resourceName The name of resource to load.
*/
getOrLoad(resourceName: string): Promise<pixi_spine.TextureAtlas> {
const resource = this._getAtlasResource(resourceName);
if (!resource) {
return Promise.reject(
`Unable to find atlas for resource '${resourceName}'.`
);
}
let loadingPromise = this._loadingSpineAtlases.get(resource);
if (!loadingPromise) {
loadingPromise = new Promise<pixi_spine.TextureAtlas>(
(resolve, reject) => { | This one might be unnecessary unless you have an idea like making it very clear it can throw? | private _loadingSpineAtlases = new gdjs.ResourceCache<
Promise<pixi_spine.TextureAtlas>
>();
/**
* @param resourceLoader The resources loader of the game.
* @param imageManager The image manager of the game.
*/
constructor(
resourceLoader: gdjs.ResourceLoader,
imageManager: ImageManager
) {
this._resourceLoader = resourceLoader;
this._imageManager = imageManager;
}
getResourceKinds(): ResourceKind[] {
return atlasKinds;
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because pixi-spine parses resources by itself.
}
async loadResource(resourceName: string): Promise<void> {
await this.getOrLoad(resourceName);
}
/**
* Returns promisified loaded atlas resource if it is available, loads it otherwise.
*
* @param resourceName The name of resource to load.
*/
getOrLoad(resourceName: string): Promise<pixi_spine.TextureAtlas> {
const resource = this._getAtlasResource(resourceName);
if (!resource) {
return Promise.reject(
`Unable to find atlas for resource '${resourceName}'.`
);
}
let loadingPromise = this._loadingSpineAtlases.get(resource);
if (!loadingPromise) {
loadingPromise = new Promise<pixi_spine.TextureAtlas>(
(resolve, reject) => {
const onLoad: SpineAtlasManagerRequestCallback = (
error,
content
) => { | @@ -50,7 +50,11 @@ namespace gdjs {
}
async loadResource(resourceName: string): Promise<void> {
- await this.getOrLoad(resourceName);
+ try { | Extensions/Spine/managers/pixi-spine-atlas-manager.ts | 26 | TypeScript | 0.214 | question | 93 | 51 | 51 | false | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
logger.warn(
'There was an error while preloading an audio file: ' + error
);
throw error;
}
} else if (
resource.preloadInCache ||
// Force downloading of sounds.
// TODO Decide if sounds should be allowed to be downloaded after the scene starts.
// - they should be requested automatically at the end of the scene loading
// - they will be downloaded while the scene is playing
// - other scenes will be pre-loaded only when all the sounds for the current scene are in cache
!resource.preloadAsMusic
) {
// preloading as sound already does a XHR request, hence "else if"
try {
const file = resource.file;
await new Promise((resolve, reject) => {
const sound = new XMLHttpRequest();
sound.withCredentials =
this._resourceLoader.checkIfCredentialsRequired(file);
sound.addEventListener('load', () => {
if (sound.status >= 200 && sound.status < 300) {
resolve(undefined);
} else {
reject(`HTTP error! status: ${sound.status}`);
}
});
sound.addEventListener('error', (_) =>
reject('XHR error: ' + file)
);
sound.addEventListener('abort', (_) =>
reject('XHR abort: ' + file)
);
sound.open('GET', this._getDefaultSoundUrl(resource));
sound.send();
});
} catch (error) {
delete this._availableResources[resource.name];
logger.warn(
'There was an error while preloading an audio file: ' + error
);
throw error;
}
}
}
getNetworkSyncData(): SoundManagerSyncData {
const freeMusicsNetworkSyncData: SoundSyncData[] = [];
this._freeMusics.forEach((freeMusic) => {
const musicSyncData = freeMusic.getNetworkSyncData(); | I suggest an exception that gives more context to ease debugging:
```suggestion
reject(`HTTP error while preloading audio file in cache. Status is ${sound.status}.`);
``` | logger.warn(
'There was an error while preloading an audio file: ' + error
);
throw error;
}
} else if (
resource.preloadInCache ||
// Force downloading of sounds.
// TODO Decide if sounds should be allowed to be downloaded after the scene starts.
// - they should be requested automatically at the end of the scene loading
// - they will be downloaded while the scene is playing
// - other scenes will be pre-loaded only when all the sounds for the current scene are in cache
!resource.preloadAsMusic
) {
// preloading as sound already does a XHR request, hence "else if"
try {
const file = resource.file;
await new Promise((resolve, reject) => {
const sound = new XMLHttpRequest();
sound.withCredentials =
this._resourceLoader.checkIfCredentialsRequired(file);
sound.addEventListener('load', () => {
if (sound.status >= 200 && sound.status < 300) {
resolve(undefined);
} else {
reject(
`HTTP error while preloading audio file in cache. Status is ${sound.status}.`
);
}
});
sound.addEventListener('error', (_) =>
reject('XHR error: ' + file)
);
sound.addEventListener('abort', (_) =>
reject('XHR abort: ' + file)
);
sound.open('GET', this._getDefaultSoundUrl(resource));
sound.send();
});
} catch (error) {
delete this._availableResources[resource.name];
logger.warn(
'There was an error while preloading an audio file: ' + error
);
throw error;
}
}
}
getNetworkSyncData(): SoundManagerSyncData {
const freeMusicsNetworkSyncData: SoundSyncData[] = []; | @@ -1059,7 +1068,13 @@ namespace gdjs {
const sound = new XMLHttpRequest();
sound.withCredentials =
this._resourceLoader.checkIfCredentialsRequired(file);
- sound.addEventListener('load', resolve);
+ sound.addEventListener('load', () => {
+ if (sound.status >= 200 && sound.status < 300) {
+ resolve(undefined);
+ } else {
+ reject(`HTTP error! status: ${sound.status}`); | GDJS/Runtime/howler-sound-manager/howler-sound-manager.ts | 26 | TypeScript | 0.857 | bug | 186 | 51 | 51 | false | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
if (!resource) {
logger.warn(
'Unable to find bitmap font for resource "' + resourceName + '".'
);
return;
}
if (this._loadedFontsData.get(resource)) {
return;
}
try {
const response = await fetch(
this._resourceLoader.getFullUrl(resource.file),
{
credentials: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? // Any resource stored on the GDevelop Cloud buckets needs the "credentials" of the user,
// i.e: its gdevelop.io cookie, to be passed.
'include'
: // For other resources, use "same-origin" as done by default by fetch.
'same-origin',
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fontDataRaw = await response.text();
// Sanitize: remove lines starting with # (acting as comments)
const sanitizedFontData = fontDataRaw
.split('\n')
.filter((line) => !line.trim().startsWith('#'))
.join('\n');
this._loadedFontsData.set(resource, sanitizedFontData);
} catch (error) {
logger.error(
"Can't fetch the bitmap font file " +
resource.file +
', error: ' +
error
);
this._loadedFontsData.delete(resource);
throw error;
}
}
/**
* To be called when the game is disposed. | ```suggestion
throw new Error(`HTTP error while loading bitmap font. Status is ${sound.status}.`);
``` | if (!resource) {
logger.warn(
'Unable to find bitmap font for resource "' + resourceName + '".'
);
return;
}
if (this._loadedFontsData.get(resource)) {
return;
}
try {
const response = await fetch(
this._resourceLoader.getFullUrl(resource.file),
{
credentials: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? // Any resource stored on the GDevelop Cloud buckets needs the "credentials" of the user,
// i.e: its gdevelop.io cookie, to be passed.
'include'
: // For other resources, use "same-origin" as done by default by fetch.
'same-origin',
}
);
if (!response.ok) {
throw new Error(
`HTTP error while loading bitmap font. Status is ${response.status}.`
);
}
const fontDataRaw = await response.text();
// Sanitize: remove lines starting with # (acting as comments)
const sanitizedFontData = fontDataRaw
.split('\n')
.filter((line) => !line.trim().startsWith('#'))
.join('\n');
this._loadedFontsData.set(resource, sanitizedFontData);
} catch (error) {
logger.error(
"Can't fetch the bitmap font file " +
resource.file +
', error: ' +
error
);
this._loadedFontsData.delete(resource);
throw error;
}
}
| @@ -278,6 +278,10 @@ namespace gdjs {
'same-origin',
}
);
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`); | GDJS/Runtime/pixi-renderers/pixi-bitmapfont-manager.ts | 26 | TypeScript | 0.857 | suggestion | 112 | 51 | 51 | false | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
? resource
: null;
};
/**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
try {
await this._loadTexture(resource);
} catch (error) {
throw error;
}
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
* @param onProgress Callback called each time a new file is loaded.
*/
async _loadTexture(resource: ResourceData): Promise<void> {
if (this._loadedTextures.get(resource)) {
return;
}
const resourceUrl = this._resourceLoader.getFullUrl(resource.file);
try {
if (resource.kind === 'video') {
// For videos, we want to preload them so they are available as soon as we want to use them.
// We cannot use Pixi.assets.load() as it does not allow passing options (autoplay) to the resource loader.
// Pixi.Texture.from() does not return a promise, so we need to ensure we look at the 'loaded' event of the baseTexture, | Same comment here: this looks unnecessary? | ? resource
: null;
};
/**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
await this._loadTexture(resource);
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
* @param onProgress Callback called each time a new file is loaded.
*/
async _loadTexture(resource: ResourceData): Promise<void> {
if (this._loadedTextures.get(resource)) {
return;
}
const resourceUrl = this._resourceLoader.getFullUrl(resource.file);
try {
if (resource.kind === 'video') {
// For videos, we want to preload them so they are available as soon as we want to use them.
// We cannot use Pixi.assets.load() as it does not allow passing options (autoplay) to the resource loader.
// Pixi.Texture.from() does not return a promise, so we need to ensure we look at the 'loaded' event of the baseTexture,
// to continue, otherwise if we try to play the video too soon (at the beginning of scene for instance),
// it will fail.
await new Promise<void>((resolve, reject) => {
const texture = PIXI.Texture.from(resourceUrl, {
resourceOptions: { | @@ -400,7 +400,12 @@ namespace gdjs {
);
return;
}
- await this._loadTexture(resource);
+
+ try { | GDJS/Runtime/pixi-renderers/pixi-image-manager.ts | 26 | TypeScript | 0.071 | question | 42 | 51 | 51 | false | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
})
.on('error', (error) => {
reject(error);
});
});
} else {
// If the file has no extension, PIXI.assets.load cannot find
// an adequate load parser and does not load the file although
// we would like to force it to load (we are confident it's an image).
// TODO: When PIXI v8+ is used, PIXI.Assets.load can be used because
// loadParser can be forced in PIXI.Assets.load
// (see https://github.com/pixijs/pixijs/blob/71ed56c569ebc6b53da19e3c49258a0a84892101/packages/assets/src/loader/Loader.ts#L68)
const loadedTexture = PIXI.Texture.from(resourceUrl, {
resourceOptions: {
autoLoad: false,
crossorigin: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? 'use-credentials'
: 'anonymous',
},
});
await loadedTexture.baseTexture.resource.load();
this._loadedTextures.set(resource, loadedTexture);
// TODO What if 2 assets share the same file with different settings?
applyTextureSettings(loadedTexture, resource);
}
} catch (error) {
logFileLoadingError(resource.file, error);
PIXI.Texture.removeFromCache(resourceUrl);
PIXI.BaseTexture.removeFromCache(resourceUrl);
throw error;
}
}
/**
* Return a texture containing a circle filled with white.
* @param radius The circle radius
* @param pixiRenderer The renderer used to generate the texture
*/
getOrCreateDiskTexture(
radius: float,
pixiRenderer: PIXI.Renderer
): PIXI.Texture {
let particleTexture = this._diskTextures.get(radius);
if (!particleTexture) {
const graphics = new PIXI.Graphics();
graphics.lineStyle(0, 0, 0);
graphics.beginFill(gdjs.rgbToHexNumber(255, 255, 255), 1);
graphics.drawCircle(0, 0, radius); | Have you observed this to be useful? I wonder if this will work because the internal texture id used by PixiJS could be different than the resourceUrl? | } else {
// If the file has no extension, PIXI.assets.load cannot find
// an adequate load parser and does not load the file although
// we would like to force it to load (we are confident it's an image).
// TODO: When PIXI v8+ is used, PIXI.Assets.load can be used because
// loadParser can be forced in PIXI.Assets.load
// (see https://github.com/pixijs/pixijs/blob/71ed56c569ebc6b53da19e3c49258a0a84892101/packages/assets/src/loader/Loader.ts#L68)
const loadedTexture = PIXI.Texture.from(resourceUrl, {
resourceOptions: {
autoLoad: false,
crossorigin: this._resourceLoader.checkIfCredentialsRequired(
resource.file
)
? 'use-credentials'
: 'anonymous',
},
});
await loadedTexture.baseTexture.resource.load();
this._loadedTextures.set(resource, loadedTexture);
// TODO What if 2 assets share the same file with different settings?
applyTextureSettings(loadedTexture, resource);
}
} catch (error) {
logFileLoadingError(resource.file, error);
PIXI.Texture.removeFromCache(resourceUrl);
PIXI.BaseTexture.removeFromCache(resourceUrl);
throw error;
}
}
/**
* Return a texture containing a circle filled with white.
* @param radius The circle radius
* @param pixiRenderer The renderer used to generate the texture
*/
getOrCreateDiskTexture(
radius: float,
pixiRenderer: PIXI.Renderer
): PIXI.Texture {
let particleTexture = this._diskTextures.get(radius);
if (!particleTexture) {
const graphics = new PIXI.Graphics();
graphics.lineStyle(0, 0, 0);
graphics.beginFill(gdjs.rgbToHexNumber(255, 255, 255), 1);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
particleTexture = pixiRenderer.generateTexture(graphics);
graphics.destroy();
this._diskTextures.set(radius, particleTexture); | @@ -479,6 +479,9 @@ namespace gdjs {
}
} catch (error) {
logFileLoadingError(resource.file, error);
+ PIXI.Texture.removeFromCache(resourceUrl); | GDJS/Runtime/pixi-renderers/pixi-image-manager.ts | 26 | TypeScript | 0.429 | question | 151 | 51 | 51 | false | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
alignItems: 'stretch',
overflowY: 'auto',
},
planCardsLineContainer: {
display: 'inline-flex',
flexDirection: 'row',
alignItems: 'stretch',
gap: 8,
overflowY: 'auto',
},
currentPlanPaper: {
padding: '8px 12px',
},
};
const cancelConfirmationTexts = {
title: t`Cancel your subscription?`,
message: t`By canceling your subscription, you will lose all your premium features at the end of the period you already paid for. Continue?`,
confirmButtonLabel: t`Continue`,
dismissButtonLabel: t`Keep subscription`,
maxWidth: 'sm',
};
const seamlesslyChangeConfirmationTexts = {
title: t`Update your subscription`,
message: t`Are you sure you want to change your plan? Your next payment will be pro-rated.`,
confirmButtonLabel: t`Update my subscription`,
dismissButtonLabel: t`Go back`,
maxWidth: 'sm',
};
const cancelAndChangeConfirmationTexts = {
title: t`Update your subscription`,
message: t`To get this new subscription, we need to stop your existing one before you can pay for the new one. This is immediate but your payment will NOT be pro-rated (you will pay the full price for the new subscription). You won't lose any project, game or other data.`,
confirmButtonLabel: t`Cancel and upgrade my subscription`,
dismissButtonLabel: t`Go back`,
maxWidth: 'sm',
};
const cancelAndChangeWithValidRedeemedCodeConfirmationTexts = {
title: t`Update your subscription`,
message: t`To get this new subscription, we need to stop your existing one before you can pay for the new one. The change will be immediate. You will also lose your redeemed code.`,
confirmButtonLabel: t`Update my subscription`,
dismissButtonLabel: t`Go back`,
maxWidth: 'sm',
};
const getSubscriptionPricingSystemPeriod = (
subscription: ?Subscription,
subscriptionPlansWithPricingSystems: ?(SubscriptionPlanWithPricingSystems[])
): null | 'year' | 'month' => {
if (!subscription || !subscriptionPlansWithPricingSystems) return null;
const allPricingSystems = subscriptionPlansWithPricingSystems
.map( | should this be danger / warning too? | overflowY: 'auto',
},
planCardsLineContainer: {
display: 'inline-flex',
flexDirection: 'row',
alignItems: 'stretch',
gap: 8,
overflowY: 'auto',
},
currentPlanPaper: {
padding: '8px 12px',
},
};
const cancelConfirmationTexts = {
level: 'normal',
dialogTexts: {
title: t`Cancel your subscription?`,
message: t`By canceling your subscription, you will lose all your premium features at the end of the period you already paid for. Continue?`,
confirmButtonLabel: t`Continue`,
dismissButtonLabel: t`Keep subscription`,
maxWidth: 'sm',
},
};
const cancelAndChangeConfirmationTexts = {
level: 'normal',
dialogTexts: {
title: t`Update your subscription`,
message: t`To get this new subscription, we need to stop your existing one before you can pay for the new one. This is immediate but your payment will NOT be pro-rated (you will pay the full price for the new subscription). You won't lose any project, game or other data.`,
confirmButtonLabel: t`Cancel and upgrade my subscription`,
dismissButtonLabel: t`Go back`,
maxWidth: 'sm',
},
};
const cancelAndChangeWithValidRedeemedCodeConfirmationTexts = {
level: 'danger',
dialogTexts: {
title: t`Update your subscription`,
message: t`To buy this new subscription, we need to stop your existing one before you can pay for the new one. This means the redemption code you're currently used won't be usable anymore.`,
confirmButtonLabel: t`Forfeit my redeemed subscription and continue`,
dismissButtonLabel: t`Go back`,
maxWidth: 'sm',
},
};
const getSubscriptionPricingSystemPeriod = (
subscription: ?Subscription,
subscriptionPlansWithPricingSystems: ?(SubscriptionPlanWithPricingSystems[])
): null | 'year' | 'month' => {
if (!subscription || !subscriptionPlansWithPricingSystems) return null;
const allPricingSystems = subscriptionPlansWithPricingSystems | @@ -94,32 +93,34 @@ const styles = {
};
const cancelConfirmationTexts = {
- title: t`Cancel your subscription?`,
- message: t`By canceling your subscription, you will lose all your premium features at the end of the period you already paid for. Continue?`,
- confirmButtonLabel: t`Continue`,
- dismissButtonLabel: t`Keep subscription`,
- maxWidth: 'sm',
-};
-const seamlesslyChangeConfirmationTexts = {
- title: t`Update your subscription`,
- message: t`Are you sure you want to change your plan? Your next payment will be pro-rated.`,
- confirmButtonLabel: t`Update my subscription`,
- dismissButtonLabel: t`Go back`,
- maxWidth: 'sm',
+ level: 'normal',
+ dialogTexts: {
+ title: t`Cancel your subscription?`,
+ message: t`By canceling your subscription, you will lose all your premium features at the end of the period you already paid for. Continue?`,
+ confirmButtonLabel: t`Continue`,
+ dismissButtonLabel: t`Keep subscription`,
+ maxWidth: 'sm',
+ },
};
const cancelAndChangeConfirmationTexts = {
- title: t`Update your subscription`,
- message: t`To get this new subscription, we need to stop your existing one before you can pay for the new one. This is immediate but your payment will NOT be pro-rated (you will pay the full price for the new subscription). You won't lose any project, game or other data.`,
- confirmButtonLabel: t`Cancel and upgrade my subscription`,
- dismissButtonLabel: t`Go back`,
- maxWidth: 'sm',
+ level: 'normal', | newIDE/app/src/Profile/Subscription/SubscriptionDialog.js | 26 | JavaScript | 0.143 | question | 36 | 51 | 51 | false | Make clearer warning when stopping subscription with a redemption code | 8,070 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | 4ian |
// @flow
import { type ProjectSettings } from './ProjectSettingsReader';
import { type Preferences } from '../MainFrame/Preferences/PreferencesContext';
/**
* Applies project-specific settings from a settings.ini file to the editor preferences.
* This allows projects to override certain editor preferences when they are opened.
*
* @param settings - The parsed project settings from settings.ini
* @param preferences - The preferences context with setters
*/
export const applyProjectSettings = (
settings: ProjectSettings,
preferences: Preferences
): void => {
// At launch settings
if (typeof settings.showCreateSectionByDefault === 'boolean') {
preferences.setShowCreateSectionByDefault(
settings.showCreateSectionByDefault
);
}
if (typeof settings.autoOpenMostRecentProject === 'boolean') {
preferences.setAutoOpenMostRecentProject(
settings.autoOpenMostRecentProject
);
}
// Preview settings
if (typeof settings.autosaveOnPreview === 'boolean') {
preferences.setAutosaveOnPreview(settings.autosaveOnPreview);
}
if (typeof settings.fetchPlayerTokenForPreviewAutomatically === 'boolean') {
preferences.setFetchPlayerTokenForPreviewAutomatically(
settings.fetchPlayerTokenForPreviewAutomatically
);
}
if (typeof settings.openDiagnosticReportAutomatically === 'boolean') {
preferences.setOpenDiagnosticReportAutomatically(
settings.openDiagnosticReportAutomatically
);
} | This is fairly verbose. I wonder if we could reduce everything to a few key concepts:
- ProjectSettings renamed to "ProjectSpecificPreferences". It can be a "Partial<Preferences>" (or in Flow, I think it's `$Shape<Preferences>`).
- An "allowlist" of names of preferences that can be overwritten.
- When a project is loaded, preferences are loaded from it and applied without needing to code the calls to the setters.
This would reduce this function to something that iterates on the allowlist. | // @flow
import { type ParsedProjectSettings } from './ProjectSettingsReader';
import {
type Preferences,
type ProjectSpecificPreferencesValues,
} from '../MainFrame/Preferences/PreferencesContext';
/** Allowlist of preference keys that can be overridden per-project. */
const allowedPreferenceKeys: $ReadOnlyArray<
$Keys<ProjectSpecificPreferencesValues>
> = [
'language',
'autoDownloadUpdates',
'themeName',
'codeEditorThemeName',
'autoDisplayChangelog',
'lastLaunchedVersion',
'eventsSheetShowObjectThumbnails',
'autosaveOnPreview',
'useGDJSDevelopmentWatcher',
'eventsSheetUseAssignmentOperators',
'eventsSheetIndentScale',
'eventsSheetZoomLevel',
'showEffectParameterNames',
'autoOpenMostRecentProject',
'hasProjectOpened',
'newObjectDialogDefaultTab',
'shareDialogDefaultTab',
'isMenuBarHiddenInPreview',
'isAlwaysOnTopInPreview',
'backdropClickBehavior',
'eventsSheetCancelInlineParameter',
'showExperimentalExtensions',
'showCreateSectionByDefault',
'showInAppTutorialDeveloperMode',
'showDeprecatedInstructionWarning',
'openDiagnosticReportAutomatically',
'use3DEditor',
'showBasicProfilingCounters',
'newProjectsDefaultFolder',
'newProjectsDefaultStorageProviderName', | @@ -0,0 +1,117 @@
+// @flow
+import { type ProjectSettings } from './ProjectSettingsReader';
+import { type Preferences } from '../MainFrame/Preferences/PreferencesContext';
+
+/**
+ * Applies project-specific settings from a settings.ini file to the editor preferences.
+ * This allows projects to override certain editor preferences when they are opened.
+ *
+ * @param settings - The parsed project settings from settings.ini
+ * @param preferences - The preferences context with setters
+ */
+export const applyProjectSettings = (
+ settings: ProjectSettings,
+ preferences: Preferences
+): void => {
+ // At launch settings | newIDE/app/src/Utils/ApplyProjectSettings.js | 16 | JavaScript | 0.643 | suggestion | 496 | 41 | 41 | false | feat: Project-specific Editor Settings | 8,101 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | malec-palec |
});
test('ignores non-boolean values', () => {
const rawSettings = {
autosaveOnPreview: 'true',
use3DEditor: 42,
showDeprecatedInstructionWarning: null,
};
expect(convertToProjectSettings(rawSettings)).toEqual({});
});
test('handles all valid preference keys', () => {
const rawSettings: { [string]: boolean } = {};
VALID_PREFERENCE_KEYS.forEach(key => {
rawSettings[key] = true;
});
const result = convertToProjectSettings(rawSettings);
VALID_PREFERENCE_KEYS.forEach(key => {
expect(result[key]).toBe(true);
});
});
});
describe('VALID_PREFERENCE_KEYS', () => {
test('contains expected keys', () => {
expect(VALID_PREFERENCE_KEYS.has('autosaveOnPreview')).toBe(true);
expect(VALID_PREFERENCE_KEYS.has('use3DEditor')).toBe(true);
expect(
VALID_PREFERENCE_KEYS.has('showDeprecatedInstructionWarning')
).toBe(true);
expect(VALID_PREFERENCE_KEYS.has('useGDJSDevelopmentWatcher')).toBe(true);
});
test('does not contain invalid keys', () => {
expect(VALID_PREFERENCE_KEYS.has('invalidKey')).toBe(false);
expect(VALID_PREFERENCE_KEYS.has('')).toBe(false);
});
});
});
| These tests are a bit of a "tautology". I would rather reduce the noise-to-signal ratio by not having them, as "testing a Set" is not super interesting and will actually make the codebase less flexible (because you have to remember updating these if at some point you rework the set to be something else). In other words, the Set is not really something I would expose to the "outside world".
I think the only test that would be worth having is one that the content from a file (Yaml file maybe, as discussed in my other comment) is properly applied to preferences. | // @flow
import {
filterAllowedPreferences,
applyProjectSettings,
} from './ApplyProjectSettings';
import YAML from 'yaml';
describe('ProjectSettingsReader', () => {
describe('end-to-end: YAML content applied to preferences', () => {
test('gdevelop-settings.yaml content is properly parsed, filtered, and applied to preferences', () => {
const yamlContent = `
# Project settings
preferences:
# Boolean values
autosaveOnPreview: true
takeScreenshotOnPreview: false
use3DEditor: true
showBasicProfilingCounters: false
showDeprecatedInstructionWarning: true
# String values
themeName: "Dark"
language: "en"
newProjectsDefaultFolder: "/path/to/projects"
# Number values
eventsSheetZoomLevel: 1.5
eventsSheetIndentScale: 2
# Unknown preference (not in allowlist)
unknownPreference: true
# Unsupported types (should be ignored by readProjectSettings)
arrayValue:
- item1
- item2
objectValue:
nested: true
nullValue: null
`;
// Step 1: Parse YAML
const parsed = YAML.parse(yamlContent);
expect(parsed).toHaveProperty('preferences');
// Step 2: Extract preferences section - includes all types from YAML
const rawPreferences = parsed.preferences;
expect(rawPreferences).toEqual({
autosaveOnPreview: true,
takeScreenshotOnPreview: false,
use3DEditor: true,
showBasicProfilingCounters: false,
showDeprecatedInstructionWarning: true,
themeName: 'Dark',
language: 'en',
newProjectsDefaultFolder: '/path/to/projects',
eventsSheetZoomLevel: 1.5,
eventsSheetIndentScale: 2,
unknownPreference: true,
arrayValue: ['item1', 'item2'],
objectValue: { nested: true },
nullValue: null,
});
// Step 3: Filter by allowlist (only allowed primitive types pass through)
const filtered = filterAllowedPreferences(rawPreferences);
expect(filtered).toEqual({
autosaveOnPreview: true,
takeScreenshotOnPreview: false,
use3DEditor: true,
showBasicProfilingCounters: false,
showDeprecatedInstructionWarning: true,
themeName: 'Dark',
language: 'en',
newProjectsDefaultFolder: '/path/to/projects',
eventsSheetZoomLevel: 1.5,
eventsSheetIndentScale: 2,
});
// Step 4: Apply to preferences via setMultipleValues
const mockSetMultipleValues = jest.fn();
const mockPreferences = {
values: {},
setMultipleValues: mockSetMultipleValues,
};
// $FlowFixMe - partial mock
applyProjectSettings({ preferences: rawPreferences }, mockPreferences);
expect(mockSetMultipleValues).toHaveBeenCalledWith({
autosaveOnPreview: true,
takeScreenshotOnPreview: false,
use3DEditor: true,
showBasicProfilingCounters: false,
showDeprecatedInstructionWarning: true,
themeName: 'Dark',
language: 'en',
newProjectsDefaultFolder: '/path/to/projects',
eventsSheetZoomLevel: 1.5,
eventsSheetIndentScale: 2,
});
});
test('readProjectSettings would return null when preferences section is missing', () => {
const yamlContent = `
# Project settings without preferences
someOtherSection:
key: value
`;
const parsed = YAML.parse(yamlContent);
// readProjectSettings checks for preferences and returns null if missing
expect(parsed.preferences).toBeUndefined();
});
test('readProjectSettings would return null when preferences section is empty', () => {
const yamlContent = `
# Project settings with empty preferences
preferences:
`;
const parsed = YAML.parse(yamlContent);
// readProjectSettings checks for preferences and returns null if empty/null
expect(parsed.preferences).toBeNull();
});
});
});
| @@ -0,0 +1,265 @@
+// @flow
+import {
+ flattenIniObject,
+ convertToProjectSettings,
+ VALID_PREFERENCE_KEYS,
+} from './ProjectSettingsReader';
+import ini from 'ini';
+
+describe('ProjectSettingsReader', () => {
+ describe('ini library parsing', () => {
+ test('parses true/false as native booleans', () => {
+ const content = `
+key1 = true
+key2 = false
+`;
+ const parsed = ini.parse(content);
+ expect(parsed.key1).toBe(true);
+ expect(parsed.key2).toBe(false);
+ expect(typeof parsed.key1).toBe('boolean');
+ expect(typeof parsed.key2).toBe('boolean');
+ });
+
+ test('parses yes/no as strings', () => {
+ const content = `
+key1 = yes
+key2 = no
+`;
+ const parsed = ini.parse(content);
+ expect(parsed.key1).toBe('yes');
+ expect(parsed.key2).toBe('no');
+ expect(typeof parsed.key1).toBe('string');
+ expect(typeof parsed.key2).toBe('string');
+ });
+
+ test('parses 1/0 as strings', () => {
+ const content = `
+key1 = 1
+key2 = 0
+`;
+ const parsed = ini.parse(content);
+ expect(parsed.key1).toBe('1');
+ expect(parsed.key2).toBe('0');
+ expect(typeof parsed.key1).toBe('string');
+ expect(typeof parsed.key2).toBe('string');
+ });
+
+ test('parses sections correctly', () => {
+ const content = `
+[Section1]
+key1 = true
+
+[Section2]
+key2 = false
+`;
+ const parsed = ini.parse(content);
+ expect(parsed.Section1.key1).toBe(true);
+ expect(parsed.Section2.key2).toBe(false);
+ });
+
+ test('parses case variations as strings (not booleans)', () => {
+ const content = `
+key1 = True
+key2 = TRUE
+key3 = False
+key4 = FALSE
+key5 = fAlSe
+`;
+ const parsed = ini.parse(content);
+ // ini library only recognizes lowercase true/false as booleans
+ // All case variations are parsed as strings
+ expect(parsed.key1).toBe('True');
+ expect(parsed.key2).toBe('TRUE');
+ expect(parsed.key3).toBe('False');
+ expect(parsed.key4).toBe('FALSE');
+ expect(parsed.key5).toBe('fAlSe');
+ expect(typeof parsed.key1).toBe('string');
+ });
+ });
+
+ describe('flattenIniObject', () => {
+ test('returns empty object for empty input', () => {
+ expect(flattenIniObject({})).toEqual({});
+ });
+
+ test('handles flat key-value pairs', () => {
+ const parsed = {
+ autosaveOnPreview: true,
+ use3DEditor: false,
+ };
+ expect(flattenIniObject(parsed)).toEqual({
+ autosaveOnPreview: true,
+ use3DEditor: false,
+ });
+ });
+
+ test('flattens sectioned INI object', () => {
+ const parsed = {
+ Previews: {
+ autosaveOnPreview: true,
+ takeScreenshotOnPreview: false,
+ },
+ SceneEditor: {
+ use3DEditor: true,
+ },
+ };
+ expect(flattenIniObject(parsed)).toEqual({
+ autosaveOnPreview: true,
+ takeScreenshotOnPreview: false,
+ use3DEditor: true,
+ });
+ });
+
+ test('handles mixed flat and sectioned values', () => {
+ const parsed = {
+ autosaveOnPreview: true,
+ Previews: {
+ takeScreenshotOnPreview: false,
+ },
+ };
+ expect(flattenIniObject(parsed)).toEqual({
+ autosaveOnPreview: true,
+ takeScreenshotOnPreview: false,
+ });
+ });
+
+ test('handles string values', () => {
+ const parsed = {
+ someKey: 'someValue',
+ };
+ expect(flattenIniObject(parsed)).toEqual({
+ someKey: 'someValue',
+ });
+ });
+
+ test('handles number values', () => {
+ const parsed = {
+ someNumber: 42,
+ };
+ expect(flattenIniObject(parsed)).toEqual({
+ someNumber: 42,
+ });
+ });
+
+ test('warns on duplicate keys across sections', () => {
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const parsed = {
+ Section1: {
+ duplicateKey: true,
+ },
+ Section2: {
+ duplicateKey: false,
+ },
+ };
+ const result = flattenIniObject(parsed);
+
+ expect(result).toEqual({ duplicateKey: false });
+ expect(warnSpy).toHaveBeenCalledWith(
+ '[ProjectSettingsReader] Duplicate key "duplicateKey" found, overwriting previous value'
+ );
+
+ warnSpy.mockRestore();
+ });
+
+ test('warns on duplicate keys between root and section', () => {
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const parsed = {
+ myKey: true,
+ Section: {
+ myKey: false,
+ },
+ };
+ const result = flattenIniObject(parsed);
+
+ expect(result).toEqual({ myKey: false });
+ expect(warnSpy).toHaveBeenCalledWith(
+ '[ProjectSettingsReader] Duplicate key "myKey" found, overwriting previous value'
+ );
+
+ warnSpy.mockRestore();
+ });
+ });
+
+ describe('convertToProjectSettings', () => {
+ test('returns empty object for empty input', () => {
+ expect(convertToProjectSettings({})).toEqual({});
+ });
+
+ test('converts valid boolean settings', () => {
+ const rawSettings = {
+ autosaveOnPreview: true,
+ use3DEditor: false,
+ showDeprecatedInstructionWarning: true,
+ };
+ expect(convertToProjectSettings(rawSettings)).toEqual({
+ autosaveOnPreview: true,
+ use3DEditor: false,
+ showDeprecatedInstructionWarning: true,
+ });
+ });
+
+ test('ignores unknown keys and logs warning', () => {
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const rawSettings = {
+ autosaveOnPreview: true,
+ unknownKey: true,
+ anotherUnknown: false,
+ };
+ const result = convertToProjectSettings(rawSettings);
+
+ expect(result).toEqual({
+ autosaveOnPreview: true,
+ });
+ expect(warnSpy).toHaveBeenCalledTimes(2);
+ expect(warnSpy).toHaveBeenCalledWith(
+ '[ProjectSettingsReader] Unknown setting key: unknownKey'
+ );
+ expect(warnSpy).toHaveBeenCalledWith(
+ '[ProjectSettingsReader] Unknown setting key: anotherUnknown'
+ );
+
+ warnSpy.mockRestore();
+ });
+
+ test('ignores non-boolean values', () => {
+ const rawSettings = {
+ autosaveOnPreview: 'true',
+ use3DEditor: 42,
+ showDeprecatedInstructionWarning: null,
+ };
+ expect(convertToProjectSettings(rawSettings)).toEqual({});
+ });
+
+ test('handles all valid preference keys', () => {
+ const rawSettings: { [string]: boolean } = {};
+ VALID_PREFERENCE_KEYS.forEach(key => {
+ rawSettings[key] = true;
+ });
+
+ const result = convertToProjectSettings(rawSettings);
+
+ VALID_PREFERENCE_KEYS.forEach(key => {
+ expect(result[key]).toBe(true);
+ });
+ });
+ });
+
+ describe('VALID_PREFERENCE_KEYS', () => { | newIDE/app/src/Utils/ProjectSettingsReader.spec.js | 26 | JavaScript | 0.5 | suggestion | 566 | 42 | 121 | false | feat: Project-specific Editor Settings | 8,101 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | malec-palec |
// @flow
import optionalRequire from './OptionalRequire';
import YAML from 'yaml';
const fs = optionalRequire('node:fs');
const fsPromises = fs ? fs.promises : null;
const path = optionalRequire('node:path');
export type RawProjectSettings = {
preferences?: { [string]: mixed },
};
export type ParsedProjectSettings = {
preferences: { [string]: boolean | string | number },
};
const SETTINGS_FILE_NAME = 'settings.yaml';
/**
* Gets the directory path from a project file path.
*/
const getProjectDirectory = (projectFilePath: string): string | null => {
if (!path) return null;
return path.dirname(projectFilePath);
};
/**
* Reads and parses the settings.yaml file from a project's root directory.
* Returns null if:
* - The file doesn't exist
* - The file system is not available (running in browser)
* - The project path is not a local file path
*
* @param projectFilePath - The full path to the project's main JSON file
* @returns Parsed project settings or null
*/
export const readProjectSettings = async (
projectFilePath: string
): Promise<ParsedProjectSettings | null> => {
if (!fsPromises || !path) {
return null;
} | I suggest we use a slightly more specific name to avoid conflicts:
```suggestion
const SETTINGS_FILE_NAME = 'gdevelop-settings.yaml';
``` | // @flow
import optionalRequire from './OptionalRequire';
import YAML from 'yaml';
import { SafeExtractor } from './SafeExtractor';
const fs = optionalRequire('fs');
const fsPromises = fs ? fs.promises : null;
const path = optionalRequire('path');
export type ParsedProjectSettings = {
preferences: { [string]: boolean | string | number },
};
const SETTINGS_FILE_NAME = 'gdevelop-settings.yaml';
const getProjectDirectory = (projectFilePath: string): string | null => {
if (!path) return null;
return path.dirname(projectFilePath);
};
/**
* Reads and parses the gdevelop-settings.yaml file from a project's root directory.
* Returns null if:
* - The file doesn't exist
* - The file system is not available (running in browser)
* - The project path is not a local file path
*/
export const readProjectSettings = async (
projectFilePath: string
): Promise<ParsedProjectSettings | null> => {
if (!fsPromises || !path) {
return null;
}
const projectDirectory = getProjectDirectory(projectFilePath);
if (!projectDirectory) {
return null;
}
const settingsFilePath = path.join(projectDirectory, SETTINGS_FILE_NAME);
try { | @@ -0,0 +1,97 @@
+// @flow
+import optionalRequire from './OptionalRequire';
+import YAML from 'yaml';
+
+const fs = optionalRequire('node:fs');
+const fsPromises = fs ? fs.promises : null;
+const path = optionalRequire('node:path');
+
+export type RawProjectSettings = {
+ preferences?: { [string]: mixed },
+};
+
+export type ParsedProjectSettings = {
+ preferences: { [string]: boolean | string | number },
+};
+
+const SETTINGS_FILE_NAME = 'settings.yaml'; | newIDE/app/src/Utils/ProjectSettingsReader.js | 17 | JavaScript | 0.786 | suggestion | 137 | 42 | 42 | false | feat: Project-specific Editor Settings | 8,101 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | malec-palec |
!!remote &&
!!this.props.fileMetadata &&
this.props.storageProvider.internalName === 'LocalFile'
}
onToggleProperties={this.toggleProperties}
isPropertiesShown={openedEditorNames.includes('properties')}
canDelete={!!this.state.selectedResource}
onDeleteSelection={() =>
this.deleteResource(this.state.selectedResource)
}
/>
);
};
deleteResource = (resource: ?gdResource) => {
const { project, onDeleteResource } = this.props;
if (!resource) return;
const answer = Window.showConfirmDialog(
"Are you sure you want to remove this resource? This can't be undone."
);
if (!answer) return;
const resourcesManager = project.getResourcesManager();
const allNames = resourcesManager.getAllResourceNames().toJSArray();
const currentIndex = allNames.indexOf(resource.getName());
let nextResourceName = null;
if (allNames.length > 1) {
const nextIndex =
currentIndex < allNames.length - 1
? currentIndex + 1
: currentIndex - 1;
nextResourceName = allNames[nextIndex];
}
onDeleteResource(resource, doRemove => {
if (!doRemove || !resource) return;
resourcesManager.removeResource(resource.getName());
const nextResourceToSelect = nextResourceName
? resourcesManager.getResource(nextResourceName)
: null;
this.setState(
{
selectedResource: nextResourceToSelect,
},
() => {
if (this._resourcesList) { | Use `GetResourcePosition`. No need for allNames | );
onDeleteResource(resource, doRemove => {
if (!doRemove || !resource) return;
resourcesManager.removeResource(resource.getName());
const newCount = resourcesManager.count();
const nextResourceToSelect =
newCount > 0
? resourcesManager.getResourceAt(Math.min(currentIndex, newCount - 1))
: null;
this.setState(
{
selectedResource: nextResourceToSelect,
},
() => {
const resourcesList = this._resourcesList;
if (resourcesList) {
resourcesList.forceUpdateList();
resourcesList.focusList();
}
const propertiesEditor = this._propertiesEditor;
if (propertiesEditor) propertiesEditor.forceUpdate();
this.updateToolbar();
}
);
});
};
renameResource = (resource: gdResource, newName: string) => {
const { project, onRenameResource } = this.props;
// Nothing to do if the name is not changed or empty.
if (resource.getName() === newName || newName.length === 0) return;
// Check for duplicate names.
const resourcesManager = project.getResourcesManager();
if (resourcesManager.hasResource(newName)) {
showWarningBox('Another resource with this name already exists', {
delayToNextTick: true,
});
return;
}
onRenameResource(resource, newName, doRename => {
if (!doRename) return;
resource.setName(newName);
| @@ -126,18 +157,38 @@ export default class ResourcesEditor extends React.Component<Props, State> {
);
if (!answer) return;
+ const resourcesManager = project.getResourcesManager();
+ const allNames = resourcesManager.getAllResourceNames().toJSArray();
+ const currentIndex = allNames.indexOf(resource.getName()); | newIDE/app/src/ResourcesEditor/index.js | 26 | JavaScript | 0.286 | suggestion | 47 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
}
onToggleProperties={this.toggleProperties}
isPropertiesShown={openedEditorNames.includes('properties')}
canDelete={!!this.state.selectedResource}
onDeleteSelection={() =>
this.deleteResource(this.state.selectedResource)
}
/>
);
};
deleteResource = (resource: ?gdResource) => {
const { project, onDeleteResource } = this.props;
if (!resource) return;
const answer = Window.showConfirmDialog(
"Are you sure you want to remove this resource? This can't be undone."
);
if (!answer) return;
const resourcesManager = project.getResourcesManager();
const allNames = resourcesManager.getAllResourceNames().toJSArray();
const currentIndex = allNames.indexOf(resource.getName());
let nextResourceName = null;
if (allNames.length > 1) {
const nextIndex =
currentIndex < allNames.length - 1
? currentIndex + 1
: currentIndex - 1;
nextResourceName = allNames[nextIndex];
}
onDeleteResource(resource, doRemove => {
if (!doRemove || !resource) return;
resourcesManager.removeResource(resource.getName());
const nextResourceToSelect = nextResourceName
? resourcesManager.getResource(nextResourceName)
: null;
this.setState(
{
selectedResource: nextResourceToSelect,
},
() => {
if (this._resourcesList) {
this._resourcesList.forceUpdateList();
if (this._resourcesList.focus) this._resourcesList.focus();
} | Ideally we would expose `Count` in Bindings.idl for ResourcesContainer | if (!doRemove || !resource) return;
resourcesManager.removeResource(resource.getName());
const newCount = resourcesManager.count();
const nextResourceToSelect =
newCount > 0
? resourcesManager.getResourceAt(Math.min(currentIndex, newCount - 1))
: null;
this.setState(
{
selectedResource: nextResourceToSelect,
},
() => {
const resourcesList = this._resourcesList;
if (resourcesList) {
resourcesList.forceUpdateList();
resourcesList.focusList();
}
const propertiesEditor = this._propertiesEditor;
if (propertiesEditor) propertiesEditor.forceUpdate();
this.updateToolbar();
}
);
});
};
renameResource = (resource: gdResource, newName: string) => {
const { project, onRenameResource } = this.props;
// Nothing to do if the name is not changed or empty.
if (resource.getName() === newName || newName.length === 0) return;
// Check for duplicate names.
const resourcesManager = project.getResourcesManager();
if (resourcesManager.hasResource(newName)) {
showWarningBox('Another resource with this name already exists', {
delayToNextTick: true,
});
return;
}
onRenameResource(resource, newName, doRename => {
if (!doRename) return;
resource.setName(newName);
const resourcesList = this._resourcesList;
if (resourcesList) {
resourcesList.forceUpdateList(); | @@ -126,18 +157,38 @@ export default class ResourcesEditor extends React.Component<Props, State> {
);
if (!answer) return;
+ const resourcesManager = project.getResourcesManager();
+ const allNames = resourcesManager.getAllResourceNames().toJSArray();
+ const currentIndex = allNames.indexOf(resource.getName());
+
+ let nextResourceName = null;
+ if (allNames.length > 1) { | newIDE/app/src/ResourcesEditor/index.js | 26 | JavaScript | 0.357 | suggestion | 70 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
properties: {
type: 'secondary',
title: t`Properties`,
renderEditor: () => (
<ResourcePropertiesEditor
key={selectedResource ? selectedResource.ptr : undefined}
resources={selectedResource ? [selectedResource] : []}
project={project}
resourcesLoader={this.resourcesLoader}
ref={propertiesEditor =>
(this._propertiesEditor = propertiesEditor)
}
onResourcePathUpdated={() => {
if (this._resourcesList) {
this._resourcesList.checkMissingPaths();
}
}}
resourceManagementProps={resourceManagementProps}
/>
),
},
'resources-list': {
type: 'primary',
noTitleBar: true,
renderEditor: () => (
<div
style={styles.container}
onKeyDown={this._onKeyDown}
>
<ResourcesList
project={project}
fileMetadata={fileMetadata}
onDeleteResource={this.deleteResource}
onRenameResource={onRenameResource}
onSelectResource={this._onResourceSelected}
selectedResource={selectedResource}
ref={resourcesList => (this._resourcesList = resourcesList)}
onRemoveUnusedResources={this._removeUnusedResources}
onRemoveAllResourcesWithInvalidPath={
this._removeAllResourcesWithInvalidPath
}
getResourceActionsSpecificToStorageProvider={
resourcesActionsMenuBuilder
}
onResourceRenamed={() => {
if (this._propertiesEditor) {
this._propertiesEditor.forceUpdate();
}
}}
/>
</div> | Do we really need this container? Could we have a "onKeyDown" on the ResourcesList? |
const editors = {
properties: {
type: 'secondary',
title: t`Properties`,
renderEditor: () => (
<ResourcePropertiesEditor
key={selectedResource ? selectedResource.ptr : undefined}
resources={selectedResource ? [selectedResource] : []}
project={project}
resourcesLoader={this.resourcesLoader}
ref={propertiesEditor =>
(this._propertiesEditor = propertiesEditor)
}
onResourcePathUpdated={() => {
if (this._resourcesList) {
this._resourcesList.checkMissingPaths();
}
}}
resourceManagementProps={resourceManagementProps}
/>
),
},
'resources-list': {
type: 'primary',
noTitleBar: true,
renderEditor: () => (
<ResourcesList
project={project}
fileMetadata={fileMetadata}
onDeleteResource={this.deleteResource}
onRenameResource={this.renameResource}
onSelectResource={this._onResourceSelected}
selectedResource={selectedResource}
ref={resourcesList => (this._resourcesList = resourcesList)}
onRemoveUnusedResources={this._removeUnusedResources}
onRemoveAllResourcesWithInvalidPath={
this._removeAllResourcesWithInvalidPath
}
getResourceActionsSpecificToStorageProvider={
resourcesActionsMenuBuilder
}
/>
),
},
};
return (
<div style={styles.container}>
<PreferencesContext.Consumer>
{({ getDefaultEditorMosaicNode, setDefaultEditorMosaicNode }) => ( | @@ -273,22 +324,32 @@ export default class ResourcesEditor extends React.Component<Props, State> {
type: 'primary',
noTitleBar: true,
renderEditor: () => (
- <ResourcesList
- project={project}
- fileMetadata={fileMetadata}
- onDeleteResource={this.deleteResource}
- onRenameResource={onRenameResource}
- onSelectResource={this._onResourceSelected}
- selectedResource={selectedResource}
- ref={resourcesList => (this._resourcesList = resourcesList)}
- onRemoveUnusedResources={this._removeUnusedResources}
- onRemoveAllResourcesWithInvalidPath={
- this._removeAllResourcesWithInvalidPath
- }
- getResourceActionsSpecificToStorageProvider={
- resourcesActionsMenuBuilder
- }
- />
+ <div | newIDE/app/src/ResourcesEditor/index.js | 26 | JavaScript | 0.286 | question | 83 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
}
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
_onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
this._moveSelection(event.key === 'ArrowDown' ? 1 : -1);
event.preventDefault();
}
};
_moveSelection = (delta: number) => {
const { project } = this.props;
const { selectedResource } = this.state;
const resourcesManager = project.getResourcesManager();
const allNames = resourcesManager.getAllResourceNames().toJSArray();
if (allNames.length === 0) return;
let nextIndex = 0;
if (selectedResource) {
const currentIndex = allNames.indexOf(selectedResource.getName());
nextIndex = Math.max(
0,
Math.min(allNames.length - 1, currentIndex + delta)
);
}
const nextResource = resourcesManager.getResource(allNames[nextIndex]);
if (nextResource !== selectedResource) {
this._onResourceSelected(nextResource);
}
};
refreshResourcesList() {
if (this._resourcesList) this._resourcesList.forceUpdateList();
}
updateToolbar = () => {
const openedEditorNames = this.editorMosaic
? this.editorMosaic.getOpenedEditorNames()
: [];
this.props.setToolbar(
<Toolbar
onOpenProjectFolder={this.openProjectFolder}
canOpenProjectFolder={ | Same as the other, I think it would be worth exposing Count and using GetResourcePosition rather than everytime getting getAllResourceNames + calling to JSArray which creates useless copies of the list of names in memory. | componentDidMount() {
this.resourceExternallyChangedCallbackId = registerOnResourceExternallyChangedCallback(
this.onResourceExternallyChanged.bind(this)
);
}
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
refreshResourcesList() {
if (this._resourcesList) this._resourcesList.forceUpdateList();
}
updateToolbar = () => {
const openedEditorNames = this.editorMosaic
? this.editorMosaic.getOpenedEditorNames()
: [];
this.props.setToolbar(
<Toolbar
onOpenProjectFolder={this.openProjectFolder}
canOpenProjectFolder={
!!remote &&
!!this.props.fileMetadata &&
this.props.storageProvider.internalName === 'LocalFile'
}
onToggleProperties={this.toggleProperties}
isPropertiesShown={openedEditorNames.includes('properties')}
canDelete={!!this.state.selectedResource}
onDeleteSelection={() =>
this.deleteResource(this.state.selectedResource)
}
/>
);
};
deleteResource = (resource: ?gdResource) => {
const { project, onDeleteResource } = this.props;
if (!resource) return;
const answer = Window.showConfirmDialog(
"Are you sure you want to remove this resource? This can't be undone."
);
if (!answer) return;
const resourcesManager = project.getResourcesManager();
const currentIndex = resourcesManager.getResourcePosition(
resource.getName() | @@ -84,12 +84,43 @@ export default class ResourcesEditor extends React.Component<Props, State> {
this.onResourceExternallyChanged.bind(this)
);
}
+
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
+ _onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ this._moveSelection(event.key === 'ArrowDown' ? 1 : -1);
+ event.preventDefault();
+ }
+ };
+
+ _moveSelection = (delta: number) => {
+ const { project } = this.props;
+ const { selectedResource } = this.state;
+ const resourcesManager = project.getResourcesManager();
+ const allNames = resourcesManager.getAllResourceNames().toJSArray();
+
+ if (allNames.length === 0) return;
+
+ let nextIndex = 0;
+ if (selectedResource) {
+ const currentIndex = allNames.indexOf(selectedResource.getName()); | newIDE/app/src/ResourcesEditor/index.js | 26 | JavaScript | 0.643 | suggestion | 221 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
return (
<Background>
<Line>
<Column expand>
<SearchBar
value={searchText}
onRequestSearch={() => {}}
onChange={text => setSearchText(text)}
placeholder={t`Search resources`}
/>
</Column>
</Line>
<div
ref={listContainerRef}
style={styles.listContainer}
tabIndex={0}
onKeyDown={event => keyboardShortcutsRef.current.onKeyDown(event)}
>
<AutoSizer>
{({ height, width }) => (
<I18n>
{({ i18n }) => (
<SortableVirtualizedItemList
key={listKey}
ref={sortableListRef}
fullList={filteredList}
width={width}
height={height}
getItemName={getResourceName}
getItemThumbnail={getResourceThumbnail}
selectedItems={selectedResource ? [selectedResource] : []}
onItemSelected={onSelectResource}
renamedItem={renamedResource}
onRename={renameResource}
onMoveSelectionToItem={moveSelectionTo}
buildMenuTemplate={renderResourceMenuTemplate(i18n)}
erroredItems={resourcesWithErrors}
reactDndType="GD_RESOURCE"
/>
)}
</I18n>
)}
</AutoSizer>
</div>
{!!infoBarContent && (
<InfoBar
duration={7000}
visible
hide={() => setInfoBarContent(null)}
{...infoBarContent} | Add a comment explaining why you don't set onDelete and onRename here. | const checkMissingPaths = React.useCallback(
() => {
const resourcesManager = project.getResourcesManager();
const resourceNames = resourcesManager
.getAllResourceNames()
.toJSArray();
const newResourcesWithErrors = {};
resourceNames.forEach(resourceName => {
// $FlowFixMe[prop-missing]
newResourcesWithErrors[resourceName] = getResourceFilePathStatus(
project,
resourceName
);
});
setResourcesWithErrors(newResourcesWithErrors);
forceUpdateList();
},
[project, forceUpdateList]
);
// KeyboardShortcuts callbacks are set dynamically in useEffect below
// instead of here, because they depend on selectedResource which can change.
// This ensures the callbacks always use the current selectedResource.
const keyboardShortcutsRef = React.useRef<KeyboardShortcuts>(
new KeyboardShortcuts({
shortcutCallbacks: {},
})
);
React.useEffect(
() => {
if (!selectedResource) return;
keyboardShortcutsRef.current.setShortcutCallback('onDelete', () => {
deleteResource(selectedResource);
});
keyboardShortcutsRef.current.setShortcutCallback('onRename', () => {
editName(selectedResource);
});
},
[selectedResource, deleteResource, editName]
);
// Scroll to selected item when selection changes
React.useEffect(
() => {
if (!selectedResource || !sortableListRef.current) return;
if (sortableListRef.current.scrollToItem) {
sortableListRef.current.scrollToItem(selectedResource);
}
}, | @@ -257,9 +264,32 @@ const ResourcesList = React.memo<Props, ResourcesListInterface>(
[project, forceUpdateList]
);
+ const keyboardShortcutsRef = React.useRef<KeyboardShortcuts>(
+ new KeyboardShortcuts({
+ shortcutCallbacks: {}, | newIDE/app/src/ResourcesList/index.js | 26 | JavaScript | 0.286 | suggestion | 70 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
export default class ResourcesEditor extends React.Component<Props, State> {
static defaultProps = {
setToolbar: () => {},
};
resourceExternallyChangedCallbackId: ?string;
editorMosaic: ?EditorMosaicInterface = null;
_propertiesEditor: ?ResourcePropertiesEditorInterface = null;
_resourcesList: ?ResourcesListInterface = null;
resourcesLoader = ResourcesLoader;
state = {
selectedResource: null,
};
componentDidMount() {
this.resourceExternallyChangedCallbackId = registerOnResourceExternallyChangedCallback(
this.onResourceExternallyChanged.bind(this)
);
}
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
_onKeyDown = (event: KeyboardEvent) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
this._moveSelection(event.key === 'ArrowDown' ? 1 : -1);
event.preventDefault();
}
};
_moveSelection = (delta: number) => {
const { project } = this.props;
const { selectedResource } = this.state;
const resourcesManager = project.getResourcesManager();
const allNames = resourcesManager.getAllResourceNames().toJSArray();
if (allNames.length === 0) return;
let nextIndex = 0;
if (selectedResource) {
const currentIndex = allNames.indexOf(selectedResource.getName());
nextIndex = Math.max(
0,
Math.min(allNames.length - 1, currentIndex + delta)
);
}
const nextResource = resourcesManager.getResource(allNames[nextIndex]);
if (nextResource !== selectedResource) { | As written in another comment, it could be the ResourcesList that take care of this. A good LLM model could probably find the best way to do it. |
export default class ResourcesEditor extends React.Component<Props, State> {
// $FlowFixMe[missing-local-annot]
static defaultProps = {
setToolbar: () => {},
};
resourceExternallyChangedCallbackId: ?string;
editorMosaic: ?EditorMosaicInterface = null;
_propertiesEditor: ?ResourcePropertiesEditorInterface = null;
_resourcesList: ?ResourcesListInterface = null;
// $FlowFixMe[missing-local-annot]
resourcesLoader = ResourcesLoader;
// $FlowFixMe[missing-local-annot]
state = {
selectedResource: null,
};
componentDidMount() {
this.resourceExternallyChangedCallbackId = registerOnResourceExternallyChangedCallback(
this.onResourceExternallyChanged.bind(this)
);
}
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
refreshResourcesList() {
if (this._resourcesList) this._resourcesList.forceUpdateList();
}
updateToolbar = () => {
const openedEditorNames = this.editorMosaic
? this.editorMosaic.getOpenedEditorNames()
: [];
this.props.setToolbar(
<Toolbar
onOpenProjectFolder={this.openProjectFolder}
canOpenProjectFolder={
!!remote &&
!!this.props.fileMetadata &&
this.props.storageProvider.internalName === 'LocalFile'
}
onToggleProperties={this.toggleProperties}
isPropertiesShown={openedEditorNames.includes('properties')}
canDelete={!!this.state.selectedResource}
onDeleteSelection={() =>
this.deleteResource(this.state.selectedResource) | @@ -84,12 +84,43 @@ export default class ResourcesEditor extends React.Component<Props, State> {
this.onResourceExternallyChanged.bind(this)
);
}
+
componentWillUnmount() {
unregisterOnResourceExternallyChangedCallback(
this.resourceExternallyChangedCallbackId
);
}
+ _onKeyDown = (event: KeyboardEvent) => { | newIDE/app/src/ResourcesEditor/index.js | 26 | JavaScript | 0.429 | suggestion | 144 | 51 | 51 | false | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
_('y position of spine _PARAM1_ point attachment for _PARAM2_ slot'),
_('Animations and images'),
'JsPlatform/Extensions/spine.svg'
)
.addParameter('object', _('Spine'), 'SpineObject')
.addParameter('string', _('Attachment name'))
.addParameter('string', _('Slot name (use "" if names are the same)'))
.addParameter('expression', _('World scaleY? (0=no, 1=yes)'), '', true)
.setDefaultValue('0')
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentScaleY');
object
.addExpressionAndCondition(
'number',
'PointAttachmentRotation',
_('Point attachment rotation'),
_('rotation of spine point attachment'),
_('rotation of spine _PARAM1_ point attachment for _PARAM2_ slot'),
_('Animations and images'),
'JsPlatform/Extensions/spine.svg'
)
.addParameter('object', _('Spine'), 'SpineObject')
.addParameter('string', _('Attachment name'))
.addParameter('string', _('Slot name (use "" if names are the same)'))
.addParameter('expression', _('World rotation? (0=no, 1=yes)'), '', true)
.setDefaultValue('0')
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentRotation');
return extension;
},
/**
* You can optionally add sanity tests that will check the basic working
* of your extension behaviors/objects by instantiating behaviors/objects
* and setting the property to a given value.
*
* If you don't have any tests, you can simply return an empty array.
*
* But it is recommended to create tests for the behaviors/objects properties you created
* to avoid mistakes.
*/
runExtensionSanityTests: function (gd, extension) {
return [];
},
/**
* Register editors for objects.
*
* ℹ️ Run `node import-GDJS-Runtime.js` (in newIDE/app/scripts) if you make any change.
*/ | Is there any chance we can make this a `yesorno` boolean parameter? Same for the other conditions? | 'JsPlatform/Extensions/spine.svg'
)
.addParameter('object', _('Spine'), 'SpineObject')
.addParameter('string', _('Attachment name'))
.addParameter('string', _('Slot name (use "" if names are the same)'))
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentScaleXLocal');
object
.addExpressionAndCondition(
'number',
'PointAttachmentScaleYWorld',
_('Point attachment scale world Y position'),
_('world y position of spine point attachment scale'),
_(
'world y position of spine _PARAM1_ point attachment for _PARAM2_ slot'
),
_('Animations and images'),
'JsPlatform/Extensions/spine.svg'
)
.addParameter('object', _('Spine'), 'SpineObject')
.addParameter('string', _('Attachment name'))
.addParameter('string', _('Slot name (use "" if names are the same)'))
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentScaleYWorld');
object
.addExpressionAndCondition(
'number',
'PointAttachmentScaleYLocal',
_('Point attachment scale local Y position'),
_('local y position of spine point attachment scale'),
_(
'local y position of spine _PARAM1_ point attachment for _PARAM2_ slot'
),
_('Animations and images'),
'JsPlatform/Extensions/spine.svg'
)
.addParameter('object', _('Spine'), 'SpineObject')
.addParameter('string', _('Attachment name'))
.addParameter('string', _('Slot name (use "" if names are the same)'))
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentScaleYLocal');
object
.addExpressionAndCondition(
'number',
'PointAttachmentRotationWorld',
_('Point attachment world rotation'),
_('world rotation of spine point attachment'),
_( | @@ -106,6 +106,60 @@ module.exports = {
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentY');
+ object
+ .addExpressionAndCondition(
+ 'number',
+ 'PointAttachmentScaleX',
+ _('Point attachment scale X position'),
+ _('x position of spine point attachment scale'),
+ _('x position of spine _PARAM1_ point attachment for _PARAM2_ slot'),
+ _('Animations and images'),
+ 'JsPlatform/Extensions/spine.svg'
+ )
+ .addParameter('object', _('Spine'), 'SpineObject')
+ .addParameter('string', _('Attachment name'))
+ .addParameter('string', _('Slot name (use "" if names are the same)'))
+ .addParameter('expression', _('World scaleX? (0=no, 1=yes)'), '', true)
+ .setDefaultValue('0')
+ .useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
+ .setFunctionName('getPointAttachmentScaleX');
+
+ object
+ .addExpressionAndCondition(
+ 'number',
+ 'PointAttachmentScaleY',
+ _('Point attachment scale Y position'),
+ _('y position of spine point attachment scale'),
+ _('y position of spine _PARAM1_ point attachment for _PARAM2_ slot'),
+ _('Animations and images'),
+ 'JsPlatform/Extensions/spine.svg'
+ )
+ .addParameter('object', _('Spine'), 'SpineObject')
+ .addParameter('string', _('Attachment name'))
+ .addParameter('string', _('Slot name (use "" if names are the same)'))
+ .addParameter('expression', _('World scaleY? (0=no, 1=yes)'), '', true)
+ .setDefaultValue('0')
+ .useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
+ .setFunctionName('getPointAttachmentScaleY');
+
+ object
+ .addExpressionAndCondition(
+ 'number',
+ 'PointAttachmentRotation',
+ _('Point attachment rotation'),
+ _('rotation of spine point attachment'),
+ _('rotation of spine _PARAM1_ point attachment for _PARAM2_ slot'),
+ _('Animations and images'),
+ 'JsPlatform/Extensions/spine.svg'
+ )
+ .addParameter('object', _('Spine'), 'SpineObject')
+ .addParameter('string', _('Attachment name'))
+ .addParameter('string', _('Slot name (use "" if names are the same)'))
+ .addParameter('expression', _('World rotation? (0=no, 1=yes)'), '', true) | Extensions/Spine/JsExtension.js | 26 | JavaScript | 0.357 | question | 98 | 51 | 51 | false | Add point attachment rotation and scale expression for spine | 8,125 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
clipboardContent,
'actionsCount'
);
if (actionsCount === null) return false;
return actionsCount > 0;
};
export const copySelectionToClipboard = (selection: SelectionState) => {
const eventsList = new gd.EventsList();
const actionsList = new gd.InstructionsList();
const conditionsList = new gd.InstructionsList();
getSelectedEvents(selection).forEach(event =>
eventsList.insertEvent(event, eventsList.getEventsCount())
);
getSelectedInstructionsContexts(selection).forEach(instructionContext => {
if (instructionContext.isCondition) {
conditionsList.insert(
instructionContext.instruction,
conditionsList.size()
);
} else {
actionsList.insert(instructionContext.instruction, actionsList.size());
}
});
Clipboard.set(CLIPBOARD_KIND, {
eventsList: serializeToJSObject(eventsList),
eventsCount: eventsList.getEventsCount(),
actionsList: serializeToJSObject(actionsList),
actionsCount: actionsList.size(),
conditionsList: serializeToJSObject(conditionsList),
conditionsCount: conditionsList.size(),
});
eventsList.delete();
actionsList.delete();
conditionsList.delete();
};
export const pasteEventsFromClipboardInSelection = (
project: gdProject,
selection: SelectionState
): boolean => {
const lastSelectEventContext = getLastSelectedEventContext(selection);
if (!lastSelectEventContext || !hasClipboardEvents()) return false;
const clipboardContent = Clipboard.get(CLIPBOARD_KIND);
const eventsListContent = SafeExtractor.extractArrayProperty(
clipboardContent, | Not sure if useful, but could you use contains:
https://github.com/4ian/GDevelop/blob/6377ece6f97ec3dc4d323066afdab8b28ff82ea6/Core/GDCore/Events/EventsList.h#L138-L144
(maybe not because you don't have an EventsList). | clipboardContent,
'actionsCount'
);
if (actionsCount === null) return false;
return actionsCount > 0;
};
const addAllSubEvents = (
event: gdBaseEvent,
events: Set<gdBaseEvent>
): void => {
const subEvents = event.getSubEvents();
for (let i = 0; i < subEvents.getEventsCount(); i++) {
const subEvent = subEvents.getEventAt(i);
events.add(subEvent);
addAllSubEvents(subEvent, events);
}
};
const excludeEventsChildren = (
events: Array<gdBaseEvent>
): Array<gdBaseEvent> => {
const filteredEvents: Array<gdBaseEvent> = [];
const allChildren = new Set<gdBaseEvent>();
// Children may come first because the selection is ordered by selection time.
for (const event of events) {
if (!allChildren.has(event)) {
addAllSubEvents(event, allChildren);
}
}
for (const event of events) {
if (!allChildren.has(event)) {
filteredEvents.push(event);
}
}
return filteredEvents;
};
export const copySelectionToClipboard = (selection: SelectionState) => {
const eventsList = new gd.EventsList();
const actionsList = new gd.InstructionsList();
const conditionsList = new gd.InstructionsList();
excludeEventsChildren(getSelectedEvents(selection)).forEach(event =>
eventsList.insertEvent(event, eventsList.getEventsCount())
);
getSelectedInstructionsContexts(selection).forEach(instructionContext => {
if (instructionContext.isCondition) {
conditionsList.insert(
instructionContext.instruction, | @@ -56,12 +56,43 @@ export const hasClipboardActions = () => {
return actionsCount > 0;
};
+const addAllSubEvents = (
+ event: gdBaseEvent,
+ events: Set<gdBaseEvent>
+): void => {
+ const subEvents = event.getSubEvents();
+ for (let i = 0; i < subEvents.getEventsCount(); i++) {
+ const subEvent = subEvents.getEventAt(i);
+ events.add(subEvent);
+ addAllSubEvents(subEvent, events);
+ }
+};
+
+const excludeEventsChildren = (
+ events: Array<gdBaseEvent>
+): Array<gdBaseEvent> => {
+ const filteredEvents: Array<gdBaseEvent> = [];
+ const allChildren = new Set<gdBaseEvent>();
+ // Children may come first because the selection is ordered by selection time. | newIDE/app/src/EventsSheet/ClipboardKind.js | 26 | JavaScript | 0.5 | suggestion | 221 | 51 | 51 | false | Fix duplicated pasted events when the selection contains an event and its sub-events | 8,155 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
.slice(1)
.split(/(?=[A-Z])/)
.join(' ')
);
};
const getDescription = () => propertyDescription;
const getEndAdornment = (instance: Instance) => {
const property = getProperties(instance).get(name);
const measurementUnit = property.getMeasurementUnit();
return {
label: getMeasurementUnitShortLabel(measurementUnit),
tooltipContent: (
<MeasurementUnitDocumentation
label={measurementUnit.getLabel()}
description={measurementUnit.getDescription()}
elementsWithWords={measurementUnit.getElementsWithWords()}
/>
),
};
};
const defaultValueNumber = defaultValue
? parseFloat(defaultValue) || 0
: null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon = defaultValueNumber
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment = defaultValueNumber
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
const visibility: FieldVisibility = property.isDeprecated()
? 'deprecated'
: property.isAdvanced()
? 'advanced'
: 'basic';
const valueType = property.getType().toLowerCase();
if (valueType === 'number') {
return {
name,
valueType, | @D8H what if the default value is 0? This will be falsy. | .slice(1)
.split(/(?=[A-Z])/)
.join(' ')
);
};
const getDescription = () => propertyDescription;
const getEndAdornment = (instance: Instance) => {
const property = getProperties(instance).get(name);
const measurementUnit = property.getMeasurementUnit();
return {
label: getMeasurementUnitShortLabel(measurementUnit),
tooltipContent: (
<MeasurementUnitDocumentation
label={measurementUnit.getLabel()}
description={measurementUnit.getDescription()}
elementsWithWords={measurementUnit.getElementsWithWords()}
/>
),
};
};
const visibility: FieldVisibility = property.isDeprecated()
? 'deprecated'
: property.isAdvanced()
? 'advanced'
: 'basic';
const valueType = property.getType().toLowerCase();
if (valueType === 'number') {
const defaultValueNumber =
defaultValue !== null ? parseFloat(defaultValue) || 0 : null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
return {
name, | @@ -67,6 +68,26 @@ const createField = (
),
};
};
+ const defaultValueNumber = defaultValue
+ ? parseFloat(defaultValue) || 0
+ : null;
+ const getValue = (instance: Instance): number =>
+ getNumberValue(instance, name);
+ const getEndAdornmentIcon = defaultValueNumber | newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js | 26 | JavaScript | 0.214 | suggestion | 56 | 51 | 51 | false | Add a button to reset properties to their default values | 8,163 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
const measurementUnit = property.getMeasurementUnit();
return {
label: getMeasurementUnitShortLabel(measurementUnit),
tooltipContent: (
<MeasurementUnitDocumentation
label={measurementUnit.getLabel()}
description={measurementUnit.getDescription()}
elementsWithWords={measurementUnit.getElementsWithWords()}
/>
),
};
};
const defaultValueNumber = defaultValue
? parseFloat(defaultValue) || 0
: null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon = defaultValueNumber
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment = defaultValueNumber
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
const visibility: FieldVisibility = property.isDeprecated()
? 'deprecated'
: property.isAdvanced()
? 'advanced'
: 'basic';
const valueType = property.getType().toLowerCase();
if (valueType === 'number') {
return {
name,
valueType,
getValue: (instance: Instance): number => getNumberValue(instance, name),
setValue,
defaultValue: defaultValueNumber,
getLabel,
getDescription,
hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(),
canBeUnlimitedUsingMinus1: property
.getExtraInfo() | It's strange to see a setValue that calls a setNumberValue, because who tells us that this is a number field?
I would rather put this inside the `if (valueType === 'number')` branch? | const measurementUnit = property.getMeasurementUnit();
return {
label: getMeasurementUnitShortLabel(measurementUnit),
tooltipContent: (
<MeasurementUnitDocumentation
label={measurementUnit.getLabel()}
description={measurementUnit.getDescription()}
elementsWithWords={measurementUnit.getElementsWithWords()}
/>
),
};
};
const visibility: FieldVisibility = property.isDeprecated()
? 'deprecated'
: property.isAdvanced()
? 'advanced'
: 'basic';
const valueType = property.getType().toLowerCase();
if (valueType === 'number') {
const defaultValueNumber =
defaultValue !== null ? parseFloat(defaultValue) || 0 : null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
return {
name,
valueType,
getValue,
setValue,
defaultValue: defaultValueNumber,
getLabel,
getDescription,
hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(),
canBeUnlimitedUsingMinus1: property | @@ -67,6 +68,26 @@ const createField = (
),
};
};
+ const defaultValueNumber = defaultValue
+ ? parseFloat(defaultValue) || 0
+ : null;
+ const getValue = (instance: Instance): number =>
+ getNumberValue(instance, name);
+ const getEndAdornmentIcon = defaultValueNumber
+ ? (instance: gdInitialInstance) => {
+ return getValue(instance) === defaultValueNumber
+ ? null
+ : className => <Restore className={className} />;
+ }
+ : undefined;
+ const setValue = (instance: Instance, newValue: number) => {
+ setNumberValue(instance, name, newValue); | newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js | 26 | JavaScript | 0.714 | question | 182 | 51 | 51 | false | Add a button to reset properties to their default values | 8,163 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
if (valueType === 'number') {
const defaultValueNumber =
defaultValue !== null ? parseFloat(defaultValue) || 0 : null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
return {
name,
valueType,
getValue: (instance: Instance): number => getNumberValue(instance, name),
setValue,
defaultValue: defaultValueNumber,
getLabel,
getDescription,
hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(),
canBeUnlimitedUsingMinus1: property
.getExtraInfo()
.toJSArray()
.includes('canBeUnlimitedUsingMinus1'),
getEndAdornment,
getEndAdornmentIcon,
onClickEndAdornment,
visibility,
};
} else if (valueType === 'string' || valueType === '') {
return {
name,
valueType: 'string',
getValue: (instance: Instance): string => getStringValue(instance, name),
setValue: (instance: Instance, newValue: string) => {
setStringValue(instance, name, newValue);
},
defaultValue,
getLabel,
getDescription, | ```suggestion
getValue,
``` | if (valueType === 'number') {
const defaultValueNumber =
defaultValue !== null ? parseFloat(defaultValue) || 0 : null;
const getValue = (instance: Instance): number =>
getNumberValue(instance, name);
const getEndAdornmentIcon =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
return getValue(instance) === defaultValueNumber
? null
: className => <Restore className={className} />;
}
: undefined;
const setValue = (instance: Instance, newValue: number) => {
setNumberValue(instance, name, newValue);
};
const onClickEndAdornment =
defaultValueNumber !== null
? (instance: gdInitialInstance) => {
setValue(instance, defaultValueNumber);
}
: undefined;
return {
name,
valueType,
getValue,
setValue,
defaultValue: defaultValueNumber,
getLabel,
getDescription,
hasImpactOnAllOtherFields: property.hasImpactOnOtherProperties(),
canBeUnlimitedUsingMinus1: property
.getExtraInfo()
.toJSArray()
.includes('canBeUnlimitedUsingMinus1'),
getEndAdornment,
getEndAdornmentIcon,
onClickEndAdornment,
visibility,
};
} else if (valueType === 'string' || valueType === '') {
return {
name,
valueType: 'string',
getValue: (instance: Instance): string => getStringValue(instance, name),
setValue: (instance: Instance, newValue: string) => {
setStringValue(instance, name, newValue);
},
defaultValue,
getLabel,
getDescription, | @@ -75,14 +76,33 @@ const createField = (
const valueType = property.getType().toLowerCase();
if (valueType === 'number') {
+ const defaultValueNumber =
+ defaultValue !== null ? parseFloat(defaultValue) || 0 : null;
+ const getValue = (instance: Instance): number =>
+ getNumberValue(instance, name);
+ const getEndAdornmentIcon =
+ defaultValueNumber !== null
+ ? (instance: gdInitialInstance) => {
+ return getValue(instance) === defaultValueNumber
+ ? null
+ : className => <Restore className={className} />;
+ }
+ : undefined;
+ const setValue = (instance: Instance, newValue: number) => {
+ setNumberValue(instance, name, newValue);
+ };
+ const onClickEndAdornment =
+ defaultValueNumber !== null
+ ? (instance: gdInitialInstance) => {
+ setValue(instance, defaultValueNumber);
+ }
+ : undefined;
return {
name,
valueType,
getValue: (instance: Instance): number => getNumberValue(instance, name), | newIDE/app/src/PropertiesEditor/PropertiesMapToSchema.js | 26 | JavaScript | 0.429 | suggestion | 33 | 51 | 51 | false | Add a button to reset properties to their default values | 8,163 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
export type InstancesEditorSettings = {|
/** Is grid shown? */
grid: boolean,
gridType: 'isometric' | 'rectangular',
gridWidth: number,
gridHeight: number,
gridDepth: number,
gridOffsetX: number,
gridOffsetY: number,
gridOffsetZ: number,
gridColor: number,
gridAlpha: number,
/** Is snap to grid activated? */
snap: boolean,
/** The zoom of the editor, 1 by default. */
zoomFactor: number,
/** Is the window mask shown? */
windowMask: boolean,
/** The name of the layer selected to place instances on. */
selectedLayer: string,
/** The game editor mode: 'embedded-game' or 'instances-editor' */
gameEditorMode: 'embedded-game' | 'instances-editor',
|};
export const getRecommendedInitialZoomFactor = (
largestSizeInPixels: number
) => {
// 700 is an empirical value obtained multiplying the largest size (1920) with
// the zoom factor (0.36) so that the screen black rectangle fits nicely on the canvas
// with only the left and right side panels opened on a Macbook screen.
return 700 / largestSizeInPixels;
};
export const prepareInstancesEditorSettings = (
object: any,
projectLargestResolutionSizeInPixels: number
): InstancesEditorSettings => {
return {
grid: object.grid || false,
gridType: object.gridType || 'rectangular',
gridWidth: object.gridWidth || 32,
gridHeight: object.gridHeight || 32,
gridDepth: object.gridDepth || 32,
gridOffsetX: object.gridOffsetX || 0,
gridOffsetY: object.gridOffsetY || 0,
gridOffsetZ: object.gridOffsetZ || 0, | Could as well remove this comment | export type InstancesEditorSettings = {|
/** Is grid shown? */
grid: boolean,
gridType: 'isometric' | 'rectangular',
gridWidth: number,
gridHeight: number,
gridDepth: number,
gridOffsetX: number,
gridOffsetY: number,
gridOffsetZ: number,
gridColor: number,
gridAlpha: number,
/** Is snap to grid activated? */
snap: boolean,
/** The zoom of the editor, 1 by default. */
zoomFactor: number,
/** Is the window mask shown? */
windowMask: boolean,
/** The name of the layer selected to place instances on. */
selectedLayer: string,
gameEditorMode: 'embedded-game' | 'instances-editor',
|};
export const getRecommendedInitialZoomFactor = (
largestSizeInPixels: number
) => {
// 700 is an empirical value obtained multiplying the largest size (1920) with
// the zoom factor (0.36) so that the screen black rectangle fits nicely on the canvas
// with only the left and right side panels opened on a Macbook screen.
return 700 / largestSizeInPixels;
};
export const prepareInstancesEditorSettings = (
object: any,
projectLargestResolutionSizeInPixels: number
): InstancesEditorSettings => {
return {
grid: object.grid || false,
gridType: object.gridType || 'rectangular',
gridWidth: object.gridWidth || 32,
gridHeight: object.gridHeight || 32,
gridDepth: object.gridDepth || 32,
gridOffsetX: object.gridOffsetX || 0,
gridOffsetY: object.gridOffsetY || 0,
gridOffsetZ: object.gridOffsetZ || 0,
gridColor: | @@ -25,6 +25,9 @@ export type InstancesEditorSettings = {|
/** The name of the layer selected to place instances on. */
selectedLayer: string,
+
+ /** The game editor mode: 'embedded-game' or 'instances-editor' */ | newIDE/app/src/InstancesEditor/InstancesEditorSettings.js | 26 | JavaScript | 0.143 | refactor | 33 | 51 | 51 | false | Save Editor Mode (2D/3D) per scene instead of globally | 8,169 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
#include "BehaviorPropertyRenamer.h"
#include "GDCore/Events/Instruction.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/PlatformExtension.h"
#include "GDCore/IDE/WholeProjectRefactorer.h"
#include "GDCore/Project/Behavior.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/Project.h"
namespace gd {
void BehaviorPropertyRenamer::DoVisitObject(gd::Object &object) {};
void BehaviorPropertyRenamer::DoVisitBehavior(gd::Behavior &behavior) {
if (behavior.GetTypeName() == behaviorType) {
behavior.RenameProperty(oldName, newName);
}
};
BehaviorPropertyRenamer::~BehaviorPropertyRenamer() {}
} // namespace gd
| Any reason why implementing this empty is useful? | #include "BehaviorPropertyRenamer.h"
#include "GDCore/Events/Instruction.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/PlatformExtension.h"
#include "GDCore/IDE/WholeProjectRefactorer.h"
#include "GDCore/Project/Behavior.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/Project.h"
namespace gd {
void BehaviorPropertyRenamer::DoVisitBehavior(gd::Behavior &behavior) {
if (behavior.GetTypeName() == behaviorType) {
behavior.RenameProperty(oldName, newName);
}
};
BehaviorPropertyRenamer::~BehaviorPropertyRenamer() {}
} // namespace gd
| @@ -0,0 +1,23 @@
+#include "BehaviorPropertyRenamer.h"
+
+#include "GDCore/Events/Instruction.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
+#include "GDCore/Extensions/PlatformExtension.h"
+#include "GDCore/IDE/WholeProjectRefactorer.h"
+#include "GDCore/Project/Behavior.h"
+#include "GDCore/Project/Object.h"
+#include "GDCore/Project/Project.h"
+
+namespace gd {
+
+void BehaviorPropertyRenamer::DoVisitObject(gd::Object &object) {}; | Core/GDCore/IDE/Events/BehaviorPropertyRenamer.cpp | 13 | C++ | 0.143 | question | 49 | 24 | 22 | false | Fix property value loss when renaming a property in the extension editor | 8,211 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | D8H |
// @flow
import * as React from 'react';
import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null);
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
// Sound loaded callback
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
ref={soundPlayerRef}
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
);
};
export default AudioPreview;
| useless comment
```suggestion
``` | // @flow
import * as React from 'react';
import SoundPlayer from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
);
};
export default AudioPreview;
| @@ -0,0 +1,41 @@
+// @flow
+import * as React from 'react';
+import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
+import GenericIconPreview from './GenericIconPreview';
+import Music from '../../UI/CustomSvgIcons/Music';
+
+type Props = {|
+ resourceName: string,
+ audioResourceSource: string,
+|};
+
+const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
+ const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null);
+ const [hasError, setHasError] = React.useState(false);
+
+ const onSoundLoaded = React.useCallback(() => {
+ // Sound loaded callback | newIDE/app/src/ResourcesList/ResourcePreview/AudioPreview.js | 17 | JavaScript | 0.5 | suggestion | 33 | 42 | 39 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
// @flow
import * as React from 'react';
import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null);
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
// Sound loaded callback
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
ref={soundPlayerRef}
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
);
};
export default AudioPreview;
| Would probably be worth showing something but that's ok for now. | // @flow
import * as React from 'react';
import SoundPlayer from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
);
};
export default AudioPreview;
| @@ -0,0 +1,41 @@
+// @flow
+import * as React from 'react';
+import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
+import GenericIconPreview from './GenericIconPreview';
+import Music from '../../UI/CustomSvgIcons/Music';
+
+type Props = {|
+ resourceName: string,
+ audioResourceSource: string,
+|};
+
+const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
+ const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null);
+ const [hasError, setHasError] = React.useState(false);
+
+ const onSoundLoaded = React.useCallback(() => {
+ // Sound loaded callback
+ setHasError(false);
+ }, []);
+
+ const onSoundError = React.useCallback(() => {
+ setHasError(true);
+ }, []);
+
+ if (hasError) {
+ return <GenericIconPreview renderIcon={props => <Music {...props} />} />; | newIDE/app/src/ResourcesList/ResourcePreview/AudioPreview.js | 24 | JavaScript | 0.214 | suggestion | 64 | 42 | 39 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
// @flow
import * as React from 'react';
import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null);
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
// Sound loaded callback
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
ref={soundPlayerRef}
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
); | This ref is unused -> remove it.
```suggestion
``` | // @flow
import * as React from 'react';
import SoundPlayer from '../../UI/SoundPlayer';
import GenericIconPreview from './GenericIconPreview';
import Music from '../../UI/CustomSvgIcons/Music';
type Props = {|
resourceName: string,
audioResourceSource: string,
|};
const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
const [hasError, setHasError] = React.useState(false);
const onSoundLoaded = React.useCallback(() => {
setHasError(false);
}, []);
const onSoundError = React.useCallback(() => {
setHasError(true);
}, []);
if (hasError) {
return <GenericIconPreview renderIcon={props => <Music {...props} />} />;
}
return (
<SoundPlayer
soundSrc={audioResourceSource || null}
onSoundLoaded={onSoundLoaded}
onSoundError={onSoundError}
title={resourceName}
subtitle={null}
/>
);
};
export default AudioPreview; | @@ -0,0 +1,41 @@
+// @flow
+import * as React from 'react';
+import SoundPlayer, { type SoundPlayerInterface } from '../../UI/SoundPlayer';
+import GenericIconPreview from './GenericIconPreview';
+import Music from '../../UI/CustomSvgIcons/Music';
+
+type Props = {|
+ resourceName: string,
+ audioResourceSource: string,
+|};
+
+const AudioPreview = ({ resourceName, audioResourceSource }: Props) => {
+ const soundPlayerRef = React.useRef<?SoundPlayerInterface>(null); | newIDE/app/src/ResourcesList/ResourcePreview/AudioPreview.js | 13 | JavaScript | 0.643 | suggestion | 50 | 38 | 38 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
|};
export type CompactSoundPlayerInterface = {|
playPause: (forcePlay: boolean) => void,
|};
const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
const mobileAudioRef = React.useRef<?Audio>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onLoad = React.useCallback(() => {
setIsPlaying(false);
}, []);
const onAudioReady = React.useCallback(
() => {
if (!mobileAudioRef.current) return;
if (onSoundLoaded) onSoundLoaded();
},
[onSoundLoaded]
);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
}));
React.useEffect(
() => {
if (!mobileAudioRef.current) return;
if (isPlaying) {
mobileAudioRef.current.play();
} else {
mobileAudioRef.current.pause();
}
},
[isPlaying]
);
React.useEffect(
() => {
if (soundSrc) {
if (mobileAudioRef.current) { | Looks useless? The ref is not used in this function. No reason not to do the rest. | onSoundLoaded?: () => void,
onSoundError?: () => void,
|};
const CompactSoundPlayer = ({
soundSrc,
onSoundLoaded,
onSoundError,
}: Props) => {
const audioRef = React.useRef<?HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const [isAudioLoaded, setIsAudioLoaded] = React.useState(false);
const isMountedRef = useIsMounted();
const abortControllerRef = React.useRef<?AbortController>(null);
const cleanupAudioAndListeners = React.useCallback(() => {
const audio = audioRef.current;
if (!audio) return;
audio.pause();
if (abortControllerRef.current) abortControllerRef.current.abort();
audio.src = '';
audioRef.current = null;
abortControllerRef.current = null;
setIsPlaying(false);
setIsLoading(false);
setIsAudioLoaded(false);
}, []);
const initializeAudio = React.useCallback(
() => {
if (!soundSrc || audioRef.current) return;
setIsLoading(true);
const audio = new Audio(soundSrc);
audio.loop = false;
const abortController = new AbortController();
abortControllerRef.current = abortController;
const handleLoadedMetadata = () => {
if (!isMountedRef.current) return;
setIsLoading(false);
setIsAudioLoaded(true);
if (onSoundLoaded) onSoundLoaded();
};
const handleError = () => {
if (!isMountedRef.current) return; | @@ -0,0 +1,91 @@
+// @flow
+
+import * as React from 'react';
+import IconButton from '@material-ui/core/IconButton';
+import Play from '../CustomSvgIcons/Play';
+import Pause from '../CustomSvgIcons/Pause';
+
+type Props = {|
+ soundSrc: string | null,
+ onSoundLoaded?: () => void,
+ onSoundError?: () => void,
+|};
+
+export type CompactSoundPlayerInterface = {|
+ playPause: (forcePlay: boolean) => void,
+|};
+
+const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
+ ({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
+ const mobileAudioRef = React.useRef<?Audio>(null);
+ const [isPlaying, setIsPlaying] = React.useState(false);
+
+ const onPlayPause = React.useCallback(
+ (forcePlay?: boolean) => {
+ if (!soundSrc) return;
+ setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
+ },
+ [soundSrc]
+ );
+
+ const onLoad = React.useCallback(() => {
+ setIsPlaying(false);
+ }, []);
+
+ const onAudioReady = React.useCallback(
+ () => {
+ if (!mobileAudioRef.current) return; | newIDE/app/src/UI/SoundPlayer/CompactSoundPlayer.js | 26 | JavaScript | 0.286 | suggestion | 82 | 51 | 51 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
const mobileAudioRef = React.useRef<?Audio>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onLoad = React.useCallback(() => {
setIsPlaying(false);
}, []);
const onAudioReady = React.useCallback(
() => {
if (!mobileAudioRef.current) return;
if (onSoundLoaded) onSoundLoaded();
},
[onSoundLoaded]
);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
}));
React.useEffect(
() => {
if (!mobileAudioRef.current) return;
if (isPlaying) {
mobileAudioRef.current.play();
} else {
mobileAudioRef.current.pause();
}
},
[isPlaying]
);
React.useEffect(
() => {
if (soundSrc) {
if (mobileAudioRef.current) {
mobileAudioRef.current.pause();
}
const audio = new Audio(soundSrc);
audio.loop = true;
audio.addEventListener('loadstart', onLoad);
audio.addEventListener('loadedmetadata', onAudioReady);
audio.addEventListener('error', () => {
if (onSoundError) onSoundError(); | You only use onPlayPause in this file. No reason to expose it to the outside world.
```suggestion
``` | }: Props) => {
const audioRef = React.useRef<?HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const [isAudioLoaded, setIsAudioLoaded] = React.useState(false);
const isMountedRef = useIsMounted();
const abortControllerRef = React.useRef<?AbortController>(null);
const cleanupAudioAndListeners = React.useCallback(() => {
const audio = audioRef.current;
if (!audio) return;
audio.pause();
if (abortControllerRef.current) abortControllerRef.current.abort();
audio.src = '';
audioRef.current = null;
abortControllerRef.current = null;
setIsPlaying(false);
setIsLoading(false);
setIsAudioLoaded(false);
}, []);
const initializeAudio = React.useCallback(
() => {
if (!soundSrc || audioRef.current) return;
setIsLoading(true);
const audio = new Audio(soundSrc);
audio.loop = false;
const abortController = new AbortController();
abortControllerRef.current = abortController;
const handleLoadedMetadata = () => {
if (!isMountedRef.current) return;
setIsLoading(false);
setIsAudioLoaded(true);
if (onSoundLoaded) onSoundLoaded();
};
const handleError = () => {
if (!isMountedRef.current) return;
setIsLoading(false);
setIsPlaying(false);
setIsAudioLoaded(false);
if (onSoundError) onSoundError();
};
const handleEnded = () => {
if (!isMountedRef.current) return; | @@ -0,0 +1,91 @@
+// @flow
+
+import * as React from 'react';
+import IconButton from '@material-ui/core/IconButton';
+import Play from '../CustomSvgIcons/Play';
+import Pause from '../CustomSvgIcons/Pause';
+
+type Props = {|
+ soundSrc: string | null,
+ onSoundLoaded?: () => void,
+ onSoundError?: () => void,
+|};
+
+export type CompactSoundPlayerInterface = {|
+ playPause: (forcePlay: boolean) => void,
+|};
+
+const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
+ ({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
+ const mobileAudioRef = React.useRef<?Audio>(null);
+ const [isPlaying, setIsPlaying] = React.useState(false);
+
+ const onPlayPause = React.useCallback(
+ (forcePlay?: boolean) => {
+ if (!soundSrc) return;
+ setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
+ },
+ [soundSrc]
+ );
+
+ const onLoad = React.useCallback(() => {
+ setIsPlaying(false);
+ }, []);
+
+ const onAudioReady = React.useCallback(
+ () => {
+ if (!mobileAudioRef.current) return;
+ if (onSoundLoaded) onSoundLoaded();
+ },
+ [onSoundLoaded]
+ );
+
+ React.useImperativeHandle(ref, () => ({
+ playPause: onPlayPause,
+ })); | newIDE/app/src/UI/SoundPlayer/CompactSoundPlayer.js | 26 | JavaScript | 0.786 | suggestion | 102 | 51 | 51 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
// @flow
import * as React from 'react';
import IconButton from '@material-ui/core/IconButton';
import Play from '../CustomSvgIcons/Play';
import Pause from '../CustomSvgIcons/Pause';
type Props = {|
soundSrc: string | null,
onSoundLoaded?: () => void,
onSoundError?: () => void,
|};
export type CompactSoundPlayerInterface = {|
playPause: (forcePlay: boolean) => void,
|};
const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
const mobileAudioRef = React.useRef<?Audio>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onLoad = React.useCallback(() => {
setIsPlaying(false);
}, []);
const onAudioReady = React.useCallback(
() => {
if (!mobileAudioRef.current) return;
if (onSoundLoaded) onSoundLoaded();
},
[onSoundLoaded]
);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause, | Interface "playPause" is used nowhere by other components, so no need to complexify the component.
```suggestion
const CompactSoundPlayer = ({ soundSrc, onSoundLoaded, onSoundError }: Props) => {
``` | // @flow
import * as React from 'react';
import IconButton from '@material-ui/core/IconButton';
import CircularProgress from '@material-ui/core/CircularProgress';
import Play from '../CustomSvgIcons/Play';
import Pause from '../CustomSvgIcons/Pause';
import { useIsMounted } from '../../Utils/UseIsMounted';
type Props = {|
soundSrc: string | null,
onSoundLoaded?: () => void,
onSoundError?: () => void,
|};
const CompactSoundPlayer = ({
soundSrc,
onSoundLoaded,
onSoundError,
}: Props) => {
const audioRef = React.useRef<?HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const [isAudioLoaded, setIsAudioLoaded] = React.useState(false);
const isMountedRef = useIsMounted();
const abortControllerRef = React.useRef<?AbortController>(null);
const cleanupAudioAndListeners = React.useCallback(() => {
const audio = audioRef.current;
if (!audio) return;
audio.pause();
if (abortControllerRef.current) abortControllerRef.current.abort();
audio.src = '';
audioRef.current = null;
abortControllerRef.current = null;
setIsPlaying(false);
setIsLoading(false);
setIsAudioLoaded(false);
}, []);
const initializeAudio = React.useCallback(
() => { | @@ -0,0 +1,91 @@
+// @flow
+
+import * as React from 'react';
+import IconButton from '@material-ui/core/IconButton';
+import Play from '../CustomSvgIcons/Play';
+import Pause from '../CustomSvgIcons/Pause';
+
+type Props = {|
+ soundSrc: string | null,
+ onSoundLoaded?: () => void,
+ onSoundError?: () => void,
+|};
+
+export type CompactSoundPlayerInterface = {|
+ playPause: (forcePlay: boolean) => void,
+|};
+
+const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
+ ({ soundSrc, onSoundLoaded, onSoundError }, ref) => { | newIDE/app/src/UI/SoundPlayer/CompactSoundPlayer.js | 19 | JavaScript | 1 | suggestion | 200 | 44 | 44 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
() => {
if (!mobileAudioRef.current) return;
if (onSoundLoaded) onSoundLoaded();
},
[onSoundLoaded]
);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
}));
React.useEffect(
() => {
if (!mobileAudioRef.current) return;
if (isPlaying) {
mobileAudioRef.current.play();
} else {
mobileAudioRef.current.pause();
}
},
[isPlaying]
);
React.useEffect(
() => {
if (soundSrc) {
if (mobileAudioRef.current) {
mobileAudioRef.current.pause();
}
const audio = new Audio(soundSrc);
audio.loop = true;
audio.addEventListener('loadstart', onLoad);
audio.addEventListener('loadedmetadata', onAudioReady);
audio.addEventListener('error', () => {
if (onSoundError) onSoundError();
});
mobileAudioRef.current = audio;
}
onLoad();
},
[soundSrc, onLoad, onAudioReady, onSoundError]
);
if (!soundSrc) {
return null;
}
return (
<IconButton size="small" onClick={() => onPlayPause()}>
{isPlaying ? <Pause /> : <Play />}
</IconButton> | This will force the browser to load the audio source anytime the button is displayed. For a large game/long session, this means the browser may have to load dozens of audio files, wasting computing and network.
Can you adapt this component so that it only load the audio file when play is pressed?
- Default state: no audio loaded. Play button is shown
- You press play: audio is loaded. While it's the case, a loading spinner is shown (`CircularProgress`). Same size as the button so no layout shift.
- If the component is dismounted, stop the audio. (use a `useIsMounted` hook).
- When the audio plays, the button is now showing pause. If you pause it, and press play again, it resumes.
So there is a bit more logic here to handle all of this, but it's doable. | audioRef.current = null;
abortControllerRef.current = null;
setIsPlaying(false);
setIsLoading(false);
setIsAudioLoaded(false);
}, []);
const initializeAudio = React.useCallback(
() => {
if (!soundSrc || audioRef.current) return;
setIsLoading(true);
const audio = new Audio(soundSrc);
audio.loop = false;
const abortController = new AbortController();
abortControllerRef.current = abortController;
const handleLoadedMetadata = () => {
if (!isMountedRef.current) return;
setIsLoading(false);
setIsAudioLoaded(true);
if (onSoundLoaded) onSoundLoaded();
};
const handleError = () => {
if (!isMountedRef.current) return;
setIsLoading(false);
setIsPlaying(false);
setIsAudioLoaded(false);
if (onSoundError) onSoundError();
};
const handleEnded = () => {
if (!isMountedRef.current) return;
setIsPlaying(false);
};
audio.addEventListener('loadedmetadata', handleLoadedMetadata, {
signal: abortController.signal,
});
audio.addEventListener('error', handleError, {
signal: abortController.signal,
});
audio.addEventListener('ended', handleEnded, {
signal: abortController.signal,
});
audioRef.current = audio;
audio.play().catch(() => {
if (isMountedRef.current) { | @@ -0,0 +1,91 @@
+// @flow
+
+import * as React from 'react';
+import IconButton from '@material-ui/core/IconButton';
+import Play from '../CustomSvgIcons/Play';
+import Pause from '../CustomSvgIcons/Pause';
+
+type Props = {|
+ soundSrc: string | null,
+ onSoundLoaded?: () => void,
+ onSoundError?: () => void,
+|};
+
+export type CompactSoundPlayerInterface = {|
+ playPause: (forcePlay: boolean) => void,
+|};
+
+const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
+ ({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
+ const mobileAudioRef = React.useRef<?Audio>(null);
+ const [isPlaying, setIsPlaying] = React.useState(false);
+
+ const onPlayPause = React.useCallback(
+ (forcePlay?: boolean) => {
+ if (!soundSrc) return;
+ setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
+ },
+ [soundSrc]
+ );
+
+ const onLoad = React.useCallback(() => {
+ setIsPlaying(false);
+ }, []);
+
+ const onAudioReady = React.useCallback(
+ () => {
+ if (!mobileAudioRef.current) return;
+ if (onSoundLoaded) onSoundLoaded();
+ },
+ [onSoundLoaded]
+ );
+
+ React.useImperativeHandle(ref, () => ({
+ playPause: onPlayPause,
+ }));
+
+ React.useEffect(
+ () => {
+ if (!mobileAudioRef.current) return;
+ if (isPlaying) {
+ mobileAudioRef.current.play();
+ } else {
+ mobileAudioRef.current.pause();
+ }
+ },
+ [isPlaying]
+ );
+
+ React.useEffect(
+ () => {
+ if (soundSrc) { | newIDE/app/src/UI/SoundPlayer/CompactSoundPlayer.js | 26 | JavaScript | 0.786 | suggestion | 766 | 51 | 51 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
// @flow
import * as React from 'react';
import IconButton from '@material-ui/core/IconButton';
import Play from '../CustomSvgIcons/Play';
import Pause from '../CustomSvgIcons/Pause';
type Props = {|
soundSrc: string | null,
onSoundLoaded?: () => void,
onSoundError?: () => void,
|};
export type CompactSoundPlayerInterface = {|
playPause: (forcePlay: boolean) => void,
|};
const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
const mobileAudioRef = React.useRef<?Audio>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onLoad = React.useCallback(() => {
setIsPlaying(false);
}, []);
const onAudioReady = React.useCallback(
() => {
if (!mobileAudioRef.current) return;
if (onSoundLoaded) onSoundLoaded();
},
[onSoundLoaded]
);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
})); | ```suggestion
const audioRef = React.useRef<?Audio>(null);
```
No reason to add "mobile" in the name, this is confusing for the reader. | // @flow
import * as React from 'react';
import IconButton from '@material-ui/core/IconButton';
import CircularProgress from '@material-ui/core/CircularProgress';
import Play from '../CustomSvgIcons/Play';
import Pause from '../CustomSvgIcons/Pause';
import { useIsMounted } from '../../Utils/UseIsMounted';
type Props = {|
soundSrc: string | null,
onSoundLoaded?: () => void,
onSoundError?: () => void,
|};
const CompactSoundPlayer = ({
soundSrc,
onSoundLoaded,
onSoundError,
}: Props) => {
const audioRef = React.useRef<?HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const [isAudioLoaded, setIsAudioLoaded] = React.useState(false);
const isMountedRef = useIsMounted();
const abortControllerRef = React.useRef<?AbortController>(null);
const cleanupAudioAndListeners = React.useCallback(() => {
const audio = audioRef.current;
if (!audio) return;
audio.pause();
if (abortControllerRef.current) abortControllerRef.current.abort();
audio.src = '';
audioRef.current = null;
abortControllerRef.current = null;
setIsPlaying(false);
setIsLoading(false);
setIsAudioLoaded(false);
}, []);
const initializeAudio = React.useCallback(
() => {
if (!soundSrc || audioRef.current) return; | @@ -0,0 +1,91 @@
+// @flow
+
+import * as React from 'react';
+import IconButton from '@material-ui/core/IconButton';
+import Play from '../CustomSvgIcons/Play';
+import Pause from '../CustomSvgIcons/Pause';
+
+type Props = {|
+ soundSrc: string | null,
+ onSoundLoaded?: () => void,
+ onSoundError?: () => void,
+|};
+
+export type CompactSoundPlayerInterface = {|
+ playPause: (forcePlay: boolean) => void,
+|};
+
+const CompactSoundPlayer = React.forwardRef<Props, CompactSoundPlayerInterface>(
+ ({ soundSrc, onSoundLoaded, onSoundError }, ref) => {
+ const mobileAudioRef = React.useRef<?Audio>(null); | newIDE/app/src/UI/SoundPlayer/CompactSoundPlayer.js | 20 | JavaScript | 0.929 | suggestion | 140 | 45 | 45 | false | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
[forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
// Find the layer ID from the layer name
const layer = layersContainer.getLayer(layerName);
if (!layer) return;
const itemId = `layer-${layer.ptr}`;
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges]
);
const triggerOnLayersModified = React.useCallback(
() => { | ```suggestion
const itemId = getLayerTreeViewItemId(layer);
``` | [forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
if (!layersContainer.hasLayerNamed(layerName)) return;
const layer = layersContainer.getLayer(layerName);
const itemId = getLayerTreeViewItemId(layer);
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges]
);
const triggerOnLayersModified = React.useCallback(
() => {
onLayersModified(); | @@ -335,7 +335,15 @@ const LayersList = React.forwardRef<Props, LayersListInterface>(
}));
const editName = React.useCallback(
- (itemId: string) => {
+ (layerName: string) => {
+ // Don't allow renaming base layer (empty name)
+ if (!layerName) return;
+
+ // Find the layer ID from the layer name
+ const layer = layersContainer.getLayer(layerName);
+ if (!layer) return;
+
+ const itemId = `layer-${layer.ptr}`; | newIDE/app/src/LayersList/index.js | 26 | JavaScript | 0.571 | suggestion | 71 | 51 | 51 | false | Avoid crash when renaming with F2 to edit "Base layer" | 8,222 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
() => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
[forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
// Find the layer ID from the layer name
const layer = layersContainer.getLayer(layerName);
if (!layer) return;
const itemId = `layer-${layer.ptr}`;
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges] | While the first comment is ok (it gives an information), this one is just telling exactly what the lines of codes are doing. So the code is already sufficient => remove it.
```suggestion
``` | () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
[forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
if (!layersContainer.hasLayerNamed(layerName)) return;
const layer = layersContainer.getLayer(layerName);
const itemId = getLayerTreeViewItemId(layer);
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges]
); | @@ -335,7 +335,15 @@ const LayersList = React.forwardRef<Props, LayersListInterface>(
}));
const editName = React.useCallback(
- (itemId: string) => {
+ (layerName: string) => {
+ // Don't allow renaming base layer (empty name)
+ if (!layerName) return;
+
+ // Find the layer ID from the layer name | newIDE/app/src/LayersList/index.js | 26 | JavaScript | 0.786 | suggestion | 190 | 51 | 51 | false | Avoid crash when renaming with F2 to edit "Base layer" | 8,222 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
[forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
// Find the layer ID from the layer name
const layer = layersContainer.getLayer(layerName);
if (!layer) return;
const itemId = `layer-${layer.ptr}`;
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges]
);
| Check the type or even the C++ code: the layer will never be null. This is a difference compared to JS libraries (which are indeed often returning null when something does not exist. But we can't do it in C++ converted to JS).
To save you from a crash, the C++ will return a "bad layer" (i.e: an empty layer) in case you get one with a wrong name.
To be safe, you need to do:
```suggestion
if (!layersContainer.hasLayerNamed(layerName)) return;
const layer = layersContainer.getLayer(layerName);
``` | if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
[forceUpdate]
);
const scrollToItem = React.useCallback((itemId: string) => {
if (treeViewRef.current) {
treeViewRef.current.scrollToItemFromId(itemId);
}
}, []);
React.useImperativeHandle(ref, () => ({
forceUpdateList: () => {
forceUpdate();
if (treeViewRef.current) treeViewRef.current.forceUpdateList();
},
}));
const editName = React.useCallback(
(layerName: string) => {
// Don't allow renaming base layer (empty name)
if (!layerName) return;
if (!layersContainer.hasLayerNamed(layerName)) return;
const layer = layersContainer.getLayer(layerName);
const itemId = getLayerTreeViewItemId(layer);
const treeView = treeViewRef.current;
if (treeView) {
if (isMobile) {
// Position item at top of the screen to make sure it will be visible
// once the keyboard is open.
treeView.scrollToItemFromId(itemId, 'start');
}
treeView.renameItemFromId(itemId);
}
},
[isMobile, layersContainer]
);
const onTreeModified = React.useCallback(
(shouldForceUpdateList: boolean) => {
triggerUnsavedChanges();
if (shouldForceUpdateList) forceUpdateList();
else forceUpdate();
},
[forceUpdate, forceUpdateList, triggerUnsavedChanges]
);
const triggerOnLayersModified = React.useCallback( | @@ -335,7 +335,15 @@ const LayersList = React.forwardRef<Props, LayersListInterface>(
}));
const editName = React.useCallback(
- (itemId: string) => {
+ (layerName: string) => {
+ // Don't allow renaming base layer (empty name)
+ if (!layerName) return;
+
+ // Find the layer ID from the layer name
+ const layer = layersContainer.getLayer(layerName);
+ if (!layer) return; | newIDE/app/src/LayersList/index.js | 26 | JavaScript | 0.929 | bug | 516 | 51 | 51 | false | Avoid crash when renaming with F2 to edit "Base layer" | 8,222 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | Bouh |
const spineResourceName = spineConfiguration.getSpineResourceName();
if (!spineResourceName) {
setSkinNames([]);
return;
}
let cancelled = false;
(async () => {
const spineData = await PixiResourcesLoader.getSpineData(
project,
spineResourceName
);
if (cancelled) return;
if (spineData.skeleton && spineData.skeleton.skins) {
setSkinNames(spineData.skeleton.skins.map(skin => skin.name));
} else {
setSkinNames([]);
}
})();
return () => {
cancelled = true;
};
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[project, objectName]
);
const onChangeSelectValue = (event, value) => {
props.onChange(event.target.value);
};
const fieldLabel = props.parameterMetadata
? props.parameterMetadata.getDescription()
: undefined;
const selectOptions = skinNames.map(skinName => {
return (
<SelectOption
key={skinName}
value={`"${skinName}"`}
label={skinName}
shouldNotTranslate
/>
);
});
return (
<SelectField
ref={field} | Can you enter a comment explaining what is not listed and why this is not a problem? | const spineResourceName = spineConfiguration.getSpineResourceName();
if (!spineResourceName) {
setSkinNames([]);
return;
}
let cancelled = false;
(async () => {
const spineData = await PixiResourcesLoader.getSpineData(
project,
spineResourceName
);
if (cancelled) return;
if (spineData.skeleton && spineData.skeleton.skins) {
setSkinNames(spineData.skeleton.skins.map(skin => skin.name));
} else {
setSkinNames([]);
}
})();
return () => {
cancelled = true;
};
},
[project, objectName, globalObjectsContainer, objectsContainer]
);
const onChangeSelectValue = (event, value) => {
props.onChange(event.target.value);
};
const fieldLabel = props.parameterMetadata
? props.parameterMetadata.getDescription()
: undefined;
const selectOptions = skinNames.map(skinName => {
return (
<SelectOption
key={skinName}
value={`"${skinName}"`}
label={skinName}
shouldNotTranslate
/>
);
});
return (
<SelectField
ref={field}
id={ | @@ -0,0 +1,144 @@
+// @flow
+import * as React from 'react';
+import { t } from '@lingui/macro';
+import GenericExpressionField from './GenericExpressionField';
+import {
+ type ParameterFieldProps,
+ type ParameterFieldInterface,
+ type FieldFocusFunction,
+} from './ParameterFieldCommons';
+import { getLastObjectParameterValue } from './ParameterMetadataTools';
+import SelectField, { type SelectFieldInterface } from '../../UI/SelectField';
+import SelectOption from '../../UI/SelectOption';
+import getObjectByName from '../../Utils/GetObjectByName';
+import PixiResourcesLoader from '../../ObjectsRendering/PixiResourcesLoader';
+
+const gd: libGDevelop = global.gd;
+
+export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>(
+ function ObjectSkinNameField(props: ParameterFieldProps, ref) {
+ const field = React.useRef<?(
+ | GenericExpressionField
+ | SelectFieldInterface
+ )>(null);
+ const focus: FieldFocusFunction = options => {
+ if (field.current) field.current.focus(options);
+ };
+ React.useImperativeHandle(ref, () => ({
+ focus,
+ }));
+
+ const {
+ project,
+ globalObjectsContainer,
+ objectsContainer,
+ instructionMetadata,
+ instruction,
+ expressionMetadata,
+ expression,
+ parameterIndex,
+ } = props;
+
+ const [skinNames, setSkinNames] = React.useState<Array<string>>([]);
+
+ const objectName = getLastObjectParameterValue({
+ instructionMetadata,
+ instruction,
+ expressionMetadata,
+ expression,
+ parameterIndex,
+ });
+
+ React.useEffect(
+ () => {
+ if (!project || !objectName) {
+ setSkinNames([]);
+ return;
+ }
+
+ const object = getObjectByName(
+ globalObjectsContainer,
+ objectsContainer,
+ objectName
+ );
+ if (!object || object.getType() !== 'SpineObject::SpineObject') {
+ setSkinNames([]);
+ return;
+ }
+
+ const spineConfiguration = gd.asSpineConfiguration(
+ object.getConfiguration()
+ );
+ const spineResourceName = spineConfiguration.getSpineResourceName();
+ if (!spineResourceName) {
+ setSkinNames([]);
+ return;
+ }
+
+ let cancelled = false;
+ (async () => {
+ const spineData = await PixiResourcesLoader.getSpineData(
+ project,
+ spineResourceName
+ );
+ if (cancelled) return;
+
+ if (spineData.skeleton && spineData.skeleton.skins) {
+ setSkinNames(spineData.skeleton.skins.map(skin => skin.name));
+ } else {
+ setSkinNames([]);
+ }
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps | newIDE/app/src/EventsSheet/ParameterFields/ObjectSkinNameField.js | 26 | JavaScript | 0.214 | question | 84 | 51 | 51 | false | feat: Add support for skin management in Spine objects | 8,229 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
setSpineData(spineData);
if (spineData.skeleton) {
setSourceSelectOptions(
spineData.skeleton.animations.map(animation => (
<SelectOption
key={animation.name}
value={animation.name}
label={animation.name}
shouldNotTranslate
/>
))
);
}
})();
},
[project, spineResourceName, setSourceSelectOptions]
);
/**
* Manage Spine skins
*
* @skinsSelectOptionsList - evaluated skins list from spineData.skeleton
* @skinName - current used skinName (in the first open - is "" empty string, because the next step we set first default skinName in useEffect)
* @handleChangeSkinSelect - handler for change (select) event of skins
*/
const skinsSelectOptionsList = React.useMemo(
() => {
if (spineData.skeleton && spineData.skeleton.skins) {
return spineData.skeleton.skins.map(skin => skin.name);
} else {
return [];
}
},
[spineData.skeleton]
);
const skinName = spineConfiguration.getSkinName();
const changeSpineSkin = React.useCallback(
skinName => {
objectConfiguration.updateProperty('skinName', skinName);
if (onObjectUpdated) onObjectUpdated();
forceUpdate();
},
[objectConfiguration, onObjectUpdated, forceUpdate]
);
React.useEffect( | Nitpicking, but I find it weird to list like this the functions/variables using @. This looks like JSDoc but isn't and is not standard.
It seems rather that you're trying to group things together (which is a great idea!) and in this case a custom hook "useSpineSkin" might do the trick (I'm not 100% sure a hook is really needed, but that's how I would do if I feel the need to regroup React things together, rather than using a comment) |
setSpineData(spineData);
if (spineData.skeleton) {
setSourceSelectOptions(
spineData.skeleton.animations.map(animation => (
<SelectOption
key={animation.name}
value={animation.name}
label={animation.name}
shouldNotTranslate
/>
))
);
}
})();
},
[project, spineResourceName, setSourceSelectOptions]
);
const skinsSelectOptionsList = React.useMemo(
() => {
if (spineData.skeleton && spineData.skeleton.skins) {
return spineData.skeleton.skins.map(skin => skin.name);
} else {
return [];
}
},
[spineData.skeleton]
);
const skinName = spineConfiguration.getSkinName();
const changeSpineSkin = React.useCallback(
skinName => {
objectConfiguration.updateProperty('skinName', skinName);
if (onObjectUpdated) onObjectUpdated();
forceUpdate();
},
[objectConfiguration, onObjectUpdated, forceUpdate]
);
React.useEffect(
() => {
if (
skinsSelectOptionsList.length &&
(!skinName || !skinsSelectOptionsList.includes(skinName))
) {
const defaultSkinObject = skinsSelectOptionsList[0] || '';
changeSpineSkin(defaultSkinObject);
} | @@ -139,6 +139,49 @@ const SpineEditor = ({
[project, spineResourceName, setSourceSelectOptions]
);
+ /**
+ * Manage Spine skins
+ *
+ * @skinsSelectOptionsList - evaluated skins list from spineData.skeleton
+ * @skinName - current used skinName (in the first open - is "" empty string, because the next step we set first default skinName in useEffect)
+ * @handleChangeSkinSelect - handler for change (select) event of skins | newIDE/app/src/ObjectEditor/Editors/SpineEditor.js | 26 | JavaScript | 0.5 | nitpick | 438 | 51 | 51 | false | feat: Add support for skin management in Spine objects | 8,229 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ViktorVovk |
}
// Stop any existing server for this window
if (existingServer && existingServer.serverInstance) {
existingServer.serverInstance.shutdown().catch(() => {
// Ignore shutdown errors
});
}
getAvailablePort(2929, 4000).then(
port => {
const serverParams = {
port,
root,
open: false,
wait: 1000,
https: useHttps ? httpsConfiguration : undefined,
// Disable the "live-reloading" by watching nothing, because
// the hot-reloading built into the game engine is what should
// be used - and the user can still reload manually on its browser.
watch: [],
middleware: [
// Handle requests with query parameters by serving index.html
// This ensures URLs like http://localhost:2929/?i=123 work correctly
function handleQueryParams(req, res, next) {
const url = new URL(req.url, `http://${req.headers.host}`);
// If the request is for the root path with query parameters,
// rewrite to serve index.html while preserving the query string
if (url.pathname === '/' && url.search) {
req.url = '/index.html' + url.search;
}
next();
},
// Disable caching, as it can lead to older generated code being served
// in case preview files are proxied through a CDN (see
// https://github.com/4ian/GDevelop/pull/6553 for example)
function noCache(_, res, next) {
res.setHeader('Surrogate-Control', 'no-store');
res.setHeader(
'Cache-Control',
'no-store, no-cache, must-revalidate, proxy-revalidate'
);
res.setHeader('Expires', '0');
next();
},
],
};
const serverInstance = new FiveServer();
serverInstance | Out of caution, can you add a try catch around this so that if URL throws it still works (url will be unchanged)? | }
// Stop any existing server for this window
if (existingServer && existingServer.serverInstance) {
existingServer.serverInstance.shutdown().catch(() => {
// Ignore shutdown errors
});
}
getAvailablePort(2929, 4000).then(
port => {
const serverParams = {
port,
root,
open: false,
wait: 1000,
https: useHttps ? httpsConfiguration : undefined,
// Disable the "live-reloading" by watching nothing, because
// the hot-reloading built into the game engine is what should
// be used - and the user can still reload manually on its browser.
watch: [],
middleware: [
// Handle requests with query parameters by serving index.html
// This ensures URLs like http://localhost:2929/?i=123 work correctly
function handleQueryParams(req, res, next) {
try {
const url = new URL(req.url, `http://${req.headers.host}`);
// If the request is for the root path with query parameters,
// rewrite to serve index.html while preserving the query string
if (url.pathname === '/' && url.search) {
req.url = '/index.html' + url.search;
}
} catch (e) {
// If URL parsing fails, leave req.url unchanged
}
next();
},
// Disable caching, as it can lead to older generated code being served
// in case preview files are proxied through a CDN (see
// https://github.com/4ian/GDevelop/pull/6553 for example)
function noCache(_, res, next) {
res.setHeader('Surrogate-Control', 'no-store');
res.setHeader(
'Cache-Control',
'no-store, no-cache, must-revalidate, proxy-revalidate'
);
res.setHeader('Expires', '0');
next();
},
], | @@ -38,6 +38,17 @@ module.exports = {
// be used - and the user can still reload manually on its browser.
watch: [],
middleware: [
+ // Handle requests with query parameters by serving index.html
+ // This ensures URLs like http://localhost:2929/?i=123 work correctly
+ function handleQueryParams(req, res, next) {
+ const url = new URL(req.url, `http://${req.headers.host}`); | newIDE/electron-app/app/ServeFolder.js | 26 | JavaScript | 0.429 | question | 113 | 51 | 51 | false | Fix url params not handled when doinga preview over network | 8,285 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
// Initialize keyboard shortcuts as empty.
// onDelete callback is set outside because it deletes the selected
// item (that is a props). As it is stored in a ref, the keyboard shortcut
// instance does not update with selectedItems changes.
const keyboardShortcutsRef = React.useRef<KeyboardShortcuts>(
new KeyboardShortcuts({
shortcutCallbacks: {},
})
);
React.useEffect(
() => {
if (keyboardShortcutsRef.current) {
keyboardShortcutsRef.current.setShortcutCallback('onDelete', () => {
if (selectedItems.length > 0) {
deleteItem(selectedItems[0]);
}
});
keyboardShortcutsRef.current.setShortcutCallback('onRename', () => {
// Don't allow renaming base layer (empty name)
if (
selectedItems.length > 0 &&
selectedLayer &&
selectedLayer.getName()
) {
editName(selectedItems[0].content.getId());
}
});
}
},
[editName, selectedItems, selectedLayer]
);
const getTreeViewData = React.useCallback(
(i18n: I18nType): Array<TreeViewItem> => {
if (!project || !layerTreeViewItemProps) {
return [];
}
// $FlowFixMe[incompatible-type]
return [
{
isRoot: false,
content: new LabelTreeViewItemContent(
layersRootFolderId,
'',
// $FlowFixMe[incompatible-type]
[
gameEditorMode === 'embedded-game'
? {
icon: !project.areEffectsHiddenInEditor() ? ( | It may be safer to keep the base layer check where is was initially. | ? createLayerItem(selectedLayer)
: null;
return selectedItem ? [selectedItem] : [];
},
[createLayerItem, selectedLayer]
);
// Initialize keyboard shortcuts as empty.
// onDelete callback is set outside because it deletes the selected
// item (that is a props). As it is stored in a ref, the keyboard shortcut
// instance does not update with selectedItems changes.
const keyboardShortcutsRef = React.useRef<KeyboardShortcuts>(
new KeyboardShortcuts({
shortcutCallbacks: {},
})
);
React.useEffect(
() => {
if (keyboardShortcutsRef.current) {
keyboardShortcutsRef.current.setShortcutCallback('onDelete', () => {
if (selectedItems.length > 0) {
deleteItem(selectedItems[0]);
}
});
keyboardShortcutsRef.current.setShortcutCallback('onRename', () => {
if (selectedItems.length > 0) {
editName(selectedItems[0].content.getId());
}
});
}
},
[editName, selectedItems]
);
const getTreeViewData = React.useCallback(
(i18n: I18nType): Array<TreeViewItem> => {
if (!project || !layerTreeViewItemProps) {
return [];
}
// $FlowFixMe[incompatible-type]
return [
{
isRoot: false,
content: new LabelTreeViewItemContent(
layersRootFolderId,
'',
// $FlowFixMe[incompatible-type]
[
gameEditorMode === 'embedded-game'
? { | @@ -575,13 +568,18 @@ const LayersList = React.forwardRef<Props, LayersListInterface>(
}
});
keyboardShortcutsRef.current.setShortcutCallback('onRename', () => {
- if (selectedItems.length > 0) {
+ // Don't allow renaming base layer (empty name)
+ if (
+ selectedItems.length > 0 &&
+ selectedLayer &&
+ selectedLayer.getName()
+ ) { | newIDE/app/src/LayersList/index.js | 26 | JavaScript | 0.214 | suggestion | 68 | 51 | 51 | false | Fix being able to rename a layer with shortcut | 8,309 | 4ian/GDevelop | 10,154 | JavaScript | D8H | ClementPasteau |
};
}
if (objectType === 'PanelSpriteObject::PanelSprite') {
const config = gd.asPanelSpriteConfiguration(objectConfiguration);
const width = config.getWidth();
const height = config.getHeight();
return {
size: `${width}x${height}`,
origin: '0;0',
center: `${width / 2};${height / 2}`,
};
}
// Events-based (custom) objects: derive size from their declared area.
if (project.hasEventsBasedObject(objectType)) {
const eventsBasedObject = project.getEventsBasedObject(objectType);
const minX = eventsBasedObject.getAreaMinX();
const maxX = eventsBasedObject.getAreaMaxX();
const minY = eventsBasedObject.getAreaMinY();
const maxY = eventsBasedObject.getAreaMaxY();
const width = maxX - minX;
const height = maxY - minY;
return {
size: `${width}x${height}`,
origin: '0;0',
center: `${(minX + maxX) / 2};${(minY + maxY) / 2}`,
};
}
return null;
};
| @codex This origin is false because it depends on min/max X/Y/Z (for example if minX = -10, the origin is actually at 10)
Can you also adapt this for 3D objects (IsRenderedIn3D)?
And adapt the tests to add a test case with a non 0;0 origin and another test case for 3D events based objects | };
}
if (objectType === 'PanelSpriteObject::PanelSprite') {
const config = gd.asPanelSpriteConfiguration(objectConfiguration);
const width = config.getWidth();
const height = config.getHeight();
return {
size: `${width}x${height}`,
origin: '0;0',
center: `${width / 2};${height / 2}`,
};
}
// Events-based (custom) objects: derive size from their declared area.
if (project.hasEventsBasedObject(objectType)) {
const eventsBasedObject = project.getEventsBasedObject(objectType);
const minX = eventsBasedObject.getAreaMinX();
const maxX = eventsBasedObject.getAreaMaxX();
const minY = eventsBasedObject.getAreaMinY();
const maxY = eventsBasedObject.getAreaMaxY();
const isRenderedIn3D = eventsBasedObject.isRenderedIn3D();
const minZ = isRenderedIn3D ? eventsBasedObject.getAreaMinZ() : 0;
const maxZ = isRenderedIn3D ? eventsBasedObject.getAreaMaxZ() : 0;
const width = maxX - minX;
const height = maxY - minY;
const depth = maxZ - minZ;
const origin = `${-minX};${-minY}${isRenderedIn3D ? `;${-minZ}` : ''}`;
const center = `${width / 2};${height / 2}${
isRenderedIn3D ? `;${depth / 2}` : ''
}`;
return {
size: `${width}x${height}${isRenderedIn3D ? `x${depth}` : ''}`,
origin,
center,
};
}
return null;
};
| @@ -0,0 +1,96 @@
+// @flow
+import { type AssetShortHeader } from '../Utils/GDevelopServices/Asset';
+
+const gd: libGDevelop = global.gd;
+
+/**
+ * Returns size, origin and center for an asset short header.
+ * Returns null for object types where this information cannot be determined statically.
+ */
+export const getObjectSizeAndOriginInfo = (
+ object: gdObject,
+ project: gdProject,
+ assetShortHeader?: AssetShortHeader | null
+): {| size: string, origin: string, center: string |} | null => {
+ const objectConfiguration = object.getConfiguration();
+ const objectType = object.getType();
+
+ if (objectType === 'Sprite') {
+ const spriteConfiguration = gd.asSpriteConfiguration(objectConfiguration);
+ const animations = spriteConfiguration.getAnimations();
+ if (
+ animations.getAnimationsCount() > 0 &&
+ animations.getAnimation(0).getDirectionsCount() > 0 &&
+ animations
+ .getAnimation(0)
+ .getDirection(0)
+ .getSpritesCount() > 0
+ ) {
+ const sprite = animations
+ .getAnimation(0)
+ .getDirection(0)
+ .getSprite(0);
+ const origin = sprite.getOrigin();
+ const originStr = `${origin.getX()};${origin.getY()}`;
+
+ let centerStr;
+ if (sprite.isDefaultCenterPoint()) {
+ centerStr =
+ assetShortHeader != null
+ ? `${assetShortHeader.width / 2};${assetShortHeader.height / 2}`
+ : 'center of image';
+ } else {
+ const center = sprite.getCenter();
+ centerStr = `${center.getX()};${center.getY()}`;
+ }
+
+ const sizeStr =
+ assetShortHeader != null
+ ? `${assetShortHeader.width}x${assetShortHeader.height}`
+ : 'unknown';
+
+ return { size: sizeStr, origin: originStr, center: centerStr };
+ }
+ return null;
+ }
+
+ if (objectType === 'TiledSpriteObject::TiledSprite') {
+ const config = gd.asTiledSpriteConfiguration(objectConfiguration);
+ const width = config.getWidth();
+ const height = config.getHeight();
+ return {
+ size: `${width}x${height}`,
+ origin: '0;0',
+ center: `${width / 2};${height / 2}`,
+ };
+ }
+
+ if (objectType === 'PanelSpriteObject::PanelSprite') {
+ const config = gd.asPanelSpriteConfiguration(objectConfiguration);
+ const width = config.getWidth();
+ const height = config.getHeight();
+ return {
+ size: `${width}x${height}`,
+ origin: '0;0',
+ center: `${width / 2};${height / 2}`,
+ };
+ }
+
+ // Events-based (custom) objects: derive size from their declared area.
+ if (project.hasEventsBasedObject(objectType)) {
+ const eventsBasedObject = project.getEventsBasedObject(objectType);
+ const minX = eventsBasedObject.getAreaMinX();
+ const maxX = eventsBasedObject.getAreaMaxX();
+ const minY = eventsBasedObject.getAreaMinY();
+ const maxY = eventsBasedObject.getAreaMaxY();
+ const width = maxX - minX;
+ const height = maxY - minY;
+ return {
+ size: `${width}x${height}`,
+ origin: '0;0', | newIDE/app/src/EditorFunctions/Utils.js | 26 | JavaScript | 0.5 | suggestion | 290 | 33 | 42 | false | Improve details of center/origin when a common object is created by the AI | 8,322 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | ClementPasteau |
object.setUnscaledWidthAndHeight(100, 100);
object.setCustomWidthAndHeight(10, 10);
runtimeScene.addObject(object);
return object;
};
describe('(anchor horizontal edge)', function () {
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window left (fixed)`, function () {
const object = createObject({ [objectEdge]: 1 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(500);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window right (fixed)`, function () {
const object = createObject({ [objectEdge]: 2 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(1500);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window center (fixed)`, function () {
const object = createObject({ [objectEdge]: 4 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(1000);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
it('anchors the right and left edge of object (fixed)', function () {
const object = createObject({ leftEdgeAnchor: 1, rightEdgeAnchor: 2 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60); | No issues found. | object.setUnscaledWidthAndHeight(100, 100);
object.setCustomWidthAndHeight(10, 10);
runtimeScene.addObject(object);
return object;
};
describe('(anchor horizontal edge)', function () {
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window left (fixed)`, function () {
const object = createObject({ [objectEdge]: 1 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(500);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window right (fixed)`, function () {
const object = createObject({ [objectEdge]: 2 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(1500);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window center (fixed)`, function () {
const object = createObject({ [objectEdge]: 4 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60);
setGameResolutionSizeAndStep(2000, 2000);
expect(object.getX()).to.equal(1000);
expect(object.getY()).to.equal(500);
expect(object.getWidth()).to.equal(10);
});
});
it('anchors the right and left edge of object (fixed)', function () {
const object = createObject({ leftEdgeAnchor: 1, rightEdgeAnchor: 2 });
object.setPosition(500, 500);
runtimeScene.renderAndStep(1000 / 60); | @@ -70,6 +70,50 @@ describe('gdjs.AnchorRuntimeBehavior', function () {
return object;
}
+ const createSpriteWithOriginAtCenter = (behaviorProperties) => {
+ const object = new gdjs.TestSpriteRuntimeObject(runtimeScene, {
+ name: 'obj1',
+ type: '',
+ behaviors: [
+ {
+ name: anchorBehaviorName,
+ type: 'AnchorBehavior::AnchorBehavior',
+ // @ts-ignore - properties are not typed
+ rightEdgeAnchor: 0,
+ leftEdgeAnchor: 0,
+ topEdgeAnchor: 0,
+ bottomEdgeAnchor: 0,
+ relativeToOriginalWindowSize: false,
+ useLegacyBottomAndRightAnchors: false,
+ ...behaviorProperties,
+ },
+ ],
+ effects: [],
+ animations: [
+ {
+ name: 'animation',
+ directions: [
+ {
+ sprites: [
+ {
+ originPoint: { x: 50, y: 50 },
+ centerPoint: { x: 50, y: 50 },
+ points: [],
+ hasCustomCollisionMask: false,
+ customCollisionMask: [],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ object.setUnscaledWidthAndHeight(100, 100);
+ object.setCustomWidthAndHeight(10, 10);
+ runtimeScene.addObject(object);
+ return object;
+ };
+
describe('(anchor horizontal edge)', function () {
['rightEdgeAnchor', 'leftEdgeAnchor'].forEach((objectEdge) => {
it(`anchors the ${objectEdge} edge of object to window left (fixed)`, function () {
@@ -200,5 +244,26 @@ describe('gdjs.AnchorRuntimeBehavior', function () {
expect(object.getY()).to.equal(1000);
expect(object.getWidth()).to.equal(10);
});
+
+ it('can fill the screen with an object (with custom origin)', function () {
+ setGameResolutionSizeAndStep(1000, 500);
+
+ const object = createSpriteWithOriginAtCenter({
+ leftEdgeAnchor: 1,
+ topEdgeAnchor: | Extensions/AnchorBehavior/tests/anchorruntimebehavior.spec.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix anchor behavior when objects has custom origin | 6,970 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
* \brief Return true if the type of the parameter is a number.
* \note If you had a new type of parameter, also add it in the IDE (
* see EventsFunctionParametersEditor, ParameterRenderingService
* and ExpressionAutocompletion) and in the EventsCodeGenerator.
*/
bool IsVariable() const {
return gd::ValueTypeMetadata::GetPrimitiveValueType(name) == "variable";
}
/**
* \brief Return true if the type is a variable but from a specific scope
* (scene, project or object). In new code, prefer to use the more generic "variable"
* parameter (which accepts any variable coming from an object or from containers in the scope).
*/
bool IsLegacyPreScopedVariable() const {
return gd::ValueTypeMetadata::IsTypeLegacyPreScopedVariable(name);
}
/**
* \brief Return true if the type is a variable but from a specific scope
* (scene, project or object). In new code, prefer to use the more generic "variable"
* parameter (which accepts any variable coming from an object or from containers in the scope).
*/
static bool IsTypeLegacyPreScopedVariable(const gd::String &type) {
return type == "scenevar" || type == "globalvar" || type == "objectvar";
}
/**
* \brief Return true if the type is representing one object
* (or more, i.e: an object group).
*/
static bool IsTypeObject(const gd::String ¶meterType) {
return parameterType == "object" || parameterType == "objectPtr" ||
parameterType == "objectList" ||
parameterType == "objectListOrEmptyIfJustDeclared" ||
parameterType == "objectListOrEmptyWithoutPicking";
}
/**
* \brief Return true if the type is "behavior".
*/
static bool IsTypeBehavior(const gd::String ¶meterType) {
return parameterType == "behavior";
}
/**
* \brief Return true if the type is an expression of the given type from the
* caller point of view.
*
* \note If you are adding a new type of parameter, also add it in the IDE (
* see EventsFunctionParametersEditor, ParameterRenderingService | No issues found. | * \brief Return true if the type of the parameter is a number.
* \note If you had a new type of parameter, also add it in the IDE (
* see EventsFunctionParametersEditor, ParameterRenderingService
* and ExpressionAutocompletion) and in the EventsCodeGenerator.
*/
bool IsVariable() const {
return gd::ValueTypeMetadata::GetPrimitiveValueType(name) == "variable";
}
/**
* \brief Return true if the type is a variable but from a specific scope
* (scene, project or object). In new code, prefer to use the more generic "variable"
* parameter (which accepts any variable coming from an object or from containers in the scope).
*/
bool IsLegacyPreScopedVariable() const {
return gd::ValueTypeMetadata::IsTypeLegacyPreScopedVariable(name);
}
/**
* \brief Return true if the type is a variable but from a specific scope
* (scene, project or object). In new code, prefer to use the more generic "variable"
* parameter (which accepts any variable coming from an object or from containers in the scope).
*/
static bool IsTypeLegacyPreScopedVariable(const gd::String &type) {
return type == "scenevar" || type == "globalvar" || type == "objectvar";
}
/**
* \brief Return true if the type is representing one object
* (or more, i.e: an object group).
*/
static bool IsTypeObject(const gd::String ¶meterType) {
return parameterType == "object" || parameterType == "objectPtr" ||
parameterType == "objectList" ||
parameterType == "objectListOrEmptyIfJustDeclared" ||
parameterType == "objectListOrEmptyWithoutPicking";
}
/**
* \brief Return true if the type is "behavior".
*/
static bool IsTypeBehavior(const gd::String ¶meterType) {
return parameterType == "behavior";
}
/**
* \brief Return true if the type is an expression of the given type from the
* caller point of view.
*
* \note If you are adding a new type of parameter, also add it in the IDE (
* see EventsFunctionParametersEditor, ParameterRenderingService | @@ -111,21 +111,21 @@ class GD_CORE_API ValueTypeMetadata {
* given type.
*/
bool IsNumber() const {
- return gd::ValueTypeMetadata::IsTypeExpression("number", name);
+ return gd::ValueTypeMetadata::IsTypeValue("number", name);
}
/**
* \brief Return true if the type is a string.
*/
bool IsString() const {
- return gd::ValueTypeMetadata::IsTypeExpression("string", name);
+ return gd::ValueTypeMetadata::IsTypeValue("string", name);
}
/**
* \brief Return true if the type is a boolean.
*/
bool IsBoolean() const {
- return gd::ValueTypeMetadata::IsTypeExpression("boolean", name);
+ return gd::ValueTypeMetadata::IsTypeValue("boolean", name);
}
/**
@@ -135,7 +135,7 @@ class GD_CORE_API ValueTypeMetadata {
* and ExpressionAutocompletion) and in the EventsCodeGenerator.
*/
bool IsVariable() const {
- return gd::ValueTypeMetadata::IsTypeExpression("variable", name);
+ return gd::ValueTypeMetadata::GetPrimitiveValueType(name) == "variable";
}
/**
@@ -175,7 +175,9 @@ class GD_CORE_API ValueTypeMetadata {
}
/**
- * \brief Return true if the type is an expression of the given type.
+ * \brief Return true if the type is an expression of the given type from the
+ * caller point of view.
+ *
* \note If you are adding a new type of parameter, also add it in the IDE (
* see EventsFunctionParametersEditor, ParameterRenderingService
* and ExpressionAutocompletion) and in the EventsCodeGenerator.
@@ -186,6 +188,7 @@ class GD_CORE_API ValueTypeMetadata {
return parameterType == "number" || parameterType == "expression" ||
parameterType == "camera" || parameterType == "forceMultiplier";
} else if (type == "string") {
+ // "key" and "mouse" are not mapped her, see GetPrimitiveValueType.
return parameterType == "string" || parameterType == "layer" ||
parameterType == "color" || parameterType == "file" ||
| Core/GDCore/Extensions/Metadata/ValueTypeMetadata.h | 0 | C/C++ | 1 | none | 16 | 51 | 51 | true | Fix mouse and key parameters for event-functions | 7,052 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
++i) // Some conditions already have a "conditionInverted" parameter
{
if (instrInfos.parameters.GetParameter(i).GetType() == "conditionInverted")
conditionAlreadyTakeCareOfInversion = true;
}
if (!conditionAlreadyTakeCareOfInversion && conditionInverted)
predicate = GenerateNegatedPredicate(predicate);
// Generate condition code
return GenerateBooleanFullName(returnBoolean, context) + " = " + predicate +
";\n";
}
gd::String EventsCodeGenerator::GenerateObjectCondition(
const gd::String& objectName,
const gd::ObjectMetadata& objInfo,
const std::vector<gd::String>& arguments,
const gd::InstructionMetadata& instrInfos,
const gd::String& returnBoolean,
bool conditionInverted,
gd::EventsCodeGenerationContext& context) {
gd::String conditionCode;
// Prepare call
gd::String objectFunctionCallNamePart =
GetObjectListName(objectName, context) + "[i]." +
instrInfos.codeExtraInformation.functionCallName;
// Create call
gd::String predicate;
if ((instrInfos.codeExtraInformation.type == "number" ||
instrInfos.codeExtraInformation.type == "string")) {
predicate = GenerateRelationalOperatorCall(
instrInfos, arguments, objectFunctionCallNamePart, 1);
} else {
predicate = objectFunctionCallNamePart + "(" +
GenerateArgumentsList(arguments, 1) + ")";
}
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Generate whole condition code
conditionCode +=
"for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) +
".length;i<l;++i) {\n";
conditionCode += " if ( " + predicate + " ) {\n";
conditionCode += " " +
GenerateBooleanFullName(returnBoolean, context) +
" = true;\n";
conditionCode += " " + GetObjectListName(objectName, context) +
"[k] = " + GetObjectListName(objectName, context) + "[i];\n";
conditionCode += " ++k;\n"; | No issues found. | ++i) // Some conditions already have a "conditionInverted" parameter
{
if (instrInfos.parameters.GetParameter(i).GetType() == "conditionInverted")
conditionAlreadyTakeCareOfInversion = true;
}
if (!conditionAlreadyTakeCareOfInversion && conditionInverted)
predicate = GenerateNegatedPredicate(predicate);
// Generate condition code
return GenerateBooleanFullName(returnBoolean, context) + " = " + predicate +
";\n";
}
gd::String EventsCodeGenerator::GenerateObjectCondition(
const gd::String& objectName,
const gd::ObjectMetadata& objInfo,
const std::vector<gd::String>& arguments,
const gd::InstructionMetadata& instrInfos,
const gd::String& returnBoolean,
bool conditionInverted,
gd::EventsCodeGenerationContext& context) {
gd::String conditionCode;
// Prepare call
gd::String objectFunctionCallNamePart =
GetObjectListName(objectName, context) + "[i]." +
instrInfos.codeExtraInformation.functionCallName;
// Create call
gd::String predicate;
if ((instrInfos.codeExtraInformation.type == "number" ||
instrInfos.codeExtraInformation.type == "string")) {
predicate = GenerateRelationalOperatorCall(
instrInfos, arguments, objectFunctionCallNamePart, 1);
} else {
predicate = objectFunctionCallNamePart + "(" +
GenerateArgumentsList(arguments, 1) + ")";
}
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Generate whole condition code
conditionCode +=
"for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) +
".length;i<l;++i) {\n";
conditionCode += " if ( " + predicate + " ) {\n";
conditionCode += " " +
GenerateBooleanFullName(returnBoolean, context) +
" = true;\n";
conditionCode += " " + GetObjectListName(objectName, context) +
"[k] = " + GetObjectListName(objectName, context) + "[i];\n";
conditionCode += " ++k;\n"; | @@ -204,7 +204,9 @@ gd::String EventsCodeGenerator::GenerateBehaviorEventsFunctionCode(
gd::String fullPreludeCode =
preludeCode + "\n" + "var that = this;\n" +
// runtimeScene is supposed to be always accessible, read
- // it from the behavior
+ // it from the behavior.
+ // TODO: this should be renamed to "instanceContainer" and have the code generation
+ // adapted for this (rely less on `gdjs.RuntimeScene`, and more on `RuntimeInstanceContainer`).
"var runtimeScene = this._runtimeScene;\n" +
// By convention of Behavior Events Function, the object is accessible
// as a parameter called "Object", and thisObjectList is an array
@@ -284,7 +286,9 @@ gd::String EventsCodeGenerator::GenerateObjectEventsFunctionCode(
gd::String fullPreludeCode =
preludeCode + "\n" + "var that = this;\n" +
// runtimeScene is supposed to be always accessible, read
- // it from the object
+ // it from the object.
+ // TODO: this should be renamed to "instanceContainer" and have the code generation
+ // adapted for this (rely less on `gdjs.RuntimeScene`, and more on `RuntimeInstanceContainer`).
"var runtimeScene = this._instanceContainer;\n" +
// By convention of Object Events Function, the object is accessible
// as a parameter called "Object", and thisObjectList is an array | GDJS/GDJS/Events/CodeGeneration/EventsCodeGenerator.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix wait action in custom objects | 7,056 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
_("the mouse cursor Y position"),
"",
"res/conditions/mouse24.png")
.AddCodeOnlyParameter("currentScene", "")
.UseStandardParameters("number", ParameterOptions::MakeNewOptions())
.AddParameter("layer", _("Layer"), "", true)
.SetDefaultValue("\"\"")
.AddParameter("expression", _("Camera number (default : 0)"), "", true)
.SetDefaultValue("0")
// It's only useful for extensions as they can't use TouchSimulateMouse.
.SetHidden();
extension
.AddCondition("IsMouseInsideCanvas",
_("Mouse cursor is inside the window"),
_("Check if the mouse cursor is inside the window."),
_("The mouse cursor is inside the window"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.MarkAsAdvanced();
extension
.AddCondition("MouseButtonPressed",
_("Mouse button pressed or touch held"),
_("Check if the specified mouse button is pressed or "
"if a touch is in contact with the screen."),
_("Touch or _PARAM1_ mouse button is down"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.AddParameter("mouse", _("Button to check"))
.MarkAsSimple();
// Support for deprecated names:
extension.AddDuplicatedCondition("SourisBouton", "MouseButtonPressed")
.SetHidden();
extension
.AddCondition("MouseButtonReleased",
_("Mouse button released"),
_("Check if the specified mouse button was released."),
_("_PARAM1_ mouse button was released"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.AddParameter("mouse", _("Button to check"))
.MarkAsSimple(); | No issues found. | _("the mouse cursor Y position"),
"",
"res/conditions/mouse24.png")
.AddCodeOnlyParameter("currentScene", "")
.UseStandardParameters("number", ParameterOptions::MakeNewOptions())
.AddParameter("layer", _("Layer"), "", true)
.SetDefaultValue("\"\"")
.AddParameter("expression", _("Camera number (default : 0)"), "", true)
.SetDefaultValue("0")
// It's only useful for extensions as they can't use TouchSimulateMouse.
.SetHidden();
extension
.AddCondition("IsMouseInsideCanvas",
_("Mouse cursor is inside the window"),
_("Check if the mouse cursor is inside the window."),
_("The mouse cursor is inside the window"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.MarkAsAdvanced();
extension
.AddCondition("MouseButtonPressed",
_("Mouse button pressed or touch held"),
_("Check if the specified mouse button is pressed or "
"if a touch is in contact with the screen."),
_("Touch or _PARAM1_ mouse button is down"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.AddParameter("mouse", _("Button to check"))
.MarkAsSimple();
// Support for deprecated names:
extension.AddDuplicatedCondition("SourisBouton", "MouseButtonPressed")
.SetHidden();
extension
.AddCondition("MouseButtonReleased",
_("Mouse button released"),
_("Check if the specified mouse button was released."),
_("_PARAM1_ mouse button was released"),
"",
"res/conditions/mouse24.png",
"res/conditions/mouse.png")
.AddCodeOnlyParameter("currentScene", "")
.AddParameter("mouse", _("Button to check"))
.MarkAsSimple(); | @@ -338,6 +338,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsMouseExtension(
.AddParameter("expression", _("Camera number (default : 0)"), "", true)
.SetDefaultValue("0");
+ // Deprecated
extension
.AddCondition(
"PopStartedTouch",
@@ -354,6 +355,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsMouseExtension(
.AddCodeOnlyParameter("currentScene", "")
.SetHidden();
+ // Deprecated
extension
.AddCondition(
"PopEndedTouch",
@@ -370,6 +372,7 @@ void GD_CORE_API BuiltinExtensionsImplementer::ImplementsMouseExtension(
.AddCodeOnlyParameter("currentScene", "")
.SetHidden();
+ // Deprecated
extension
.AddCondition(
"HasAnyTouchStarted", | Core/GDCore/Extensions/Builtin/MouseExtension.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Add tutorial bubbles on actions replacing deprecated ones | 7,077 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
if (addInstancesInTheForeground) {
if (
addedInstancesLowestZOrder === null ||
addedInstancesLowestZOrder > instance.getZOrder()
) {
addedInstancesLowestZOrder = instance.getZOrder();
}
}
const newInstance = this._instances
.insertInitialInstance(instance)
.resetPersistentUuid();
instance.delete();
return newInstance;
})
.filter(Boolean);
if (addInstancesInTheForeground && addedInstancesLowestZOrder !== null) {
newInstances.forEach(instance => {
instance.setZOrder(
instance.getZOrder() -
// Flow is not happy with addedInstancesLowestZOrder possible null value
// so 0 is used as a fallback.
(addedInstancesLowestZOrder || 0) +
sceneForegroundZOrder
);
});
}
return newInstances;
};
/**
* Immediately create new instance at the specified position
* (specified in scene coordinates).
*/
addInstances = (
pos: [number, number],
objectNames: Array<string>,
layer: string
): Array<gdInitialInstance> => {
this._zOrderFinder.reset();
this._instances.iterateOverInstances(this._zOrderFinder);
const zOrder = this._zOrderFinder.getHighestZOrder() + 1;
const newPos = roundPositionsToGrid(pos, this._instancesEditorSettings);
const addedInstances = objectNames.map(objectName => {
const instance: gdInitialInstance = this._instances.insertNewInitialInstance();
instance.setObjectName(objectName);
instance.setX(newPos[0]);
instance.setY(newPos[1]);
instance.setLayer(layer); | No issues found. | if (addInstancesInTheForeground) {
if (
addedInstancesLowestZOrder === null ||
addedInstancesLowestZOrder > instance.getZOrder()
) {
addedInstancesLowestZOrder = instance.getZOrder();
}
}
const newInstance = this._instances
.insertInitialInstance(instance)
.resetPersistentUuid();
instance.delete();
return newInstance;
})
.filter(Boolean);
if (addInstancesInTheForeground && addedInstancesLowestZOrder !== null) {
newInstances.forEach(instance => {
instance.setZOrder(
instance.getZOrder() -
// Flow is not happy with addedInstancesLowestZOrder possible null value
// so 0 is used as a fallback.
(addedInstancesLowestZOrder || 0) +
sceneForegroundZOrder
);
});
}
return newInstances;
};
/**
* Immediately create new instance at the specified position
* (specified in scene coordinates).
*/
addInstances = (
pos: [number, number],
objectNames: Array<string>,
layer: string
): Array<gdInitialInstance> => {
this._zOrderFinder.reset();
this._instances.iterateOverInstances(this._zOrderFinder);
const zOrder = this._zOrderFinder.getHighestZOrder() + 1;
const newPos = roundPositionsToGrid(pos, this._instancesEditorSettings);
const addedInstances = objectNames.map(objectName => {
const instance: gdInitialInstance = this._instances.insertNewInitialInstance();
instance.setObjectName(objectName);
instance.setX(newPos[0]);
instance.setY(newPos[1]);
instance.setLayer(layer); | @@ -58,45 +58,53 @@ export default class InstancesAdder {
serializedInstances,
preventSnapToGrid = false,
addInstancesInTheForeground = false,
+ doesObjectExistInContext,
}: {|
position: [number, number],
copyReferential: [number, number],
serializedInstances: Array<Object>,
preventSnapToGrid?: boolean,
addInstancesInTheForeground?: boolean,
+ doesObjectExistInContext: string => boolean,
|}): Array<gdInitialInstance> => {
this._zOrderFinder.reset();
this._instances.iterateOverInstances(this._zOrderFinder);
const sceneForegroundZOrder = this._zOrderFinder.getHighestZOrder() + 1;
let addedInstancesLowestZOrder = null;
- const newInstances = serializedInstances.map(serializedInstance => {
- const instance = new gd.InitialInstance();
- unserializeFromJSObject(instance, serializedInstance);
- const desiredPosition = [
- instance.getX() - copyReferential[0] + position[0],
- instance.getY() - copyReferential[1] + position[1],
- ];
- const newPos = preventSnapToGrid
- ? desiredPosition
- : roundPositionsToGrid(desiredPosition, this._instancesEditorSettings);
- instance.setX(newPos[0]);
- instance.setY(newPos[1]);
- if (addInstancesInTheForeground) {
- if (
- addedInstancesLowestZOrder === null ||
- addedInstancesLowestZOrder > instance.getZOrder()
- ) {
- addedInstancesLowestZOrder = instance.getZOrder();
+ const newInstances = serializedInstances
+ .map(serializedInstance => {
+ const instance = new gd.InitialInstance();
+ unserializeFromJSObject(instance, serializedInstance);
+ if (!doesObjectExistInContext(instance.getObjectName())) return null;
+ const desiredPosition = [
+ instance.getX() - copyReferential[0] + position[0],
+ instance.getY() - copyReferential[1] + position[1],
+ ];
+ const newPos = preventSnapToGrid
+ | newIDE/app/src/InstancesEditor/InstancesAdder.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix instances paste from a scene to another | 7,105 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
// @flow
import * as React from 'react';
export const useDoNowOrAfterRender = <T>(ref: {|
current: T,
|}): (((T) => void) => void) => {
const [
shouldTriggerAfterRender,
setShouldTriggerAfterRender,
] = React.useState<null | (T => void)>(null);
const doNowOrAfterRender = React.useCallback(
(callback: T => void) => {
if (ref.current) {
callback(ref.current);
} else {
setShouldTriggerAfterRender((): (T => void) => callback);
}
},
[ref]
);
React.useEffect(
() => {
if (shouldTriggerAfterRender) {
if (ref.current) shouldTriggerAfterRender(ref.current);
setShouldTriggerAfterRender(null);
}
},
[shouldTriggerAfterRender, ref]
);
return doNowOrAfterRender;
};
| No issues found. | // @flow
import * as React from 'react';
export const useDoNowOrAfterRender = <T>(ref: {|
current: T,
|}): (((T) => void) => void) => {
const [
shouldTriggerAfterRender,
setShouldTriggerAfterRender,
] = React.useState<null | (T => void)>(null);
const doNowOrAfterRender = React.useCallback(
(callback: T => void) => {
if (ref.current) {
callback(ref.current);
} else {
setShouldTriggerAfterRender((): (T => void) => callback);
}
},
[ref]
);
React.useEffect(
() => {
if (shouldTriggerAfterRender) {
if (ref.current) shouldTriggerAfterRender(ref.current);
setShouldTriggerAfterRender(null);
}
},
[shouldTriggerAfterRender, ref]
);
return doNowOrAfterRender;
};
| @@ -0,0 +1,34 @@
+// @flow
+import * as React from 'react';
+
+export const useDoNowOrAfterRender = <T>(ref: {|
+ current: T,
+|}): (((T) => void) => void) => {
+ const [
+ shouldTriggerAfterRender,
+ setShouldTriggerAfterRender,
+ ] = React.useState<null | (T => void)>(null);
+
+ const doNowOrAfterRender = React.useCallback(
+ (callback: T => void) => {
+ if (ref.current) {
+ callback(ref.current);
+ } else {
+ setShouldTriggerAfterRender((): (T => void) => callback);
+ }
+ },
+ [ref]
+ );
+
+ React.useEffect(
+ () => {
+ if (shouldTriggerAfterRender) {
+ if (ref.current) shouldTriggerAfterRender(ref.current);
+ setShouldTriggerAfterRender(null);
+ }
+ },
+ [shouldTriggerAfterRender, ref]
+ );
+
+ return doNowOrAfterRender;
+}; | newIDE/app/src/Utils/UseDoNowOrAfterRender.js | 0 | JavaScript | 1 | none | 16 | 35 | 35 | true | Fix adding an object from context menu when the Objects panel is closed | 7,107 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
);
setGame(updatedGame);
}
setBuildOrGameUrl(
game
? getGameUrl(game)
: build
? getBuildArtifactUrl(build, 's3Key')
: ''
);
setExportState('succeeded');
} catch (err) {
console.error('Unable to update the game', err);
setExportState('errored');
}
},
[setExportState, setGame, game, profile, getAuthorizationHeader]
);
const hasNotSavedProject = !profile && exportState === '';
return (
<ColumnStackLayout
noMargin
expand
alignItems="center"
justifyContent="space-between"
>
<ColumnStackLayout alignItems="center">
<div style={styles.imageContainer}>
<GameImage project={project} />
</div>
<Spacer />
{profile ? (
isLoadingCloudProjects ? (
<PlaceholderLoader />
) : cantContinueBecauseCloudProjectsMaximumReached && limits ? (
renderCallout(limits)
) : (
<I18n>
{({ i18n }) => (
<ColumnStackLayout noMargin expand alignItems="stretch">
<ExportLauncher
ref={exportLauncherRef}
i18n={i18n}
project={project}
onSaveProject={onSaveProject}
isSavingProject={isSavingProject}
onChangeSubscription={() => {
// Nothing to do. | No issues found. | );
setGame(updatedGame);
}
setBuildOrGameUrl(
game
? getGameUrl(game)
: build
? getBuildArtifactUrl(build, 's3Key')
: ''
);
setExportState('succeeded');
} catch (err) {
console.error('Unable to update the game', err);
setExportState('errored');
}
},
[setExportState, setGame, game, profile, getAuthorizationHeader]
);
const hasNotSavedProject = !profile && exportState === '';
return (
<ColumnStackLayout
noMargin
expand
alignItems="center"
justifyContent="space-between"
>
<ColumnStackLayout alignItems="center">
<div style={styles.imageContainer}>
<GameImage project={project} />
</div>
<Spacer />
{profile ? (
isLoadingCloudProjects ? (
<PlaceholderLoader />
) : cantContinueBecauseCloudProjectsMaximumReached && limits ? (
renderCallout(limits)
) : (
<I18n>
{({ i18n }) => (
<ColumnStackLayout noMargin expand alignItems="stretch">
<ExportLauncher
ref={exportLauncherRef}
i18n={i18n}
project={project}
onSaveProject={onSaveProject}
isSavingProject={isSavingProject}
onChangeSubscription={() => {
// Nothing to do. | @@ -10,6 +10,10 @@ import { I18n } from '@lingui/react';
import { type Exporter } from '../ExportAndShare/ShareDialog';
import Text from '../UI/Text';
import { type Limits } from '../Utils/GDevelopServices/Usage';
+import {
+ getBuildArtifactUrl,
+ type Build,
+} from '../Utils/GDevelopServices/Build';
import { type GameAndBuildsManager } from '../Utils/UseGameAndBuildsManager';
import FlatButton from '../UI/FlatButton';
import { Column, Spacer } from '../UI/Grid';
@@ -23,9 +27,12 @@ import TextButton from '../UI/TextButton';
import Trash from '../UI/CustomSvgIcons/Trash';
import GameImage from './GameImage';
import ShareLink from '../UI/ShareDialog/ShareLink';
-import { getGameUrl } from '../Utils/GDevelopServices/Game';
+import { getGameUrl, updateGame } from '../Utils/GDevelopServices/Game';
import PlaceholderLoader from '../UI/PlaceholderLoader';
-import { MaxProjectCountAlertMessage } from '../MainFrame/EditorContainers/HomePage/BuildSection/MaxProjectCountAlertMessage';
+import {
+ checkIfHasTooManyCloudProjects,
+ MaxProjectCountAlertMessage,
+} from '../MainFrame/EditorContainers/HomePage/BuildSection/MaxProjectCountAlertMessage';
import { SubscriptionSuggestionContext } from '../Profile/Subscription/SubscriptionSuggestionContext';
import ArrowLeft from '../UI/CustomSvgIcons/ArrowLeft';
@@ -38,6 +45,7 @@ type Props = {|
onlineWebExporter: Exporter,
onSaveProject: () => Promise<void>,
isSavingProject: boolean,
+ isRequiredToSaveAsNewCloudProject: () => boolean,
onClose: () => Promise<void>,
onContinueQuickCustomization: () => void,
onTryAnotherGame: () => void,
@@ -50,6 +58,7 @@ export const QuickPublish = ({
onlineWebExporter,
onSaveProject,
isSavingProject,
+ isRequiredToSaveAsNewCloudProject,
onClose,
onContinueQuickCustomization,
onTryAnotherGame,
@@ -63,17 +72,15 @@ export const QuickPublish = ({
onOpenCreateAccountDialog,
limits,
cloudProjects,
+ getAuthorizationHeader,
} = aut | newIDE/app/src/QuickCustomization/QuickPublish.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix issues when reworking a quick customization project | 7,109 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
buildMenuTemplate(i18n: I18nType, index: number) {
const {
globalObjectsContainer,
objectsContainer,
expandFolders,
addFolder,
onAddNewObject,
onMovedObjectFolderOrObjectToAnotherFolderInSameContainer,
forceUpdate,
} = this.props;
const container = this._isGlobal
? globalObjectsContainer
: objectsContainer;
if (!container) {
return [];
}
const folderAndPathsInContainer = enumerateFoldersInContainer(container);
folderAndPathsInContainer.unshift({
path: i18n._(t`Root folder`),
folder: container.getRootFolder(),
});
const filteredFolderAndPathsInContainer = folderAndPathsInContainer.filter(
folderAndPath =>
!folderAndPath.folder.isADescendantOf(this.objectFolder) &&
folderAndPath.folder !== this.objectFolder
);
return [
{
label: this._getPasteLabel(i18n, {
isGlobalObject: this._isGlobal,
isFolder: true,
}),
enabled: Clipboard.has(OBJECT_CLIPBOARD_KIND),
click: () => this.paste(),
},
{
label: i18n._(t`Rename`),
click: () => this.props.editName(this.getId()),
accelerator: 'F2',
},
{
label: i18n._(t`Delete`),
click: () => this.delete(),
accelerator: 'Backspace',
},
{
label: i18n._('Move to folder'),
submenu: filteredFolderAndPathsInContainer.map(({ folder, path }) => ({
label: path, | No issues found. | buildMenuTemplate(i18n: I18nType, index: number) {
const {
globalObjectsContainer,
objectsContainer,
expandFolders,
addFolder,
onAddNewObject,
onMovedObjectFolderOrObjectToAnotherFolderInSameContainer,
forceUpdate,
} = this.props;
const container = this._isGlobal
? globalObjectsContainer
: objectsContainer;
if (!container) {
return [];
}
const folderAndPathsInContainer = enumerateFoldersInContainer(container);
folderAndPathsInContainer.unshift({
path: i18n._(t`Root folder`),
folder: container.getRootFolder(),
});
const filteredFolderAndPathsInContainer = folderAndPathsInContainer.filter(
folderAndPath =>
!folderAndPath.folder.isADescendantOf(this.objectFolder) &&
folderAndPath.folder !== this.objectFolder
);
return [
{
label: this._getPasteLabel(i18n, {
isGlobalObject: this._isGlobal,
isFolder: true,
}),
enabled: Clipboard.has(OBJECT_CLIPBOARD_KIND),
click: () => this.paste(),
},
{
label: i18n._(t`Rename`),
click: () => this.props.editName(this.getId()),
accelerator: 'F2',
},
{
label: i18n._(t`Delete`),
click: () => this.delete(),
accelerator: 'Backspace',
},
{
label: i18n._('Move to folder'),
submenu: filteredFolderAndPathsInContainer.map(({ folder, path }) => ({
label: path, | @@ -20,6 +20,24 @@ import { type MessageDescriptor } from '../Utils/i18n/MessageDescriptor.flow';
import type { ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import { type HTMLDataset } from '../Utils/HTMLDataset';
+export const expandAllSubfolders = (
+ objectFolder: gdObjectFolderOrObject,
+ isGlobal: boolean,
+ expandFolders: (
+ objectFolderOrObjectWithContexts: Array<ObjectFolderOrObjectWithContext>
+ ) => void
+) => {
+ const subFolders = enumerateFoldersInFolder(objectFolder).map(
+ folderAndPath => folderAndPath.folder
+ );
+ expandFolders(
+ [objectFolder, ...subFolders].map(folder => ({
+ objectFolderOrObject: folder,
+ global: isGlobal,
+ }))
+ );
+};
+
export type ObjectFolderTreeViewItemCallbacks = {|
onObjectPasted?: gdObject => void,
onRenameObjectFolderOrObjectWithContextFinish: (
@@ -262,17 +280,8 @@ export class ObjectFolderTreeViewItemContent implements TreeViewItemContent {
{ type: 'separator' },
{
label: i18n._(t`Expand all sub folders`),
- click: () => {
- const subFolders = enumerateFoldersInFolder(this.objectFolder).map(
- folderAndPath => folderAndPath.folder
- );
- expandFolders(
- [this.objectFolder, ...subFolders].map(folder => ({
- objectFolderOrObject: folder,
- global: this._isGlobal,
- }))
- );
- },
+ click: () =>
+ expandAllSubfolders(this.objectFolder, this._isGlobal, expandFolders),
},
];
} | newIDE/app/src/ObjectsList/ObjectFolderTreeViewItemContent.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Replace the "add folder" button by a drop-down menu action | 7,117 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
asset: {},
userData: {},
//@ts-ignore
parser: null,
};
}
}
getResourceKinds(): ResourceKind[] {
return resourceKinds;
}
async processResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
const loader = this._loader;
if (!loader) {
return;
}
const data = this._downloadedArrayBuffers.get(resource);
if (!data) {
return;
}
this._downloadedArrayBuffers.delete(resource);
try {
const gltf: THREE_ADDONS.GLTF = await loader.parseAsync(data, '');
this._loadedThreeModels.set(resource, gltf);
} catch (error) {
logger.error(
"Can't fetch the 3D model file " + resource.file + ', error: ' + error
);
}
}
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
const loader = this._loader;
if (!loader) {
return;
} | No issues found. | asset: {},
userData: {},
//@ts-ignore
parser: null,
};
}
}
getResourceKinds(): ResourceKind[] {
return resourceKinds;
}
async processResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
const loader = this._loader;
if (!loader) {
return;
}
const data = this._downloadedArrayBuffers.get(resource);
if (!data) {
return;
}
this._downloadedArrayBuffers.delete(resource);
try {
const gltf: THREE_ADDONS.GLTF = await loader.parseAsync(data, '');
this._loadedThreeModels.set(resource, gltf);
} catch (error) {
logger.error(
"Can't fetch the 3D model file " + resource.file + ', error: ' + error
);
}
}
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
const loader = this._loader;
if (!loader) {
return;
} | @@ -143,5 +143,25 @@ namespace gdjs {
this._loadedThreeModels.getFromName(resourceName) || this._invalidModel
);
}
+
+ /**
+ * To be called when the game is disposed.
+ * Clear the models, resources loaded and destroy 3D models loaders in this manager.
+ */
+ dispose(): void {
+ this._loadedThreeModels.clear();
+ this._downloadedArrayBuffers.clear();
+ this._loader = null;
+ this._dracoLoader = null;
+
+ if (this._invalidModel) {
+ this._invalidModel.cameras = [];
+ this._invalidModel.animations = [];
+ this._invalidModel.scenes = [];
+ this._invalidModel.userData = {};
+ this._invalidModel.asset = {};
+ this._invalidModel.scene.clear();
+ }
+ }
}
} | GDJS/Runtime/Model3DManager.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add dispose method to Runtimegame | 7,118 | 4ian/GDevelop | 10,154 | JavaScript | danvervlad | |
&eventsFunctionsExtension.GetGlobalVariables(),
&eventsFunctionsExtension.GetSceneVariables(),
PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
projectScopedContainers.AddParameters(
eventsFunction.GetParametersForEvents(eventsFunctionsExtension));
return projectScopedContainers;
};
ProjectScopedContainers
ProjectScopedContainers::MakeNewProjectScopedContainersForBehaviorEventsFunction(
const gd::Project &project, const gd::EventsFunctionsExtension &eventsFunctionsExtension,
const gd::EventsBasedBehavior& eventsBasedBehavior,
const gd::EventsFunction &eventsFunction,
gd::ObjectsContainer ¶meterObjectsContainer) {
gd::EventsFunctionTools::BehaviorEventsFunctionToObjectsContainer(
project,
eventsBasedBehavior,
eventsFunction,
parameterObjectsContainer);
ProjectScopedContainers projectScopedContainers(
ObjectsContainersList::MakeNewObjectsContainersListForContainer(
parameterObjectsContainer),
VariablesContainersList::
MakeNewVariablesContainersListForEventsFunctionsExtension(eventsFunctionsExtension),
&eventsFunctionsExtension.GetGlobalVariables(),
&eventsFunctionsExtension.GetSceneVariables(),
PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
projectScopedContainers.AddPropertiesContainer(
eventsBasedBehavior.GetSharedPropertyDescriptors());
projectScopedContainers.AddPropertiesContainer(
eventsBasedBehavior.GetPropertyDescriptors());
projectScopedContainers.AddParameters(eventsFunction.GetParametersForEvents(
eventsBasedBehavior.GetEventsFunctions()));
return projectScopedContainers;
}
ProjectScopedContainers
ProjectScopedContainers::MakeNewProjectScopedContainersForObjectEventsFunction(
const gd::Project &project,
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
const gd::EventsBasedObject &eventsBasedObject,
const gd::EventsFunction &eventsFunction,
gd::ObjectsContainer ¶meterObjectsContainer) {
gd::EventsFunctionTools::ObjectEventsFunctionToObjectsContainer( | No issues found. | &eventsFunctionsExtension.GetGlobalVariables(),
&eventsFunctionsExtension.GetSceneVariables(),
PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
projectScopedContainers.AddParameters(
eventsFunction.GetParametersForEvents(eventsFunctionsExtension));
return projectScopedContainers;
};
ProjectScopedContainers
ProjectScopedContainers::MakeNewProjectScopedContainersForBehaviorEventsFunction(
const gd::Project &project, const gd::EventsFunctionsExtension &eventsFunctionsExtension,
const gd::EventsBasedBehavior& eventsBasedBehavior,
const gd::EventsFunction &eventsFunction,
gd::ObjectsContainer ¶meterObjectsContainer) {
gd::EventsFunctionTools::BehaviorEventsFunctionToObjectsContainer(
project,
eventsBasedBehavior,
eventsFunction,
parameterObjectsContainer);
ProjectScopedContainers projectScopedContainers(
ObjectsContainersList::MakeNewObjectsContainersListForContainer(
parameterObjectsContainer),
VariablesContainersList::
MakeNewVariablesContainersListForEventsFunctionsExtension(eventsFunctionsExtension),
&eventsFunctionsExtension.GetGlobalVariables(),
&eventsFunctionsExtension.GetSceneVariables(),
PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
projectScopedContainers.AddPropertiesContainer(
eventsBasedBehavior.GetSharedPropertyDescriptors());
projectScopedContainers.AddPropertiesContainer(
eventsBasedBehavior.GetPropertyDescriptors());
projectScopedContainers.AddParameters(eventsFunction.GetParametersForEvents(
eventsBasedBehavior.GetEventsFunctions()));
return projectScopedContainers;
}
ProjectScopedContainers
ProjectScopedContainers::MakeNewProjectScopedContainersForObjectEventsFunction(
const gd::Project &project,
const gd::EventsFunctionsExtension &eventsFunctionsExtension,
const gd::EventsBasedObject &eventsBasedObject,
const gd::EventsFunction &eventsFunction,
gd::ObjectsContainer ¶meterObjectsContainer) {
gd::EventsFunctionTools::ObjectEventsFunctionToObjectsContainer( | @@ -4,12 +4,55 @@
#include "GDCore/Project/EventsFunctionsExtension.h"
#include "GDCore/Project/EventsBasedBehavior.h"
#include "GDCore/Project/EventsBasedObject.h"
+#include "GDCore/Project/Layout.h"
#include "GDCore/Project/ObjectsContainer.h"
+#include "GDCore/Project/Project.h"
#include "GDCore/Events/Event.h"
#include "GDCore/Extensions/PlatformExtension.h"
namespace gd {
+ProjectScopedContainers
+ProjectScopedContainers::MakeNewProjectScopedContainersForProjectAndLayout(
+ const gd::Project &project, const gd::Layout &layout) {
+ ProjectScopedContainers projectScopedContainers(
+ ObjectsContainersList::MakeNewObjectsContainersListForProjectAndLayout(
+ project, layout),
+ VariablesContainersList::
+ MakeNewVariablesContainersListForProjectAndLayout(project, layout),
+ &project.GetVariables(), &layout.GetVariables(),
+ PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
+
+ return projectScopedContainers;
+}
+
+ProjectScopedContainers
+ProjectScopedContainers::MakeNewProjectScopedContainersForProject(
+ const gd::Project &project) {
+ ProjectScopedContainers projectScopedContainers(
+ ObjectsContainersList::MakeNewObjectsContainersListForProject(project),
+ VariablesContainersList::MakeNewVariablesContainersListForProject(
+ project),
+ &project.GetVariables(), nullptr,
+ PropertiesContainersList::MakeNewEmptyPropertiesContainersList());
+
+ return projectScopedContainers;
+}
+
+ProjectScopedContainers
+ProjectScopedContainers::MakeNewProjectScopedContainersFor(
+ const gd::ObjectsContainer &globalObjectsContainers,
+ const gd::ObjectsContainer &objectsContainers) {
+ ProjectScopedContainers projectScopedContainers(
+ ObjectsContainersList::MakeNewObjectsContainersListForContainers(
+ globalObjectsContainers, objectsContainers),
+ VariablesContainersList::MakeNewEmptyVariablesContainersList(),
+ nullptr, nullptr,
+ Propertie | Core/GDCore/Project/ProjectScopedContainers.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Allow legacy scene variable parameters to use extension variables | 7,121 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
#include "GDCore/Project/Project.h"
#include "GDCore/Project/PropertyDescriptor.h"
#include "GDCore/String.h"
namespace gd {
void LeaderboardIdRenamer::DoVisitObject(gd::Object &object) {
for (auto &pair : object.GetConfiguration().GetProperties()) {
auto &propertyName = pair.first;
auto &property = pair.second;
if (property.GetType() == "LeaderboardId") {
auto &leaderboardId = property.GetValue();
allLeaderboardIds.insert(leaderboardId);
if (leaderboardIdMap.find(leaderboardId) != leaderboardIdMap.end()) {
object.GetConfiguration().UpdateProperty(
propertyName, leaderboardIdMap[leaderboardId]);
}
}
}
};
void LeaderboardIdRenamer::DoVisitBehavior(gd::Behavior &behavior) {};
bool LeaderboardIdRenamer::DoVisitInstruction(gd::Instruction &instruction,
bool isCondition) {
const gd::InstructionMetadata &instrInfo =
isCondition ? MetadataProvider::GetConditionMetadata(
project.GetCurrentPlatform(), instruction.GetType())
: MetadataProvider::GetActionMetadata(
project.GetCurrentPlatform(), instruction.GetType());
for (int i = 0; i < instruction.GetParametersCount() &&
i < instrInfo.GetParametersCount();
++i) {
const gd::ParameterMetadata parameter = instrInfo.GetParameter(i);
if (parameter.GetType() != "leaderboardId") {
continue;
}
const gd::String leaderboardIdExpression =
instruction.GetParameter(i).GetPlainString();
if (leaderboardIdExpression[0] != '"' ||
leaderboardIdExpression[leaderboardIdExpression.size() - 1] != '"') {
continue;
}
const gd::String leaderboardId =
leaderboardIdExpression.substr(1, leaderboardIdExpression.size() - 2);
allLeaderboardIds.insert(leaderboardId); | No issues found. | #include "GDCore/Project/Project.h"
#include "GDCore/Project/PropertyDescriptor.h"
#include "GDCore/String.h"
namespace gd {
void LeaderboardIdRenamer::DoVisitObject(gd::Object &object) {
for (auto &pair : object.GetConfiguration().GetProperties()) {
auto &propertyName = pair.first;
auto &property = pair.second;
if (property.GetType() == "LeaderboardId") {
auto &leaderboardId = property.GetValue();
allLeaderboardIds.insert(leaderboardId);
if (leaderboardIdMap.find(leaderboardId) != leaderboardIdMap.end()) {
object.GetConfiguration().UpdateProperty(
propertyName, leaderboardIdMap[leaderboardId]);
}
}
}
};
void LeaderboardIdRenamer::DoVisitBehavior(gd::Behavior &behavior) {};
bool LeaderboardIdRenamer::DoVisitInstruction(gd::Instruction &instruction,
bool isCondition) {
const gd::InstructionMetadata &instrInfo =
isCondition ? MetadataProvider::GetConditionMetadata(
project.GetCurrentPlatform(), instruction.GetType())
: MetadataProvider::GetActionMetadata(
project.GetCurrentPlatform(), instruction.GetType());
for (int i = 0; i < instruction.GetParametersCount() &&
i < instrInfo.GetParametersCount();
++i) {
const gd::ParameterMetadata parameter = instrInfo.GetParameter(i);
if (parameter.GetType() != "leaderboardId") {
continue;
}
const gd::String leaderboardIdExpression =
instruction.GetParameter(i).GetPlainString();
if (leaderboardIdExpression[0] != '"' ||
leaderboardIdExpression[leaderboardIdExpression.size() - 1] != '"') {
continue;
}
const gd::String leaderboardId =
leaderboardIdExpression.substr(1, leaderboardIdExpression.size() - 2);
allLeaderboardIds.insert(leaderboardId); | @@ -1,8 +1,19 @@
#include "LeaderboardIdRenamer.h"
+#include <map>
+#include <memory>
+#include <vector>
+
+#include "GDCore/Events/Event.h"
+#include "GDCore/Events/EventsList.h"
+#include "GDCore/Extensions/Metadata/InstructionMetadata.h"
+#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Project/Behavior.h"
+#include "GDCore/Project/Layout.h"
#include "GDCore/Project/Object.h"
+#include "GDCore/Project/Project.h"
#include "GDCore/Project/PropertyDescriptor.h"
+#include "GDCore/String.h"
namespace gd {
@@ -12,15 +23,54 @@ void LeaderboardIdRenamer::DoVisitObject(gd::Object &object) {
auto &property = pair.second;
if (property.GetType() == "LeaderboardId") {
auto &leaderboardId = property.GetValue();
+
+ allLeaderboardIds.insert(leaderboardId);
+
if (leaderboardIdMap.find(leaderboardId) != leaderboardIdMap.end()) {
- object.GetConfiguration().UpdateProperty(propertyName, leaderboardIdMap[leaderboardId]);
+ object.GetConfiguration().UpdateProperty(
+ propertyName, leaderboardIdMap[leaderboardId]);
}
}
}
};
-void LeaderboardIdRenamer::DoVisitBehavior(gd::Behavior &behavior){};
+void LeaderboardIdRenamer::DoVisitBehavior(gd::Behavior &behavior) {};
+
+bool LeaderboardIdRenamer::DoVisitInstruction(gd::Instruction &instruction,
+ bool isCondition) {
+ const gd::InstructionMetadata &instrInfo =
+ isCondition ? MetadataProvider::GetConditionMetadata(
+ project.GetCurrentPlatform(), instruction.GetType())
+ : MetadataProvider::GetActionMetadata(
+ project.GetCurrentPlatform(), instruction.GetType());
+
+ for (int i = 0; i < instruction.GetParametersCount() &&
+ i < instrInfo.GetParametersCount();
+ ++i) {
+ const gd::ParameterMetadata parameter = instrInfo.GetParameter(i);
+
+ if (parameter.GetType() != "leaderboardId") {
+ | Core/GDCore/IDE/Events/LeaderboardIdRenamer.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix leaderboards not properly replaced in projects using them in custom objects | 7,131 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
if (this.dialogueData.select) {
this.selectedOption -= 1;
this.selectedOption = gdjs.dialogueTree._cycledOptionIndex(
this.selectedOption
);
this.selectedOptionUpdated = true;
}
};
/**
* Select option by index during Options type line parsing.
* @param optionIndex The index of the option to select
*/
gdjs.dialogueTree.selectOption = function (optionIndex: float) {
if (!this.dialogueIsRunning) {
return;
}
if (this.dialogueData.select) {
this.selectedOption = gdjs.dialogueTree._normalizedOptionIndex(
optionIndex
);
this.selectedOptionUpdated = true;
}
};
/**
* Get the currently selected option
* @returns The index of the currently selected option
*/
gdjs.dialogueTree.getSelectedOption = function (): number {
if (!this.dialogueIsRunning) {
return;
}
if (this.dialogueData.select) {
return this.selectedOption;
}
return 0;
};
/**
* Check when the player has changed option selection since the last call to this function.
*
* Can be used to re-render your displayed dialogue options when needed.
*
* @returns true if the selected option was updated since the last call to this function
*/
gdjs.dialogueTree.hasSelectedOptionChanged = function (): boolean {
if (this.selectedOptionUpdated) {
this.selectedOptionUpdated = false;
if (this.selectedOption === -1) {
this.selectedOption = 0; | No issues found. | if (this.dialogueData.select) {
this.selectedOption -= 1;
this.selectedOption = gdjs.dialogueTree._cycledOptionIndex(
this.selectedOption
);
this.selectedOptionUpdated = true;
}
};
/**
* Select option by index during Options type line parsing.
* @param optionIndex The index of the option to select
*/
gdjs.dialogueTree.selectOption = function (optionIndex: float) {
if (!this.dialogueIsRunning) {
return;
}
if (this.dialogueData.select) {
this.selectedOption = gdjs.dialogueTree._normalizedOptionIndex(
optionIndex
);
this.selectedOptionUpdated = true;
}
};
/**
* Get the currently selected option
* @returns The index of the currently selected option
*/
gdjs.dialogueTree.getSelectedOption = function (): number {
if (!this.dialogueIsRunning) {
return;
}
if (this.dialogueData.select) {
return this.selectedOption;
}
return 0;
};
/**
* Check when the player has changed option selection since the last call to this function.
*
* Can be used to re-render your displayed dialogue options when needed.
*
* @returns true if the selected option was updated since the last call to this function
*/
gdjs.dialogueTree.hasSelectedOptionChanged = function (): boolean {
if (this.selectedOptionUpdated) {
this.selectedOptionUpdated = false;
if (this.selectedOption === -1) {
this.selectedOption = 0; | @@ -422,8 +422,9 @@ namespace gdjs {
return;
}
if (this.dialogueData.select) {
- this.selectedOption =
- gdjs.dialogueTree._normalizedOptionIndex(optionIndex);
+ this.selectedOption = gdjs.dialogueTree._normalizedOptionIndex(
+ optionIndex
+ );
this.selectedOptionUpdated = true;
}
}; | Extensions/DialogueTree/dialoguetools.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | [Physics2] Fix a memory leak on object instances | 7,136 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
return loginProvider
.loginOrSignupWithProvider({ provider, signal })
.then(userCredentials => {
// The user is now stored in `this.auth`.
})
.catch(error => {
if (error.name !== userCancellationErrorName) {
console.error('Error while login with provider:', error);
}
throw error;
});
};
forgotPassword = (form: ForgotPasswordForm): Promise<void> => {
return sendPasswordResetEmail(this.auth, form.email);
};
getFirebaseUser = async (): Promise<?FirebaseUser> => {
const { currentUser } = this.auth;
if (!currentUser) {
return null;
}
// In order to fetch the latest firebaseUser properties (like emailVerified)
// we have to call the reload method.
await currentUser.reload();
return this.auth.currentUser;
};
sendFirebaseEmailVerification = async (): Promise<void> => {
{
const { currentUser } = this.auth;
if (!currentUser)
throw new Error(
'Tried to send verification email while not authenticated.'
);
await currentUser.reload();
}
const { currentUser } = this.auth;
if (!currentUser || currentUser.emailVerified) return;
try {
await sendEmailVerification(currentUser);
} catch (error) {
showErrorBox({
message:
'An email has been sent recently, check your inbox or please try again later.',
rawError: error,
errorId: 'email-verification-send-error',
}); | No issues found. | return loginProvider
.loginOrSignupWithProvider({ provider, signal })
.then(userCredentials => {
// The user is now stored in `this.auth`.
})
.catch(error => {
if (error.name !== userCancellationErrorName) {
console.error('Error while login with provider:', error);
}
throw error;
});
};
forgotPassword = (form: ForgotPasswordForm): Promise<void> => {
return sendPasswordResetEmail(this.auth, form.email);
};
getFirebaseUser = async (): Promise<?FirebaseUser> => {
const { currentUser } = this.auth;
if (!currentUser) {
return null;
}
// In order to fetch the latest firebaseUser properties (like emailVerified)
// we have to call the reload method.
await currentUser.reload();
return this.auth.currentUser;
};
sendFirebaseEmailVerification = async (): Promise<void> => {
{
const { currentUser } = this.auth;
if (!currentUser)
throw new Error(
'Tried to send verification email while not authenticated.'
);
await currentUser.reload();
}
const { currentUser } = this.auth;
if (!currentUser || currentUser.emailVerified) return;
try {
await sendEmailVerification(currentUser);
} catch (error) {
showErrorBox({
message:
'An email has been sent recently, check your inbox or please try again later.',
rawError: error,
errorId: 'email-verification-send-error',
}); | @@ -16,6 +16,7 @@ import { GDevelopFirebaseConfig, GDevelopUserApi } from './ApiConfigs';
import type { LoginProvider } from '../../LoginProvider';
import { showErrorBox } from '../../UI/Messages/MessageBox';
import { type CommunityLinks, type UserSurvey } from './User';
+import { userCancellationErrorName } from '../../LoginProvider/Utils';
export type Profile = {|
id: string,
@@ -267,7 +268,9 @@ export default class Authentication {
// The user is now stored in `this.auth`.
})
.catch(error => {
- console.error('Error while login with provider:', error);
+ if (error.name !== userCancellationErrorName) {
+ console.error('Error while login with provider:', error);
+ }
throw error;
});
}; | newIDE/app/src/Utils/GDevelopServices/Authentication.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix infinite loading when canceling login with provider | 7,138 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
onParametersUpdated();
}
);
}
},
[
eventsBasedBehavior,
eventsBasedObject,
eventsFunction,
forceUpdate,
onMoveBehaviorEventsParameter,
onMoveFreeEventsParameter,
onMoveObjectEventsParameter,
onParametersUpdated,
]
);
const moveParameterBefore = React.useCallback(
(targetParameter: gdParameterMetadata) => {
const { current } = draggedParameter;
if (!current) return;
const parameters = eventsFunction.getParameters();
const draggedIndex = parameters.getParameterPosition(current);
const targetIndex = parameters.getParameterPosition(targetParameter);
moveParameter(
draggedIndex,
targetIndex > draggedIndex ? targetIndex - 1 : targetIndex
);
},
[eventsFunction, moveParameter]
);
const addLongDescription = React.useCallback(
(index: number) => {
// Show the long description field
setLongDescriptionShownIndexes({
...longDescriptionShownIndexes,
[index]: true,
});
},
[longDescriptionShownIndexes]
);
const removeLongDescription = React.useCallback(
(index: number) => {
const parameters = eventsFunction.getParameters();
const parameter = parameters.getParameterAt(index);
// Reset the long description and hide the field | No issues found. | onParametersUpdated();
}
);
}
},
[
eventsBasedBehavior,
eventsBasedObject,
eventsFunction,
forceUpdate,
onMoveBehaviorEventsParameter,
onMoveFreeEventsParameter,
onMoveObjectEventsParameter,
onParametersUpdated,
]
);
const moveParameterBefore = React.useCallback(
(targetParameter: gdParameterMetadata) => {
const { current } = draggedParameter;
if (!current) return;
const parameters = eventsFunction.getParameters();
const draggedIndex = parameters.getParameterPosition(current);
const targetIndex = parameters.getParameterPosition(targetParameter);
moveParameter(
draggedIndex,
targetIndex > draggedIndex ? targetIndex - 1 : targetIndex
);
},
[eventsFunction, moveParameter]
);
const addLongDescription = React.useCallback(
(index: number) => {
// Show the long description field
setLongDescriptionShownIndexes({
...longDescriptionShownIndexes,
[index]: true,
});
},
[longDescriptionShownIndexes]
);
const removeLongDescription = React.useCallback(
(index: number) => {
const parameters = eventsFunction.getParameters();
const parameter = parameters.getParameterAt(index);
// Reset the long description and hide the field | @@ -39,6 +39,7 @@ import ResponsiveFlatButton from '../../UI/ResponsiveFlatButton';
import { EmptyPlaceholder } from '../../UI/EmptyPlaceholder';
import useAlertDialog from '../../UI/Alert/useAlertDialog';
import Text from '../../UI/Text';
+import { ProjectScopedContainersAccessor } from '../../InstructionOrExpression/EventsScope';
const gd: libGDevelop = global.gd;
@@ -75,8 +76,26 @@ export const useParameterOverridingAlertDialog = () => {
};
};
+const getValidatedParameterName = (
+ parameters: gdParameterMetadataContainer,
+ projectScopedContainers: gdProjectScopedContainers,
+ newName: string
+): string => {
+ const variablesContainersList = projectScopedContainers.getVariablesContainersList();
+ const objectsContainersList = projectScopedContainers.getObjectsContainersList();
+ const safeAndUniqueNewName = newNameGenerator(
+ gd.Project.getSafeName(newName),
+ tentativeNewName =>
+ parameters.hasParameterNamed(tentativeNewName) ||
+ variablesContainersList.has(tentativeNewName) ||
+ objectsContainersList.hasObjectNamed(tentativeNewName)
+ );
+ return safeAndUniqueNewName;
+};
+
type Props = {|
project: gdProject,
+ projectScopedContainersAccessor: ProjectScopedContainersAccessor,
eventsFunction: gdEventsFunction,
eventsBasedBehavior: gdEventsBasedBehavior | null,
eventsBasedObject: gdEventsBasedObject | null,
@@ -109,6 +128,7 @@ type Props = {|
export const EventsFunctionParametersEditor = ({
project,
+ projectScopedContainersAccessor,
eventsFunction,
eventsBasedBehavior,
eventsBasedObject,
@@ -548,7 +568,7 @@ export const EventsFunctionParametersEditor = ({
<I18n>
{({ i18n }) => (
<Column noMargin expand useFullHeight>
- {parameters.getParametersCount() > 0 ? (
+ {parameters.getParametersCount() > 0 || freezeParameters ? (
<React.Fragment>
<ScrollView ref={scrollView}>
<Line>
@@ -623,10 +643,14 @@ export c | newIDE/app/src/EventsFunctionsExtensionEditor/EventsFunctionConfigurationEditor/EventsFunctionParametersEditor.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Reduce the risk of name collisions between objects, variables, parameters and properties | 7,148 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
},
[]
);
const onCaptureFinished = React.useCallback(
async (captureOptions: CaptureOptions) => {
if (!project) return;
const projectId = project.getProjectUuid();
try {
const screenshots = captureOptions.screenshots;
if (!screenshots) return;
const screenshotPublicUrls: string[] = screenshots.map(
screenshot => screenshot.publicUrl
);
// Check if they have been properly uploaded.
const responseUploadedScreenshotPublicUrls: Array<
string | null
> = await Promise.all(
screenshotPublicUrls.map(
async (screenshotUrl): Promise<string | null> => {
const response = await fetch(screenshotUrl, { method: 'HEAD' });
if (!response.ok) {
return null;
}
return screenshotUrl;
}
)
);
const uploadedScreenshotPublicUrls = responseUploadedScreenshotPublicUrls.filter(
Boolean
);
if (!uploadedScreenshotPublicUrls.length) return;
const game = gamesList.games
? gamesList.games.find(game => game.id === projectId)
: null;
setLastPreviewScreenshotsTakenAt(lastPreviewScreenshotsTakenAt => ({
...lastPreviewScreenshotsTakenAt,
[projectId]: Date.now(),
}));
// The game is registered, let's update it.
if (game && profile) {
try { | No issues found. | },
[]
);
const onCaptureFinished = React.useCallback(
async (captureOptions: CaptureOptions) => {
if (!project) return;
const projectId = project.getProjectUuid();
try {
const screenshots = captureOptions.screenshots;
if (!screenshots) return;
const screenshotPublicUrls: string[] = screenshots.map(
screenshot => screenshot.publicUrl
);
// Check if they have been properly uploaded.
const responseUploadedScreenshotPublicUrls: Array<
string | null
> = await Promise.all(
screenshotPublicUrls.map(
async (screenshotUrl): Promise<string | null> => {
const response = await fetch(screenshotUrl, { method: 'HEAD' });
if (!response.ok) {
return null;
}
return screenshotUrl;
}
)
);
const uploadedScreenshotPublicUrls = responseUploadedScreenshotPublicUrls.filter(
Boolean
);
if (!uploadedScreenshotPublicUrls.length) return;
const game = gamesList.games
? gamesList.games.find(game => game.id === projectId)
: null;
setLastPreviewScreenshotsTakenAt(lastPreviewScreenshotsTakenAt => ({
...lastPreviewScreenshotsTakenAt,
[projectId]: Date.now(),
}));
// The game is registered, let's update it.
if (game && profile) {
try { | @@ -5,9 +5,23 @@ import {
type LaunchCaptureOptions,
type CaptureOptions,
} from '../ExportAndShare/PreviewLauncher.flow';
-import { createGameResourceSignedUrls } from '../Utils/GDevelopServices/Game';
-
-const useCapturesManager = ({ project }: { project: ?gdProject }) => {
+import {
+ createGameResourceSignedUrls,
+ updateGame,
+} from '../Utils/GDevelopServices/Game';
+import { type GamesList } from '../GameDashboard/UseGamesList';
+import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
+import PreferencesContext from './Preferences/PreferencesContext';
+
+export const TIME_BETWEEN_PREVIEW_SCREENSHOTS = 1000 * 60 * 3; // 3 minutes
+
+const useCapturesManager = ({
+ project,
+ gamesList,
+}: {
+ project: ?gdProject,
+ gamesList: GamesList,
+}) => {
const [
unverifiedGameScreenshots,
setUnverifiedGameScreenshots,
@@ -17,6 +31,14 @@ const useCapturesManager = ({ project }: { project: ?gdProject }) => {
unverifiedPublicUrl: string,
|}>
>([]);
+ const [
+ lastPreviewScreenshotsTakenAt,
+ setLastPreviewScreenshotsTakenAt,
+ ] = React.useState<{ [projectUuid: string]: number }>({});
+ const { getAuthorizationHeader, profile } = React.useContext(
+ AuthenticatedUserContext
+ );
+ const preferences = React.useContext(PreferencesContext);
const createCaptureOptionsForPreview = React.useCallback(
async (
@@ -70,6 +92,7 @@ const useCapturesManager = ({ project }: { project: ?gdProject }) => {
const onCaptureFinished = React.useCallback(
async (captureOptions: CaptureOptions) => {
if (!project) return;
+ const projectId = project.getProjectUuid();
try {
const screenshots = captureOptions.screenshots;
@@ -101,18 +124,54 @@ const useCapturesManager = ({ project }: { project: ?gdProject }) => {
if (!uploadedScreenshotPublicUrls.length) return;
+ const game = gamesList.games
+ ? gamesList.games.find(game => game.id === projectId | newIDE/app/src/MainFrame/UseCapturesManager.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Take a screenshot on preview | 7,156 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
}
return false;
}
const ResourceFolder& ResourcesManager::GetFolder(
const gd::String& name) const {
for (std::size_t i = 0; i < folders.size(); ++i) {
if (folders[i].GetName() == name) return folders[i];
}
return badFolder;
}
ResourceFolder& ResourcesManager::GetFolder(const gd::String& name) {
for (std::size_t i = 0; i < folders.size(); ++i) {
if (folders[i].GetName() == name) return folders[i];
}
return badFolder;
}
void ResourcesManager::RemoveFolder(const gd::String& name) {
for (std::size_t i = 0; i < folders.size();) {
if (folders[i].GetName() == name) {
folders.erase(folders.begin() + i);
} else
++i;
}
}
void ResourcesManager::CreateFolder(const gd::String& name) {
ResourceFolder newFolder;
newFolder.SetName(name);
folders.push_back(newFolder);
}
std::vector<gd::String> ResourcesManager::GetAllFolderList() {
std::vector<gd::String> allFolders;
for (std::size_t i = 0; i < folders.size(); ++i)
allFolders.push_back(folders[i].GetName());
return allFolders;
}
bool ResourceFolder::HasResource(const gd::String& name) const {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == name) return true;
}
| No issues found. | }
return false;
}
const ResourceFolder& ResourcesManager::GetFolder(
const gd::String& name) const {
for (std::size_t i = 0; i < folders.size(); ++i) {
if (folders[i].GetName() == name) return folders[i];
}
return badFolder;
}
ResourceFolder& ResourcesManager::GetFolder(const gd::String& name) {
for (std::size_t i = 0; i < folders.size(); ++i) {
if (folders[i].GetName() == name) return folders[i];
}
return badFolder;
}
void ResourcesManager::RemoveFolder(const gd::String& name) {
for (std::size_t i = 0; i < folders.size();) {
if (folders[i].GetName() == name) {
folders.erase(folders.begin() + i);
} else
++i;
}
}
void ResourcesManager::CreateFolder(const gd::String& name) {
ResourceFolder newFolder;
newFolder.SetName(name);
folders.push_back(newFolder);
}
std::vector<gd::String> ResourcesManager::GetAllFolderList() {
std::vector<gd::String> allFolders;
for (std::size_t i = 0; i < folders.size(); ++i)
allFolders.push_back(folders[i].GetName());
return allFolders;
}
bool ResourceFolder::HasResource(const gd::String& name) const {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == name) return true;
}
| @@ -173,9 +173,6 @@ std::map<gd::String, gd::PropertyDescriptor> ImageResource::GetProperties()
properties[_("Smooth the image")]
.SetValue(smooth ? "true" : "false")
.SetType("Boolean");
- properties[_("Always loaded in memory")]
- .SetValue(alwaysLoaded ? "true" : "false")
- .SetType("Boolean");
return properties;
}
@@ -184,8 +181,6 @@ bool ImageResource::UpdateProperty(const gd::String& name,
const gd::String& value) {
if (name == _("Smooth the image"))
smooth = value == "1";
- else if (name == _("Always loaded in memory"))
- alwaysLoaded = value == "1";
return true;
}
@@ -569,14 +564,12 @@ void ImageResource::SetFile(const gd::String& newFile) {
}
void ImageResource::UnserializeFrom(const SerializerElement& element) {
- alwaysLoaded = element.GetBoolAttribute("alwaysLoaded");
smooth = element.GetBoolAttribute("smoothed");
SetUserAdded(element.GetBoolAttribute("userAdded"));
SetFile(element.GetStringAttribute("file"));
}
void ImageResource::SerializeTo(SerializerElement& element) const {
- element.SetAttribute("alwaysLoaded", alwaysLoaded);
element.SetAttribute("smoothed", smooth);
element.SetAttribute("userAdded", IsUserAdded());
element.SetAttribute("file", GetFile());
| Core/GDCore/Project/ResourcesManager.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Remove dead code of alwaysLoaded | 7,175 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunction", 1, 3);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in instructions have been updated
auto &action = static_cast<const gd::StandardEvent &>(
eventsList->GetEvent(FreeFunctionAction))
.GetActions()
.Get(0);
REQUIRE(action.GetParameter(0).GetPlainString() == "scene");
REQUIRE(action.GetParameter(1).GetPlainString() == "Second parameter");
REQUIRE(action.GetParameter(2).GetPlainString() == "Third parameter");
REQUIRE(action.GetParameter(3).GetPlainString() == "First parameter");
}
}
SECTION("(Free) events expression parameter moved") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
// The index 0 is reserved for the RuntimeScene.
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunctionExpression", 1, 2);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in expressions have been updated
REQUIRE(GetEventFirstActionFirstParameterString(
eventsList->GetEvent(FreeFunctionWithExpression)) ==
"1 + MyEventsExtension::MyEventsFunctionExpression(456, 123)");
}
}
SECTION("(Free) events expression and condition parameter moved") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
// The index 0 is reserved for the RuntimeScene.
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunctionExpressionAndCondition", 1, 2);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in expressions have been updated
REQUIRE(GetEventFirstActionFirstParameterString(
eventsList->GetEvent(FreeExpressionFromExpressionAndCondition)) ==
"2 + MyEventsExtension::MyEventsFunctionExpressionAndCondition(222, 111)"); | No issues found. | auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunction", 1, 3);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in instructions have been updated
auto &action = static_cast<const gd::StandardEvent &>(
eventsList->GetEvent(FreeFunctionAction))
.GetActions()
.Get(0);
REQUIRE(action.GetParameter(0).GetPlainString() == "scene");
REQUIRE(action.GetParameter(1).GetPlainString() == "Second parameter");
REQUIRE(action.GetParameter(2).GetPlainString() == "Third parameter");
REQUIRE(action.GetParameter(3).GetPlainString() == "First parameter");
}
}
SECTION("(Free) events expression parameter moved") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
// The index 0 is reserved for the RuntimeScene.
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunctionExpression", 1, 2);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in expressions have been updated
REQUIRE(GetEventFirstActionFirstParameterString(
eventsList->GetEvent(FreeFunctionWithExpression)) ==
"1 + MyEventsExtension::MyEventsFunctionExpression(456, 123)");
}
}
SECTION("(Free) events expression and condition parameter moved") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
// The index 0 is reserved for the RuntimeScene.
gd::WholeProjectRefactorer::MoveEventsFunctionParameter(
project, eventsExtension, "MyEventsFunctionExpressionAndCondition", 1, 2);
for (auto *eventsList : GetEventsLists(project)) {
// Check that events function calls in expressions have been updated
REQUIRE(GetEventFirstActionFirstParameterString(
eventsList->GetEvent(FreeExpressionFromExpressionAndCondition)) ==
"2 + MyEventsExtension::MyEventsFunctionExpressionAndCondition(222, 111)"); | @@ -91,6 +91,20 @@ CreateInstructionWithNumberParameter(gd::Project &project,
return event.GetActions().Insert(instruction);
}
+const gd::Instruction &
+CreateInstructionWithVariableParameter(gd::Project &project,
+ gd::EventsList &events,
+ const gd::String &expression) {
+ gd::StandardEvent &event = dynamic_cast<gd::StandardEvent &>(
+ events.InsertNewEvent(project, "BuiltinCommonInstructions::Standard"));
+
+ gd::Instruction instruction;
+ instruction.SetType("MyExtension::DoSomethingWithAnyVariable");
+ instruction.SetParametersCount(1);
+ instruction.SetParameter(0, expression);
+ return event.GetActions().Insert(instruction);
+}
+
enum TestEvent {
FreeFunctionAction,
FreeFunctionWithExpression,
@@ -3067,13 +3081,49 @@ TEST_CASE("WholeProjectRefactorer", "[common]") {
eventsExtension, eventsBasedBehavior);
auto &instruction = CreateInstructionWithNumberParameter(
project, behaviorAction.GetEvents(), "MyProperty");
+ auto &instruction2 = CreateInstructionWithNumberParameter(
+ project, behaviorAction.GetEvents(),
+ "MyExtension::GetVariableAsNumber(MyVariable.MyChild[MyProperty])");
gd::WholeProjectRefactorer::RenameEventsBasedBehaviorProperty(
project, eventsExtension, eventsBasedBehavior, "MyProperty",
"MyRenamedProperty");
REQUIRE(instruction.GetParameter(0).GetPlainString() ==
"MyRenamedProperty");
+ REQUIRE(instruction2.GetParameter(0).GetPlainString() ==
+ "MyExtension::GetVariableAsNumber(MyVariable.MyChild[MyRenamedProperty])");
+ }
+
+ SECTION("(Events based behavior) property not renamed (in variable parameter)") {
+ gd::Project project;
+ gd::Platform platform;
+ SetupProjectWithDummyPlatform(project, platform);
+ auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
+ auto &eventsBasedBehavior =
+ eventsExtension.Ge | Core/tests/WholeProjectRefactorer.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix variables from being renamed with a property | 7,186 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
]}
/>
}
>
{currentTab === 'properties' && (
<ColumnStackLayout noMargin>
{layer.isLightingLayer() ? (
<DismissableAlertMessage
kind="info"
identifier="lighting-layer-usage"
>
<Trans>
The lighting layer renders an ambient light on the scene. All
lights should be placed on this layer so that shadows are
properly rendered. By default, the layer follows the base layer
camera. Uncheck this if you want to manually move the camera
using events.
</Trans>
</DismissableAlertMessage>
) : null}
<Text size="block-title">
<Trans>Camera positioning</Trans>
</Text>
<SelectField
fullWidth
floatingLabelText={<Trans>Default camera behavior</Trans>}
value={layer.getDefaultCameraBehavior()}
onChange={(e, i, value: string) => {
layer.setDefaultCameraBehavior(value);
forceUpdate();
}}
>
<SelectOption
value={'do-nothing'}
label={t`Keep centered (best for game content)`}
/>
<SelectOption
value={'top-left-anchored-if-never-moved'}
label={t`Keep top-left corner fixed (best for content that can extend)`}
/>
</SelectField>
<Text size="block-title">
<Trans>Visibility and instances ordering</Trans>
</Text>
<Text>
<Trans>
There are {instancesCount} instances of objects on this layer.
</Trans>
</Text>
{!project.getUseDeprecatedZeroAsDefaultZOrder() && (
<Paper background="light" variant="outlined"> | No issues found. | ]}
/>
}
>
{currentTab === 'properties' && (
<ColumnStackLayout noMargin>
{layer.isLightingLayer() ? (
<DismissableAlertMessage
kind="info"
identifier="lighting-layer-usage"
>
<Trans>
The lighting layer renders an ambient light on the scene. All
lights should be placed on this layer so that shadows are
properly rendered. By default, the layer follows the base layer
camera. Uncheck this if you want to manually move the camera
using events.
</Trans>
</DismissableAlertMessage>
) : null}
<Text size="block-title">
<Trans>Camera positioning</Trans>
</Text>
<SelectField
fullWidth
floatingLabelText={<Trans>Default camera behavior</Trans>}
value={layer.getDefaultCameraBehavior()}
onChange={(e, i, value: string) => {
layer.setDefaultCameraBehavior(value);
forceUpdate();
}}
>
<SelectOption
value={'do-nothing'}
label={t`Keep centered (best for game content)`}
/>
<SelectOption
value={'top-left-anchored-if-never-moved'}
label={t`Keep top-left corner fixed (best for content that can extend)`}
/>
</SelectField>
<Text size="block-title">
<Trans>Visibility and instances ordering</Trans>
</Text>
<Text>
<Trans>
There are {instancesCount} instances of objects on this layer.
</Trans>
</Text>
{!project.getUseDeprecatedZeroAsDefaultZOrder() && (
<Paper background="light" variant="outlined"> | @@ -21,10 +21,11 @@ import HotReloadPreviewButton, {
import HelpButton from '../UI/HelpButton';
import { Tabs } from '../UI/Tabs';
import EffectsList from '../EffectsList';
-import { Spacer } from '../UI/Grid';
+import { Column, Line, Spacer } from '../UI/Grid';
import SemiControlledTextField from '../UI/SemiControlledTextField';
import SelectField from '../UI/SelectField';
import SelectOption from '../UI/SelectOption';
+import Paper from '../UI/Paper';
const gd: libGDevelop = global.gd;
@@ -237,20 +238,51 @@ const LayerEditorDialog = ({
</Trans>
</DismissableAlertMessage>
) : null}
+ <Text size="block-title">
+ <Trans>Camera positioning</Trans>
+ </Text>
+ <SelectField
+ fullWidth
+ floatingLabelText={<Trans>Default camera behavior</Trans>}
+ value={layer.getDefaultCameraBehavior()}
+ onChange={(e, i, value: string) => {
+ layer.setDefaultCameraBehavior(value);
+ forceUpdate();
+ }}
+ >
+ <SelectOption
+ value={'do-nothing'}
+ label={t`Keep centered (best for game content)`}
+ />
+ <SelectOption
+ value={'top-left-anchored-if-never-moved'}
+ label={t`Keep top-left corner fixed (best for content that can extend)`}
+ />
+ </SelectField>
+ <Text size="block-title">
+ <Trans>Visibility and instances ordering</Trans>
+ </Text>
<Text>
<Trans>
There are {instancesCount} instances of objects on this layer.
</Trans>
</Text>
{!project.getUseDeprecatedZeroAsDefaultZOrder() && (
- <Text>
- <Trans>
- Objects created using events on this layer will be given a "Z
- order" of {highestZOrder + 1}, so that they appear in front of
- all | newIDE/app/src/LayersList/LayerEditorDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix anchor behavior and add option to center layer or keep top-left fixed when resized | 7,188 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
beforeEach(() => {
runtimeGame = gdjs.getPixiRuntimeGame();
renderer = runtimeGame.getRenderer();
gameContainer = document.createElement('div');
});
it('should correctly create standard canvas and domElementsContainer', () => {
renderer.createStandardCanvas(gameContainer);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas.parentElement).to.be(gameContainer);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
});
it('should correctly initialize external canvas and create domElementsContainer', () => {
const gameCanvas = document.createElement('canvas');
gameContainer.appendChild(gameCanvas);
renderer.initializeForCanvas(gameCanvas);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas).to.be(gameCanvas);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
});
it('should remove canvas and domElementsContainer on dispose', () => {
renderer.createStandardCanvas(gameContainer);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas.parentElement).to.be(gameContainer);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
runtimeGame.dispose(true);
const actualGameCanvasAfterDispose = renderer.getCanvas();
const actualDomElementsContainerAfterDispose = renderer.getDomElementContainer();
expect(actualGameCanvasAfterDispose).to.be(null);
expect(actualDomElementsContainerAfterDispose).to.be(null); | No issues found. |
beforeEach(() => {
runtimeGame = gdjs.getPixiRuntimeGame();
renderer = runtimeGame.getRenderer();
gameContainer = document.createElement('div');
});
it('should correctly create standard canvas and domElementsContainer', () => {
renderer.createStandardCanvas(gameContainer);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas.parentElement).to.be(gameContainer);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
});
it('should correctly initialize external canvas and create domElementsContainer', () => {
const gameCanvas = document.createElement('canvas');
gameContainer.appendChild(gameCanvas);
renderer.initializeForCanvas(gameCanvas);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas).to.be(gameCanvas);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
});
it('should remove canvas and domElementsContainer on dispose', () => {
renderer.createStandardCanvas(gameContainer);
const actualGameCanvas = renderer.getCanvas();
const actualDomElementsContainer = renderer.getDomElementContainer();
expect(actualGameCanvas).to.not.be(null);
expect(actualDomElementsContainer).to.not.be(null);
expect(actualGameCanvas.parentElement).to.be(gameContainer);
expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
runtimeGame.dispose(true);
const actualGameCanvasAfterDispose = renderer.getCanvas();
const actualDomElementsContainerAfterDispose = renderer.getDomElementContainer();
expect(actualGameCanvasAfterDispose).to.be(null);
expect(actualDomElementsContainerAfterDispose).to.be(null); | @@ -0,0 +1,59 @@
+describe('gdjs.RuntimeGameRenderer canvas tests', () => {
+ let runtimeGame;
+ let renderer;
+ let gameContainer;
+
+ beforeEach(() => {
+ runtimeGame = gdjs.getPixiRuntimeGame();
+ renderer = runtimeGame.getRenderer();
+ gameContainer = document.createElement('div');
+ });
+
+ it('should correctly create standard canvas and domElementsContainer', () => {
+ renderer.createStandardCanvas(gameContainer);
+
+ const actualGameCanvas = renderer.getCanvas();
+ const actualDomElementsContainer = renderer.getDomElementContainer();
+
+ expect(actualGameCanvas).to.not.be(null);
+ expect(actualDomElementsContainer).to.not.be(null);
+ expect(actualGameCanvas.parentElement).to.be(gameContainer);
+ expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
+ });
+
+ it('should correctly initialize external canvas and create domElementsContainer', () => {
+ const gameCanvas = document.createElement('canvas');
+ gameContainer.appendChild(gameCanvas);
+ renderer.initializeForCanvas(gameCanvas);
+
+ const actualGameCanvas = renderer.getCanvas();
+ const actualDomElementsContainer = renderer.getDomElementContainer();
+
+ expect(actualGameCanvas).to.not.be(null);
+ expect(actualDomElementsContainer).to.not.be(null);
+ expect(actualGameCanvas).to.be(gameCanvas);
+ expect(actualDomElementsContainer.parentElement).to.be(gameContainer);
+ });
+
+ it('should remove canvas and domElementsContainer on dispose', () => {
+ renderer.createStandardCanvas(gameContainer);
+
+ const actualGameCanvas = renderer.getCanvas();
+ const actualDomElementsContainer = renderer.getDomElementContainer();
+
+ expect(actualGameCanvas).to.not.be(null);
+ expect(actualDomElementsContainer).to.not.be(null);
+ expect(actualGameCanvas.parentElement).to.be(gameContainer);
+ expect | GDJS/tests/tests/game-canvas.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add external canvas usage to RuntimeGamePixiRenderer | 7,199 | 4ian/GDevelop | 10,154 | JavaScript | danvervlad | |
* \brief Return a reference to the layout at position "index" in the layout
* list
*/
Layout& GetLayout(std::size_t index);
/**
* \brief Return a reference to the layout at position "index" in the layout
* list
*/
const Layout& GetLayout(std::size_t index) const;
/**
* \brief Return the position of the layout called "name" in the layout list
*/
std::size_t GetLayoutPosition(const gd::String& name) const;
/**
* Change the position of the specified layout.
*/
void MoveLayout(std::size_t oldIndex, std::size_t newIndex);
/**
* \brief Swap the specified layouts.
*
* Do nothing if indexes are not correct.
*/
void SwapLayouts(std::size_t first, std::size_t second);
/**
* \brief Return the number of layouts.
*/
std::size_t GetLayoutsCount() const;
/**
* \brief Add a new empty layout called "name" at the specified
* position in the layout list.
*/
gd::Layout& InsertNewLayout(const gd::String& name, std::size_t position);
/**
* \brief Add a new layout constructed from the layout passed as
* parameter.
* \param layout The layout that must be copied and inserted
* into the project
* \param position Insertion position. Even if the position
* is invalid, the layout must be inserted at the end of the layout list.
*
* \note No pointer or reference must be kept on the layout passed
* as parameter.
*
*/
| No issues found. | * \brief Return a reference to the layout at position "index" in the layout
* list
*/
Layout& GetLayout(std::size_t index);
/**
* \brief Return a reference to the layout at position "index" in the layout
* list
*/
const Layout& GetLayout(std::size_t index) const;
/**
* \brief Return the position of the layout called "name" in the layout list
*/
std::size_t GetLayoutPosition(const gd::String& name) const;
/**
* Change the position of the specified layout.
*/
void MoveLayout(std::size_t oldIndex, std::size_t newIndex);
/**
* \brief Swap the specified layouts.
*
* Do nothing if indexes are not correct.
*/
void SwapLayouts(std::size_t first, std::size_t second);
/**
* \brief Return the number of layouts.
*/
std::size_t GetLayoutsCount() const;
/**
* \brief Add a new empty layout called "name" at the specified
* position in the layout list.
*/
gd::Layout& InsertNewLayout(const gd::String& name, std::size_t position);
/**
* \brief Add a new layout constructed from the layout passed as
* parameter.
* \param layout The layout that must be copied and inserted
* into the project
* \param position Insertion position. Even if the position
* is invalid, the layout must be inserted at the end of the layout list.
*
* \note No pointer or reference must be kept on the layout passed
* as parameter.
*
*/
| @@ -523,13 +523,7 @@ class GD_CORE_API Project {
std::unique_ptr<gd::Object> CreateObject(const gd::String& type,
const gd::String& name) const;
- /**
- * Create an object configuration of the given type.
- *
- * \param type The type of the object
- */
- std::unique_ptr<gd::ObjectConfiguration> CreateObjectConfiguration(
- const gd::String& type) const;
+ void EnsureObjectDefaultBehaviors(gd::Object& object) const;
/**
* Create an event of the given type.
@@ -1078,12 +1072,20 @@ class GD_CORE_API Project {
/**
* @brief Get the project extensions names in the order they have to be unserialized.
- *
+ *
* Child-objects need the event-based objects they use to be loaded completely
* before they are unserialized.
*/
std::vector<gd::String> GetUnserializingOrderExtensionNames(const gd::SerializerElement &eventsFunctionsExtensionsElement);
+ /**
+ * Create an object configuration of the given type.
+ *
+ * \param type The type of the object
+ */
+ std::unique_ptr<gd::ObjectConfiguration> CreateObjectConfiguration(
+ const gd::String& type) const;
+
gd::String name; ///< Game name
gd::String description; ///< Game description
gd::String version; ///< Game version number (used for some exports)
| Core/GDCore/Project/Project.h | 0 | C/C++ | 1 | none | 16 | 51 | 51 | true | Fix default behaviors not added properly to objects in functions | 7,206 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
});
const projectFilesWithoutGame = allRecentProjectFiles
.filter(
file => !games.find(game => game.id === file.fileMetadata.gameId)
)
.map(file => ({ projectFiles: [file] }));
return [...projectFilesWithGame, ...projectFilesWithoutGame];
},
[games, allRecentProjectFiles]
);
const totalNumberOfPages = allDashboardItems
? Math.ceil(allDashboardItems.length / pageSize)
: 1;
const onCurrentPageChange = React.useCallback(
newPage => {
const minPage = 1;
const maxPage = totalNumberOfPages;
if (newPage < minPage) {
setCurrentPage(minPage);
} else if (newPage > maxPage) {
setCurrentPage(maxPage);
} else {
setCurrentPage(newPage);
}
},
[setCurrentPage, totalNumberOfPages]
);
const searchClient = React.useMemo(
() =>
new Fuse(allDashboardItems || [], {
...sharedFuseConfiguration,
keys: [
{ name: 'game.gameName', weight: 1 },
{ name: 'projectFiles.fileMetadata.name', weight: 1 },
],
}),
[allDashboardItems]
);
const [
displayedDashboardItems,
setDisplayedDashboardItems,
] = React.useState<?Array<DashboardItem>>(
getDashboardItemsToDisplay({
project,
currentFileMetadata,
allDashboardItems,
searchText,
searchClient, | No issues found. | });
const projectFilesWithoutGame = allRecentProjectFiles
.filter(
file => !games.find(game => game.id === file.fileMetadata.gameId)
)
.map(file => ({ projectFiles: [file] }));
return [...projectFilesWithGame, ...projectFilesWithoutGame];
},
[games, allRecentProjectFiles]
);
const totalNumberOfPages = allDashboardItems
? Math.ceil(allDashboardItems.length / pageSize)
: 1;
const onCurrentPageChange = React.useCallback(
newPage => {
const minPage = 1;
const maxPage = totalNumberOfPages;
if (newPage < minPage) {
setCurrentPage(minPage);
} else if (newPage > maxPage) {
setCurrentPage(maxPage);
} else {
setCurrentPage(newPage);
}
},
[setCurrentPage, totalNumberOfPages]
);
const searchClient = React.useMemo(
() =>
new Fuse(allDashboardItems || [], {
...sharedFuseConfiguration,
keys: [
{ name: 'game.gameName', weight: 1 },
{ name: 'projectFiles.fileMetadata.name', weight: 1 },
],
}),
[allDashboardItems]
);
const [
displayedDashboardItems,
setDisplayedDashboardItems,
] = React.useState<?Array<DashboardItem>>(
getDashboardItemsToDisplay({
project,
currentFileMetadata,
allDashboardItems,
searchText,
searchClient, | @@ -395,17 +395,20 @@ const GamesList = ({
searchText ? 250 : 150
);
- // Refresh games to display, depending on a few parameters.
- React.useEffect(getDashboardItemsToDisplayDebounced, [
+ React.useEffect(
getDashboardItemsToDisplayDebounced,
- searchText, // search text changes (user input)
- games, // games change (when updating a game for instance)
- currentPage, // user changes page
- orderBy, // user changes order
- currentFileMetadata, // opened project changes (when opening or closing a project from here)
- allRecentProjectFiles.length, // list of recent projects changes (when a project is removed from list)
- project, // opened project changes (when closing a project from here)
- ]);
+ // Refresh games to display, depending on a few parameters.
+ [
+ getDashboardItemsToDisplayDebounced,
+ searchText, // search text changes (user input)
+ games, // games change (when updating a game for instance)
+ currentPage, // user changes page
+ orderBy, // user changes order
+ currentFileMetadata, // opened project changes (when opening or closing a project from here)
+ allRecentProjectFiles.length, // list of recent projects changes (when a project is removed from list)
+ project, // opened project changes (when closing a project from here)
+ ]
+ );
const projectUuid = project ? project.getProjectUuid() : null;
@@ -428,10 +431,11 @@ const GamesList = ({
lastModifiedInfoByProjectId,
setLastModifiedInfoByProjectId,
] = React.useState({});
- // Look at projects where lastCommittedBy is not the current user (cloud projects only), and fetch
- // public profiles of the users that have modified them.
+
React.useEffect(
() => {
+ // Look at projects where lastCommittedBy is not the current user (cloud projects only), and fetch
+ // public profiles of the users that have modified them.
const updateModificationInfoByProjectId = async () => {
| newIDE/app/src/GameDashboard/GamesList.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Polishing the new Create tab | 7,236 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
] = React.useState<boolean>(
props.displayOptionToGenerateNewProjectUuid ? false : true
);
const [error, setError] = React.useState<?string>(null);
const onSave = (i18n: I18nType) => {
setError(null);
if (!name) {
setError(i18n._(t`Project name cannot be empty.`));
return;
}
props.onSave({ name, generateNewProjectUuid });
};
return (
<I18n>
{({ i18n }) => (
<Dialog
title={<Trans>Save project as</Trans>}
onApply={() => onSave(i18n)}
actions={[
<FlatButton
key="cancel"
label={<Trans>Cancel</Trans>}
primary={false}
onClick={props.onCancel}
/>,
<DialogPrimaryButton
key="save"
label={props.mainActionLabel || <Trans>Save</Trans>}
primary
onClick={() => onSave(i18n)}
/>,
]}
open
onRequestClose={props.onCancel}
maxWidth="sm"
flexBody
>
<ColumnStackLayout noMargin expand>
<TextField
autoFocus="desktop"
fullWidth
maxLength={props.nameMaxLength}
errorText={error}
type="text"
value={name}
floatingLabelText={<Trans>Project name</Trans>}
onChange={(e, newName) => {
setName(newName);
}} | No issues found. | ] = React.useState<boolean>(
props.displayOptionToGenerateNewProjectUuid ? false : true
);
const [error, setError] = React.useState<?string>(null);
const onSave = (i18n: I18nType) => {
setError(null);
if (!name) {
setError(i18n._(t`Project name cannot be empty.`));
return;
}
props.onSave({ name, generateNewProjectUuid });
};
return (
<I18n>
{({ i18n }) => (
<Dialog
title={<Trans>Save project as</Trans>}
onApply={() => onSave(i18n)}
actions={[
<FlatButton
key="cancel"
label={<Trans>Cancel</Trans>}
primary={false}
onClick={props.onCancel}
/>,
<DialogPrimaryButton
key="save"
label={props.mainActionLabel || <Trans>Save</Trans>}
primary
onClick={() => onSave(i18n)}
/>,
]}
open
onRequestClose={props.onCancel}
maxWidth="sm"
flexBody
>
<ColumnStackLayout noMargin expand>
<TextField
autoFocus="desktop"
fullWidth
maxLength={props.nameMaxLength}
errorText={error}
type="text"
value={name}
floatingLabelText={<Trans>Project name</Trans>}
onChange={(e, newName) => {
setName(newName);
}} | @@ -0,0 +1,105 @@
+// @flow
+
+import * as React from 'react';
+import { I18n } from '@lingui/react';
+import { type I18n as I18nType } from '@lingui/core';
+import { Trans, t } from '@lingui/macro';
+
+import Dialog, { DialogPrimaryButton } from '../UI/Dialog';
+import FlatButton from '../UI/FlatButton';
+import TextField from '../UI/TextField';
+import SelectField from '../UI/SelectField';
+import SelectOption from '../UI/SelectOption';
+import { ColumnStackLayout } from '../UI/Layout';
+
+type Props = {|
+ onCancel: () => void,
+ nameSuggestion: string,
+ onSave: ({ name: string, generateNewProjectUuid: boolean }) => void,
+ nameMaxLength?: number,
+ mainActionLabel?: React.Node,
+ displayOptionToGenerateNewProjectUuid: boolean,
+|};
+
+const SaveAsOptionsDialog = (props: Props) => {
+ const [name, setName] = React.useState<string>(props.nameSuggestion);
+ const [
+ generateNewProjectUuid,
+ setGenerateNewProjectUuid,
+ ] = React.useState<boolean>(
+ props.displayOptionToGenerateNewProjectUuid ? false : true
+ );
+ const [error, setError] = React.useState<?string>(null);
+
+ const onSave = (i18n: I18nType) => {
+ setError(null);
+ if (!name) {
+ setError(i18n._(t`Project name cannot be empty.`));
+ return;
+ }
+ props.onSave({ name, generateNewProjectUuid });
+ };
+
+ return (
+ <I18n>
+ {({ i18n }) => (
+ <Dialog
+ title={<Trans>Save project as</Trans>}
+ onApply={() => onSave(i18n)}
+ actions={[
+ <FlatButton
+ key="cancel"
+ label={<Trans>Cancel</Trans>}
+ primary={false}
+ onClick={props.onCancel}
+ />,
+ <DialogPrimaryButton
+ key="save"
+ label={props.mainActionLabel || <Trans>Save</Trans>}
+ primary
+ onClick={() => onSave(i18n)}
+ />,
+ ]}
+ open
+ onRequestClose={props.onCancel}
+ maxWidt | newIDE/app/src/ProjectsStorage/SaveAsOptionsDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | When duplicating a project, ask for the new name and if link with game should be kept | 7,253 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
);
const renderLastModification = (i18n: I18nType) =>
projectFileMetadataAndStorageProviderName ? (
<LastModificationInfo
file={projectFileMetadataAndStorageProviderName}
lastModifiedInfo={lastModifiedInfo}
storageProvider={itemStorageProvider}
authenticatedUser={authenticatedUser}
currentFileMetadata={currentFileMetadata}
textColor="secondary"
textSize="body-small"
textPrefix={isCurrentProjectOpened ? null : <Trans>Last edited:</Trans>}
/>
) : game ? (
<LineStackLayout noMargin expand>
<Text color="secondary" noMargin size="body-small">
{!itemStorageProvider && isCurrentProjectOpened ? (
<Trans>Draft created:</Trans>
) : (
<Trans>Last edited:</Trans>
)}
</Text>
<Tooltip
placement="right"
title={getDetailedProjectDisplayDate(
i18n,
(game.updatedAt || 0) * 1000
)}
>
<Text color="secondary" noMargin size="body-small">
{getProjectDisplayDate(i18n, (game.updatedAt || 0) * 1000)}
</Text>
</Tooltip>
</LineStackLayout>
) : null;
const renderStorageProvider = (i18n: I18nType) => {
const icon = itemStorageProvider ? (
itemStorageProvider.renderIcon ? (
itemStorageProvider.renderIcon({
size: 'small',
})
) : null
) : (
<WarningRound />
);
const name = itemStorageProvider ? (
i18n._(itemStorageProvider.name)
) : isCurrentProjectOpened ? (
<Trans>Project not saved</Trans> | No issues found. | );
const renderLastModification = (i18n: I18nType) =>
projectFileMetadataAndStorageProviderName ? (
<LastModificationInfo
file={projectFileMetadataAndStorageProviderName}
lastModifiedInfo={lastModifiedInfo}
storageProvider={itemStorageProvider}
authenticatedUser={authenticatedUser}
currentFileMetadata={currentFileMetadata}
textColor="secondary"
textSize="body-small"
textPrefix={isCurrentProjectOpened ? null : <Trans>Last edited:</Trans>}
/>
) : game ? (
<LineStackLayout noMargin expand>
<Text color="secondary" noMargin size="body-small">
{!itemStorageProvider && isCurrentProjectOpened ? (
<Trans>Draft created:</Trans>
) : (
<Trans>Last edited:</Trans>
)}
</Text>
<Tooltip
placement="right"
title={getDetailedProjectDisplayDate(
i18n,
(game.updatedAt || 0) * 1000
)}
>
<Text color="secondary" noMargin size="body-small">
{getProjectDisplayDate(i18n, (game.updatedAt || 0) * 1000)}
</Text>
</Tooltip>
</LineStackLayout>
) : null;
const renderStorageProvider = (i18n: I18nType) => {
const icon = itemStorageProvider ? (
itemStorageProvider.renderIcon ? (
itemStorageProvider.renderIcon({
size: 'small',
})
) : null
) : (
<WarningRound />
);
const name = itemStorageProvider ? (
i18n._(itemStorageProvider.name)
) : isCurrentProjectOpened ? (
<Trans>Project not saved</Trans> | @@ -417,18 +417,16 @@ const GameDashboardCard = ({
const actions = [];
if (projectsList.length > 1) {
actions.push(
- ...[
- ...projectsList.map(fileMetadataAndStorageProviderName => {
- return {
- label: getProjectItemLabel(
- fileMetadataAndStorageProviderName,
- storageProviders,
- i18n
- ),
- click: () => onOpenProject(fileMetadataAndStorageProviderName),
- };
- }),
- ]
+ ...projectsList.slice(0, 3).map(fileMetadataAndStorageProviderName => {
+ return {
+ label: getProjectItemLabel(
+ fileMetadataAndStorageProviderName,
+ storageProviders,
+ i18n
+ ),
+ click: () => onOpenProject(fileMetadataAndStorageProviderName),
+ };
+ })
);
if (game) { | newIDE/app/src/GameDashboard/GameDashboardCard.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Paginate feedbacks | 7,259 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
_('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg',
'JsPlatform/Extensions/physics3d.svg'
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Length (N·s or kg·m·s⁻¹)'))
.setParameterLongDescription(
_('An impulse is like a speed addition but depends on the mass.')
)
.addParameter('expression', _('X position'))
.addParameter('expression', _('Y position'))
.addParameter('expression', _('Z position'))
.getCodeExtraInformation()
.setFunctionName('applyImpulseTowardPosition');
aut
.addScopedAction(
'ApplyTorque',
_('Apply torque (rotational force)'),
_(
'Apply a torque (also called "rotational force") to the object. It "accelerates" an object rotation and must be used every frame during a time period.'
),
_('Apply a torque of _PARAM2_ ; _PARAM3_ ; _PARAM4_ to _PARAM0_ an'),
_('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg',
'JsPlatform/Extensions/physics3d.svg'
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Torque around X (N·m)'))
.addParameter('expression', _('Torque around Y (N·m)'))
.addParameter('expression', _('Torque around Z (N·m)'))
.setParameterLongDescription(
_('A torque is like a rotation acceleration but depends on the mass.')
)
.getCodeExtraInformation()
.setFunctionName('applyTorque');
aut
.addScopedAction(
'ApplyAngularImpulse',
_('Apply angular impulse (rotational impulse)'),
_(
'Apply an angular impulse (also called a "rotational impulse") to the object. It instantly changes the rotation speed, to give an initial speed for instance.'
),
_(
'Apply angular impulse of _PARAM2_ ; _PARAM3_ ; _PARAM4_ to _PARAM0_ an'
),
_('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg', | No issues found. | _('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg',
'JsPlatform/Extensions/physics3d.svg'
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Length (N·s or kg·m·s⁻¹)'))
.setParameterLongDescription(
_('An impulse is like a speed addition but depends on the mass.')
)
.addParameter('expression', _('X position'))
.addParameter('expression', _('Y position'))
.addParameter('expression', _('Z position'))
.getCodeExtraInformation()
.setFunctionName('applyImpulseTowardPosition');
aut
.addScopedAction(
'ApplyTorque',
_('Apply torque (rotational force)'),
_(
'Apply a torque (also called "rotational force") to the object. It "accelerates" an object rotation and must be used every frame during a time period.'
),
_('Apply a torque of _PARAM2_ ; _PARAM3_ ; _PARAM4_ to _PARAM0_ an'),
_('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg',
'JsPlatform/Extensions/physics3d.svg'
)
.addParameter('object', _('Object'), '', false)
.addParameter('behavior', _('Behavior'), 'Physics3DBehavior')
.addParameter('expression', _('Torque around X (N·m)'))
.addParameter('expression', _('Torque around Y (N·m)'))
.addParameter('expression', _('Torque around Z (N·m)'))
.setParameterLongDescription(
_('A torque is like a rotation acceleration but depends on the mass.')
)
.getCodeExtraInformation()
.setFunctionName('applyTorque');
aut
.addScopedAction(
'ApplyAngularImpulse',
_('Apply angular impulse (rotational impulse)'),
_(
'Apply an angular impulse (also called a "rotational impulse") to the object. It instantly changes the rotation speed, to give an initial speed for instance.'
),
_(
'Apply angular impulse of _PARAM2_ ; _PARAM3_ ; _PARAM4_ to _PARAM0_ an'
),
_('Forces & impulses'),
'JsPlatform/Extensions/physics3d.svg', | @@ -1535,6 +1535,15 @@ module.exports = {
return true;
}
+ if (propertyName === 'stairHeightMax') {
+ const newValueAsNumber = parseFloat(newValue);
+ if (newValueAsNumber !== newValueAsNumber) return false;
+ behaviorContent
+ .getChild('stairHeightMax')
+ .setDoubleValue(newValueAsNumber);
+ return true;
+ }
+
if (propertyName === 'shouldBindObjectAndForwardAngle') {
behaviorContent
.getChild('shouldBindObjectAndForwardAngle')
@@ -1703,6 +1712,24 @@ module.exports = {
.setAdvanced(true)
.setQuickCustomizationVisibility(gd.QuickCustomization.Hidden);
+ if (!behaviorContent.hasChild('stairHeightMax')) {
+ behaviorContent.addChild('stairHeightMax').setDoubleValue(20);
+ }
+ behaviorProperties
+ .getOrCreate('stairHeightMax')
+ .setLabel('Max. stair height')
+ .setGroup(_('Walk'))
+ .setType('Number')
+ .setMeasurementUnit(gd.MeasurementUnit.getPixel())
+ .setValue(
+ behaviorContent
+ .getChild('stairHeightMax')
+ .getDoubleValue()
+ .toString(10)
+ )
+ .setAdvanced(true)
+ .setQuickCustomizationVisibility(gd.QuickCustomization.Hidden);
+
behaviorProperties
.getOrCreate('shouldBindObjectAndForwardAngle')
.setLabel('Keep object angle and forward direction the same')
@@ -1734,6 +1761,7 @@ module.exports = {
behaviorContent.addChild('sidewaysDeceleration').setDoubleValue(800);
behaviorContent.addChild('sidewaysSpeedMax').setDoubleValue(400);
behaviorContent.addChild('slopeMaxAngle').setDoubleValue(50);
+ behaviorContent.addChild('stairHeightMax').setDoubleValue(20);
behaviorContent
.addChild('shouldBindObjectAndForwardAngle')
.setBoolValue(true); | Extensions/Physics3DBehavior/JsExtension.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add a property to choose the maximum stair height a 3D character can walk | 7,265 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
'Unable to read GDJS files for setting up autocompletions:',
error
);
return;
}
filenames.forEach(filename => {
const fullPath = path.join(folderPath, filename);
const isDirectory = fs.lstatSync(fullPath).isDirectory();
if (isDirectory) {
importAllJsFilesFromFolderRecursively(fullPath);
} else if (filename.endsWith('.ts') || filename.endsWith('.js')) {
fs.readFile(fullPath, 'utf8', (fileError, content) => {
if (fileError) {
console.error(
`Unable to read ${fullPath} for setting up autocompletions:`,
fileError
);
return;
}
monaco.languages.typescript.javascriptDefaults.addExtraLib(
content,
fullPath
);
});
}
});
});
findGDJS().then(({ gdjsRoot }) => {
// Autocompletions are generated by reading the sources of the game engine
// (much like how autocompletions work in Visual Studio Code) - *not* the built files.
// The built files are stripped of their types and documentation, so it would
// not work.
//
// We could also use the TypeScript compiler to emit .d.ts files when building GDJS,
// but this would make TypeScript slower (at least 2x slower) and we would still need
// to copy and read an equivalent number of files.
const runtimePath = path.join(gdjsRoot, 'Runtime-sources');
const runtimeTypesPath = path.join(runtimePath, 'types');
const runtimeLibsPath = path.join(runtimePath, 'libs');
const runtimePixiRenderersPath = path.join(runtimePath, 'pixi-renderers');
const runtimeHowlerSoundManagerPath = path.join(
runtimePath,
'howler-sound-manager'
);
const runtimeFontfaceobserverFontManagerPath = path.join(
runtimePath,
'fontfaceobserver-font-manager'
); | No issues found. | 'Unable to read GDJS files for setting up autocompletions:',
error
);
return;
}
filenames.forEach(filename => {
const fullPath = path.join(folderPath, filename);
const isDirectory = fs.lstatSync(fullPath).isDirectory();
if (isDirectory) {
importAllJsFilesFromFolderRecursively(fullPath);
} else if (filename.endsWith('.ts') || filename.endsWith('.js')) {
fs.readFile(fullPath, 'utf8', (fileError, content) => {
if (fileError) {
console.error(
`Unable to read ${fullPath} for setting up autocompletions:`,
fileError
);
return;
}
monaco.languages.typescript.javascriptDefaults.addExtraLib(
content,
fullPath
);
});
}
});
});
findGDJS().then(({ gdjsRoot }) => {
// Autocompletions are generated by reading the sources of the game engine
// (much like how autocompletions work in Visual Studio Code) - *not* the built files.
// The built files are stripped of their types and documentation, so it would
// not work.
//
// We could also use the TypeScript compiler to emit .d.ts files when building GDJS,
// but this would make TypeScript slower (at least 2x slower) and we would still need
// to copy and read an equivalent number of files.
const runtimePath = path.join(gdjsRoot, 'Runtime-sources');
const runtimeTypesPath = path.join(runtimePath, 'types');
const runtimeLibsPath = path.join(runtimePath, 'libs');
const runtimePixiRenderersPath = path.join(runtimePath, 'pixi-renderers');
const runtimeHowlerSoundManagerPath = path.join(
runtimePath,
'howler-sound-manager'
);
const runtimeFontfaceobserverFontManagerPath = path.join(
runtimePath,
'fontfaceobserver-font-manager'
); | @@ -4,6 +4,16 @@ import optionalRequire from '../Utils/OptionalRequire';
const fs = optionalRequire('fs');
const path = optionalRequire('path');
+// Avoid conflicts in declaration of PIXI and THREE namespaces.
+const excludedFiles = [
+ 'global-three.d.ts',
+ 'global-pixi.d.ts',
+ 'pixi-particles-pixi-renderer.d.ts',
+ 'pixi-tilemap.d.ts',
+ 'pixi.js',
+ 'three.js',
+];
+
export const setupAutocompletions = (monaco: any) => {
const importAllJsFilesFromFolder = (folderPath: string) =>
fs.readdir(folderPath, (error: ?Error, filenames: Array<string>) => {
@@ -21,6 +31,7 @@ export const setupAutocompletions = (monaco: any) => {
.isDirectory();
if (
(filename.endsWith('.ts') || filename.endsWith('.js')) &&
+ !excludedFiles.includes(filename) &&
// Dialogue tree uses a folder called `bondage.js` that should not be read as a file.
!isDirectory
) {
@@ -43,6 +54,40 @@ export const setupAutocompletions = (monaco: any) => {
});
});
+ const importAllJsFilesFromFolderRecursively = (folderPath: string) =>
+ fs.readdir(folderPath, (error: ?Error, filenames: Array<string>) => {
+ if (error) {
+ console.error(
+ 'Unable to read GDJS files for setting up autocompletions:',
+ error
+ );
+ return;
+ }
+
+ filenames.forEach(filename => {
+ const fullPath = path.join(folderPath, filename);
+ const isDirectory = fs.lstatSync(fullPath).isDirectory();
+ if (isDirectory) {
+ importAllJsFilesFromFolderRecursively(fullPath);
+ } else if (filename.endsWith('.ts') || filename.endsWith('.js')) {
+ fs.readFile(fullPath, 'utf8', (fileError, content) => {
+ if (fileError) {
+ console.error(
+ `Unable to read ${fullPath} for setting up autocompletions:`,
+ fileError
+ );
+ return;
+ }
+
+ monaco. | newIDE/app/src/CodeEditor/LocalCodeEditorAutocompletions.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add Pixi and Three type definitions for JS events | 7,266 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
/**
* \brief Set the description of the behavior or object, to be displayed in the editor.
*/
virtual AbstractEventsBasedEntity& SetDescription(const gd::String& description_) {
description = description_;
return *this;
}
/**
* \brief Get the internal name of the behavior or object.
*/
const gd::String& GetName() const { return name; };
/**
* \brief Set the internal name of the behavior or object.
*/
AbstractEventsBasedEntity& SetName(const gd::String& name_) {
name = name_;
return *this;
}
/**
* \brief Get the name of the behavior or object, that is displayed in the editor.
*/
const gd::String& GetFullName() const { return fullName; };
/**
* \brief Set the name of the behavior or object, to be displayed in the editor.
*/
AbstractEventsBasedEntity& SetFullName(const gd::String& fullName_) {
fullName = fullName_;
return *this;
}
/**
* \brief Return a reference to the functions of the events based behavior or object.
*/
EventsFunctionsContainer& GetEventsFunctions() {
return eventsFunctionsContainer;
}
/**
* \brief Return a const reference to the functions of the events based
* behavior or object.
*/
const EventsFunctionsContainer& GetEventsFunctions() const {
return eventsFunctionsContainer;
}
/** | No issues found. |
/**
* \brief Set the description of the behavior or object, to be displayed in the editor.
*/
virtual AbstractEventsBasedEntity& SetDescription(const gd::String& description_) {
description = description_;
return *this;
}
/**
* \brief Get the internal name of the behavior or object.
*/
const gd::String& GetName() const { return name; };
/**
* \brief Set the internal name of the behavior or object.
*/
AbstractEventsBasedEntity& SetName(const gd::String& name_) {
name = name_;
return *this;
}
/**
* \brief Get the name of the behavior or object, that is displayed in the editor.
*/
const gd::String& GetFullName() const { return fullName; };
/**
* \brief Set the name of the behavior or object, to be displayed in the editor.
*/
AbstractEventsBasedEntity& SetFullName(const gd::String& fullName_) {
fullName = fullName_;
return *this;
}
/**
* \brief Return a reference to the functions of the events based behavior or object.
*/
EventsFunctionsContainer& GetEventsFunctions() {
return eventsFunctionsContainer;
}
/**
* \brief Return a const reference to the functions of the events based
* behavior or object.
*/
const EventsFunctionsContainer& GetEventsFunctions() const {
return eventsFunctionsContainer;
}
/** | @@ -3,8 +3,7 @@
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
-#ifndef GDCORE_ABSTRACTEVENTSBASEDENTITY_H
-#define GDCORE_ABSTRACTEVENTSBASEDENTITY_H
+#pragma once
#include <vector>
#include "GDCore/Project/NamedPropertyDescriptor.h"
@@ -40,6 +39,21 @@ class GD_CORE_API AbstractEventsBasedEntity {
*/
AbstractEventsBasedEntity* Clone() const { return new AbstractEventsBasedEntity(*this); };
+ /**
+ * \brief Check if the behavior or object is private - it can't be used outside of its
+ * extension.
+ */
+ bool IsPrivate() const { return isPrivate; }
+
+ /**
+ * \brief Set that the behavior or object is private - it can't be used outside of its
+ * extension.
+ */
+ AbstractEventsBasedEntity& SetPrivate(bool isPrivate_) {
+ isPrivate = isPrivate_;
+ return *this;
+ }
+
/**
* \brief Get the description of the behavior or object, that is displayed in the
* editor.
@@ -151,8 +165,7 @@ class GD_CORE_API AbstractEventsBasedEntity {
gd::EventsFunctionsContainer eventsFunctionsContainer;
gd::PropertiesContainer propertyDescriptors;
gd::String extensionName;
+ bool isPrivate = false;
};
} // namespace gd
-
-#endif // GDCORE_ABSTRACTEVENTSBASEDENTITY_H | Core/GDCore/Project/AbstractEventsBasedEntity.h | 0 | C/C++ | 1 | none | 16 | 51 | 51 | true | Allow to make custom objects private to an extension | 7,275 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
project,
objectsContainer: targetObjectsContainer,
targetObjectFolderOrObject:
targetObjectFolderOrObjectWithContext &&
!targetObjectFolderOrObjectWithContext.global
? targetObjectFolderOrObjectWithContext.objectFolderOrObject
: null,
});
if (!installOutput) {
throw new Error('Unable to install the asset.');
}
return installOutput;
});
if (errors.length) {
throw new Error(
'Error(s) while installing assets. The first error is: ' +
errors[0].message
);
}
await resourceManagementProps.onFetchNewlyAddedResources();
setAreAssetsBeingInstalled(false);
const createdObjects = results
.map(result => result.createdObjects)
.flat();
onAssetsAdded(createdObjects);
} catch (error) {
setAreAssetsBeingInstalled(false);
console.error('Error while installing the assets', error);
showErrorBox({
message:
'There was an error while installing the assets. Verify your internet connection or try again later.',
rawError: error,
errorId: 'install-asset-pack-error',
});
}
},
[
fetchAssets,
project,
showExtensionUpdateConfirmation,
eventsFunctionsExtensionsState,
resourceManagementProps,
onAssetsAdded,
installPrivateAsset,
targetObjectsContainer,
targetObjectFolderOrObjectWithContext, | No issues found. | project,
objectsContainer: targetObjectsContainer,
targetObjectFolderOrObject:
targetObjectFolderOrObjectWithContext &&
!targetObjectFolderOrObjectWithContext.global
? targetObjectFolderOrObjectWithContext.objectFolderOrObject
: null,
});
if (!installOutput) {
throw new Error('Unable to install the asset.');
}
return installOutput;
});
if (errors.length) {
throw new Error(
'Error(s) while installing assets. The first error is: ' +
errors[0].message
);
}
await resourceManagementProps.onFetchNewlyAddedResources();
setAreAssetsBeingInstalled(false);
const createdObjects = results
.map(result => result.createdObjects)
.flat();
onAssetsAdded(createdObjects);
} catch (error) {
setAreAssetsBeingInstalled(false);
console.error('Error while installing the assets', error);
showErrorBox({
message:
'There was an error while installing the assets. Verify your internet connection or try again later.',
rawError: error,
errorId: 'install-asset-pack-error',
});
}
},
[
fetchAssets,
project,
showExtensionUpdateConfirmation,
eventsFunctionsExtensionsState,
resourceManagementProps,
onAssetsAdded,
installPrivateAsset,
targetObjectsContainer,
targetObjectFolderOrObjectWithContext, | @@ -35,6 +35,7 @@ import {
useFetchAssets,
} from './NewObjectDialog';
import { type InstallAssetOutput } from './InstallAsset';
+import { type ObjectFolderOrObjectWithContext } from '../ObjectsList/EnumerateObjectFolderOrObject';
// We limit the number of assets that can be installed at once to avoid
// timeouts especially with premium packs.
@@ -45,10 +46,11 @@ type Props = {|
assetShortHeaders: Array<AssetShortHeader>,
addedAssetIds: Set<string>,
onClose: () => void,
- onAssetsAdded: () => void,
+ onAssetsAdded: (createdObjects: gdObject[]) => void,
project: gdProject,
objectsContainer: ?gdObjectsContainer,
resourceManagementProps: ResourceManagementProps,
+ targetObjectFolderOrObjectWithContext?: ?ObjectFolderOrObjectWithContext,
|};
const AssetPackInstallDialog = ({
@@ -60,6 +62,7 @@ const AssetPackInstallDialog = ({
project,
objectsContainer,
resourceManagementProps,
+ targetObjectFolderOrObjectWithContext,
}: Props) => {
const missingAssetShortHeaders = assetShortHeaders.filter(
assetShortHeader => !addedAssetIds.has(assetShortHeader.id)
@@ -168,20 +171,22 @@ const AssetPackInstallDialog = ({
});
// Use a pool to avoid installing an unbounded amount of assets at the same time.
- const { errors } = await PromisePool.withConcurrency(6)
+ const { errors, results } = await PromisePool.withConcurrency(6)
.for(assets)
.process<InstallAssetOutput>(async asset => {
- const installOutput = isPrivateAsset(asset)
- ? await installPrivateAsset({
- asset,
- project,
- objectsContainer: targetObjectsContainer,
- })
- : await installPublicAsset({
- asset,
- project,
- objectsContainer: targetObjectsContainer,
- });
+ const doInstall = isPrivateAsset(asset)
+ ? installPrivateAss | newIDE/app/src/AssetStore/AssetPackInstallDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add objects installed from the asset store in selected folder | 7,287 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.