CCFileUtils-apple.mm 15.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011      Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import <Foundation/Foundation.h>

#include "platform/apple/CCFileUtils-apple.h"

#include <ftw.h>

#include <string>
#include <stack>

#include "base/CCDirector.h"
#include "platform/CCFileUtils.h"
#include "platform/CCSAXParser.h"


#define DECLARE_GUARD std::lock_guard<std::recursive_mutex> mutexGuard(_mutex)

NS_CC_BEGIN

struct FileUtilsApple::IMPL {
    IMPL(NSBundle* bundle):bundle_([NSBundle mainBundle]) {}
    void setBundle(NSBundle* bundle) {
        bundle_ = bundle;
    }
    NSBundle* getBundle() const {
        return bundle_;
    }
private:
    NSBundle* bundle_;
};

static id convertCCValueToNSObject(const cocos2d::Value &value);
static cocos2d::Value convertNSObjectToCCValue(id object);

static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict);
static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict);
static void addNSObjectToCCVector(id item, ValueVector& array);
static void addCCValueToNSArray(const Value& value, NSMutableArray *array);

static id convertCCValueToNSObject(const cocos2d::Value &value)
{
    switch (value.getType())
    {
        case Value::Type::NONE:
            return [NSNull null];
            
        case Value::Type::STRING:
            return [NSString stringWithCString:value.asString().c_str() encoding:NSUTF8StringEncoding];
            
        case Value::Type::BYTE:
            return [NSNumber numberWithInt:value.asByte()];
            
        case Value::Type::INTEGER:
            return [NSNumber numberWithInt:value.asInt()];
            
        case Value::Type::UNSIGNED:
            return [NSNumber numberWithUnsignedInt:value.asUnsignedInt()];
            
        case Value::Type::FLOAT:
            return [NSNumber numberWithFloat:value.asFloat()];
            
        case Value::Type::DOUBLE:
            return [NSNumber numberWithDouble:value.asDouble()];
            
        case Value::Type::BOOLEAN:
            return [NSNumber numberWithBool:value.asBool()];
            
        case Value::Type::VECTOR: {
            NSMutableArray *array = [NSMutableArray array];
            const ValueVector &vector = value.asValueVector();
            for (const auto &e : vector) {
                addCCValueToNSArray(e, array);
            }
            return array;
        }
            
        case Value::Type::MAP: {
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
            const ValueMap &map = value.asValueMap();
            for (auto& iter : map) {
                addCCValueToNSDictionary(iter.first, iter.second, dictionary);
            }
            return dictionary;
        }
            
        case Value::Type::INT_KEY_MAP:
            break;
    }
    
    return [NSNull null];
}

static cocos2d::Value convertNSObjectToCCValue(id item)
{
    // add string value into array
    if ([item isKindOfClass:[NSString class]])
    {
        return Value([item UTF8String]);
    }
    
    // add number value into array(such as int, float, bool and so on)
    // the value is a number
    if ([item isKindOfClass:[NSNumber class]])
    {
        NSNumber* num = item;
        const char* numType = [num objCType];
        if(num == (void*)kCFBooleanFalse || num == (void*)kCFBooleanTrue)
        {
            bool v = [num boolValue];
            return Value(v);
        }
        else if(strcmp(numType, @encode(float)) == 0)
        {
            return Value([num floatValue]);
        }
        else if(strcmp(numType, @encode(double)) == 0)
        {
            return Value([num doubleValue]);
        }
        else
        {
            return Value([num intValue]);
        }
    }
    
    
    // add dictionary value into array
    if ([item isKindOfClass:[NSDictionary class]])
    {
        ValueMap dict;
        for (id subKey in [item allKeys])
        {
            id subValue = [item objectForKey:subKey];
            addNSObjectToCCMap(subKey, subValue, dict);
        }
        
        return Value(dict);
    }
    
    // add array value into array
    if ([item isKindOfClass:[NSArray class]])
    {
        ValueVector subArray;
        for (id subItem in item)
        {
            addNSObjectToCCVector(subItem, subArray);
        }
        return Value(subArray);
    }
    
    return Value::Null;
}

static void addNSObjectToCCVector(id item, ValueVector& array)
{
    array.push_back(convertNSObjectToCCValue(item));
}

static void addCCValueToNSArray(const Value& value, NSMutableArray *array)
{
    [array addObject:convertCCValueToNSObject(value)];
}

static void addNSObjectToCCMap(id nsKey, id nsValue, ValueMap& dict)
{
    // the key must be a string
    CCASSERT([nsKey isKindOfClass:[NSString class]], "The key should be a string!");
    std::string key = [nsKey UTF8String];
    dict[key] = convertNSObjectToCCValue(nsValue);
}

static void addCCValueToNSDictionary(const std::string& key, const Value& value, NSMutableDictionary *dict)
{
    NSString *NSkey = [NSString stringWithCString:key.c_str() encoding:NSUTF8StringEncoding];
    [dict setObject:convertCCValueToNSObject(value) forKey:NSkey];
}


FileUtilsApple::FileUtilsApple() : pimpl_(new IMPL([NSBundle mainBundle])) {
}

FileUtilsApple::~FileUtilsApple() = default;

#if CC_FILEUTILS_APPLE_ENABLE_OBJC
void FileUtilsApple::setBundle(NSBundle* bundle) {
    pimpl_->setBundle(bundle);
}
#endif

#pragma mark - FileUtils

static NSFileManager* s_fileManager = [NSFileManager defaultManager];

FileUtils* FileUtils::getInstance()
{
    if (s_sharedFileUtils == nullptr)
    {
        s_sharedFileUtils = new (std::nothrow) FileUtilsApple();
        if(!s_sharedFileUtils->init())
        {
          delete s_sharedFileUtils;
          s_sharedFileUtils = nullptr;
          CCLOG("ERROR: Could not init CCFileUtilsApple");
        }
    }
    return s_sharedFileUtils;
}


std::string FileUtilsApple::getWritablePath() const
{
    DECLARE_GUARD;
    if (_writablePath.length())
    {
        return _writablePath;
    }

    // save to document folder
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    std::string strRet = [documentsDirectory UTF8String];
    strRet.append("/");
    return strRet;
}

bool FileUtilsApple::isFileExistInternal(const std::string& filePath) const
{
    if (filePath.empty())
    {
        return false;
    }

    bool ret = false;

    if (filePath[0] != '/')
    {
        std::string path;
        std::string file;
        size_t pos = filePath.find_last_of("/");
        if (pos != std::string::npos)
        {
            file = filePath.substr(pos+1);
            path = filePath.substr(0, pos+1);
        }
        else
        {
            file = filePath;
        }

        NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:file.c_str()]
                                                             ofType:nil
                                                        inDirectory:[NSString stringWithUTF8String:path.c_str()]];
        if (fullpath != nil) {
            ret = true;
        }
    }
    else
    {
        // Search path is an absolute path.
        if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:filePath.c_str()]]) {
            ret = true;
        }
    }

    return ret;
}

static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    auto ret = remove(fpath);
    if (ret)
    {
        log("Fail to remove: %s ",fpath);
    }

    return ret;
}

bool FileUtilsApple::removeDirectory(const std::string& path) const
{
    if (path.empty())
    {
        CCLOGERROR("Fail to remove directory, path is empty!");
        return false;
    }

    if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS))
        return false;
    else
        return true;
}

std::string FileUtilsApple::getPathForDirectory(const std::string &dir, const std::string &resolutionDiretory, const std::string &searchPath) const
{
    auto path = searchPath + resolutionDiretory + dir;
    
    if(!path.empty() && path[path.length() -1] == '/') {
        path.erase(path.end() - 1);
    }
    
    if(path[0] == '/')
    {
        BOOL isDir = false;
        if([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:dir.c_str()]
                               isDirectory:&isDir]) {
            return isDir ? path : "";
        }
    }
    else
    {
        NSString *fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:path.c_str()]
                                                           ofType:nil];
        if(fullpath != nil) {
            return [fullpath UTF8String];
        }
    }
    return "";
}


std::string FileUtilsApple::getFullPathForFilenameWithinDirectory(const std::string& directory, const std::string& filename) const
{
    if (directory[0] != '/')
    {
        NSString* fullpath = [pimpl_->getBundle() pathForResource:[NSString stringWithUTF8String:filename.c_str()]
                                                             ofType:nil
                                                        inDirectory:[NSString stringWithUTF8String:directory.c_str()]];
        if (fullpath != nil) {
            return [fullpath UTF8String];
        }
    }
    else
    {
        std::string fullPath = directory+filename;
        // Search path is an absolute path.
        if ([s_fileManager fileExistsAtPath:[NSString stringWithUTF8String:fullPath.c_str()]]) {
            return fullPath;
        }
    }
    return "";
}

ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename) const
{
    auto d(FileUtils::getInstance()->getDataFromFile(filename));
    return getValueMapFromData(reinterpret_cast<char*>(d.getBytes()), static_cast<int>(d.getSize()));
}

ValueMap FileUtilsApple::getValueMapFromData(const char* filedata, int filesize) const
{
    NSData* file = [NSData dataWithBytes:filedata length:filesize];
    NSPropertyListFormat format;
    NSError* error;
    NSDictionary* dict = [NSPropertyListSerialization propertyListWithData:file options:NSPropertyListImmutable format:&format error:&error];

    ValueMap ret;

    if (dict != nil)
    {
        for (id key in [dict allKeys])
        {
            id value = [dict objectForKey:key];
            addNSObjectToCCMap(key, value, ret);
        }
    }
    return ret;
}

bool FileUtilsApple::writeToFile(const ValueMap& dict, const std::string &fullPath) const
{
    return writeValueMapToFile(dict, fullPath);
}

bool FileUtils::writeValueMapToFile(const ValueMap& dict, const std::string& fullPath) const
{
    valueMapCompact(const_cast<ValueMap&>(dict));
    //CCLOG("iOS||Mac Dictionary %d write to file %s", dict->_ID, fullPath.c_str());
    NSMutableDictionary *nsDict = [NSMutableDictionary dictionary];

    for (auto& iter : dict)
    {
        addCCValueToNSDictionary(iter.first, iter.second, nsDict);
    }

    NSString *file = [NSString stringWithUTF8String:fullPath.c_str()];
    // do it atomically
    return [nsDict writeToFile:file atomically:YES];
}

void FileUtilsApple::valueMapCompact(ValueMap& valueMap) const
{
    auto itr = valueMap.begin();
    while(itr != valueMap.end()){
        auto vtype = itr->second.getType();
        switch(vtype){
            case Value::Type::NONE:{
                itr = valueMap.erase(itr);
                continue;
            }
                break;
            case Value::Type::MAP:{
                valueMapCompact(itr->second.asValueMap());
            }
                break;
            case Value::Type::VECTOR:{
                valueVectorCompact(itr->second.asValueVector());
            }
                break;
            default:
                break;
        }
        ++itr;
    }
}

void FileUtilsApple::valueVectorCompact(ValueVector& valueVector) const
{
    auto itr = valueVector.begin();
    while(itr != valueVector.end()){
        auto vtype = (*itr).getType();
        switch(vtype){
            case Value::Type::NONE:{
                itr = valueVector.erase(itr);
                continue;
            }
                break;
            case Value::Type::MAP:{
                valueMapCompact((*itr).asValueMap());
            }
                break;
            case Value::Type::VECTOR:{
                valueVectorCompact((*itr).asValueVector());
            }
                break;
            default:
                break;
        }
        ++itr;
    }
}

bool FileUtils::writeValueVectorToFile(const ValueVector& vecData, const std::string& fullPath) const
{
    NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
    NSMutableArray* array = [NSMutableArray array];

    for (const auto &e : vecData)
    {
        addCCValueToNSArray(e, array);
    }

    [array writeToFile:path atomically:YES];

    return true;
}
ValueVector FileUtilsApple::getValueVectorFromFile(const std::string& filename) const
{
    //    NSString* pPath = [NSString stringWithUTF8String:pFileName];
    //    NSString* pathExtension= [pPath pathExtension];
    //    pPath = [pPath stringByDeletingPathExtension];
    //    pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
    //    fixing cannot read data using Array::createWithContentsOfFile
    std::string fullPath = fullPathForFilename(filename);
    NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
    NSArray* array = [NSArray arrayWithContentsOfFile:path];

    ValueVector ret;

    for (id value in array)
    {
        addNSObjectToCCVector(value, ret);
    }

    return ret;
}

bool FileUtilsApple::createDirectory(const std::string& path) const
{
    CCASSERT(!path.empty(), "Invalid path");
    
    if (isDirectoryExist(path))
        return true;
    
    NSError* error;
    
    bool result = [s_fileManager createDirectoryAtPath:[NSString stringWithUTF8String:path.c_str()] withIntermediateDirectories:YES attributes:nil error:&error];
    
    if(!result && error != nil)
    {
        CCLOGERROR("Fail to create directory \"%s\": %s", path.c_str(), [error.localizedDescription UTF8String]);
    }
    
    return result;
}

NS_CC_END