Beispiel #1
0
void Audio::Create(const String& nameRef)
{
	TCHAR buffer[100];

	String sendString;

	if (nameRef.EndsWith(".mp3")) sendString = String("open \"") + m_FileName + "\" type mpegvideo alias " + m_Alias;
	else if (nameRef.EndsWith(".wav")) sendString = String("open \"") + m_FileName + "\" type waveaudio alias " + m_Alias;
	else if (nameRef.EndsWith(".mid")) sendString = String("open \"") + m_FileName + "\" type sequencer alias " + m_Alias;

	int result = mciSendString(sendString.ToTChar(), 0, 0, 0);	
	if (result != 0) return;
	
	sendString = String("set ") + m_Alias + " time format milliseconds";
	mciSendString(sendString.ToTChar(), 0, 0, 0);

	sendString = String("status ") + m_Alias + " length";
	mciSendString(sendString.ToTChar(), buffer, 100, 0);

	m_Duration = String(buffer).ToInteger();
	
	// Create a window to catch the MM_MCINOTIFY message with
	m_hWnd = CreateWindow(TEXT("STATIC"), TEXT(""), 0, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), 0);
	SetWindowLong(m_hWnd, GWL_WNDPROC, (LONG) AudioProcStatic);	// set the custom message loop (subclassing)
	SetWindowLong(m_hWnd, GWL_USERDATA, (LONG) this);			// set this object as the parameter for the Proc
}
AssetStoragePtr HttpAssetProvider::TryCreateStorage(HashMap<String, String> &storageParams, bool fromNetwork)
{
    if (!storageParams.Contains("src") || !IsValidRef(storageParams["src"], ""))
        return AssetStoragePtr();
    if (storageParams.Contains("type") && storageParams["type"].Compare("HttpAssetStorage", false) != 0)
        return AssetStoragePtr();

    String baseUrl = storageParams["src"];
    if (!baseUrl.EndsWith("/") && baseUrl.Contains("/"))
        baseUrl = baseUrl.Substring(0, baseUrl.FindLast('/')+1);
    if (!baseUrl.EndsWith("/"))
        return AssetStoragePtr();

    String name = UniqueName(storageParams["name"]);

    // @todo liveupdate, liveupload, autodiscoverable etc. when actually needed
    AssetStoragePtr storage = StorageForBaseURL(baseUrl);
    if (!storage)
    {
        storage = AssetStoragePtr(new HttpAssetStorage(framework_->GetContext(), name, baseUrl, storageParams["localdir"]));
        httpStorages_.Push(storage);
    }

    storage->SetReplicated(Urho3D::ToBool(storageParams["replicated"]));
    return storage;
}
Beispiel #3
0
void PixInsightX11Installer::CopyFiles( const String& targetDir, const String& sourceDir )
{
   if ( !targetDir.BeginsWith( '/' ) )
      throw Error( "CopyFiles(): Relative target directory." );
   if ( !sourceDir.BeginsWith( '/' ) )
      throw Error( "CopyFiles(): Relative source directory." );
   if ( targetDir.EndsWith( '/' ) || sourceDir.EndsWith( '/' ) )
      throw Error( "CopyFiles(): Incorrectly terminated directories." );
   if ( !File::DirectoryExists( targetDir ) )
      throw Error( "CopyFiles(): Nonexistent target directory." );
   if ( !File::DirectoryExists( sourceDir ) )
      throw Error( "CopyFiles(): Nonexistent source directory." );

   StringList sourceItems = SearchDirectory( sourceDir );

   size_type sourceDirLen = sourceDir.Length();
   for ( StringList::const_iterator i = sourceItems.Begin(); i != sourceItems.End(); ++i )
   {
      String relSourcePath = *i;
      relSourcePath.DeleteLeft( sourceDirLen );

      String targetPath = targetDir + relSourcePath;
      if ( targetPath.EndsWith( '/' ) )
      {
         /*
          * Create a subdirectory
          */
         targetPath.Delete( targetPath.UpperBound() );
         if ( !File::DirectoryExists( targetPath ) )
         {
            File::CreateDirectory( targetPath );
            String sourcePath = *i;
            sourcePath.Delete( sourcePath.UpperBound() );
            File::CopyTimesAndPermissions( targetPath, sourcePath );
         }
      }
      else
      {
         /*
          * Copy a file
          */
         /*
          * ### N.B. We don't have to create subdirectories here becase they
          * have been reported by SearchDirectory(), and we are creating them
          * before copying files. SearchDirectory() promises that all
          * subdirectories are reported before their contained files.
          */
         /*
         String targetSubdir = File::ExtractDirectory( targetPath );
         if ( targetSubdir.EndsWith( '/' ) )
            targetSubdir.Delete( targetSubdir.UpperBound() );
         if ( !File::DirectoryExists( targetSubdir ) )
            File::CreateDirectory( targetSubdir );
         */
         File::CopyFile( targetPath, *i );
      }
   }
}
Beispiel #4
0
String Path::Combine(const String & path1, const String & path2)
{
    StringBuilder sb(path1.Length()+path2.Length()+2);
    sb.Append(path1);
    if (!path1.EndsWith(L'\\') && !path1.EndsWith(L'/'))
        sb.Append(L'\\');
    sb.Append(path2);
    return sb.ProduceString();
}
Beispiel #5
0
		String Path::Combine(const String & path1, const String & path2)
		{
			if (path1.Length() == 0) return path2;
			StringBuilder sb(path1.Length()+path2.Length()+2);
			sb.Append(path1);
			if (!path1.EndsWith('\\') && !path1.EndsWith('/'))
				sb.Append(PathDelimiter);
			sb.Append(path2);
			return sb.ProduceString();
		}
Beispiel #6
0
Audio::Audio(String const& nameRef) : m_Playing(false), m_Paused(false), m_MustRepeat(false), m_hWnd(0), m_Volume(100)
{	
	if (nameRef.EndsWith(".mp3") || nameRef.EndsWith(".wav") || nameRef.EndsWith(".mid"))
	{
		m_Alias = String("audio") + m_nr++;
		m_FileName = nameRef;

		Create(nameRef);
	}
}
static status_t WriteZipFileAux(zipFile zf, const String & baseName, const Message & msg, int compressionLevel, zip_fileinfo * fileInfo)
{
   for (MessageFieldNameIterator iter = msg.GetFieldNameIterator(); iter.HasData(); iter++)
   {
      const String & fn = iter.GetFieldName();

      uint32 fieldType;
      if (msg.GetInfo(fn, &fieldType) != B_NO_ERROR) return B_ERROR;
      switch(fieldType)
      {
         case B_MESSAGE_TYPE:
         {
            String newBaseName = baseName;
            if ((newBaseName.HasChars())&&(newBaseName.EndsWith('/') == false)) newBaseName += '/';
            newBaseName += fn;

            // Message fields we treat as sub-directories   
            MessageRef subMsg;
            for (int32 i=0; msg.FindMessage(fn, i, subMsg) == B_NO_ERROR; i++) if (WriteZipFileAux(zf, newBaseName, *subMsg(), compressionLevel, fileInfo) != B_NO_ERROR) return B_ERROR;
         }
         break;

         case B_RAW_TYPE:
         {
            String fileName = baseName;
            if ((fileName.HasChars())&&(fileName.EndsWith('/') == false)) fileName += '/';
            fileName += fn;

            const void * data;
            uint32 numBytes;
            for (int32 i=0; msg.FindData(fn, B_RAW_TYPE, i, &data, &numBytes) == B_NO_ERROR; i++)
            {
               if (zipOpenNewFileInZip2(zf,
                                        fileName(),  // file name
                                        fileInfo,    // file info
                                        NULL,        // const void* extrafield_local,
                                        0,           // uInt size_extrafield_local,
                                        NULL,        // const void* extrafield_global,
                                        0,           // uInt size_extrafield_global,
                                        NULL,        // const char* comment,
                                        (compressionLevel>0)?Z_DEFLATED:0,  // int method,
                                        compressionLevel,  // int compressionLevel
                                        0) != ZIP_OK) return B_ERROR;
               if (zipWriteInFileInZip(zf, data, numBytes) != ZIP_OK) return B_ERROR;
               if (zipCloseFileInZip(zf) != ZIP_OK) return B_ERROR;
            }
         }
         break;
      }
   }
   return B_NO_ERROR;
}
   String 
   FileUtilities::Combine(const String &path1, const String &path2)
   {
      String firstHalf = path1;
      String secondHalf = path2;

      if (firstHalf.EndsWith(_T("\\")) || firstHalf.EndsWith(_T("/")))
         firstHalf = firstHalf.Mid(0, firstHalf.GetLength() -1);

      if (secondHalf.StartsWith(_T("\\")) || secondHalf.StartsWith(_T("/")))
         secondHalf = secondHalf.Mid(1);

      String result = firstHalf + "\\" + secondHalf;

      return result;
   }
Beispiel #9
0
void PixInsightX11Installer::DirectorySearch_Recursive( StringList& foundItems, const String& dirPath, const String& baseDir )
{
   if ( dirPath.Has( ".." ) )
      throw Error( "SearchDirectory(): Attempt to redirect outside the base directory." );
   if ( !dirPath.BeginsWith( baseDir ) )
      throw Error( "SearchDirectory(): Attempt to redirect outside the base directory." );
   if ( !File::DirectoryExists( dirPath ) )
      throw Error( "SearchDirectory(): Attempt to search a nonexistent directory." );

   String currentDir = dirPath;
   if ( !currentDir.EndsWith( '/' ) )
      currentDir += '/';

   StringList directories;
   FindFileInfo info;
   for ( File::Find f( currentDir + "*" ); f.NextItem( info ); )
      if ( info.IsDirectory() )
      {
         if ( info.name != "." && info.name != ".." )
         {
            directories.Add( info.name );
            foundItems.Add( currentDir + info.name + '/' );
         }
      }
      else
         foundItems.Add( currentDir + info.name );

   for ( StringList::const_iterator i = directories.Begin(); i != directories.End(); ++i )
      DirectorySearch_Recursive( foundItems, currentDir + *i, baseDir );
}
Beispiel #10
0
void PixInsightX11Installer::RemoveDirectory_Recursive( const String& dirPath, const String& baseDir )
{
   if ( dirPath.Has( ".." ) )
      throw Error( "RemoveDirectory(): Attempt to climb up the filesystem." );
   if ( !dirPath.BeginsWith( baseDir ) )
      throw Error( "RemoveDirectory(): Attempt to redirect outside the base directory." );
   if ( !File::DirectoryExists( dirPath ) )
      throw Error( "RemoveDirectory(): Attempt to remove a nonexistent directory." );

   String currentDir = dirPath;
   if ( !currentDir.EndsWith( '/' ) )
      currentDir += '/';

   FindFileInfo info;
   for ( File::Find f( currentDir + "*" ); f.NextItem( info ); )
   {
      String itemPath = currentDir + info.name;
      if ( info.IsDirectory() )
      {
         if ( info.name != "." && info.name != ".." )
         {
            RemoveDirectory_Recursive( itemPath, baseDir );
            File::RemoveDirectory( itemPath );
         }
      }
      else
      {
         File::Remove( itemPath );
      }
   }
}
bool ResourceOps::CheckCreate2DLevel(const String& resourcePath, const String& resourceName, bool reportError)
{

    Editor* editor = GetSubsystem<Editor>();
    Project* project = editor->GetProject();

    String fullpath = resourcePath + resourceName;
    if (!resourceName.EndsWith(".tmx"))
        fullpath += ".tmx";

    FileSystem* fs = GetSubsystem<FileSystem>();

    if (fs->FileExists(fullpath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("The level:\n\n%s\n\nalready exists", fullpath.CString());
            editor->PostModalError("Create 2D Level Error", errorMsg);
        }

        return false;
    }

    return true;

}
Beispiel #12
0
String PixInsightX11Installer::Unquoted( const String& s )
{
   String r = s;
   if ( s.BeginsWith( '\"' ) )
      if ( s.EndsWith( '\"' ) )
      {
         r.DeleteRight( r.UpperBound() );
         r.DeleteLeft( 1 );
      }
   if ( s.BeginsWith( '\'' ) )
      if ( s.EndsWith( '\'' ) )
      {
         r.DeleteRight( r.UpperBound() );
         r.DeleteLeft( 1 );
      }
   return r;
}
Beispiel #13
0
bool FilterLibrary::IsWritable() const
{
   /*
    * If wheter this is a new library, or the current library file does not
    * exist, or it is a read-only file, then this library is not writable.
    */
   if ( filePath.IsEmpty() )
      return false;
   if ( !File::Exists( filePath ) )
      return false;
   if ( File::IsReadOnly( filePath ) )
      return false;

   /*
    * Do not allow rewriting the default filter collection.
    */
#ifdef __PCL_WINDOWS
   // Windows filesystem is case-insensitive
   if ( filePath.CompareIC( DefaultLibraryPath() ) == 0 )
#else
   if ( filePath == DefaultLibraryPath() )
#endif
      return false;

   /*
    * Attempt to create a file on the same directory where we have the current
    * filter collection file. If we can create a file, then the current filter
    * library is (should be) writable.
    */
   try
   {
      String dirPath = File::ExtractDrive( filePath ) + File::ExtractDirectory( filePath );
      if ( !File::DirectoryExists( dirPath ) ) // ?? cannot happen
         return false;

      if ( !dirPath.EndsWith( '/' ) )
         dirPath += '/';
      String testFileName = dirPath + "test_file";
      if ( File::Exists( testFileName ) )
      {
         String baseName = testFileName;
         unsigned i = 0;
         do
            testFileName = baseName + String( ++i );
         while ( File::Exists( testFileName ) );
      }
      File f;
      f.CreateForWriting( testFileName );
      f.Close();
      File::Remove( testFileName );
      return true;
   }
   catch ( ... )
   {
      return false;
   }
}
int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {
    int realLineNumber = lineNumber;
    String path = fileName;
    if (!path.EndsWith(".js.map"))
        path += ".js.map";
    if (path.EndsWith(".js")) {
        return realLineNumber;
    }
    SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));
    //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
    if (mapFile.Null()) 
    {
        return realLineNumber;
    }    
    String map;
    mapFile->ReadText(map);
    int top = duk_get_top(ctx_);
    duk_get_global_string(ctx_, "require");
    duk_push_string(ctx_, "AtomicEditor/Script/jsutils");
    if (duk_pcall(ctx_, 1))
    {
        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
        duk_set_top(ctx_, top);
        return false;
    }

    duk_get_prop_string(ctx_, -1, "getRealLineNumber");
    duk_push_string(ctx_, map.CString());
    duk_push_int(ctx_, lineNumber);
    bool ok = true;
    if (duk_pcall(ctx_, 2))
    {
        ok = false;
        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
    }
    else
    {
        realLineNumber = duk_to_int(ctx_, -1);
    }
    duk_set_top(ctx_, top);

    return realLineNumber;
}
Beispiel #15
0
StringList PixInsightX11Installer::SearchDirectory( const String& dirPath )
{
   if ( !dirPath.BeginsWith( '/' ) )
      throw Error( "SearchDirectory(): Relative search directory." );
   if ( dirPath.EndsWith( '/' ) )
      throw Error( "SearchDirectory(): Incorrectly terminated directory." );

   StringList foundItems;
   DirectorySearch_Recursive( foundItems, dirPath, dirPath );
   return foundItems;
}
Beispiel #16
0
static void DoSearch(const String & path, Queue<String> & codes)
{
   Directory d(path());
   if (d.IsValid())
   {
      const char * nextName;
      while((nextName = d.GetCurrentFileName()) != NULL)
      {
         if (nextName[0] != '.')
         {
            String subPath = path + GetFilePathSeparator() + nextName;
            FilePathInfo fpi(subPath());
                 if (fpi.IsDirectory()) DoSearch(subPath, codes);
            else if (fpi.IsRegularFile())
            {
               String iName = nextName; iName = iName.ToLowerCase();
               if ((iName.EndsWith(".c"))||(iName.EndsWith(".cpp"))||(iName.EndsWith(".h"))||(iName.EndsWith(".hpp"))||(iName.EndsWith(".cc"))) CheckFile(subPath, codes);
            }
         }
         d++;
      }
   }
}
	Void DebugOutput(const TChar* format, ...)
	{
		va_list argList;
		va_start(argList, format);

		String buffer;
		buffer.FormatV(format, argList);

		if (!buffer.EndsWith(Text("\n")))
		{
			buffer += Text("\n");
		}
		::OutputDebugString(buffer);
	}
Beispiel #18
0
String CleanupDNSLabel(const String & s, const String & optAdditionalAllowedChars)
{
   const uint32 len = muscleMin(s.Length(), (uint32)63);  // DNS spec says maximum 63 chars per label!
   String ret; if (ret.Prealloc(len) != B_NO_ERROR) return ret;

   const char * p = s();
   for (uint32 i=0; i<len; i++)
   {
      const char c = p[i];
      switch(c)
      {
         case '\'': case '\"': case '(': case ')': case '[': case ']': case '{': case '}':
            // do nothing -- we will omit delimiters
         break;

         default:
                 if ((muscleInRange(c, '0', '9'))||(muscleInRange(c, 'A', 'Z'))||(muscleInRange(c, 'a', 'z'))||(optAdditionalAllowedChars.Contains(c))) ret += c;
            else if ((ret.HasChars())&&(ret.EndsWith('-') == false)) ret += '-';
         break;
      }
   }
   while(ret.EndsWith('-')) ret -= '-';  // remove any trailing dashes
   return ret;
}
Beispiel #19
0
	bool DynLibImpl::Load(const String& libraryPath, String* errorMessage)
	{
		String path = libraryPath;
		if (!path.EndsWith(".dll"))
			path += ".dll";

		m_handle = LoadLibraryExW(path.GetWideString().data(), nullptr, (File::IsAbsolute(path)) ? LOAD_WITH_ALTERED_SEARCH_PATH : 0);
		if (m_handle)
			return true;
		else
		{
			*errorMessage = Error::GetLastSystemError();
			return false;
		}
	}
void BuildBase::ScanResourceDirectory(const String& resourceDir)
{
    Vector<String> fileNames;
    FileSystem* fileSystem = GetSubsystem<FileSystem>();
    fileSystem->ScanDir(fileNames, resourceDir, "*.*", SCAN_FILES, true);

    for (unsigned i = 0; i < fileNames.Size(); i++)
    {
        const String& filename = fileNames[i];

        for (unsigned j = 0; j < resourceEntries_.Size(); j++)
        {
            const BuildResourceEntry* entry = resourceEntries_[j];

            if (entry->packagePath_ == filename)
            {
                BuildWarn(ToString("Resource Path: %s already exists", filename.CString()));
                continue;
            }
        }

        // TODO: Add additional filters
        if (GetExtension(filename) == ".psd")
            continue;

        BuildResourceEntry* newEntry = new BuildResourceEntry;

// BEGIN LICENSE MANAGEMENT
        if (GetExtension(filename) == ".mdl")
        {
            containsMDL_ = true;
        }
// END LICENSE MANAGEMENT

        newEntry->absolutePath_ = resourceDir + filename;
        newEntry->resourceDir_ = resourceDir;

        if (resourceDir.EndsWith("/Cache/"))
            newEntry->packagePath_ = "Cache/" + filename;
        else
            newEntry->packagePath_ = filename;

        resourceEntries_.Push(newEntry);

        //LOGINFOF("Adding resource: %s : %s", newEntry->absolutePath_.CString(), newEntry->packagePath_.CString());
    }
}
Beispiel #21
0
   bool 
   NameChanger::UpdateDomainName_(String &sAddress, const String &oldDomainName, const String& newDomainName)
   {

      if (!sAddress.EndsWith("@" + oldDomainName))
      {
         // Doesn't seem to contain the domain name.
         return false;
      }

      int atPos = sAddress.Find(_T("@"));


      // Remove the current domain name.
      sAddress = sAddress.Mid(0, atPos+1);

      // Add the new one.
      sAddress += newDomainName;

      return true;
   }
void ParseCommand(String input, String &command, StringVector &parameters)
{
    input = input.Trimmed();
    if (input.Empty())
        return;

    uint parenPos = input.Find('(', 0);
    uint spacePos = input.Find(' ', 0);
    if (parenPos == String::NPOS && spacePos == String::NPOS)
    {
        command = input;
        return;
    }
    StringVector parts;
    if (parenPos != String::NPOS && parenPos < spacePos)
    {
        uint parenEndPos = input.FindLast(')');
        String insideParens = (parenEndPos != String::NPOS ? 
            input.Substring(parenPos+1, parenEndPos-parenPos-1).Trimmed() : input.Substring(parenPos+1).Trimmed());
        command = input.Substring(0, parenPos).Trimmed();
        // "one, two, three", "one,two,three" and "one two three"
        parts = insideParens.Contains(',') ? insideParens.Split(',') : insideParens.Split(' ');
    }
    else
    {
        command = input.Substring(0, spacePos).Trimmed();
        String remaining = input.Substring(spacePos+1).Trimmed();
        // "one, two, three", "one,two,three" and "one two three"
        parts = remaining.Contains(',') ? remaining.Split(',') : remaining.Split(' ');
    }
    for(StringVector::Iterator iter=parts.Begin(); iter!=parts.End(); ++iter)
    {
        String part = (*iter).Trimmed();
        if (part.EndsWith(","))
            part = part.Substring(0, part.Length()-1);
        if (!part.Empty())
            parameters.Push(part);
    }
}
bool ResourceOps::CheckCreateScript(const String& resourcePath, const String& resourceName, bool reportError)
{

    Editor* editor = GetSubsystem<Editor>();
    Project* project = editor->GetProject();

    String fullpath = resourcePath + resourceName;
    if (!resourceName.EndsWith(".js"))
        fullpath += ".js";

    FileSystem* fs = GetSubsystem<FileSystem>();

    if (fs->FileExists(fullpath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("The script:\n\n%s\n\nalready exists", fullpath.CString());
            editor->PostModalError("Create Script Error", errorMsg);
        }

        return false;
    }

    if (!project->IsScriptsDirOrFile(resourcePath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("Scripts must reside in or in a subfolder of the Scripts folder");
            editor->PostModalError("Create Script Error", errorMsg);
        }

        return false;
    }

    return true;

}
void ResourceOps::HandleCreate2DLevel(const String& resourcePath, const String& resourceName,
                                        bool navigateToResource, bool reportError)
{
    Editor* editor = GetSubsystem<Editor>();

    if (!CheckCreate2DLevel(resourcePath, resourceName, reportError))
        return;

    ResourceCache* cache = GetSubsystem<ResourceCache>();

    SharedPtr<File> srcFile = cache->GetFile("ClockworkEditor/templates/template_empty.tmx");
    if (srcFile.Null() || !srcFile->IsOpen())
    {
        editor->PostModalError("Create Script Error", "Could not open module template");
        return;
    }

    String fullpath = resourcePath + resourceName;
    if (!resourceName.EndsWith(".tmx"))
        fullpath += ".tmx";

    if (!CopyFile(srcFile, fullpath))
    {
        String errorMsg;
        errorMsg.AppendWithFormat("Error copying template:\n\n%s\n\nto:\n\n%s",
                                  "ClockworkEditor/template_empty.tmx", fullpath.CString());
        editor->PostModalError("Create 2D Level Error", errorMsg);
        return;
    }

    if (navigateToResource)
    {
        //ResourceFrame* rframe = GetSubsystem<MainFrame>()->GetResourceFrame();
        //rframe->EditResource(fullpath);
    }

    GetSubsystem<MainFrame>()->GetProjectFrame()->Refresh();

}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Increments the current file name
// a4.png --> a5.png
// a04.png --> a05.png
// a4b.png --> a5b.png
// xyz.png --> xyz 2.png
void AskForFileNameDlg::IncrementFileName()
{
	if( !m_incrementFileName )
	{
		return;
	}

	String strName = m_fileName;
	String strExt = ".png";
	if( strName.EndsWith(strExt) )
	{
		int nStop = m_fileName.GetLength() - strExt.GetLength();
		strName = strName.Left(nStop);
	}

	int nGroupStart, nGroupStop;
	if( !GetDigitGroup(strName, nGroupStart, nGroupStop) )
	{
		m_fileName = strName + " 2.png";
		return;
	}

	String strNum = strName.Mid(nGroupStart, nGroupStop - nGroupStart);
	int32 nNum;
	if( !strNum.ToInt(nNum) )
	{
		m_fileName = strName + " 2.png";
		return;
	}

	// Check if there are leading 0
	String strSameNum = String::FromInt(nNum);
	String strPrefix = strNum.ReplaceAll(strSameNum, "");
	String strNewNum = strPrefix + String::FromInt(nNum + 1);

	m_fileName = strName.Left(nGroupStart) + strNewNum + strName.Mid(nGroupStop) + ".png";
}
Beispiel #26
0
bool JSVM::ExecuteScript(const String& scriptPath)
{
    String path = scriptPath;
    if (!path.StartsWith("Scripts/"))
        path = "Scripts/" + path;

    if (!path.EndsWith(".js"))
        path += ".js";

    SharedPtr<File> file (GetSubsystem<ResourceCache>()->GetFile(path));

    if (file.Null())
    {
        return false;
    }

    String source;

    file->ReadText(source);
    source.Append('\n');

    duk_push_string(ctx_, file->GetFullPath().CString());
    if (duk_eval_raw(ctx_, source.CString(), 0,
                     DUK_COMPILE_EVAL | DUK_COMPILE_SAFE | DUK_COMPILE_NOSOURCE | DUK_COMPILE_STRLEN) != 0)
    {
        if (duk_is_object(ctx_, -1))
            SendJSErrorEvent(path);

        duk_pop(ctx_);
        return false;
    }

    duk_pop(ctx_);

    return true;
}
bool ZipAssetBundle::DeserializeFromDiskSource()
{
    if (!assetAPI_->Cache())
    {
        LogError("ZipAssetBundle::DeserializeFromDiskSource: Cannot process archive, AssetAPI cache is null.");
        return false;
    }
    else if (DiskSource().Empty())
    {
        LogError("ZipAssetBundle::DeserializeFromDiskSource: Cannot process archive, no disk source for " + Name());
        return false;
    }

    /* We want to detect if the extracted files are already up to date to save time.
       If the last modified date for the sub asset is the same as the parent zip file, 
       we don't extract it. If the zip is re-downloaded from source everything will get unpacked even
       if only one file would have changed inside it. We could do uncompressed size comparisons
       but that is not a absolute guarantee that the file has not changed. We'll be on the safe side
       to unpack the whole zip file. Zip files are meant for deploying the scene and should be touched
       rather rarely. Note that local:// refs are unpacked to cache but the zips disk source is not in the
       cache. Meaning that local:// zip files will always be extracted fully even if the disk source
       was not changed, we don't have a mechanism to get the last modified date properly except from
       the asset cache. For local scenes this should be fine as there is no real need to
       zip the scene up as you already have the disk sources right there in the storage.
       The last modified query will fail if the file is open with zziplib, do it first. */
    uint zipLastModified = assetAPI_->Cache()->LastModified(Name());

    const String diskSourceInternal = Urho3D::GetInternalPath(DiskSource());

    zzip_error_t error = ZZIP_NO_ERROR;
    archive_ = zzip_dir_open(diskSourceInternal.CString(), &error);
    if (CheckAndLogZzipError(error) || CheckAndLogArchiveError(archive_) || !archive_)
    {
        archive_ = 0;
        return false;
    }
    
    int uncompressing = 0;
    
    ZZIP_DIRENT archiveEntry;
    while(zzip_dir_read(archive_, &archiveEntry))
    {
        String relativePath = Urho3D::GetInternalPath(archiveEntry.d_name);
        if (!relativePath.EndsWith("/"))
        {
            String subAssetRef = GetFullAssetReference(relativePath);
            
            ZipArchiveFile file;
            file.relativePath = relativePath;
            file.cachePath = Urho3D::GetInternalPath(assetAPI_->Cache()->DiskSourceByRef(subAssetRef));
            file.lastModified = assetAPI_->Cache()->LastModified(subAssetRef);
            file.compressedSize = archiveEntry.d_csize;
            file.uncompressedSize = archiveEntry.st_size;
            
            /* Mark this file for extraction. If both cache files have valid dates
               and they differ extract. If they have the same date stamp skip extraction.
               Note that file.lastModified will be non-valid for non cached files so we 
               will cover also missing files. */
            file.doExtract = (zipLastModified > 0 && file.lastModified > 0) ? (zipLastModified != file.lastModified) : true;
            if (file.doExtract)
                uncompressing++;

            files_.Push(file);
            fileCount_++;
        }
    }
    
    // Close the zzip directory ptr
    Close();
    
    // If the zip file was empty we don't want IsLoaded to fail on the files_ check.
    // The bundle loaded fine but there was no content, log a warning.
    if (files_.Empty())
    {
        LogWarning("ZipAssetBundle: Bundle loaded but does not contain any files " + Name());
        files_.Push(ZipArchiveFile());
        Loaded.Emit(this);
        return true;
    }
    
    // Don't spin the worker if all sub assets are up to date in cache.
    if (uncompressing > 0)
    {   
        // Now that the file info has been read, continue in a worker thread.
        LogDebug("ZipAssetBundle: File information read for " + Name() + ". File count: " + String(files_.Size()) + ". Starting worker thread to uncompress " + String(uncompressing) + " files.");
        
        // ZipWorker is a QRunnable we can pass to QThreadPool, it will handle scheduling it and deletes it when done.
        worker_ = new ZipWorker(this, zipLastModified, diskSourceInternal, files_);   
        if (!worker_->Run())
        {
            LogError("ZipAssetBundle: Failed to start worker thread for " + Name());
            files_.Clear();
            return false;
        }

        assetAPI_->GetFramework()->Frame()->Updated.Connect(this, &ZipAssetBundle::CheckDone);
    }
    else
        Loaded.Emit(this);
        
    return true;
}
Beispiel #28
0
ArgumentList ExtractArguments( const StringList& argv, argument_item_mode mode, ArgumentOptions options )
{
   bool noItems             = mode == ArgumentItemMode::NoItems;
   bool itemsAsFiles        = mode == ArgumentItemMode::AsFiles;
   bool itemsAsViews        = mode == ArgumentItemMode::AsViews;
   bool allowWildcards      = !noItems && options.IsFlagSet( ArgumentOption::AllowWildcards );
   bool noPreviews          = itemsAsViews && options.IsFlagSet( ArgumentOption::NoPreviews );
   bool recursiveDirSearch  = itemsAsFiles && allowWildcards && options.IsFlagSet( ArgumentOption::RecursiveDirSearch );
   bool recursiveSearchArgs = recursiveDirSearch && options.IsFlagSet( ArgumentOption::RecursiveSearchArgs );

   // This is the recursive search mode flag, controlled by --r[+|-]
   bool recursiveSearch = false;

   // The list of existing view identifiers, in case itemsAsViews = true.
   SortedStringList imageIds;

   // The list of extracted arguments
   ArgumentList arguments;

   for ( StringList::const_iterator i = argv.Begin(); i != argv.End(); ++i )
   {
      if ( i->StartsWith( '-' ) )
      {
         Argument arg( i->At( 1 ) );

         if ( recursiveSearchArgs && arg.Id() == s_recursiveSearchArg )
         {
            if ( arg.IsSwitch() )
               recursiveSearch = arg.SwitchState();
            else if ( arg.IsLiteral() )
               recursiveSearch = true;
            else
               arguments.Add( arg );
         }
         else
            arguments.Add( arg );
      }
      else
      {
         if ( noItems )
            throw ParseError( "Non-parametric arguments are not allowed", *i  );

         StringList items;

         if ( itemsAsFiles )
         {
            String fileName = *i;
            if ( fileName.StartsWith( '\"' ) )
               fileName.Delete( 0 );
            if ( fileName.EndsWith( '\"' ) )
               fileName.Delete( fileName.UpperBound() );

            fileName.Trim();
            if ( fileName.IsEmpty() )
               throw ParseError( "Empty path specification", *i );

            fileName = File::FullPath( fileName );

            if ( fileName.HasWildcards() )
            {
               if ( !allowWildcards )
                  throw ParseError( "Wildcards not allowed", fileName );

               items = SearchDirectory( fileName, recursiveSearch );
            }
            else
               items.Add( fileName );
         }
         else if ( itemsAsViews )
         {
            String viewId = *i;

            if ( !allowWildcards )
               if ( viewId.HasWildcards() )
                  throw ParseError( "Wildcards not allowed", viewId );

            size_type p = viewId.Find( "->" );

            if ( p != String::notFound )
            {
               if ( noPreviews )
                  throw ParseError( "Preview identifiers not allowed", viewId );

               String imageId = viewId.Left( p );
               if ( imageId.IsEmpty() )
                  throw ParseError( "Missing image identifier", viewId );

               String previewId = viewId.Substring( p+2 );
               if ( previewId.IsEmpty() )
                  throw ParseError( "Missing preview identifier", viewId );

               FindPreviews( items, imageId, previewId );
            }
            else
            {
               if ( viewId.HasWildcards() )
               {
                  Array<ImageWindow> W = ImageWindow::AllWindows();
                  for ( size_type i = 0; i < W.Length(); ++i )
                  {
                     View v = W[i].MainView();
                     if ( String( v.Id() ).WildMatch( viewId ) )
                        AddView( items, v );
                  }
               }
               else
               {
                  ImageWindow w = ImageWindow::WindowById( IsoString( viewId ) );
                  if ( w.IsNull() )
                     throw ParseError( "Image not found", viewId );
                  AddView( items, w.MainView() );
               }
            }
         }
         else
            items.Add( *i );

         Argument arg( *i, items );
         arguments.Add( arg );
      }
   }

   return arguments;
}
Beispiel #29
0
ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
{
    StringHash nameHash(name);
    
    if (type == VS)
    {
        if (vsParser_.HasCombination(name))
        {
            HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Find(nameHash);
            // Create the shader variation now if not created yet
            if (i == vsVariations_.End())
            {
                ShaderCombination combination = vsParser_.GetCombination(name);
                
                i = vsVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, VS))));
                
                String path, fileName, extension;
                SplitPath(GetName(), path, fileName, extension);
                String fullName = path + fileName + "_" + name;
                if (fullName.EndsWith("_"))
                    fullName.Resize(fullName.Length() - 1);
                
                i->second_->SetName(fullName);
                i->second_->SetSourceCode(vsSourceCode_, vsSourceCodeLength_);
                i->second_->SetDefines(combination.defines_, combination.defineValues_);
                
                SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
            }
            
            return i->second_;
        }
        else
            return 0;
    }
    else
    {
        if (psParser_.HasCombination(name))
        {
            HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Find(nameHash);
            // Create the shader variation now if not created yet
            if (i == psVariations_.End())
            {
                ShaderCombination combination = psParser_.GetCombination(name);
                
                i = psVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, PS))));
                
                String path, fileName, extension;
                SplitPath(GetName(), path, fileName, extension);
                String fullName = path + fileName + "_" + name;
                if (fullName.EndsWith("_"))
                    fullName.Resize(fullName.Length() - 1);
                
                i->second_->SetName(fullName);
                i->second_->SetSourceCode(psSourceCode_, psSourceCodeLength_);
                i->second_->SetDefines(combination.defines_, combination.defineValues_);
                
                SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
            }
            
            return i->second_;
        }
        else
            return 0;
    }
}
Beispiel #30
0
int JSVM::GetRealLineNumber(const String& fileName, const int lineNumber) {

    int realLineNumber = lineNumber;

    String mapPath = fileName;

    if (!mapPath.EndsWith(".js.map"))
        mapPath += ".js.map";

    if (mapPath.EndsWith(".js")) {
        return realLineNumber;
    }

    ResourceCache* cache = GetSubsystem<ResourceCache>();

    String path;
    const Vector<String>& searchPaths = GetModuleSearchPaths();
    for (unsigned i = 0; i < searchPaths.Size(); i++)
    {
        String checkPath = searchPaths[i] + mapPath;

        if (cache->Exists(checkPath))
        {
            path = checkPath;
            break;
        }

    }

    if (!path.Length())
        return realLineNumber;


    SharedPtr<File> mapFile(GetSubsystem<ResourceCache>()->GetFile(path));

    //if there's no source map file, maybe you use a pure js, so give an error, or maybe forgot to generate source-maps :(
    if (mapFile.Null())
    {
        return realLineNumber;
    }

    String map;
    mapFile->ReadText(map);
    int top = duk_get_top(ctx_);
    duk_get_global_string(ctx_, "require");
    duk_push_string(ctx_, "AtomicEditor/EditorScripts/Lib/jsutils");
    if (duk_pcall(ctx_, 1))
    {
        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
        duk_set_top(ctx_, top);
        return false;
    }

    duk_get_prop_string(ctx_, -1, "getRealLineNumber");
    duk_push_string(ctx_, map.CString());
    duk_push_int(ctx_, lineNumber);
    bool ok = true;
    if (duk_pcall(ctx_, 2))
    {
        ok = false;
        printf("Error: %s\n", duk_safe_to_string(ctx_, -1));
    }
    else
    {
        realLineNumber = duk_to_int(ctx_, -1);
    }
    duk_set_top(ctx_, top);

    return realLineNumber;
}