chore: initialize UE 5.8 + UnLua game framework project

This commit is contained in:
szy73711 committed 2026-11-28 01:45:03 +08:00
commit 943af16954
397 files changed
+95588

No files matched your search

@@ -0,0 +1,134 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "Commandlets/UnLuaIntelliSenseCommandlet.h"
#include "Binding.h"
#include "Misc/FileHelper.h"
#include "UnLuaIntelliSenseGenerator.h"
UUnLuaIntelliSenseCommandlet::UUnLuaIntelliSenseCommandlet(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
//IntermediateDir = FPaths::ProjectIntermediateDir();
IntermediateDir = FPaths::ProjectPluginsDir();
IntermediateDir += TEXT("UnLua/Intermediate/");
}
int32 UUnLuaIntelliSenseCommandlet::Main(const FString &Params)
{
// class black list
TArray<FString> ClassBlackList;
ClassBlackList.Add("int8");
ClassBlackList.Add("int16");
ClassBlackList.Add("int32");
ClassBlackList.Add("int64");
ClassBlackList.Add("uint8");
ClassBlackList.Add("uint16");
ClassBlackList.Add("uint32");
ClassBlackList.Add("uint64");
ClassBlackList.Add("float");
ClassBlackList.Add("double");
ClassBlackList.Add("bool");
ClassBlackList.Add("FName");
ClassBlackList.Add("FString");
ClassBlackList.Add("FText");
// enum black list
TArray<FString> EnumBlackList;
// function black list
TArray<FString> FuncBlackList;
FuncBlackList.Add("OnModuleHotfixed");
const auto ExportedReflectedClasses = UnLua::GetExportedReflectedClasses();
const auto ExportedNonReflectedClasses = UnLua::GetExportedNonReflectedClasses();
const auto ExportedEnums = UnLua::GetExportedEnums();
const auto ExportedFunctions = UnLua::GetExportedFunctions();
FString GeneratedFileContent;
FString ModuleName(TEXT("StaticallyExports"));
// reflected classes
for (auto Pair : ExportedReflectedClasses)
{
if (ClassBlackList.Contains(Pair.Key))
continue;
Pair.Value->GenerateIntelliSense(GeneratedFileContent);
SaveFile(ModuleName, Pair.Key, GeneratedFileContent);
}
for (auto Pair : ExportedNonReflectedClasses)
{
if (ClassBlackList.Contains(Pair.Key))
continue;
Pair.Value->GenerateIntelliSense(GeneratedFileContent);
SaveFile(ModuleName, Pair.Key, GeneratedFileContent);
}
for (auto Enum : ExportedEnums)
{
if (EnumBlackList.Contains(Enum->GetName()))
continue;
Enum->GenerateIntelliSense(GeneratedFileContent);
SaveFile(ModuleName, Enum->GetName(), GeneratedFileContent);
}
for (auto Function : ExportedFunctions)
{
if (FuncBlackList.Contains(Function->GetName()))
continue;
Function->GenerateIntelliSense(GeneratedFileContent);
}
SaveFile(ModuleName, TEXT("GlobalFunctions"), GeneratedFileContent);
// generate blueprint intellisense if needed
TArray<FString> Tokens;
TArray<FString> Switches;
TMap<FString, FString> ParamsMap;
ParseCommandLine(*Params, Tokens, Switches, ParamsMap);
FString BPKey = TEXT("BP");
if (ParamsMap.Contains(BPKey) && ParamsMap[BPKey] == TEXT("1"))
{
auto Generator = FUnLuaIntelliSenseGenerator::Get();
Generator->Initialize();
Generator->UpdateAll();
}
return 0;
}
void UUnLuaIntelliSenseCommandlet::SaveFile(const FString &ModuleName, const FString &FileName, const FString &GeneratedFileContent)
{
IFileManager &FileManager = IFileManager::Get();
FString Directory = FString::Printf(TEXT("%sIntelliSense/%s"), *IntermediateDir, *ModuleName);
if (!FileManager.DirectoryExists(*Directory))
{
FileManager.MakeDirectory(*Directory);
}
const FString FilePath = FString::Printf(TEXT("%s/%s.lua"), *Directory, *FileName);
FString FileContent;
FFileHelper::LoadFileToString(FileContent, *FilePath);
if (FileContent != GeneratedFileContent)
{
bool bResult = FFileHelper::SaveStringToFile(GeneratedFileContent, *FilePath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
check(bResult);
}
}
@@ -0,0 +1,24 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UObject/UObjectHash.h"
#if ENGINE_MAJOR_VERSION <= 4 && ENGINE_MINOR_VERSION < 26
void ForEachObjectWithPackage(const class UPackage* Package, TFunctionRef<bool(UObject*)> Operation, bool bIncludeNestedObjects, EObjectFlags ExclusionFlags, EInternalObjectFlags ExclusionInternalFlags)
{
check(Package != nullptr);
auto WrappedOperation = [Operation](UObject* Obj) { Operation(Obj); };
ForEachObjectWithOuter(Package, WrappedOperation, bIncludeNestedObjects, ExclusionFlags, ExclusionInternalFlags);
}
#endif
@@ -0,0 +1,21 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "UObject/UObjectHash.h"
#if ENGINE_MAJOR_VERSION <= 4 && ENGINE_MINOR_VERSION < 26
void ForEachObjectWithPackage(const class UPackage* Outer, TFunctionRef<bool(UObject*)> Operation, bool bIncludeNestedObjects = true, EObjectFlags ExclusionFlags = RF_NoFlags, EInternalObjectFlags ExclusionInternalFlags = EInternalObjectFlags::None);
#endif
@@ -0,0 +1,34 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaBase.h"
#include "AnimationBlueprintToolbar.h"
#include "IAnimationBlueprintEditorModule.h"
#include "AnimationBlueprintEditorModule.h"
#include "IPersonaToolkit.h"
#include "Animation/AnimBlueprint.h"
void FAnimationBlueprintToolbar::Initialize()
{
FUnLuaEditorToolbar::Initialize();
auto& AnimationBlueprintEditorModule = FModuleManager::LoadModuleChecked<FAnimationBlueprintEditorModule>("AnimationBlueprintEditor");
auto& ToolbarExtenders = AnimationBlueprintEditorModule.GetAllAnimationBlueprintEditorToolbarExtenders();
ToolbarExtenders.Add(IAnimationBlueprintEditorModule::FAnimationBlueprintEditorToolbarExtender::CreateLambda(
[&](const TSharedRef<FUICommandList>, const TSharedRef<IAnimationBlueprintEditor> Editor)
{
const auto TargetObject = Editor->GetPersonaToolkit()->GetAnimBlueprint();
return GetExtender(TargetObject);
}));
}
@@ -0,0 +1,23 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "UnLuaEditorToolbar.h"
class FAnimationBlueprintToolbar : FUnLuaEditorToolbar
{
public:
virtual void Initialize() override;
};
@@ -0,0 +1,31 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaBase.h"
#include "BlueprintToolbar.h"
#include "BlueprintEditorModule.h"
void FBlueprintToolbar::Initialize()
{
FUnLuaEditorToolbar::Initialize();
auto& BlueprintEditorModule = FModuleManager::LoadModuleChecked<FBlueprintEditorModule>("Kismet");
auto& ExtenderDelegates = BlueprintEditorModule.GetMenuExtensibilityManager()->GetExtenderDelegates();
ExtenderDelegates.Add(FAssetEditorExtender::CreateLambda(
[&](const TSharedRef<FUICommandList>, const TArray<UObject*> ContextSensitiveObjects)
{
const auto TargetObject = ContextSensitiveObjects.Num() < 1 ? nullptr : Cast<UBlueprint>(ContextSensitiveObjects[0]);
return GetExtender(TargetObject);
}));
}
@@ -0,0 +1,23 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "UnLuaEditorToolbar.h"
class FBlueprintToolbar : FUnLuaEditorToolbar
{
public:
virtual void Initialize() override;
};
@@ -0,0 +1,143 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "MainMenuToolbar.h"
#include "ISettingsModule.h"
#include "UnLuaAboutScreen.h"
#include "UnLuaIntelliSenseGenerator.h"
#include "LevelEditor.h"
#include "UnLuaEditorCommands.h"
#include "UnLuaEditorFunctionLibrary.h"
#include "UnLuaEditorSettings.h"
#include "UnLuaFunctionLibrary.h"
#include "Interfaces/IMainFrameModule.h"
#include "ToolMenus.h"
#define LOCTEXT_NAMESPACE "UnLuaMainMenuToolbar"
FMainMenuToolbar::FMainMenuToolbar()
: CommandList(new FUICommandList)
{
CommandList->MapAction(FUnLuaEditorCommands::Get().HotReload, FExecuteAction::CreateStatic(UUnLuaFunctionLibrary::HotReload), FCanExecuteAction());
CommandList->MapAction(FUnLuaEditorCommands::Get().GenerateIntelliSense, FExecuteAction::CreateLambda([]
{
FUnLuaIntelliSenseGenerator::Get()->UpdateAll();
}), FCanExecuteAction());
CommandList->MapAction(FUnLuaEditorCommands::Get().OpenRuntimeSettings, FExecuteAction::CreateLambda([]
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
SettingsModule->ShowViewer("Project", "Plugins", "UnLua");
}), FCanExecuteAction());
CommandList->MapAction(FUnLuaEditorCommands::Get().OpenEditorSettings, FExecuteAction::CreateLambda([]
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
SettingsModule->ShowViewer("Project", "Plugins", "UnLua Editor");
}), FCanExecuteAction());
CommandList->MapAction(FUnLuaEditorCommands::Get().ReportIssue, FExecuteAction::CreateLambda([]
{
const TCHAR* URL = TEXT("cmd");
const TCHAR* Params = TEXT("/k start https://github.com/Tencent/UnLua/issues/new/choose");
FPlatformProcess::ExecProcess(URL, Params, nullptr, nullptr, nullptr);
}), FCanExecuteAction());
CommandList->MapAction(FUnLuaEditorCommands::Get().About, FExecuteAction::CreateLambda([]
{
const FText AboutWindowTitle = LOCTEXT("AboutUnLua", "About UnLua");
TSharedPtr<SWindow> AboutWindow =
SNew(SWindow)
.Title(AboutWindowTitle)
.ClientSize(FVector2D(600.f, 200.f))
.SupportsMaximize(false).SupportsMinimize(false)
.SizingRule(ESizingRule::FixedSize)
[
SNew(SUnLuaAboutScreen)
];
IMainFrameModule& MainFrame = FModuleManager::LoadModuleChecked<IMainFrameModule>("MainFrame");
TSharedPtr<SWindow> ParentWindow = MainFrame.GetParentWindow();
if (ParentWindow.IsValid())
FSlateApplication::Get().AddModalWindow(AboutWindow.ToSharedRef(), ParentWindow.ToSharedRef());
else
FSlateApplication::Get().AddWindow(AboutWindow.ToSharedRef());
}), FCanExecuteAction());
}
void FMainMenuToolbar::Initialize()
{
#if ENGINE_MAJOR_VERSION >= 5
UToolMenu* ToolbarMenu = UToolMenus::Get()->ExtendMenu("LevelEditor.LevelEditorToolBar.User");
FToolMenuSection& Section = ToolbarMenu->AddSection("UnluaSettings");
Section.AddEntry(FToolMenuEntry::InitComboButton(
"UnluaSettings",
FUIAction(),
FOnGetContent::CreateRaw(this, &FMainMenuToolbar::GenerateUnLuaSettingsMenu),
LOCTEXT("UnLua_Label", "UnLua"),
LOCTEXT("UnLua_ToolTip", "UnLua"),
FSlateIcon("UnLuaEditorStyle", "UnLuaEditor.UnLuaLogo")
));
#else
TSharedPtr<FExtender> Extender = MakeShareable(new FExtender);
Extender->AddToolBarExtension("Settings", EExtensionHook::After, CommandList,
FToolBarExtensionDelegate::CreateLambda([this](FToolBarBuilder& Builder)
{
Builder.BeginSection(NAME_None);
Builder.AddComboButton(FUIAction(),
FOnGetContent::CreateRaw(this, &FMainMenuToolbar::GenerateUnLuaSettingsMenu),
LOCTEXT("UnLua_Label", "UnLua"),
LOCTEXT("UnLua_ToolTip", "UnLua"),
FSlateIcon("UnLuaEditorStyle", "UnLuaEditor.UnLuaLogo")
);
Builder.EndSection();
})
);
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditorModule.GetToolBarExtensibilityManager()->AddExtender(Extender);
#endif
const auto& Settings = *GetDefault<UUnLuaEditorSettings>();
if (Settings.UpdateMode == EUpdateMode::Start)
UUnLuaEditorFunctionLibrary::FetchNewVersion();
}
TSharedRef<SWidget> FMainMenuToolbar::GenerateUnLuaSettingsMenu()
{
const FUnLuaEditorCommands& Commands = FUnLuaEditorCommands::Get();
FMenuBuilder MenuBuilder(true, CommandList);
MenuBuilder.BeginSection(NAME_None, LOCTEXT("Section_Action", "Action"));
MenuBuilder.AddMenuEntry(Commands.HotReload, NAME_None, LOCTEXT("HotReload", "Hot Reload"));
MenuBuilder.AddMenuEntry(Commands.GenerateIntelliSense, NAME_None, LOCTEXT("GenerateIntelliSense", "Generate IntelliSense"));
MenuBuilder.EndSection();
MenuBuilder.BeginSection(NAME_None, LOCTEXT("Section_Help", "Help"));
MenuBuilder.AddSubMenu(LOCTEXT("Section_SettingsMenu", "Settings"),
LOCTEXT("Section_SettingsMenu_ToolTip", "UnLua Settings"),
FNewMenuDelegate::CreateLambda([Commands](FMenuBuilder& SubMenuBuilder)
{
SubMenuBuilder.AddMenuEntry(Commands.OpenRuntimeSettings, NAME_None, LOCTEXT("OpenRuntimeSettings", "Runtime"));
SubMenuBuilder.AddMenuEntry(Commands.OpenEditorSettings, NAME_None, LOCTEXT("OpenEditorSettings", "Editor"));
}));
MenuBuilder.AddMenuEntry(Commands.ReportIssue, NAME_None, LOCTEXT("ReportIssue", "Report Issue"));
MenuBuilder.AddMenuEntry(Commands.About, NAME_None, LOCTEXT("About", "About"));
MenuBuilder.EndSection();
return MenuBuilder.MakeWidget();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,31 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreMinimal.h"
class FMainMenuToolbar
{
public:
FMainMenuToolbar();
virtual ~FMainMenuToolbar() = default;
void Initialize();
TSharedRef<SWidget> GenerateUnLuaSettingsMenu();
const TSharedRef<FUICommandList> CommandList;
};
@@ -0,0 +1,379 @@
#include "Misc/EngineVersionComparison.h"
#include "UnLuaPrivate.h"
#include "UnLuaEditorCore.h"
#include "UnLuaEditorToolbar.h"
#include "UnLuaEditorCommands.h"
#include "UnLuaInterface.h"
#include "Animation/AnimInstance.h"
#include "Blueprint/UserWidget.h"
#include "HAL/PlatformApplicationMisc.h"
#include "Interfaces/IPluginManager.h"
#include "BlueprintEditor.h"
#include "LuaModuleLocator.h"
#include "SBlueprintEditorToolbar.h"
#include "Framework/Docking/SDockingTabWell.h"
#include "Framework/Notifications/NotificationManager.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "Layout/Children.h"
#include "Widgets/Notifications/SNotificationList.h"
#include "ToolMenus.h"
#include "UnLuaSettings.h"
#include "UnLuaIntelliSense.h"
#include "Animation/AnimNotifies/AnimNotifyState.h"
#define LOCTEXT_NAMESPACE "FUnLuaEditorModule"
FUnLuaEditorToolbar::FUnLuaEditorToolbar()
: CommandList(new FUICommandList),
ContextObject(nullptr)
{
}
void FUnLuaEditorToolbar::Initialize()
{
BindCommands();
}
void FUnLuaEditorToolbar::BindCommands()
{
const auto& Commands = FUnLuaEditorCommands::Get();
CommandList->MapAction(Commands.CreateLuaTemplate, FExecuteAction::CreateRaw(this, &FUnLuaEditorToolbar::CreateLuaTemplate_Executed));
CommandList->MapAction(Commands.CopyAsRelativePath, FExecuteAction::CreateRaw(this, &FUnLuaEditorToolbar::CopyAsRelativePath_Executed));
CommandList->MapAction(Commands.BindToLua, FExecuteAction::CreateRaw(this, &FUnLuaEditorToolbar::BindToLua_Executed));
CommandList->MapAction(Commands.UnbindFromLua, FExecuteAction::CreateRaw(this, &FUnLuaEditorToolbar::UnbindFromLua_Executed));
CommandList->MapAction(Commands.RevealInExplorer, FExecuteAction::CreateRaw(this, &FUnLuaEditorToolbar::RevealInExplorer_Executed));
}
void FUnLuaEditorToolbar::BuildToolbar(FToolBarBuilder& ToolbarBuilder, UObject* InContextObject)
{
if (!InContextObject)
return;
ToolbarBuilder.BeginSection(NAME_None);
const auto Blueprint = Cast<UBlueprint>(InContextObject);
ToolbarBuilder.AddComboButton(
FUIAction(),
FOnGetContent::CreateLambda([&, Blueprint, InContextObject]()
{
ContextObject = InContextObject;
const auto BindingStatus = GetBindingStatus(Blueprint);
const FUnLuaEditorCommands& Commands = FUnLuaEditorCommands::Get();
FMenuBuilder MenuBuilder(true, CommandList);
if (BindingStatus == NotBound)
{
MenuBuilder.AddMenuEntry(Commands.BindToLua, NAME_None, LOCTEXT("Bind", "Bind"));
}
else
{
MenuBuilder.AddMenuEntry(Commands.CopyAsRelativePath, NAME_None, LOCTEXT("CopyAsRelativePath", "Copy as Relative Path"));
MenuBuilder.AddMenuEntry(Commands.RevealInExplorer, NAME_None, LOCTEXT("RevealInExplorer", "Reveal in Explorer"));
MenuBuilder.AddMenuEntry(Commands.CreateLuaTemplate, NAME_None, LOCTEXT("CreateLuaTemplate", "Create Lua Template"));
MenuBuilder.AddMenuEntry(Commands.UnbindFromLua, NAME_None, LOCTEXT("Unbind", "Unbind"));
}
return MenuBuilder.MakeWidget();
}),
LOCTEXT("UnLua_Label", "UnLua"),
LOCTEXT("UnLua_ToolTip", "UnLua"),
TAttribute<FSlateIcon>::Create([Blueprint]
{
const auto BindingStatus = GetBindingStatus(Blueprint);
FString InStyleName;
switch (BindingStatus)
{
case Unknown:
InStyleName = "UnLuaEditor.Status_Unknown";
break;
case NotBound:
InStyleName = "UnLuaEditor.Status_NotBound";
break;
case Bound:
InStyleName = "UnLuaEditor.Status_Bound";
break;
case BoundButInvalid:
InStyleName = "UnLuaEditor.Status_BoundButInvalid";
break;
default:
check(false);
}
return FSlateIcon("UnLuaEditorStyle", *InStyleName);
})
);
ToolbarBuilder.EndSection();
BuildNodeMenu();
}
void FUnLuaEditorToolbar::BuildNodeMenu()
{
FToolMenuOwnerScoped OwnerScoped(this);
UToolMenu* BPMenu = UToolMenus::Get()->ExtendMenu("GraphEditor.GraphNodeContextMenu.K2Node_FunctionResult");
BPMenu->AddDynamicSection("UnLua", FNewToolMenuDelegate::CreateLambda([this](UToolMenu* ToolMenu)
{
UGraphNodeContextMenuContext* GraphNodeCtx = ToolMenu->FindContext<UGraphNodeContextMenuContext>();
if (GraphNodeCtx && GraphNodeCtx->Graph)
{
if (GraphNodeCtx->Graph->GetName() == "GetModuleName")
{
FToolMenuSection& UnLuaSection = ToolMenu->AddSection("UnLua", FText::FromString("UnLua"));
UnLuaSection.AddEntry(FToolMenuEntry::InitMenuEntryWithCommandList(FUnLuaEditorCommands::Get().RevealInExplorer, CommandList, LOCTEXT("RevealInExplorer", "Reveal in Explorer")));
}
}
}), FToolMenuInsert(NAME_None, EToolMenuInsertType::First));
}
TSharedRef<FExtender> FUnLuaEditorToolbar::GetExtender(UObject* InContextObject)
{
TSharedRef<FExtender> ToolbarExtender(new FExtender());
const auto ExtensionDelegate = FToolBarExtensionDelegate::CreateLambda([this, InContextObject](FToolBarBuilder& ToolbarBuilder)
{
BuildToolbar(ToolbarBuilder, InContextObject);
});
ToolbarExtender->AddToolBarExtension("Debugging", EExtensionHook::After, CommandList, ExtensionDelegate);
return ToolbarExtender;
}
void FUnLuaEditorToolbar::BindToLua_Executed() const
{
const auto Blueprint = Cast<UBlueprint>(ContextObject);
if (!IsValid(Blueprint))
return;
const auto TargetClass = Blueprint->GeneratedClass;
if (!IsValid(TargetClass))
return;
if (TargetClass->ImplementsInterface(UUnLuaInterface::StaticClass()))
return;
#if UE_VERSION_OLDER_THAN(5, 1, 0)
const auto Ok = FBlueprintEditorUtils::ImplementNewInterface(Blueprint, FName("UnLuaInterface"));
#else
const auto Ok = FBlueprintEditorUtils::ImplementNewInterface(Blueprint, FTopLevelAssetPath(UUnLuaInterface::StaticClass()));
#endif
if (!Ok)
return;
FString LuaModuleName;
const auto ModifierKeys = FSlateApplication::Get().GetModifierKeys();
const auto bIsAltDown = ModifierKeys.IsLeftAltDown() || ModifierKeys.IsRightAltDown();
if (bIsAltDown)
{
const auto Package = Blueprint->GetTypedOuter(UPackage::StaticClass());
LuaModuleName = Package->GetName().RightChop(6).Replace(TEXT("/"), TEXT("."));
}
else
{
const auto Settings = GetDefault<UUnLuaSettings>();
if (Settings && Settings->ModuleLocatorClass)
{
const auto ModuleLocator = Cast<ULuaModuleLocator>(Settings->ModuleLocatorClass->GetDefaultObject());
LuaModuleName = ModuleLocator->Locate(TargetClass);
}
}
if (!LuaModuleName.IsEmpty())
{
const auto InterfaceDesc = *Blueprint->ImplementedInterfaces.FindByPredicate([](const FBPInterfaceDescription& Desc)
{
return Desc.Interface == UUnLuaInterface::StaticClass();
});
InterfaceDesc.Graphs[0]->Nodes[1]->Pins[1]->DefaultValue = LuaModuleName;
}
#if !UE_VERSION_OLDER_THAN(4, 26, 0)
const auto BlueprintEditors = FModuleManager::LoadModuleChecked<FBlueprintEditorModule>("Kismet").GetBlueprintEditors();
for (auto BlueprintEditor : BlueprintEditors)
{
const auto MyBlueprintEditor = static_cast<FBlueprintEditor*>(&BlueprintEditors[0].Get());
if (!MyBlueprintEditor || MyBlueprintEditor->GetBlueprintObj() != Blueprint)
continue;
MyBlueprintEditor->Compile();
const auto Func = Blueprint->GeneratedClass->FindFunctionByName(FName("GetModuleName"));
const auto GraphToOpen = FBlueprintEditorUtils::FindScopeGraph(Blueprint, Func);
MyBlueprintEditor->OpenGraphAndBringToFront(GraphToOpen);
}
#endif
}
void FUnLuaEditorToolbar::UnbindFromLua_Executed() const
{
const auto Blueprint = Cast<UBlueprint>(ContextObject);
if (!IsValid(Blueprint))
return;
const auto TargetClass = Blueprint->GeneratedClass;
if (!IsValid(TargetClass))
return;
if (!TargetClass->ImplementsInterface(UUnLuaInterface::StaticClass()))
return;
#if UE_VERSION_OLDER_THAN(5, 1, 0)
FBlueprintEditorUtils::RemoveInterface(Blueprint, FName("UnLuaInterface"));
#else
FBlueprintEditorUtils::RemoveInterface(Blueprint, FTopLevelAssetPath(UUnLuaInterface::StaticClass()));
#endif
#if !UE_VERSION_OLDER_THAN(4, 26, 0)
const auto BlueprintEditors = FModuleManager::LoadModuleChecked<FBlueprintEditorModule>("Kismet").GetBlueprintEditors();
for (auto BlueprintEditor : BlueprintEditors)
{
const auto MyBlueprintEditor = static_cast<FBlueprintEditor*>(&BlueprintEditors[0].Get());
if (!MyBlueprintEditor || MyBlueprintEditor->GetBlueprintObj() != Blueprint)
continue;
MyBlueprintEditor->Compile();
MyBlueprintEditor->RefreshEditors();
}
#endif
const auto ActiveTab = FGlobalTabmanager::Get()->GetActiveTab();
if (!ActiveTab)
return;
const auto DockingTabWell = ActiveTab->GetParent();
if (!DockingTabWell)
return;
const auto DockTabs = DockingTabWell->GetChildren(); // DockingTabWell->GetTabs();
for (auto i = 0; i < DockTabs->Num(); i++)
{
const auto DockTab = StaticCastSharedRef<SDockTab>(DockTabs->GetChildAt(i));
const auto Label = DockTab->GetTabLabel();
if (Label.ToString().Equals("$$ Get Module Name $$"))
{
DockTab->RequestCloseTab();
}
}
}
void FUnLuaEditorToolbar::CreateLuaTemplate_Executed()
{
const auto Blueprint = Cast<UBlueprint>(ContextObject);
if (!IsValid(Blueprint))
return;
UClass* Class = Blueprint->GeneratedClass;
const auto Func = Class->FindFunctionByName(FName("GetModuleName"));
if (!IsValid(Func))
return;
FString ModuleName;
Class->GetDefaultObject()->ProcessEvent(Func, &ModuleName);
if (ModuleName.IsEmpty())
{
FNotificationInfo Info(LOCTEXT("ModuleNameRequired", "Please specify a module name first"));
Info.ExpireDuration = 5;
FSlateNotificationManager::Get().AddNotification(Info);
return;
}
TArray<FString> ModuleNameParts;
ModuleName.ParseIntoArray(ModuleNameParts, TEXT("."));
const auto TemplateName = ModuleNameParts.Last();
const auto RelativePath = ModuleName.Replace(TEXT("."), TEXT("/"));
const auto FileName = FString::Printf(TEXT("%s%s.lua"), *GLuaSrcFullPath, *RelativePath);
if (FPaths::FileExists(FileName))
{
UE_LOG(LogUnLua, Warning, TEXT("%s"), *FText::Format(LOCTEXT("FileAlreadyExists", "Lua file ({0}) is already existed!"), FText::FromString(TemplateName)).ToString());
return;
}
static FString BaseDir = IPluginManager::Get().FindPlugin(TEXT("UnLua"))->GetBaseDir();
for (auto TemplateClass = Class; TemplateClass; TemplateClass = TemplateClass->GetSuperClass())
{
auto TemplateClassName = TemplateClass->GetName().EndsWith("_C") ? TemplateClass->GetName().LeftChop(2) : TemplateClass->GetName();
auto RelativeFilePath = "Config/LuaTemplates" / TemplateClassName + ".lua";
auto FullFilePath = FPaths::ProjectConfigDir() / RelativeFilePath;
if (!FPaths::FileExists(FullFilePath))
FullFilePath = BaseDir / RelativeFilePath;
if (!FPaths::FileExists(FullFilePath))
continue;
FString Content;
FFileHelper::LoadFileToString(Content, *FullFilePath);
Content = Content.Replace(TEXT("TemplateName"), *TemplateName)
.Replace(TEXT("ClassName"), *UnLua::IntelliSense::GetTypeName(Class));
FFileHelper::SaveStringToFile(Content, *FileName, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
break;
}
}
void FUnLuaEditorToolbar::RevealInExplorer_Executed()
{
const auto Blueprint = Cast<UBlueprint>(ContextObject);
if (!IsValid(Blueprint))
return;
const auto TargetClass = Blueprint->GeneratedClass;
if (!IsValid(TargetClass))
return;
if (!TargetClass->ImplementsInterface(UUnLuaInterface::StaticClass()))
return;
const auto Func = TargetClass->FindFunctionByName(FName("GetModuleName"));
if (!IsValid(Func))
return;
FString ModuleName;
const auto DefaultObject = TargetClass->GetDefaultObject();
DefaultObject->UObject::ProcessEvent(Func, &ModuleName);
const auto RelativePath = ModuleName.Replace(TEXT("."), TEXT("/"));
const auto FileName = FString::Printf(TEXT("%s%s.lua"), *GLuaSrcFullPath, *RelativePath);
if (IFileManager::Get().FileExists(*FileName))
{
FPlatformProcess::ExploreFolder(*FileName);
}
else
{
FNotificationInfo NotificationInfo(FText::FromString("UnLua Notification"));
NotificationInfo.Text = LOCTEXT("FileNotExist", "The file does not exist.");
NotificationInfo.bFireAndForget = true;
NotificationInfo.ExpireDuration = 100.0f;
NotificationInfo.bUseThrobber = true;
FSlateNotificationManager::Get().AddNotification(NotificationInfo);
}
}
void FUnLuaEditorToolbar::CopyAsRelativePath_Executed() const
{
const auto Blueprint = Cast<UBlueprint>(ContextObject);
if (!IsValid(Blueprint))
return;
const auto TargetClass = Blueprint->GeneratedClass;
if (!IsValid(TargetClass))
return;
if (!TargetClass->ImplementsInterface(UUnLuaInterface::StaticClass()))
return;
const auto Func = TargetClass->FindFunctionByName(FName("GetModuleName"));
if (!IsValid(Func))
return;
FString ModuleName;
const auto DefaultObject = TargetClass->GetDefaultObject();
DefaultObject->UObject::ProcessEvent(Func, &ModuleName);
const auto RelativePath = ModuleName.Replace(TEXT("."), TEXT("/")) + TEXT(".lua");
FPlatformApplicationMisc::ClipboardCopy(*RelativePath);
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,55 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "BlueprintEditor.h"
class FUnLuaEditorToolbar
{
public:
virtual ~FUnLuaEditorToolbar() = default;
FUnLuaEditorToolbar();
TSharedRef<FUICommandList> GetCommandList() const
{
return CommandList;
}
virtual void Initialize();
void CreateLuaTemplate_Executed();
void CopyAsRelativePath_Executed() const;
void BindToLua_Executed() const;
void UnbindFromLua_Executed() const;
void RevealInExplorer_Executed();
protected:
virtual void BindCommands();
void BuildToolbar(FToolBarBuilder& ToolbarBuilder, UObject* InContextObject);
void BuildNodeMenu();
TSharedRef<FExtender> GetExtender(UObject* InContextObject);
const TSharedRef<FUICommandList> CommandList;
UObject* ContextObject;
};
@@ -0,0 +1,166 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaAboutScreen.h"
#include "Misc/EngineVersionComparison.h"
#include "Widgets/SBoxPanel.h"
#include "Widgets/SOverlay.h"
#include "Widgets/SWindow.h"
#include "Framework/Application/SlateApplication.h"
#include "Widgets/Layout/SSpacer.h"
#include "Widgets/Images/SImage.h"
#include "Widgets/Text/STextBlock.h"
#include "Widgets/Input/SEditableText.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/Views/STableViewBase.h"
#include "Widgets/Views/STableRow.h"
#include "Widgets/Views/SListView.h"
#include "Styling/CoreStyle.h"
#include "EditorStyleSet.h"
#include "UnLuaEditorFunctionLibrary.h"
#include "UnLuaEditorStyle.h"
#define LOCTEXT_NAMESPACE "UnLuaAboutScreen"
void SUnLuaAboutScreen::Construct(const FArguments& InArgs)
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4428) // universal-character-name encountered in source
#endif
AboutLines.Add(MakeShareable(new FLineDefinition(LOCTEXT("Copyright1", "https://github.com/Tencent/UnLua"), 8, FLinearColor(1.f, 1.f, 1.f), FMargin(0.f))));
AboutLines.Add(MakeShareable(new FLineDefinition(LOCTEXT("Copyright2", "Tencent is pleased to support the open source community by making UnLua available."), 8, FLinearColor(1.f, 1.f, 1.f), FMargin(0.0f, 8.0f))));
AboutLines.Add(MakeShareable(new FLineDefinition(LOCTEXT("Copyright3", "Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved."), 8, FLinearColor(1.f, 1.f, 1.f), FMargin(0.0f, 2.0f))));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
FText Version = FText::Format(LOCTEXT("VersionLabel", "Version: {0}"), FText::FromString(UUnLuaEditorFunctionLibrary::GetCurrentVersion()));
ChildSlot
[
SNew(SOverlay)
+ SOverlay::Slot()
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Top)
.Padding(FMargin(10.f, 10.f, 0.f, 0.f))
[
SAssignNew(LogoButton, SButton)
#if UE_VERSION_OLDER_THAN(5, 1, 0)
.ButtonStyle(FEditorStyle::Get(), "NoBorder")
#else
.ButtonStyle(FAppStyle::Get(), "NoBorder")
#endif
.OnClicked(this, &SUnLuaAboutScreen::OnLogoButtonClicked)
[
SNew(SImage).Image(FUnLuaEditorStyle::GetInstance()->GetBrush("UnLuaEditor.UnLuaLogo"))
]
]
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Top)
.Padding(FMargin(10.f, 10.f, 0.f, 0.f))
+ SHorizontalBox::Slot()
.FillWidth(1.f)
.HAlign(HAlign_Right)
.Padding(FMargin(0.f, 52.f, 7.f, 0.f))
[
SNew(SEditableText)
.ColorAndOpacity(FLinearColor(0.7f, 0.7f, 0.7f))
.IsReadOnly(true)
.Text(Version)
]
]
+ SVerticalBox::Slot()
.Padding(FMargin(5.f, 5.f, 5.f, 5.f))
.VAlign(VAlign_Top)
[
SNew(SListView<TSharedRef<FLineDefinition>>)
.ListItemsSource(&AboutLines)
.OnGenerateRow(this, &SUnLuaAboutScreen::MakeAboutTextItemWidget)
.SelectionMode(ESelectionMode::None)
]
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.Padding(FMargin(5.f, 0.f, 5.f, 5.f))
+ SHorizontalBox::Slot()
.AutoWidth()
.HAlign(HAlign_Right)
.VAlign(VAlign_Bottom)
.Padding(FMargin(5.f, 0.f, 5.f, 5.f))
[
SNew(SButton)
.HAlign(HAlign_Center)
.VAlign(VAlign_Center)
.Text(LOCTEXT("Close", "Close"))
.ButtonColorAndOpacity(FLinearColor(0.6f, 0.6f, 0.6f))
.OnClicked(this, &SUnLuaAboutScreen::OnClose)
]
]
]
];
}
TSharedRef<ITableRow> SUnLuaAboutScreen::MakeAboutTextItemWidget(TSharedRef<FLineDefinition> Item, const TSharedRef<STableViewBase>& OwnerTable)
{
if (Item->Text.IsEmpty())
{
return
SNew(STableRow< TSharedPtr<FString> >, OwnerTable)
.Padding(6.0f)
[
SNew(SSpacer)
];
}
else
{
return
SNew(STableRow< TSharedPtr<FString> >, OwnerTable)
.Padding(Item->Margin)
[
SNew(STextBlock)
.ColorAndOpacity(Item->TextColor)
.Font(FCoreStyle::GetDefaultFontStyle("Regular", Item->FontSize))
.Text(Item->Text)
];
}
}
FReply SUnLuaAboutScreen::OnLogoButtonClicked()
{
const TCHAR* URL = TEXT("cmd");
const TCHAR* Params = TEXT("/k start https://github.com/Tencent/UnLua");
FPlatformProcess::ExecProcess(URL, Params, nullptr, nullptr, nullptr);
return FReply::Handled();
}
FReply SUnLuaAboutScreen::OnClose()
{
TSharedRef<SWindow> ParentWindow = FSlateApplication::Get().FindWidgetWindow(AsShared()).ToSharedRef();
FSlateApplication::Get().RequestDestroyWindow(ParentWindow);
return FReply::Handled();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,72 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreMinimal.h"
#include "Layout/Margin.h"
#include "Input/Reply.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Widgets/SCompoundWidget.h"
class ITableRow;
class SButton;
class STableViewBase;
struct FSlateBrush;
class SUnLuaAboutScreen : public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SUnLuaAboutScreen)
{
}
SLATE_END_ARGS()
UNLUAEDITOR_API void Construct(const FArguments& InArgs);
private:
struct FLineDefinition
{
public:
FText Text;
int32 FontSize;
FLinearColor TextColor;
FMargin Margin;
FLineDefinition(const FText& InText)
: Text(InText)
, FontSize(9)
, TextColor(FLinearColor(0.5f, 0.5f, 0.5f))
, Margin(FMargin(6.f, 0.f, 0.f, 0.f))
{
}
FLineDefinition(const FText& InText, int32 InFontSize, const FLinearColor& InTextColor, const FMargin& InMargin)
: Text(InText)
, FontSize(InFontSize)
, TextColor(InTextColor)
, Margin(InMargin)
{
}
};
TArray<TSharedRef<FLineDefinition>> AboutLines;
TSharedPtr<SButton> LogoButton;
TSharedRef<ITableRow> MakeAboutTextItemWidget(TSharedRef<FLineDefinition> Item, const TSharedRef<STableViewBase>& OwnerTable);
FReply OnLogoButtonClicked();
FReply OnClose();
};
@@ -0,0 +1,34 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEditorCommands.h"
#define LOCTEXT_NAMESPACE "FUnLuaEditorCommands"
void FUnLuaEditorCommands::RegisterCommands()
{
UI_COMMAND(CreateLuaTemplate, "Create Lua Template", "Create lua template file", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(CopyAsRelativePath, "Copy as Relative Path", "Copy module name as relative path.", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(BindToLua, "Bind", "Implement UnLuaInterface", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(UnbindFromLua, "Unbind", "Remove the implementation of UnLuaInterface", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(HotReload, "Hot Reload", "Hot reload all lua states", EUserInterfaceActionType::Button, FInputChord(EModifierKey::Alt, EKeys::L));
UI_COMMAND(OpenRuntimeSettings, "Open Runtime Settings", "Open UnLua Runtime settings", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(OpenEditorSettings, "Open Editor Settings", "Open UnLua Editor settings", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ReportIssue, "Report issue", "Create an issue on github", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(About, "About", "About this version", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(GenerateIntelliSense, "Generate IntelliSense", "Generate intelliSense files", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(RevealInExplorer, "Reveal in Explorer", "Reveal lua file in explorer", EUserInterfaceActionType::Button, FInputChord());
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,40 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "Framework/Commands/Commands.h"
class FUnLuaEditorCommands : public TCommands<FUnLuaEditorCommands>
{
public:
FUnLuaEditorCommands()
: TCommands<FUnLuaEditorCommands>(TEXT("UnLuaEditor"), NSLOCTEXT("Contexts", "UnLuaEditor", "UnLua Editor"), NAME_None, "UnLuaEditorStyle")
{
}
virtual void RegisterCommands() override;
TSharedPtr<FUICommandInfo> CreateLuaTemplate;
TSharedPtr<FUICommandInfo> CopyAsRelativePath;
TSharedPtr<FUICommandInfo> BindToLua;
TSharedPtr<FUICommandInfo> UnbindFromLua;
TSharedPtr<FUICommandInfo> HotReload;
TSharedPtr<FUICommandInfo> OpenRuntimeSettings;
TSharedPtr<FUICommandInfo> OpenEditorSettings;
TSharedPtr<FUICommandInfo> ReportIssue;
TSharedPtr<FUICommandInfo> About;
TSharedPtr<FUICommandInfo> GenerateIntelliSense;
TSharedPtr<FUICommandInfo> RevealInExplorer;
};
@@ -0,0 +1,53 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEditorCore.h"
#include "UnLuaInterface.h"
#include "UnLuaPrivate.h"
#include "UnLuaSettings.h"
#include "Engine/Blueprint.h"
#include "Blueprint/UserWidget.h"
ELuaBindingStatus GetBindingStatus(const UBlueprint* Blueprint)
{
if (!Blueprint)
return ELuaBindingStatus::NotBound;
if (Blueprint->Status == EBlueprintStatus::BS_Dirty)
return ELuaBindingStatus::Unknown;
const auto Target = Blueprint->GeneratedClass;
if (!IsValid(Target))
return ELuaBindingStatus::NotBound;
if (!Target->ImplementsInterface(UUnLuaInterface::StaticClass()))
return ELuaBindingStatus::NotBound;
const auto Settings = GetDefault<UUnLuaSettings>();
if (!Settings || !Settings->ModuleLocatorClass)
return ELuaBindingStatus::Unknown;
const auto ModuleLocator = Cast<ULuaModuleLocator>(Settings->ModuleLocatorClass->GetDefaultObject());
const auto ModuleName = ModuleLocator->Locate(Target);
if (ModuleName.IsEmpty())
return ELuaBindingStatus::Unknown;
const auto RelativePath = ModuleName.Replace(TEXT("."), TEXT("/")) + TEXT(".lua");
const auto FullPath = GLuaSrcFullPath + "/" + RelativePath;
if (!FPaths::FileExists(FullPath))
return ELuaBindingStatus::BoundButInvalid;
return ELuaBindingStatus::Bound;
}
@@ -0,0 +1,35 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/* 描述对象的Lua绑定状态 */
#pragma once
enum ELuaBindingStatus
{
// 未编译,未知
Unknown,
// 未绑定
NotBound,
// 已绑定
Bound,
// 已绑定,但没有找到对应的模块
BoundButInvalid
};
/* 获取指定蓝图对象上的Lua绑定状态 */
ELuaBindingStatus GetBindingStatus(const UBlueprint* Blueprint);
@@ -0,0 +1,120 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEditorFunctionLibrary.h"
#include "Modules/ModuleManager.h"
#include "DirectoryWatcherModule.h"
#include "IDirectoryWatcher.h"
#include "SocketSubsystem.h"
#include "UnLua.h"
#include "UnLuaEditorSettings.h"
#include "UnLuaFunctionLibrary.h"
#include "Common/UdpSocketBuilder.h"
#include "Interfaces/IPluginManager.h"
void UUnLuaEditorFunctionLibrary::WatchScriptDirectory()
{
FDirectoryWatcherModule& DirectoryWatcherModule = FModuleManager::LoadModuleChecked<FDirectoryWatcherModule>("DirectoryWatcher");
IDirectoryWatcher* DirectoryWatcher = DirectoryWatcherModule.Get();
if (DirectoryWatcher)
{
const auto& Delegate = IDirectoryWatcher::FDirectoryChanged::CreateStatic(&UUnLuaEditorFunctionLibrary::OnLuaFilesModified);
const auto& ScriptRootPath = UUnLuaFunctionLibrary::GetScriptRootPath();
DirectoryWatcher->RegisterDirectoryChangedCallback_Handle(ScriptRootPath, Delegate, DirectoryWatcherHandle);
}
}
void UUnLuaEditorFunctionLibrary::FetchNewVersion()
{
Async(EAsyncExecution::ThreadPool, []
{
const auto RemoteAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
bool bIsValid;
RemoteAddr->SetIp(TEXT("101.226.141.148"), bIsValid);
RemoteAddr->SetPort(8080);
const auto Client = FUdpSocketBuilder(TEXT("Client")).Build();
if (!Client->Connect(RemoteAddr.Get()))
{
UE_LOG(LogUnLua, Verbose, TEXT("Unable to fetch latest version, could not connect to server."));
return;
}
PRAGMA_DISABLE_DEPRECATION_WARNINGS
const FString Msg = FString::Printf(TEXT("cmd=3&tag=glcoud.unlua.update&version=%s&engine=%s&user_name=%s"),
*GetCurrentVersion(),
*FEngineVersion::Current().ToString(),
*FPlatformMisc::GetHashedMacAddressString()
);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
const FTCHARToUTF8 Converted(*Msg);
int32 Sent;
if (!Client->Send((uint8*)Converted.Get(), Converted.Length(), Sent))
{
UE_LOG(LogUnLua, Warning, TEXT("Unable to fetch latest version, data sending error."));
Client->Close();
return;
}
TArray<uint8> Bytes;
Bytes.SetNumZeroed(256);
int32 Read = 0;
for (int Tried = 0; Tried < 10; ++Tried)
{
FPlatformProcess::Sleep(0.5f);
if (Client->Recv(Bytes.GetData(), Bytes.Num(), Read))
break;
}
Client->Close();
if (Read == 0)
{
UE_LOG(LogUnLua, Warning, TEXT("Unable to fetch latest version, data receiving timeout."));
return;
}
const FString Received = UTF8_TO_TCHAR((char*)Bytes.GetData());
const FString CurrentVersion = GetCurrentVersion();
if (Received == CurrentVersion)
return;
UE_LOG(LogUnLua, Log, TEXT("New version available: %s."), *Received);
});
}
FString UUnLuaEditorFunctionLibrary::GetCurrentVersion()
{
auto& PluginManager = IPluginManager::Get();
auto Plugins = PluginManager.GetDiscoveredPlugins();
for (const auto& Plugin : Plugins)
{
if (Plugin->GetName() == "UnLua")
{
const auto Descriptor = Plugin->GetDescriptor();
return Descriptor.VersionName;
}
}
return "";
}
void UUnLuaEditorFunctionLibrary::OnLuaFilesModified(const TArray<FFileChangeData>& FileChanges)
{
const auto& Settings = *GetDefault<UUnLuaEditorSettings>();
if (Settings.HotReloadMode != EHotReloadMode::Auto)
return;
UUnLuaFunctionLibrary::HotReload();
}
FDelegateHandle UUnLuaEditorFunctionLibrary::DirectoryWatcherHandle;
@@ -0,0 +1,38 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreMinimal.h"
#include "IDirectoryWatcher.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "UnLuaEditorFunctionLibrary.generated.h"
UCLASS()
class UNLUAEDITOR_API UUnLuaEditorFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
static void WatchScriptDirectory();
static void FetchNewVersion();
static FString GetCurrentVersion();
private:
static void OnLuaFilesModified(const TArray<FFileChangeData>& FileChanges);
static FDelegateHandle DirectoryWatcherHandle;
};
@@ -0,0 +1,251 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "Compat/UObjectHash.h"
#include "UnLuaEditorStyle.h"
#include "UnLuaEditorCommands.h"
#include "Misc/CoreDelegates.h"
#include "Editor.h"
#include "BlueprintEditorModule.h"
#include "UnLuaIntelliSenseGenerator.h"
#include "UnLua.h"
#include "ISettingsModule.h"
#include "ISettingsSection.h"
#include "UnLuaEditorSettings.h"
#include "UnLuaEditorFunctionLibrary.h"
#include "UnLuaFunctionLibrary.h"
#include "Kismet2/DebuggerCommands.h"
#include "Interfaces/IMainFrameModule.h"
#include "Interfaces/IPluginManager.h"
#include "Settings/ProjectPackagingSettings.h"
#include "Toolbars/AnimationBlueprintToolbar.h"
#include "Toolbars/BlueprintToolbar.h"
#include "Toolbars/MainMenuToolbar.h"
#if ENGINE_MAJOR_VERSION > 4
#include "UObject/ObjectSaveContext.h"
#endif
#define LOCTEXT_NAMESPACE "FUnLuaEditorModule"
class FUnLuaEditorModule : public IModuleInterface
{
public:
FUnLuaEditorModule()
{
}
virtual void StartupModule() override
{
Style = FUnLuaEditorStyle::GetInstance();
FUnLuaEditorCommands::Register();
FCoreDelegates::OnPostEngineInit.AddRaw(this, &FUnLuaEditorModule::OnPostEngineInit);
MainMenuToolbar = MakeShareable(new FMainMenuToolbar);
BlueprintToolbar = MakeShareable(new FBlueprintToolbar);
AnimationBlueprintToolbar = MakeShareable(new FAnimationBlueprintToolbar);
UUnLuaEditorFunctionLibrary::WatchScriptDirectory();
#if ENGINE_MAJOR_VERSION > 4
UPackage::PreSavePackageWithContextEvent.AddRaw(this, &FUnLuaEditorModule::OnPackageSavingWithContext);
UPackage::PackageSavedWithContextEvent.AddRaw(this, &FUnLuaEditorModule::OnPackageSavedWithContext);
#else
UPackage::PreSavePackageEvent.AddRaw(this, &FUnLuaEditorModule::OnPackageSaving);
UPackage::PackageSavedEvent.AddRaw(this, &FUnLuaEditorModule::OnPackageSaved);
#endif
SetupPackagingSettings();
}
virtual void ShutdownModule() override
{
FUnLuaEditorCommands::Unregister();
FCoreDelegates::OnPostEngineInit.RemoveAll(this);
UnregisterSettings();
#if ENGINE_MAJOR_VERSION > 4
UPackage::PreSavePackageWithContextEvent.RemoveAll(this);
UPackage::PackageSavedWithContextEvent.RemoveAll(this);
#else
UPackage::PreSavePackageEvent.RemoveAll(this);
UPackage::PackageSavedEvent.RemoveAll(this);
#endif
}
private:
void OnPostEngineInit()
{
RegisterSettings();
if (!GEditor)
{
// Loading MainFrame module with '-game' is not supported
return;
}
MainMenuToolbar->Initialize();
BlueprintToolbar->Initialize();
AnimationBlueprintToolbar->Initialize();
FUnLuaIntelliSenseGenerator::Get()->Initialize();
IMainFrameModule& MainFrameModule = FModuleManager::LoadModuleChecked<IMainFrameModule>(TEXT("MainFrame"));
MainFrameModule.OnMainFrameCreationFinished().AddRaw(this, &FUnLuaEditorModule::OnMainFrameCreationFinished);
}
void OnMainFrameCreationFinished(TSharedPtr<SWindow> InRootWindow, bool bIsNewProjectWindow)
{
// register default key input to 'HotReload' Lua
FPlayWorldCommands::GlobalPlayWorldActions->MapAction(
FUnLuaEditorCommands::Get().HotReload, FExecuteAction::CreateStatic(UUnLuaFunctionLibrary::HotReload), FCanExecuteAction());
}
void RegisterSettings() const
{
ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings");
if (SettingsModule)
{
const TSharedPtr<ISettingsSection> Section = SettingsModule->RegisterSettings("Project", "Plugins", "UnLua Editor",
LOCTEXT("UnLuaEditorSettingsName", "UnLua Editor"),
LOCTEXT("UnLuaEditorSettingsDescription", "UnLua Editor Settings"),
GetMutableDefault<UUnLuaEditorSettings>());
Section->OnModified().BindRaw(this, &FUnLuaEditorModule::OnSettingsModified);
}
}
void UnregisterSettings() const
{
ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings");
if (SettingsModule)
SettingsModule->UnregisterSettings("Project", "Plugins", "UnLua Editor");
}
bool OnSettingsModified() const
{
const auto BuildFile = IPluginManager::Get().FindPlugin(TEXT("UnLua"))->GetBaseDir() / "Source/UnLua/UnLua.Build.cs";
auto& FileManager = IFileManager::Get();
if (FileManager.FileExists(*BuildFile))
FileManager.SetTimeStamp(*BuildFile, FDateTime::UtcNow());
return true;
}
#if ENGINE_MAJOR_VERSION > 4
void OnPackageSavingWithContext(UPackage* Package, FObjectPreSaveContext Context)
{
OnPackageSaving(Package);
}
void OnPackageSavedWithContext(const FString& PackageFileName, UPackage* Package, FObjectPostSaveContext Context)
{
OnPackageSaved(PackageFileName, Package);
}
#endif
void OnPackageSaving(UPackage* Package)
{
if (!GEditor || !GEditor->PlayWorld)
return;
ForEachObjectWithPackage(Package, [this, Package](UObject* Object)
{
const auto Class = Cast<UClass>(Object);
if (!Class || Class->GetName().StartsWith(TEXT("SKEL_")) || Class->GetName().StartsWith(TEXT("REINST_")))
return true;
SuspendedPackages.Add(Package, Class);
return false;
}, false);
for (const auto Pair : SuspendedPackages)
ULuaFunction::SuspendOverrides(Pair.Value);
}
void OnPackageSaved(const FString& PackageFileName, UObject* Outer)
{
if (!GEditor || !GEditor->PlayWorld)
return;
UPackage* Package = (UPackage*)Outer;
if (SuspendedPackages.Contains(Package))
{
ULuaFunction::ResumeOverrides(SuspendedPackages[Package]);
SuspendedPackages.Remove(Package);
}
}
void SetupPackagingSettings()
{
auto ScriptPaths = TArray<FString>{TEXT("Script"), TEXT("../Plugins/UnLua/Content/Script")};
const auto Plugins = IPluginManager::Get().GetEnabledPlugins();
for (const auto Plugin : Plugins)
{
if (!Plugin->CanContainContent())
continue;
const auto ContentDir = Plugin->GetContentDir();
if (!ContentDir.Contains("UnLuaExtensions"))
continue;
auto ScriptPath = ContentDir / "Script";
if (!FPaths::DirectoryExists(ScriptPath))
continue;
if (FPaths::MakePathRelativeTo(ScriptPath, *FPaths::ProjectContentDir()))
ScriptPaths.Add(ScriptPath);
}
const auto PackagingSettings = GetMutableDefault<UProjectPackagingSettings>();
bool bModified = false;
auto Exists = [&](const auto Path)
{
for (const auto& DirPath : PackagingSettings->DirectoriesToAlwaysStageAsUFS)
{
if (DirPath.Path == Path)
return true;
}
return false;
};
for (auto& ScriptPath : ScriptPaths)
{
if (Exists(ScriptPath))
continue;
FDirectoryPath DirectoryPath;
DirectoryPath.Path = ScriptPath;
PackagingSettings->DirectoriesToAlwaysStageAsUFS.Add(DirectoryPath);
bModified = true;
}
if (bModified)
{
#if ENGINE_MAJOR_VERSION >= 5
PackagingSettings->TryUpdateDefaultConfigFile();
#else
PackagingSettings->UpdateDefaultConfigFile();
#endif
}
}
TSharedPtr<FBlueprintToolbar> BlueprintToolbar;
TSharedPtr<FAnimationBlueprintToolbar> AnimationBlueprintToolbar;
TSharedPtr<FMainMenuToolbar> MainMenuToolbar;
TSharedPtr<FUnLuaIntelliSenseGenerator> IntelliSenseGenerator;
TSharedPtr<ISlateStyle> Style;
TMap<UPackage*, UClass*> SuspendedPackages;
};
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FUnLuaEditorModule, UnLuaEditor)
@@ -0,0 +1,16 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEditorSettings.h"
@@ -0,0 +1,113 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "UnLuaEditorSettings.generated.h"
#define LOCTEXT_NAMESPACE "UnLuaEditorSettings"
UENUM()
enum class EUpdateMode : uint8
{
Start,
Manual,
None,
};
UENUM()
enum class EHotReloadMode : uint8
{
Manual,
Auto,
Never
};
UCLASS(config=UnLuaEditor, defaultconfig, meta=(DisplayName="UnLuaEditor"))
class UNLUAEDITOR_API UUnLuaEditorSettings : public UObject
{
GENERATED_BODY()
public:
/** Pick a method for lua hot-reload. */
UPROPERTY(config, EditAnywhere, Category = "Coding", meta = (defaultValue = 0))
EHotReloadMode HotReloadMode;
/** Whether or not generate intellisense files for lua. */
UPROPERTY(config, EditAnywhere, Category = "Coding")
bool bGenerateIntelliSense = true;
/** Whether or not startup UnLua module on game start. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bAutoStartup = true;
/** Enable UnLua debug routine codes. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnableDebug = false;
/** Enable Unreal Insights to profile call performance. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnableUnrealInsights = false;
/** Enable persistent buffer for UFunction's parameters. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnablePersistentParamBuffer = true;
/** Enable type checking at lua runtime. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnableTypeChecking = true;
/** Enable 'Overridden' support at lua runtime. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnableCallOverriddenFunction = true;
/** Enable FText support at lua runtime which will no longer be treated as a string. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bEnableFText = true;
/** Whether or not compile lua module as c++ code. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
bool bLuaCompileAsCpp = false;
/** Use the specified lua version. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Build")
FString LuaVersion = TEXT("lua-5.4.3");
/** Create UE4 global table on lua env. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Legacy")
bool bWithUE4Namespace = true;
/** Place out parameters before return value. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Legacy")
bool bLegacyReturnOrder = false;
/** Auto append '_C' to blueprint class path. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Legacy")
bool bLegacyBlueprintPath = false;
/** Allow lua file with UTF-8 BOM header. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Legacy")
bool bLegacyAllowUTF8WithBOM = false;
/** Arguments are passed to lua by pointer when called from UE. (Requires restart to take effect) */
UPROPERTY(config, EditAnywhere, Category = "Legacy")
bool bLegacyArgsPassing = true;
UPROPERTY(config, EditAnywhere, Category = "System", meta = (defaultValue = 0))
EUpdateMode UpdateMode;
};
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,59 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaEditorStyle.h"
#include "Interfaces/IPluginManager.h"
#include "Styling/SlateStyleRegistry.h"
#define IMAGE_BRUSH(RelativePath, ...) FSlateImageBrush(RootToContentDir(RelativePath, TEXT(".png")), __VA_ARGS__)
#define BOX_BRUSH(RelativePath, ...) FSlateBoxBrush(RootToContentDir(RelativePath, TEXT(".png")), __VA_ARGS__)
#define BORDER_BRUSH(RelativePath, ...) FSlateBorderBrush(RootToContentDir(RelativePath, TEXT(".png")), __VA_ARGS__)
#define TTF_FONT(RelativePath, ...) FSlateFontInfo(RootToContentDir(RelativePath, TEXT(".ttf")), __VA_ARGS__)
#define OTF_FONT(RelativePath, ...) FSlateFontInfo(RootToContentDir(RelativePath, TEXT(".otf")), __VA_ARGS__)
TSharedPtr<ISlateStyle> FUnLuaEditorStyle::Instance = nullptr;
FUnLuaEditorStyle::FUnLuaEditorStyle()
: FSlateStyleSet("UnLuaEditorStyle")
{
const FVector2D Icon40x40(40.0f, 40.0f);
SetContentRoot(IPluginManager::Get().FindPlugin("UnLua")->GetBaseDir() / TEXT("Resources"));
Set("UnLuaEditor.UnLuaLogo", new IMAGE_BRUSH("Icons/icon_unlua_logo_40x", Icon40x40));
Set("UnLuaEditor.Status_NotBound", new IMAGE_BRUSH("Icons/icon_unlua_logo_40x", Icon40x40));
Set("UnLuaEditor.Status_Unknown", new IMAGE_BRUSH("Icons/icon_status_unknown_40x", Icon40x40));
Set("UnLuaEditor.Status_Bound", new IMAGE_BRUSH("Icons/icon_status_bound_40x", Icon40x40));
Set("UnLuaEditor.Status_BoundButInvalid", new IMAGE_BRUSH("Icons/icon_status_bound_but_invalid_40x", Icon40x40));
Set("UnLuaEditor.RevealInExplorer", new IMAGE_BRUSH("Icons/icon_reveal_in_explorer_40x", Icon40x40));
Set("UnLuaEditor.CreateLuaTemplate", new IMAGE_BRUSH("Icons/icon_create_template_40x", Icon40x40));
Set("UnLuaEditor.CopyAsRelativePath", new IMAGE_BRUSH("Icons/icon_copy_40x", Icon40x40));
Set("UnLuaEditor.BindToLua", new IMAGE_BRUSH("Icons/icon_bind_to_lua_40x", Icon40x40));
Set("UnLuaEditor.UnbindFromLua", new IMAGE_BRUSH("Icons/icon_unbind_from_lua_40x", Icon40x40));
Set("UnLuaEditor.HotReload", new IMAGE_BRUSH("Icons/icon_reload_40x", Icon40x40));
Set("UnLuaEditor.GenerateIntelliSense", new IMAGE_BRUSH("Icons/icon_intellisense_40x", Icon40x40));
FSlateStyleRegistry::RegisterSlateStyle(*this);
}
FUnLuaEditorStyle::~FUnLuaEditorStyle()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*this);
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
@@ -0,0 +1,34 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "Styling/SlateStyle.h"
class FUnLuaEditorStyle : public FSlateStyleSet
{
public:
FUnLuaEditorStyle();
~FUnLuaEditorStyle();
static TSharedPtr<ISlateStyle> GetInstance()
{
if (!Instance.IsValid())
Instance = MakeShared<FUnLuaEditorStyle>();
return Instance;
}
private:
static TSharedPtr<ISlateStyle> Instance;
};
@@ -0,0 +1,559 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "UnLuaIntelliSense.h"
#include "Binding.h"
#include "ObjectEditorUtils.h"
#include "UnLuaInterface.h"
namespace UnLua
{
namespace IntelliSense
{
static const FName NAME_ToolTip(TEXT("ToolTip")); // key of ToolTip meta data
static const FName NAME_LatentInfo = TEXT("LatentInfo"); // tag of latent function
static FString LuaKeywords[] = {TEXT("local"), TEXT("function"), TEXT("end")};
static FString GetCommentBlock(const UField* Field)
{
const FString ToolTip = Field->GetMetaData(NAME_ToolTip);
if (ToolTip.IsEmpty())
return "";
return "---" + EscapeComments(ToolTip, false) + "\r\n";
}
FString Get(const UBlueprint* Blueprint)
{
return Get(Blueprint->GeneratedClass);
}
FString Get(const UField* Field)
{
const UStruct* Struct = Cast<UStruct>(Field);
if (Struct)
return Get(Struct);
const UEnum* Enum = Cast<UEnum>(Field);
if (Enum)
return Get(Enum);
return "";
}
FString Get(const UEnum* Enum)
{
FString Ret = GetCommentBlock(Enum);
FString TypeName = GetTypeName(Enum);
Ret += FString::Printf(TEXT("---@class %s"), *TypeName);
// fields
const int32 Num = Enum->NumEnums();
for (int32 i = 0; i < Num; ++i)
{
Ret += FString::Printf(TEXT("\r\n---@field %s %s %s"), TEXT("public"), *Enum->GetNameStringByIndex(i), TEXT("integer"));
}
// declaration
Ret += FString::Printf(TEXT("\r\nlocal %s = {}\r\n"), *EscapeSymbolName(TypeName));
return Ret;
}
FString Get(const UStruct* Struct)
{
const UClass* Class = Cast<UClass>(Struct);
if (Class)
return Get(Class);
const UScriptStruct* ScriptStruct = Cast<UScriptStruct>(Struct);
if (ScriptStruct)
return Get(ScriptStruct);
const UFunction* Function = Cast<UFunction>(Struct);
if (Function)
return Get(Function);
return "";
}
FString Get(const UScriptStruct* ScriptStruct)
{
FString Ret = GetCommentBlock(ScriptStruct);
FString TypeName = GetTypeName(ScriptStruct);
Ret += "---@class " + TypeName;
UStruct* SuperStruct = ScriptStruct->GetSuperStruct();
if (SuperStruct)
Ret += " : " + GetTypeName(SuperStruct);
Ret += "\r\n";
// fields
for (TFieldIterator<FProperty> It(ScriptStruct, EFieldIteratorFlags::ExcludeSuper, EFieldIteratorFlags::ExcludeDeprecated); It; ++It)
{
const FProperty* Property = *It;
Ret += Get(Property) += "\r\n";
}
// declaration
Ret += FString::Printf(TEXT("local %s = {}\r\n"), *EscapeSymbolName(TypeName));
// exported functions
const auto Exported = GetExportedReflectedClasses().Find(TypeName);
if (Exported)
{
TArray<IExportedFunction*> ExportedFunctions;
(*Exported)->GetFunctions(ExportedFunctions);
for (const auto Function : ExportedFunctions)
Function->GenerateIntelliSense(Ret);
}
return Ret;
}
FString Get(const UClass* Class)
{
FString Ret = GetCommentBlock(Class);
const FString TypeName = GetTypeName(Class);
Ret += "---@class " + TypeName;
UStruct* SuperStruct = Class->GetSuperStruct();
if (SuperStruct)
Ret += " : " + GetTypeName(SuperStruct);
Ret += "\r\n";
// fields
for (TFieldIterator<FProperty> It(Class, EFieldIteratorFlags::ExcludeSuper, EFieldIteratorFlags::ExcludeDeprecated); It; ++It)
{
const FProperty* Property = *It;
Ret += Get(Property) += "\r\n";
}
// declaration
const auto EscapedClassName = EscapeSymbolName(TypeName);
Ret += FString::Printf(TEXT("local %s = {}\r\n\r\n"), *EscapedClassName);
TArray<FString> GenFunctionNames;
// functions
for (TFieldIterator<UFunction> FunctionIt(Class, EFieldIteratorFlags::ExcludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::ExcludeInterfaces); FunctionIt; ++FunctionIt)
{
const UFunction* Function = *FunctionIt;
if (!IsValid(Function))
continue;
if (FObjectEditorUtils::IsFunctionHiddenFromClass(Function, Class))
continue;
Ret += Get(Function) + "\r\n";
GenFunctionNames.Add(Function->GetName());
}
// interface functions
for (TFieldIterator<UFunction> FunctionIt(Class, EFieldIteratorFlags::IncludeSuper, EFieldIteratorFlags::ExcludeDeprecated, EFieldIteratorFlags::IncludeInterfaces); FunctionIt; ++FunctionIt)
{
const UFunction* Function = *FunctionIt;
if (!Function->GetOwnerClass()->IsChildOf(UInterface::StaticClass()))
continue;
if (!IsValid(Function))
continue;
if (FObjectEditorUtils::IsFunctionHiddenFromClass(Function, Class))
continue;
if (GenFunctionNames.Contains(Function->GetName()))
continue;
Ret += Get(Function, EscapedClassName) + "\r\n";
}
// exported functions
const auto Exported = GetExportedReflectedClasses().Find(TypeName);
if (Exported)
{
TArray<IExportedFunction*> ExportedFunctions;
(*Exported)->GetFunctions(ExportedFunctions);
for (const auto Function : ExportedFunctions)
Function->GenerateIntelliSense(Ret);
}
return Ret;
}
FString Get(const UFunction* Function, FString ForceClassName)
{
FString Ret = GetCommentBlock(Function);
FString Properties;
for (TFieldIterator<FProperty> It(Function); It && (It->PropertyFlags & CPF_Parm); ++It)
{
const FProperty* Property = *It;
if (Property->GetFName() == NAME_LatentInfo)
continue;
FString TypeName = EscapeSymbolName(GetTypeName(Property));
const FString& PropertyComment = Property->GetMetaData(NAME_ToolTip);
FString ExtraDesc;
if (Property->HasAnyPropertyFlags(CPF_ReturnParm))
{
Ret += FString::Printf(TEXT("---@return %s"), *TypeName); // return parameter
}
else
{
FString PropertyName = EscapeSymbolName(*Property->GetName());
if (Properties.IsEmpty())
Properties = PropertyName;
else
Properties += FString::Printf(TEXT(", %s"), *PropertyName);
FName KeyName = FName(*FString::Printf(TEXT("CPP_Default_%s"), *Property->GetName()));
const FString& Value = Function->GetMetaData(KeyName);
if (!Value.IsEmpty())
{
ExtraDesc = TEXT("[opt]"); // default parameter
}
else if (Property->HasAnyPropertyFlags(CPF_OutParm) && !Property->HasAnyPropertyFlags(CPF_ConstParm))
{
ExtraDesc = TEXT("[out]"); // non-const reference
}
Ret += FString::Printf(TEXT("---@param %s %s"), *PropertyName, *TypeName);
}
if (ExtraDesc.Len() > 0 || PropertyComment.Len() > 0)
{
Ret += TEXT(" @");
if (ExtraDesc.Len() > 0)
Ret += FString::Printf(TEXT("%s "), *ExtraDesc);
}
Ret += TEXT("\r\n");
}
const auto ClassName = ForceClassName.IsEmpty() ? EscapeSymbolName(GetTypeName(Function->GetOwnerClass())) : ForceClassName;
const auto FunctionName = Function->GetName();
const auto bIsStatic = Function->HasAnyFunctionFlags(FUNC_Static);
if (IsValidFunctionName(FunctionName))
{
Ret += FString::Printf(TEXT("function %s%s%s(%s) end\r\n"), *ClassName, bIsStatic ? TEXT(".") : TEXT(":"), *FunctionName, *Properties);
}
else
{
const auto Self = bIsStatic ? TEXT("") : TEXT("self");
const auto Comma = bIsStatic || Properties.IsEmpty() ? TEXT("") : TEXT(", ");
Ret += FString::Printf(TEXT("%s[\"%s\"] = function(%s%s%s) end\r\n"), *ClassName, *FunctionName, Self, Comma, *Properties);
}
return Ret;
}
FString Get(const FProperty* Property)
{
FString Ret;
const UStruct* Struct = Property->GetOwnerStruct();
// access level
FString AccessLevel;
if (Property->HasAnyPropertyFlags(CPF_NativeAccessSpecifierPublic))
AccessLevel = TEXT("public");
else if (Property->HasAllPropertyFlags(CPF_NativeAccessSpecifierProtected))
AccessLevel = TEXT("protected");
else if (Property->HasAllPropertyFlags(CPF_NativeAccessSpecifierPrivate))
AccessLevel = TEXT("private");
else
AccessLevel = Struct->IsNative() ? "private" : "public";
FString TypeName = IntelliSense::GetTypeName(Property);
Ret += FString::Printf(TEXT("---@field %s %s %s"), *AccessLevel, *Property->GetName(), *TypeName);
// comment
const FString& ToolTip = Property->GetMetaData(NAME_ToolTip);
if (!ToolTip.IsEmpty())
Ret += " @" + EscapeComments(ToolTip, true);
return Ret;
}
FString GetUE(const TArray<const UField*> AllTypes)
{
FString Content = "UE = {";
for (const auto Type : AllTypes)
{
if (!Type->IsNative())
continue;
const auto Name = GetTypeName(Type);
Content += FString::Printf(TEXT("\r\n ---@type %s\r\n"), *Name);
Content += FString::Printf(TEXT(" %s = nil,\r\n"), *Name);
}
Content += "}\r\n";
return Content;
}
FString GetTypeName(const UObject* Field)
{
if (!Field)
return "";
if (!Field->IsNative() && Field->GetName().EndsWith("_C"))
return Field->GetName();
const UStruct* Struct = Cast<UStruct>(Field);
if (Struct)
return Struct->GetPrefixCPP() + Struct->GetName();
return Field->GetName();
}
FString GetTypeName(const FProperty* Property)
{
if (!Property)
return "Unknown";
if (CastField<FByteProperty>(Property))
return "integer";
if (CastField<FInt8Property>(Property))
return "integer";
if (CastField<FInt16Property>(Property))
return "integer";
if (CastField<FIntProperty>(Property))
return "integer";
if (CastField<FInt64Property>(Property))
return "integer";
if (CastField<FUInt16Property>(Property))
return "integer";
if (CastField<FUInt32Property>(Property))
return "integer";
if (CastField<FUInt64Property>(Property))
return "integer";
if (CastField<FFloatProperty>(Property))
return "number";
if (CastField<FDoubleProperty>(Property))
return "number";
if (CastField<FEnumProperty>(Property))
return ((FEnumProperty*)Property)->GetEnum()->GetName();
if (CastField<FBoolProperty>(Property))
return TEXT("boolean");
if (CastField<FClassProperty>(Property))
{
const UClass* Class = ((FClassProperty*)Property)->MetaClass;
return FString::Printf(TEXT("TSubclassOf<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FSoftObjectProperty>(Property))
{
if (((FSoftObjectProperty*)Property)->PropertyClass->IsChildOf(UClass::StaticClass()))
{
const UClass* Class = ((FSoftClassProperty*)Property)->MetaClass;
return FString::Printf(TEXT("TSoftClassPtr<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
const UClass* Class = ((FSoftObjectProperty*)Property)->PropertyClass;
return FString::Printf(TEXT("TSoftObjectPtr<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FObjectProperty>(Property))
{
const UClass* Class = ((FObjectProperty*)Property)->PropertyClass;
if (Cast<UBlueprintGeneratedClass>(Class))
{
return FString::Printf(TEXT("%s"), *Class->GetName());
}
return FString::Printf(TEXT("%s%s"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FWeakObjectProperty>(Property))
{
const UClass* Class = ((FWeakObjectProperty*)Property)->PropertyClass;
return FString::Printf(TEXT("TWeakObjectPtr<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FLazyObjectProperty>(Property))
{
const UClass* Class = ((FLazyObjectProperty*)Property)->PropertyClass;
return FString::Printf(TEXT("TLazyObjectPtr<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FInterfaceProperty>(Property))
{
const UClass* Class = ((FInterfaceProperty*)Property)->InterfaceClass;
return FString::Printf(TEXT("TScriptInterface<%s%s>"), Class->GetPrefixCPP(), *Class->GetName());
}
if (CastField<FNameProperty>(Property))
return "string";
if (CastField<FStrProperty>(Property))
return "string";
if (CastField<FTextProperty>(Property))
return "string";
if (CastField<FArrayProperty>(Property))
{
const FProperty* Inner = ((FArrayProperty*)Property)->Inner;
return FString::Printf(TEXT("TArray<%s>"), *GetTypeName(Inner));
}
if (CastField<FMapProperty>(Property))
{
const FProperty* KeyProp = ((FMapProperty*)Property)->KeyProp;
const FProperty* ValueProp = ((FMapProperty*)Property)->ValueProp;
return FString::Printf(TEXT("TMap<%s, %s>"), *GetTypeName(KeyProp), *GetTypeName(ValueProp));
}
if (CastField<FSetProperty>(Property))
{
const FProperty* ElementProp = ((FSetProperty*)Property)->ElementProp;
return FString::Printf(TEXT("TSet<%s>"), *GetTypeName(ElementProp));
}
if (CastField<FStructProperty>(Property))
return ((FStructProperty*)Property)->Struct->GetStructCPPName();
if (CastField<FDelegateProperty>(Property))
return "Delegate";
if (CastField<FMulticastDelegateProperty>(Property))
return "MulticastDelegate";
return "Unknown";
}
FString EscapeComments(const FString Comments, const bool bSingleLine)
{
if (Comments.IsEmpty())
return Comments;
auto Filter = [](const FString Prefix, const FString Line)
{
if (Line.StartsWith("@"))
return FString();
return Prefix + Line;
};
TArray<FString> Lines;
Comments.Replace(TEXT("@"), TEXT("@@")).ParseIntoArray(Lines, TEXT("\n"));
FString Ret = Filter("", Lines[0]);
if (bSingleLine)
{
for (int i = 1; i < Lines.Num(); i++)
Ret += Filter(" ", Lines[i]);
}
else
{
for (int i = 1; i < Lines.Num(); i++)
Ret += Filter("\r\n---", Lines[i]);
}
return Ret;
}
FString EscapeSymbolName(const FString InName)
{
FString Name = InName;
// 和Lua关键字重名就加前缀
for (const auto& Keyword : LuaKeywords)
{
if (Name.Equals(Keyword, ESearchCase::CaseSensitive))
{
Name = TEXT("_") + Name;
break;
}
}
// 替换掉除中文外的特殊字符
for (int32 Index = 0; Index < Name.Len(); Index++)
{
const auto Char = Name[Index];
if ((Char < '0' || Char > '9')
&& (Char < 'a' || Char > 'z')
&& (Char < 'A' || Char > 'Z')
&& Char != '_'
&& Char < 0x100)
{
Name[Index] = TCHAR('_');
}
}
// 数字开头就加前缀
const auto PrefixChar = Name[0];
if (PrefixChar >= '0' && PrefixChar <= '9')
{
Name = TEXT("_") + Name;
}
return Name;
}
bool IsValid(const UFunction* Function)
{
if (!Function)
return false;
if (Function->HasAnyFunctionFlags(FUNC_UbergraphFunction))
return false;
// 这个会导致USubsystemBlueprintLibrary.GetWorldSubsystem之类的被过滤掉
// if (!UEdGraphSchema_K2::CanUserKismetCallFunction(Function))
// return false;
const FString Name = Function->GetName();
if (Name.IsEmpty())
return false;
// 避免运行时生成智能提示,把覆写的函数也生成了
if (Name.EndsWith("__Overridden"))
return false;
return true;
}
bool IsValidFunctionName(const FString Name)
{
if (Name.IsEmpty())
return false;
// 不能有Lua关键字
for (const auto& Keyword : LuaKeywords)
{
if (Name.Equals(Keyword, ESearchCase::CaseSensitive))
return false;
}
// 不能有中文和特殊字符
for (const auto& Char : Name)
{
if ((Char < '0' || Char > '9')
&& (Char < 'a' || Char > 'z')
&& (Char < 'A' || Char > 'Z')
&& Char != '_')
return false;
}
// 不能以数字开头
const auto& PrefixChar = Name[0];
if (PrefixChar >= '0' && PrefixChar <= '9')
return false;
return true;
}
}
}
@@ -0,0 +1,291 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#include "Misc/EngineVersionComparison.h"
#include "UnLuaIntelliSenseGenerator.h"
#if UE_VERSION_NEWER_THAN(5, 1, 0)
#include "AssetRegistry/AssetRegistryModule.h"
#else
#include "AssetRegistryModule.h"
#endif
#include "CoreUObject.h"
#include "UnLua.h"
#include "UnLuaEditorSettings.h"
#include "UnLuaIntelliSense.h"
#include "WidgetBlueprint.h"
#include "Blueprint/WidgetTree.h"
#include "Engine/Blueprint.h"
#include "Interfaces/IPluginManager.h"
#define LOCTEXT_NAMESPACE "UnLuaIntelliSenseGenerator"
TSharedPtr<FUnLuaIntelliSenseGenerator> FUnLuaIntelliSenseGenerator::Singleton;
TSharedRef<FUnLuaIntelliSenseGenerator> FUnLuaIntelliSenseGenerator::Get()
{
if (!Singleton.IsValid())
Singleton = MakeShareable(new FUnLuaIntelliSenseGenerator);
return Singleton.ToSharedRef();
}
void FUnLuaIntelliSenseGenerator::Initialize()
{
if (bInitialized)
return;
OutputDir = IPluginManager::Get().FindPlugin("UnLua")->GetBaseDir() + "/Intermediate/IntelliSense";
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry"));
AssetRegistryModule.Get().OnAssetAdded().AddRaw(this, &FUnLuaIntelliSenseGenerator::OnAssetAdded);
AssetRegistryModule.Get().OnAssetRemoved().AddRaw(this, &FUnLuaIntelliSenseGenerator::OnAssetRemoved);
AssetRegistryModule.Get().OnAssetRenamed().AddRaw(this, &FUnLuaIntelliSenseGenerator::OnAssetRenamed);
AssetRegistryModule.Get().OnAssetUpdated().AddRaw(this, &FUnLuaIntelliSenseGenerator::OnAssetUpdated);
bInitialized = true;
}
void FUnLuaIntelliSenseGenerator::UpdateAll()
{
const FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry"));
FARFilter Filter;
#if UE_VERSION_OLDER_THAN(5, 1, 0)
Filter.ClassNames.Add(UBlueprint::StaticClass()->GetFName());
Filter.ClassNames.Add(UWidgetBlueprint::StaticClass()->GetFName());
#else
Filter.ClassPaths.Add(UBlueprint::StaticClass()->GetClassPathName());
Filter.ClassPaths.Add(UWidgetBlueprint::StaticClass()->GetClassPathName());
#endif
TArray<FAssetData> BlueprintAssets;
TArray<const UField*> NativeTypes;
AssetRegistryModule.Get().GetAssets(Filter, BlueprintAssets);
CollectTypes(NativeTypes);
auto TotalCount = BlueprintAssets.Num() + NativeTypes.Num();
if (TotalCount == 0)
return;
TotalCount++;
FScopedSlowTask SlowTask(TotalCount, LOCTEXT("GeneratingBlueprintsIntelliSense", "Generating Blueprints InstelliSense"));
SlowTask.MakeDialog();
for (int32 i = 0; i < BlueprintAssets.Num(); i++)
{
if (SlowTask.ShouldCancel())
break;
OnAssetUpdated(BlueprintAssets[i]);
SlowTask.EnterProgressFrame();
}
for (const auto Type : NativeTypes)
{
if (SlowTask.ShouldCancel())
break;
Export(Type);
SlowTask.EnterProgressFrame();
}
if (SlowTask.ShouldCancel())
return;
ExportUE(NativeTypes);
ExportUnLua();
SlowTask.EnterProgressFrame();
}
bool FUnLuaIntelliSenseGenerator::IsBlueprint(const FAssetData& AssetData)
{
#if UE_VERSION_OLDER_THAN(5, 1, 0)
const FName AssetClass = AssetData.AssetClass;
return AssetClass == UBlueprint::StaticClass()->GetFName() || AssetClass == UWidgetBlueprint::StaticClass()->GetFName();
#else
const auto AssetClassPath = AssetData.AssetClassPath.ToString();
return AssetClassPath == UBlueprint::StaticClass()->GetName() || AssetClassPath == UWidgetBlueprint::StaticClass()->GetName();
#endif
}
bool FUnLuaIntelliSenseGenerator::ShouldExport(const FAssetData& AssetData, bool bLoad)
{
const auto& Settings = *GetDefault<UUnLuaEditorSettings>();
if (!Settings.bGenerateIntelliSense)
return false;
if (!IsBlueprint(AssetData))
return false;
const auto Asset = AssetData.FastGetAsset(bLoad);
if (!Asset)
return false;
const auto Blueprint = Cast<UBlueprint>(Asset);
if (!Blueprint)
return false;
if (Blueprint->SkeletonGeneratedClass || Blueprint->GeneratedClass)
return true;
return false;
}
void FUnLuaIntelliSenseGenerator::Export(const UBlueprint* Blueprint)
{
Export(Blueprint->GeneratedClass);
}
void FUnLuaIntelliSenseGenerator::Export(const UField* Field)
{
#if ENGINE_MAJOR_VERSION > 4 || (ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 26)
const UPackage* Package = Field->GetPackage();
#else
const UPackage* Package = (UPackage*)Field->GetTypedOuter(UPackage::StaticClass());
#endif
auto ModuleName = Package->GetName();
if (!Field->IsNative())
{
int32 LastSlashIndex;
if (ModuleName.FindLastChar('/', LastSlashIndex))
ModuleName.LeftInline(LastSlashIndex);
}
FString FileName = UnLua::IntelliSense::GetTypeName(Field);
if (FileName.EndsWith("_C"))
FileName.LeftChopInline(2);
const FString Content = UnLua::IntelliSense::Get(Field);
SaveFile(ModuleName, FileName, Content);
}
void FUnLuaIntelliSenseGenerator::ExportUE(const TArray<const UField*> Types)
{
const FString Content = UnLua::IntelliSense::GetUE(Types);
SaveFile("", "UE", Content);
}
void FUnLuaIntelliSenseGenerator::ExportUnLua()
{
const auto ContentDir = IPluginManager::Get().FindPlugin(TEXT("UnLua"))->GetContentDir();
const auto SrcDir = ContentDir / "IntelliSense";
const auto DstDir = OutputDir;
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
if (!PlatformFile.DirectoryExists(*SrcDir))
return;
PlatformFile.CopyDirectoryTree(*DstDir, *SrcDir, true);
}
void FUnLuaIntelliSenseGenerator::CollectTypes(TArray<const UField*>& Types)
{
for (TObjectIterator<UClass> It; It; ++It)
{
const UClass* Class = *It;
const FString ClassName = Class->GetName();
// ReSharper disable StringLiteralTypo
if (ClassName.StartsWith("SKEL_")
|| ClassName.StartsWith("PLACEHOLDER-CLASS")
|| ClassName.StartsWith("REINST_")
|| ClassName.StartsWith("TRASHCLASS_")
|| ClassName.StartsWith("HOTRELOADED_")
)
{
// skip nonsense types
continue;
}
// ReSharper restore StringLiteralTypo
Types.Add(Class);
}
for (TObjectIterator<UScriptStruct> It; It; ++It)
{
const UScriptStruct* ScriptStruct = *It;
Types.Add(ScriptStruct);
}
for (TObjectIterator<UEnum> It; It; ++It)
{
const UEnum* Enum = *It;
Types.Add(Enum);
}
}
void FUnLuaIntelliSenseGenerator::SaveFile(const FString& ModuleName, const FString& FileName, const FString& GeneratedFileContent)
{
IFileManager& FileManager = IFileManager::Get();
const FString Directory = OutputDir / ModuleName;
if (!FileManager.DirectoryExists(*Directory))
FileManager.MakeDirectory(*Directory);
const FString FilePath = FString::Printf(TEXT("%s/%s.lua"), *Directory, *FileName);
FString FileContent;
FFileHelper::LoadFileToString(FileContent, *FilePath);
if (FileContent != GeneratedFileContent)
FFileHelper::SaveStringToFile(GeneratedFileContent, *FilePath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
}
void FUnLuaIntelliSenseGenerator::DeleteFile(const FString& ModuleName, const FString& FileName)
{
IFileManager& FileManager = IFileManager::Get();
const FString Directory = OutputDir / ModuleName;
if (!FileManager.DirectoryExists(*Directory))
FileManager.MakeDirectory(*Directory);
const FString FilePath = FString::Printf(TEXT("%s/%s.lua"), *Directory, *FileName);
if (FileManager.FileExists(*FilePath))
FileManager.Delete(*FilePath);
}
void FUnLuaIntelliSenseGenerator::OnAssetAdded(const FAssetData& AssetData)
{
if (!ShouldExport(AssetData))
return;
OnAssetUpdated(AssetData);
TArray<const UField*> Types;
CollectTypes(Types);
ExportUE(Types);
}
void FUnLuaIntelliSenseGenerator::OnAssetRemoved(const FAssetData& AssetData)
{
if (!ShouldExport(AssetData))
return;
DeleteFile(FString("/Game"), AssetData.AssetName.ToString());
}
void FUnLuaIntelliSenseGenerator::OnAssetRenamed(const FAssetData& AssetData, const FString& OldPath)
{
if (!ShouldExport(AssetData))
return;
//remove old Blueprint name
const FString OldPackageName = FPackageName::GetShortName(OldPath);
DeleteFile("/Game", OldPackageName);
//update new name
OnAssetUpdated(AssetData);
}
void FUnLuaIntelliSenseGenerator::OnAssetUpdated(const FAssetData& AssetData)
{
if (!ShouldExport(AssetData, true))
return;
UBlueprint* Blueprint = LoadObject<UBlueprint>(nullptr, *AssetData.GetSoftObjectPath().ToString());
if (!Blueprint)
return;
Export(Blueprint);
}
@@ -0,0 +1,32 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "Commandlets/Commandlet.h"
#include "UnLuaIntelliSenseCommandlet.generated.h"
UCLASS()
class UUnLuaIntelliSenseCommandlet : public UCommandlet
{
GENERATED_UCLASS_BODY()
public:
virtual int32 Main(const FString& Params) override;
private:
void SaveFile(const FString &ModuleName, const FString &FileName, const FString &GeneratedFileContent);
FString IntermediateDir;
};
@@ -0,0 +1,53 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreMinimal.h"
namespace UnLua
{
namespace IntelliSense
{
UNLUAEDITOR_API FString Get(const UBlueprint* Blueprint);
UNLUAEDITOR_API FString Get(const UField* Field);
UNLUAEDITOR_API FString Get(const UEnum* Enum);
UNLUAEDITOR_API FString Get(const UStruct* Struct);
UNLUAEDITOR_API FString Get(const UScriptStruct* ScriptStruct);
UNLUAEDITOR_API FString Get(const UClass* Class);
UNLUAEDITOR_API FString Get(const UFunction* Function, FString ForceClassName = "");
UNLUAEDITOR_API FString Get(const FProperty* Property);
UNLUAEDITOR_API FString GetUE(const TArray<const UField*> AllTypes);
UNLUAEDITOR_API FString GetTypeName(const UObject* Field);
UNLUAEDITOR_API FString GetTypeName(const FProperty* Property);
UNLUAEDITOR_API FString EscapeComments(const FString Comments, bool bSingleLine);
UNLUAEDITOR_API FString EscapeSymbolName(const FString InName);
UNLUAEDITOR_API bool IsValid(const UFunction* Function);
UNLUAEDITOR_API bool IsValidFunctionName(const FString Name);
}
}
@@ -0,0 +1,66 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
#pragma once
#include "CoreUObject.h"
class UBlueprint;
class UWidgetBlueprint;
class FUnLuaIntelliSenseGenerator
{
public:
FUnLuaIntelliSenseGenerator()
: bInitialized(false)
{
}
static TSharedRef<FUnLuaIntelliSenseGenerator> Get();
// Update all Blueprints from command
void UpdateAll();
void Initialize();
private:
static TSharedPtr<FUnLuaIntelliSenseGenerator> Singleton;
static bool IsBlueprint(const FAssetData& AssetData);
static bool ShouldExport(const FAssetData& AssetData, bool bLoad = false);
void Export(const UBlueprint* Blueprint);
void Export(const UField* Field);
void ExportUE(const TArray<const UField*> Types);
void ExportUnLua();
void CollectTypes(TArray<const UField*> &Types);
// File helper
void SaveFile(const FString& ModuleName, const FString& FileName, const FString& GeneratedFileContent);
void DeleteFile(const FString& ModuleName, const FString& FileName);
// Handle asset event
void OnAssetAdded(const FAssetData& AssetData);
void OnAssetRemoved(const FAssetData& AssetData);
void OnAssetRenamed(const FAssetData& AssetData, const FString& OldPath);
void OnAssetUpdated(const FAssetData& AssetData);
FString OutputDir;
bool bInitialized;
};
@@ -0,0 +1,96 @@
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using UnrealBuildTool;
using System.IO;
public class UnLuaEditor : ModuleRules
{
public UnLuaEditor(ReadOnlyTargetRules Target) : base(Target)
{
#if UE_5_2_OR_LATER
IWYUSupport = IWYUSupport.None;
#else
bEnforceIWYU = false;
#endif
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.AddRange(
new string[]
{
}
);
string EngineDir = Path.GetFullPath(Target.RelativeEnginePath);
PrivateIncludePaths.AddRange(
new[]
{
"UnLuaEditor/Private",
"UnLua/Private",
Path.Combine(EngineDir, "Source/Editor/AnimationBlueprintEditor/Private"),
Path.Combine(EngineDir, "Source/Runtime/Slate/Private"),
}
);
PrivateIncludePathModuleNames.AddRange(
new[]
{
"Kismet",
"MainFrame",
"AnimationBlueprintEditor",
"Slate",
"SlateCore",
"Persona",
}
);
PrivateDependencyModuleNames.AddRange(
new[]
{
"Core",
"CoreUObject",
"Engine",
"UnrealEd",
#if UE_5_0_OR_LATER
"DeveloperToolSettings",
#endif
"EditorStyle",
"ApplicationCore",
"Projects",
"InputCore",
"UMG",
"UMGEditor",
"BlueprintGraph",
"Slate",
"SlateCore",
"DirectoryWatcher",
"Networking",
"Sockets",
"UnLua",
"Lua",
"ToolMenus"
}
);
DynamicallyLoadedModuleNames.AddRange(
new[]
{
"Kismet",
"MainFrame",
"AnimationBlueprintEditor",
}
);
}
}