Add iOS platform (refactor Mac into shared Apple platform impl)

This commit is contained in:
Wojtek Figat
2023-03-15 20:57:44 +01:00
parent dc29ee180e
commit 0ba261d338
84 changed files with 2806 additions and 1623 deletions

View File

@@ -0,0 +1,532 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#if PLATFORM_MAC || PLATFORM_IOS
#include "AppleFileSystem.h"
#include "AppleUtils.h"
#include "Engine/Platform/File.h"
#include "Engine/Core/Types/String.h"
#include "Engine/Core/Types/StringView.h"
#include "Engine/Core/Types/TimeSpan.h"
#include "Engine/Core/Math/Math.h"
#include "Engine/Core/Log.h"
#include "Engine/Utilities/StringConverter.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <cerrno>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
const DateTime UnixEpoch(1970, 1, 1);
bool AppleFileSystem::CreateDirectory(const StringView& path)
{
const StringAsANSI<> pathAnsi(*path, path.Length());
// Skip if already exists
struct stat fileInfo;
if (stat(pathAnsi.Get(), &fileInfo) != -1 && S_ISDIR(fileInfo.st_mode))
{
return false;
}
// Recursively do it all again for the parent directory, if any
const int32 slashIndex = path.FindLast('/');
if (slashIndex > 1)
{
if (CreateDirectory(path.Substring(0, slashIndex)))
{
return true;
}
}
// Create the last directory on the path (the recursive calls will have taken care of the parent directories by now)
return mkdir(pathAnsi.Get(), 0755) != 0 && errno != EEXIST;
}
bool DeletePathTree(const char* path)
{
size_t pathLength;
DIR* dir;
struct stat statPath, statEntry;
struct dirent* entry;
// Stat for the path
stat(path, &statPath);
// If path does not exists or is not dir - exit with status -1
if (S_ISDIR(statPath.st_mode) == 0)
{
// Is not directory
return true;
}
// If not possible to read the directory for this user
if ((dir = opendir(path)) == NULL)
{
// Cannot open directory
return true;
}
// The length of the path
pathLength = strlen(path);
// Iteration through entries in the directory
while ((entry = readdir(dir)) != NULL)
{
// Skip entries "." and ".."
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
// Determinate a full path of an entry
char full_path[256];
ASSERT(pathLength + strlen(entry->d_name) < ARRAY_COUNT(full_path));
strcpy(full_path, path);
strcat(full_path, "/");
strcat(full_path, entry->d_name);
// Stat for the entry
stat(full_path, &statEntry);
// Recursively remove a nested directory
if (S_ISDIR(statEntry.st_mode) != 0)
{
if (DeletePathTree(full_path))
return true;
continue;
}
// Remove a file object
if (unlink(full_path) != 0)
return true;
}
// Remove the devastated directory and close the object of it
if (rmdir(path) != 0)
return true;
closedir(dir);
return false;
}
bool AppleFileSystem::DeleteDirectory(const String& path, bool deleteContents)
{
const StringAsANSI<> pathANSI(*path, path.Length());
if (deleteContents)
return DeletePathTree(pathANSI.Get());
return rmdir(pathANSI.Get()) != 0;
}
bool AppleFileSystem::DirectoryExists(const StringView& path)
{
struct stat fileInfo;
const StringAsANSI<> pathANSI(*path, path.Length());
if (stat(pathANSI.Get(), &fileInfo) != -1)
{
return S_ISDIR(fileInfo.st_mode);
}
return false;
}
bool AppleFileSystem::DirectoryGetFiles(Array<String>& results, const String& path, const Char* searchPattern, DirectorySearchOption option)
{
const StringAsANSI<> pathANSI(*path, path.Length());
const StringAsANSI<> searchPatternANSI(searchPattern);
// Check if use only top directory
if (option == DirectorySearchOption::TopDirectoryOnly)
return getFilesFromDirectoryTop(results, pathANSI.Get(), searchPatternANSI.Get());
return getFilesFromDirectoryAll(results, pathANSI.Get(), searchPatternANSI.Get());
}
bool AppleFileSystem::GetChildDirectories(Array<String>& results, const String& directory)
{
size_t pathLength;
DIR* dir;
struct stat statPath, statEntry;
struct dirent* entry;
const StringAsANSI<> pathANSI(*directory, directory.Length());
const char* path = pathANSI.Get();
// Stat for the path
stat(path, &statPath);
// If path does not exists or is not dir - exit with status -1
if (S_ISDIR(statPath.st_mode) == 0)
{
// Is not directory
return true;
}
// If not possible to read the directory for this user
if ((dir = opendir(path)) == NULL)
{
// Cannot open directory
return true;
}
// The length of the path
pathLength = strlen(path);
// Iteration through entries in the directory
while ((entry = readdir(dir)) != NULL)
{
// Skip entries "." and ".."
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
// Determinate a full path of an entry
char full_path[256];
ASSERT(pathLength + strlen(entry->d_name) < ARRAY_COUNT(full_path));
strcpy(full_path, path);
strcat(full_path, "/");
strcat(full_path, entry->d_name);
// Stat for the entry
stat(full_path, &statEntry);
// Check for directory
if (S_ISDIR(statEntry.st_mode) != 0)
{
// Add directory
results.Add(String(full_path));
}
}
closedir(dir);
return false;
}
bool AppleFileSystem::FileExists(const StringView& path)
{
struct stat fileInfo;
const StringAsANSI<> pathANSI(*path, path.Length());
if (stat(pathANSI.Get(), &fileInfo) != -1)
{
return S_ISREG(fileInfo.st_mode);
}
return false;
}
bool AppleFileSystem::DeleteFile(const StringView& path)
{
const StringAsANSI<> pathANSI(*path, path.Length());
return unlink(pathANSI.Get()) == 0;
}
uint64 AppleFileSystem::GetFileSize(const StringView& path)
{
struct stat fileInfo;
fileInfo.st_size = -1;
const StringAsANSI<> pathANSI(*path, path.Length());
if (stat(pathANSI.Get(), &fileInfo) != -1)
{
// Check for directories
if (S_ISDIR(fileInfo.st_mode))
{
fileInfo.st_size = -1;
}
}
return fileInfo.st_size;
}
bool AppleFileSystem::IsReadOnly(const StringView& path)
{
const StringAsANSI<> pathANSI(*path, path.Length());
if (access(pathANSI.Get(), W_OK) == -1)
{
return errno == EACCES;
}
return false;
}
bool AppleFileSystem::SetReadOnly(const StringView& path, bool isReadOnly)
{
const StringAsANSI<> pathANSI(*path, path.Length());
struct stat fileInfo;
if (stat(pathANSI.Get(), &fileInfo) != -1)
{
if (isReadOnly)
{
fileInfo.st_mode &= ~S_IWUSR;
}
else
{
fileInfo.st_mode |= S_IWUSR;
}
return chmod(pathANSI.Get(), fileInfo.st_mode) == 0;
}
return false;
}
bool AppleFileSystem::MoveFile(const StringView& dst, const StringView& src, bool overwrite)
{
if (!overwrite && FileExists(dst))
{
// Already exists
return true;
}
if (overwrite)
{
unlink(StringAsANSI<>(*dst, dst.Length()).Get());
}
if (rename(StringAsANSI<>(*src, src.Length()).Get(), StringAsANSI<>(*dst, dst.Length()).Get()) != 0)
{
if (errno == EXDEV)
{
if (!CopyFile(dst, src))
{
unlink(StringAsANSI<>(*src, src.Length()).Get());
return false;
}
}
return true;
}
return false;
}
bool AppleFileSystem::CopyFile(const StringView& dst, const StringView& src)
{
const StringAsANSI<> srcANSI(*src, src.Length());
const StringAsANSI<> dstANSI(*dst, dst.Length());
int srcFile, dstFile;
char buffer[4096];
ssize_t readSize;
int cachedError;
srcFile = open(srcANSI.Get(), O_RDONLY);
if (srcFile < 0)
return true;
dstFile = open(dstANSI.Get(), O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (dstFile < 0)
goto out_error;
while (readSize = read(srcFile, buffer, sizeof(buffer)), readSize > 0)
{
char* ptr = buffer;
ssize_t writeSize;
do
{
writeSize = write(dstFile, ptr, readSize);
if (writeSize >= 0)
{
readSize -= writeSize;
ptr += writeSize;
}
else if (errno != EINTR)
{
goto out_error;
}
} while (readSize > 0);
}
if (readSize == 0)
{
if (close(dstFile) < 0)
{
dstFile = -1;
goto out_error;
}
close(srcFile);
// Success
return false;
}
out_error:
cachedError = errno;
close(srcFile);
if (dstFile >= 0)
close(dstFile);
errno = cachedError;
return true;
}
bool AppleFileSystem::getFilesFromDirectoryTop(Array<String>& results, const char* path, const char* searchPattern)
{
size_t pathLength;
struct stat statPath, statEntry;
struct dirent* entry;
// Stat for the path
stat(path, &statPath);
// If path does not exists or is not dir - exit with status -1
if (S_ISDIR(statPath.st_mode) == 0)
{
// Is not directory
return true;
}
// If not possible to read the directory for this user
DIR* dir = opendir(path);
if (dir == NULL)
{
// Cannot open directory
return true;
}
// The length of the path
pathLength = strlen(path);
// Iteration through entries in the directory
while ((entry = readdir(dir)) != NULL)
{
// Skip entries "." and ".."
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
// Determinate a full path of an entry
char fullPath[256];
ASSERT(pathLength + strlen(entry->d_name) < ARRAY_COUNT(fullPath));
strcpy(fullPath, path);
strcat(fullPath, "/");
strcat(fullPath, entry->d_name);
// Stat for the entry
stat(fullPath, &statEntry);
// Check for file
if (S_ISREG(statEntry.st_mode) != 0)
{
// Validate with filter
const int32 fullPathLength = StringUtils::Length(fullPath);
const int32 searchPatternLength = StringUtils::Length(searchPattern);
if (searchPatternLength == 0 || StringUtils::Compare(searchPattern, "*") == 0)
{
// All files
}
else if (searchPattern[0] == '*' && searchPatternLength < fullPathLength && StringUtils::Compare(fullPath + fullPathLength - searchPatternLength + 1, searchPattern + 1, searchPatternLength - 1) == 0)
{
// Path ending
}
else
{
// TODO: implement all cases in a generic way
continue;
}
// Add file
results.Add(String(fullPath));
}
}
closedir(dir);
return false;
}
bool AppleFileSystem::getFilesFromDirectoryAll(Array<String>& results, const char* path, const char* searchPattern)
{
// Find all files in this directory
getFilesFromDirectoryTop(results, path, searchPattern);
size_t pathLength;
DIR* dir;
struct stat statPath, statEntry;
struct dirent* entry;
// Stat for the path
stat(path, &statPath);
// If path does not exists or is not dir - exit with status -1
if (S_ISDIR(statPath.st_mode) == 0)
{
// Is not directory
return true;
}
// If not possible to read the directory for this user
if ((dir = opendir(path)) == NULL)
{
// Cannot open directory
return true;
}
// The length of the path
pathLength = strlen(path);
// Iteration through entries in the directory
while ((entry = readdir(dir)) != NULL)
{
// Skip entries "." and ".."
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
// Determinate a full path of an entry
char full_path[256];
ASSERT(pathLength + strlen(entry->d_name) < ARRAY_COUNT(full_path));
strcpy(full_path, path);
strcat(full_path, "/");
strcat(full_path, entry->d_name);
// Stat for the entry
stat(full_path, &statEntry);
// Check for directory
if (S_ISDIR(statEntry.st_mode) != 0)
{
if (getFilesFromDirectoryAll(results, full_path, searchPattern))
{
closedir(dir);
return true;
}
}
}
closedir(dir);
return false;
}
DateTime AppleFileSystem::GetFileLastEditTime(const StringView& path)
{
struct stat fileInfo;
const StringAsANSI<> pathANSI(*path, path.Length());
if (stat(pathANSI.Get(), &fileInfo) == -1)
{
return DateTime::MinValue();
}
const TimeSpan timeSinceEpoch(0, 0, fileInfo.st_mtime);
return UnixEpoch + timeSinceEpoch;
}
void AppleFileSystem::GetSpecialFolderPath(const SpecialFolder type, String& result)
{
String home;
Platform::GetEnvironmentVariable(TEXT("HOME"), home);
switch (type)
{
case SpecialFolder::Desktop:
result = home / TEXT("/Desktop");
break;
case SpecialFolder::Documents:
result = home / TEXT("/Documents");
break;
case SpecialFolder::Pictures:
result = home / TEXT("/Pictures");
break;
case SpecialFolder::AppData:
case SpecialFolder::LocalAppData:
result = home / TEXT("/Library/Caches");
break;
case SpecialFolder::ProgramData:
result = home / TEXT("/Library/Application Support");
break;
case SpecialFolder::Temporary:
Platform::GetEnvironmentVariable(TEXT("TMPDIR"), result);
break;
}
}
#endif

View File

@@ -0,0 +1,52 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#if PLATFORM_MAC || PLATFORM_IOS
#include "Engine/Platform/Base/FileSystemBase.h"
/// <summary>
/// Apple platform implementation of filesystem service.
/// </summary>
class FLAXENGINE_API AppleFileSystem : public FileSystemBase
{
public:
// [FileSystemBase]
static bool CreateDirectory(const StringView& path);
static bool DeleteDirectory(const String& path, bool deleteContents = true);
static bool DirectoryExists(const StringView& path);
static bool DirectoryGetFiles(Array<String, HeapAllocation>& results, const String& path, const Char* searchPattern, DirectorySearchOption option = DirectorySearchOption::AllDirectories);
static bool GetChildDirectories(Array<String, HeapAllocation>& results, const String& directory);
static bool FileExists(const StringView& path);
static bool DeleteFile(const StringView& path);
static uint64 GetFileSize(const StringView& path);
static bool IsReadOnly(const StringView& path);
static bool SetReadOnly(const StringView& path, bool isReadOnly);
static bool MoveFile(const StringView& dst, const StringView& src, bool overwrite = false);
static bool CopyFile(const StringView& dst, const StringView& src);
public:
/// <summary>
/// Gets last time when file has been modified (in UTC).
/// </summary>
/// <param name="path">The file path to check.</param>
/// <returns>The last write time or DateTime::MinValue() if cannot get data.</returns>
static DateTime GetFileLastEditTime(const StringView& path);
/// <summary>
/// Gets the special folder path.
/// </summary>
/// <param name="type">The folder type.</param>
/// <param name="result">The result full path.</param>
static void GetSpecialFolderPath(const SpecialFolder type, String& result);
private:
static bool getFilesFromDirectoryTop(Array<String, HeapAllocation>& results, const char* path, const char* searchPattern);
static bool getFilesFromDirectoryAll(Array<String, HeapAllocation>& results, const char* path, const char* searchPattern);
};
#endif

View File

@@ -0,0 +1,418 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#if PLATFORM_MAC || PLATFORM_IOS
#include "ApplePlatform.h"
#include "AppleUtils.h"
#include "Engine/Core/Log.h"
#include "Engine/Core/Types/Guid.h"
#include "Engine/Core/Types/String.h"
#include "Engine/Core/Collections/HashFunctions.h"
#include "Engine/Core/Collections/Array.h"
#include "Engine/Core/Collections/Dictionary.h"
#include "Engine/Core/Collections/HashFunctions.h"
#include "Engine/Core/Math/Math.h"
#include "Engine/Core/Math/Rectangle.h"
#include "Engine/Core/Math/Color32.h"
#include "Engine/Platform/CPUInfo.h"
#include "Engine/Platform/MemoryStats.h"
#include "Engine/Platform/StringUtils.h"
#include "Engine/Platform/WindowsManager.h"
#include "Engine/Platform/Clipboard.h"
#include "Engine/Platform/IGuiData.h"
#include "Engine/Platform/Base/PlatformUtils.h"
#include "Engine/Utilities/StringConverter.h"
#include "Engine/Threading/Threading.h"
#include "Engine/Engine/Engine.h"
#include "Engine/Engine/CommandLine.h"
#include <unistd.h>
#include <cstdint>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <mach/mach_time.h>
#include <mach-o/dyld.h>
#include <uuid/uuid.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreGraphics/CoreGraphics.h>
#include <SystemConfiguration/SystemConfiguration.h>
#include <IOKit/IOKitLib.h>
#include <dlfcn.h>
#if CRASH_LOG_ENABLE
#include <execinfo.h>
#endif
CPUInfo Cpu;
String UserLocale;
double SecondsPerCycle;
float ApplePlatform::ScreenScale = 1.0f;
String AppleUtils::ToString(CFStringRef str)
{
if (!str)
return String::Empty;
String result;
const int32 length = CFStringGetLength(str);
if (length > 0)
{
CFRange range = CFRangeMake(0, length);
result.ReserveSpace(length);
CFStringGetBytes(str, range, kCFStringEncodingUTF16LE, '?', false, (uint8*)result.Get(), length * sizeof(Char), nullptr);
}
return result;
}
CFStringRef AppleUtils::ToString(const StringView& str)
{
return CFStringCreateWithBytes(nullptr, (const UInt8*)str.GetText(), str.Length() * sizeof(Char), kCFStringEncodingUTF16LE, false);
}
typedef uint16_t offset_t;
#define align_mem_up(num, align) (((num) + ((align) - 1)) & ~((align) - 1))
bool ApplePlatform::Is64BitPlatform()
{
return PLATFORM_64BITS;
}
CPUInfo ApplePlatform::GetCPUInfo()
{
return Cpu;
}
int32 ApplePlatform::GetCacheLineSize()
{
return Cpu.CacheLineSize;
}
MemoryStats ApplePlatform::GetMemoryStats()
{
MemoryStats result;
int64 value64;
size_t value64Size = sizeof(value64);
if (sysctlbyname("hw.memsize", &value64, &value64Size, nullptr, 0) != 0)
value64 = 1024 * 1024;
result.TotalPhysicalMemory = value64;
int id[] = { CTL_HW, HW_MEMSIZE };
if (sysctl(id, 2, &value64, &value64Size, nullptr, 0) != 0)
value64Size = 1024;
result.UsedPhysicalMemory = value64Size;
xsw_usage swapusage;
size_t swapusageSize = sizeof(swapusage);
result.TotalVirtualMemory = result.TotalPhysicalMemory;
result.UsedVirtualMemory = result.UsedPhysicalMemory;
if (sysctlbyname("vm.swapusage", &swapusage, &swapusageSize, nullptr, 0) == 0)
{
result.TotalVirtualMemory += swapusage.xsu_total;
result.UsedVirtualMemory += swapusage.xsu_used;
}
return result;
}
ProcessMemoryStats ApplePlatform::GetProcessMemoryStats()
{
ProcessMemoryStats result;
result.UsedPhysicalMemory = 1024;
result.UsedVirtualMemory = 1024;
return result;
}
uint64 ApplePlatform::GetCurrentThreadID()
{
return (uint64)pthread_mach_thread_np(pthread_self());
}
void ApplePlatform::SetThreadPriority(ThreadPriority priority)
{
// TODO: impl this
}
void ApplePlatform::SetThreadAffinityMask(uint64 affinityMask)
{
// TODO: impl this
}
void ApplePlatform::Sleep(int32 milliseconds)
{
usleep(milliseconds * 1000);
}
double ApplePlatform::GetTimeSeconds()
{
return SecondsPerCycle * mach_absolute_time();
}
uint64 ApplePlatform::GetTimeCycles()
{
return mach_absolute_time();
}
uint64 ApplePlatform::GetClockFrequency()
{
return (uint64)(1.0 / SecondsPerCycle);
}
void ApplePlatform::GetSystemTime(int32& year, int32& month, int32& dayOfWeek, int32& day, int32& hour, int32& minute, int32& second, int32& millisecond)
{
// Query for calendar time
struct timeval time;
gettimeofday(&time, nullptr);
// Convert to local time
struct tm localTime;
localtime_r(&time.tv_sec, &localTime);
// Extract time
year = localTime.tm_year + 1900;
month = localTime.tm_mon + 1;
dayOfWeek = localTime.tm_wday;
day = localTime.tm_mday;
hour = localTime.tm_hour;
minute = localTime.tm_min;
second = localTime.tm_sec;
millisecond = time.tv_usec / 1000;
}
void ApplePlatform::GetUTCTime(int32& year, int32& month, int32& dayOfWeek, int32& day, int32& hour, int32& minute, int32& second, int32& millisecond)
{
// Get the calendar time
struct timeval time;
gettimeofday(&time, nullptr);
// Convert to UTC time
struct tm localTime;
gmtime_r(&time.tv_sec, &localTime);
// Extract time
year = localTime.tm_year + 1900;
month = localTime.tm_mon + 1;
dayOfWeek = localTime.tm_wday;
day = localTime.tm_mday;
hour = localTime.tm_hour;
minute = localTime.tm_min;
second = localTime.tm_sec;
millisecond = time.tv_usec / 1000;
}
bool ApplePlatform::Init()
{
if (UnixPlatform::Init())
return true;
// Init timing
{
mach_timebase_info_data_t info;
mach_timebase_info(&info);
SecondsPerCycle = 1e-9 * (double)info.numer / (double)info.denom;
}
// Get CPU info
int32 value32;
int64 value64;
size_t value32Size = sizeof(value32), value64Size = sizeof(value64);
if (sysctlbyname("hw.packages", &value32, &value32Size, nullptr, 0) != 0)
value32 = 1;
Cpu.ProcessorPackageCount = value32;
if (sysctlbyname("hw.physicalcpu", &value32, &value32Size, nullptr, 0) != 0)
value32 = 1;
Cpu.ProcessorCoreCount = value32;
if (sysctlbyname("hw.logicalcpu", &value32, &value32Size, nullptr, 0) != 0)
value32 = 1;
Cpu.LogicalProcessorCount = value32;
if (sysctlbyname("hw.l1icachesize", &value32, &value32Size, nullptr, 0) != 0)
value32 = 0;
Cpu.L1CacheSize = value32;
if (sysctlbyname("hw.l2cachesize", &value32, &value32Size, nullptr, 0) != 0)
value32 = 0;
Cpu.L2CacheSize = value32;
if (sysctlbyname("hw.l3cachesize", &value32, &value32Size, nullptr, 0) != 0)
value32 = 0;
Cpu.L3CacheSize = value32;
if (sysctlbyname("hw.pagesize", &value32, &value32Size, nullptr, 0) != 0)
value32 = vm_page_size;
Cpu.PageSize = value32;
if (sysctlbyname("hw.cpufrequency_max", &value64, &value64Size, nullptr, 0) != 0)
value64 = GetClockFrequency();
Cpu.ClockSpeed = value64;
if (sysctlbyname("hw.cachelinesize", &value32, &value32Size, nullptr, 0) != 0)
value32 = PLATFORM_CACHE_LINE_SIZE;
Cpu.CacheLineSize = value32;
// Get locale
{
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringRef localeLang = (CFStringRef)CFLocaleGetValue(locale, kCFLocaleLanguageCode);
CFStringRef localeCountry = (CFStringRef)CFLocaleGetValue(locale, kCFLocaleCountryCode);
UserLocale = AppleUtils::ToString(localeLang);
String localeCountryStr = AppleUtils::ToString(localeCountry);
if (localeCountryStr.HasChars())
UserLocale += TEXT("-") + localeCountryStr;
CFRelease(locale);
CFRelease(localeLang);
CFRelease(localeCountry);
}
// Init user
{
String username;
GetEnvironmentVariable(TEXT("USER"), username);
OnPlatformUserAdd(New<User>(username));
}
return false;
}
void ApplePlatform::Tick()
{
}
void ApplePlatform::BeforeExit()
{
}
void ApplePlatform::Exit()
{
}
void ApplePlatform::SetHighDpiAwarenessEnabled(bool enable)
{
// Disable resolution scaling in low dpi mode
if (!enable)
{
CustomDpiScale /= ScreenScale;
ScreenScale = 1.0f;
}
}
String ApplePlatform::GetUserLocaleName()
{
return UserLocale;
}
bool ApplePlatform::GetHasFocus()
{
// Check if any window is focused
ScopeLock lock(WindowsManager::WindowsLocker);
for (auto window : WindowsManager::Windows)
{
if (window->IsFocused())
return true;
}
// Default to true if has no windows open
return WindowsManager::Windows.IsEmpty();
}
void ApplePlatform::CreateGuid(Guid& result)
{
uuid_t uuid;
uuid_generate(uuid);
auto ptr = (uint32*)&uuid;
result.A = ptr[0];
result.B = ptr[1];
result.C = ptr[2];
result.D = ptr[3];
}
bool ApplePlatform::CanOpenUrl(const StringView& url)
{
return false;
}
void ApplePlatform::OpenUrl(const StringView& url)
{
}
String ApplePlatform::GetExecutableFilePath()
{
char buf[PATH_MAX];
uint32 size = PATH_MAX;
String result;
if (_NSGetExecutablePath(buf, &size) == 0)
result.SetUTF8(buf, StringUtils::Length(buf));
return result;
}
String ApplePlatform::GetWorkingDirectory()
{
char buffer[256];
getcwd(buffer, ARRAY_COUNT(buffer));
return String(buffer);
}
bool ApplePlatform::SetWorkingDirectory(const String& path)
{
return chdir(StringAsANSI<>(*path).Get()) != 0;
}
bool ApplePlatform::GetEnvironmentVariable(const String& name, String& value)
{
char* env = getenv(StringAsANSI<>(*name).Get());
if (env)
{
value = String(env);
return false;
}
return true;
}
bool ApplePlatform::SetEnvironmentVariable(const String& name, const String& value)
{
return setenv(StringAsANSI<>(*name).Get(), StringAsANSI<>(*value).Get(), true) != 0;
}
void* ApplePlatform::LoadLibrary(const Char* filename)
{
const StringAsANSI<> filenameANSI(filename);
void* result = dlopen(filenameANSI.Get(), RTLD_LAZY | RTLD_LOCAL);
if (!result)
{
LOG(Error, "Failed to load {0} because {1}", filename, String(dlerror()));
}
return result;
}
void ApplePlatform::FreeLibrary(void* handle)
{
dlclose(handle);
}
void* ApplePlatform::GetProcAddress(void* handle, const char* symbol)
{
return dlsym(handle, symbol);
}
Array<ApplePlatform::StackFrame> ApplePlatform::GetStackFrames(int32 skipCount, int32 maxDepth, void* context)
{
Array<StackFrame> result;
#if CRASH_LOG_ENABLE
void* callstack[120];
skipCount = Math::Min<int32>(skipCount, ARRAY_COUNT(callstack));
int32 maxCount = Math::Min<int32>(ARRAY_COUNT(callstack), skipCount + maxDepth);
int32 count = backtrace(callstack, maxCount);
int32 useCount = count - skipCount;
if (useCount > 0)
{
char** names = backtrace_symbols(callstack + skipCount, useCount);
result.Resize(useCount);
for (int32 i = 0; i < useCount; i++)
{
char* name = names[i];
StackFrame& frame = result[i];
frame.ProgramCounter = callstack[skipCount + i];
frame.ModuleName[0] = 0;
frame.FileName[0] = 0;
frame.LineNumber = 0;
int32 nameLen = Math::Min<int32>(StringUtils::Length(name), ARRAY_COUNT(frame.FunctionName) - 1);
Platform::MemoryCopy(frame.FunctionName, name, nameLen);
frame.FunctionName[nameLen] = 0;
}
free(names);
}
#endif
return result;
}
#endif

View File

@@ -0,0 +1,107 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#if PLATFORM_MAC || PLATFORM_IOS
#include "../Unix/UnixPlatform.h"
/// <summary>
/// The Apple platform implementation and application management utilities.
/// </summary>
class FLAXENGINE_API ApplePlatform : public UnixPlatform
{
public:
static float ScreenScale;
public:
// [UnixPlatform]
FORCE_INLINE static void MemoryBarrier()
{
__sync_synchronize();
}
FORCE_INLINE static int64 InterlockedExchange(int64 volatile* dst, int64 exchange)
{
return __sync_lock_test_and_set(dst, exchange);
}
FORCE_INLINE static int32 InterlockedCompareExchange(int32 volatile* dst, int32 exchange, int32 comperand)
{
return __sync_val_compare_and_swap(dst, comperand, exchange);
}
FORCE_INLINE static int64 InterlockedCompareExchange(int64 volatile* dst, int64 exchange, int64 comperand)
{
return __sync_val_compare_and_swap(dst, comperand, exchange);
}
FORCE_INLINE static int64 InterlockedIncrement(int64 volatile* dst)
{
return __sync_add_and_fetch(dst, 1);
}
FORCE_INLINE static int64 InterlockedDecrement(int64 volatile* dst)
{
return __sync_sub_and_fetch(dst, 1);
}
FORCE_INLINE static int64 InterlockedAdd(int64 volatile* dst, int64 value)
{
return __sync_fetch_and_add(dst, value);
}
FORCE_INLINE static int32 AtomicRead(int32 volatile* dst)
{
return __atomic_load_n(dst, __ATOMIC_RELAXED);
}
FORCE_INLINE static int64 AtomicRead(int64 volatile* dst)
{
return __atomic_load_n(dst, __ATOMIC_RELAXED);
}
FORCE_INLINE static void AtomicStore(int32 volatile* dst, int32 value)
{
__atomic_store(dst, &value, __ATOMIC_SEQ_CST);
}
FORCE_INLINE static void AtomicStore(int64 volatile* dst, int64 value)
{
__atomic_store(dst, &value, __ATOMIC_SEQ_CST);
}
FORCE_INLINE static void Prefetch(void const* ptr)
{
__builtin_prefetch(static_cast<char const*>(ptr));
}
static bool Is64BitPlatform();
static CPUInfo GetCPUInfo();
static int32 GetCacheLineSize();
static MemoryStats GetMemoryStats();
static ProcessMemoryStats GetProcessMemoryStats();
static uint64 GetCurrentThreadID();
static void SetThreadPriority(ThreadPriority priority);
static void SetThreadAffinityMask(uint64 affinityMask);
static void Sleep(int32 milliseconds);
static double GetTimeSeconds();
static uint64 GetTimeCycles();
static uint64 GetClockFrequency();
static void GetSystemTime(int32& year, int32& month, int32& dayOfWeek, int32& day, int32& hour, int32& minute, int32& second, int32& millisecond);
static void GetUTCTime(int32& year, int32& month, int32& dayOfWeek, int32& day, int32& hour, int32& minute, int32& second, int32& millisecond);
static bool Init();
static void Tick();
static void BeforeExit();
static void Exit();
static void SetHighDpiAwarenessEnabled(bool enable);
static String GetUserLocaleName();
static bool GetHasFocus();
static void CreateGuid(Guid& result);
static bool CanOpenUrl(const StringView& url);
static void OpenUrl(const StringView& url);
static Rectangle GetMonitorBounds(const Float2& screenPos);
static Float2 GetDesktopSize();
static Rectangle GetVirtualDesktopBounds();
static String GetMainDirectory();
static String GetExecutableFilePath();
static String GetWorkingDirectory();
static bool SetWorkingDirectory(const String& path);
static bool GetEnvironmentVariable(const String& name, String& value);
static bool SetEnvironmentVariable(const String& name, const String& value);
static void* LoadLibrary(const Char* filename);
static void FreeLibrary(void* handle);
static void* GetProcAddress(void* handle, const char* symbol);
static Array<StackFrame, HeapAllocation> GetStackFrames(int32 skipCount = 0, int32 maxDepth = 60, void* context = nullptr);
};
#endif

View File

@@ -0,0 +1,75 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#if PLATFORM_MAC || PLATFORM_IOS
#include "../Unix/UnixThread.h"
#include <signal.h>
/// <summary>
/// Thread object for Apple platform.
/// </summary>
class FLAXENGINE_API AppleThread : public UnixThread
{
public:
/// <summary>
/// Initializes a new instance of the <see cref="AppleThread"/> class.
/// </summary>
/// <param name="runnable">The runnable.</param>
/// <param name="name">The thread name.</param>
/// <param name="priority">The thread priority.</param>
AppleThread(IRunnable* runnable, const String& name, ThreadPriority priority)
: UnixThread(runnable, name, priority)
{
}
public:
/// <summary>
/// Factory method to create a thread with the specified stack size and thread priority
/// </summary>
/// <param name="runnable">The runnable object to execute</param>
/// <param name="name">Name of the thread</param>
/// <param name="priority">Tells the thread whether it needs to adjust its priority or not. Defaults to normal priority</param>
/// <param name="stackSize">The size of the stack to create. 0 means use the current thread's stack size</param>
/// <returns>Pointer to the new thread or null if cannot create it</returns>
static AppleThread* Create(IRunnable* runnable, const String& name, ThreadPriority priority = ThreadPriority::Normal, uint32 stackSize = 0)
{
return (AppleThread*)Setup(New<AppleThread>(runnable, name, priority), stackSize);
}
protected:
// [UnixThread]
int32 GetThreadPriority(ThreadPriority priority) override
{
switch (priority)
{
case ThreadPriority::Highest:
return 45;
case ThreadPriority::AboveNormal:
return 37;
case ThreadPriority::Normal:
return 31;
case ThreadPriority::BelowNormal:
return 25;
case ThreadPriority::Lowest:
return 20;
}
return 31;
}
int32 Start(pthread_attr_t& attr) override
{
return pthread_create(&_thread, &attr, ThreadProc, this);
}
void KillInternal(bool waitForJoin) override
{
if (waitForJoin)
pthread_join(_thread, nullptr);
pthread_kill(_thread, SIGKILL);
}
};
#endif

View File

@@ -0,0 +1,23 @@
// Copyright (c) 2012-2023 Wojciech Figat. All rights reserved.
#pragma once
#if PLATFORM_MAC || PLATFORM_IOS
#include "Engine/Core/Types/String.h"
#include <CoreFoundation/CoreFoundation.h>
// Apple platform utilities.
class AppleUtils
{
public:
static String ToString(CFStringRef str);
static CFStringRef ToString(const StringView& str);
#if PLATFORM_MAC
static Float2 PosToCoca(const Float2& pos);
static Float2 CocaToPos(const Float2& pos);
static Float2 GetScreensOrigin();
#endif
};
#endif