Example #1
0
//------------------------------------------------------------------------------
static void getDeviceProperties (const String& deviceID,
                                 unsigned int& minChansOut,
                                 unsigned int& maxChansOut,
                                 unsigned int& minChansIn,
                                 unsigned int& maxChansIn,
                                 Array<uint>& bufSizes,
                                 Array<double>& rates,
                                 bool testOutput,
                                 bool testInput)
{
    minChansOut = maxChansOut = minChansIn = maxChansIn = 0;

    if (deviceID.isEmpty())
        return;

    JUCE_ALSA_LOG ("getDeviceProperties(" << deviceID.toUTF8() << ")");

    snd_pcm_info_t* info;
    snd_pcm_info_alloca (&info);

    if (testOutput)
    {
        snd_pcm_t* pcmHandle;

        if (JUCE_CHECKED_RESULT (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)) >= 0)
        {
            getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
            getDeviceBufferSizes (pcmHandle, bufSizes);
            getDeviceSampleRates (pcmHandle, rates);

            snd_pcm_close (pcmHandle);
        }
    }

    if (testInput)
    {
        snd_pcm_t* pcmHandle;

        if (JUCE_CHECKED_RESULT (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK) >= 0))
        {
            getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);

            if (bufSizes.size() == 0)
                getDeviceBufferSizes (pcmHandle, bufSizes);

            if (rates.size() == 0)
                getDeviceSampleRates (pcmHandle, rates);

            snd_pcm_close (pcmHandle);
        }
    }
}
Example #2
0
JackPort JackClient::registerPort (const String& name, const String& type,
                                   int flags, int bufferSize)
{
    returnValueIfNull (client, JackPort (*this));

    String clientName = name;

    if (clientName.length() >= nameSize())
        clientName = clientName.substring (0, nameSize());

    jack_port_t* const cport = jack_port_register (client, clientName.toUTF8(), type.toUTF8(),
                                                   flags, bufferSize);
    return JackPort (*this, cport);
}
StringArray CURLEasySession::getDirectoryListing()
{
    String remoteUrl (remotePath.upToLastOccurrenceOf ("/", true, false));
    curl_easy_setopt (handle, CURLOPT_URL, remoteUrl.toUTF8().getAddress());

    directoryContentsList.setSize (0);

    curl_easy_setopt (handle, CURLOPT_PROGRESSFUNCTION, 0L);
    curl_easy_setopt (handle, CURLOPT_UPLOAD, 0L);
    curl_easy_setopt (handle, CURLOPT_DIRLISTONLY, 1L);
    curl_easy_setopt (handle, CURLOPT_WRITEDATA, this);
    curl_easy_setopt (handle, CURLOPT_WRITEFUNCTION, directoryListingCallback);

    // perform  the tranfer
    progress = 0.0f;
    CURLcode result = curl_easy_perform (handle);
    reset();

    if (result == CURLE_OK)
    {
        StringArray list;
        list.addLines (directoryContentsList.toString().trim());

        return list;
    }
    else
    {
        return StringArray (curl_easy_strerror (result));
    }
}
Example #4
0
    String stringLiteral (const String& text, int maxLineLength)
    {
        if (text.isEmpty())
            return "String::empty";

        StringArray lines;
        lines.add (text);

        if (maxLineLength > 0)
        {
            while (lines [lines.size() - 1].length() > maxLineLength)
            {
                String& lastLine = lines.getReference (lines.size() - 1);
                const String start (lastLine.substring (0, maxLineLength));
                const String end (lastLine.substring (maxLineLength));
                lastLine = start;
                lines.add (end);
            }
        }

        for (int i = 0; i < lines.size(); ++i)
            lines.getReference(i) = "\"" + addEscapeChars (lines.getReference(i)) + "\"";

        String result (lines.joinIntoString (newLine));

        if (! CharPointer_ASCII::isValidString (text.toUTF8(), std::numeric_limits<int>::max()))
            result = "CharPointer_UTF8 (" + result + ")";

        return result;
    }
Example #5
0
void JUCE_CALLTYPE Thread::setCurrentThreadName (const String& name)
{
   #if JUCE_DEBUG && JUCE_MSVC
    struct
    {
        DWORD dwType;
        LPCSTR szName;
        DWORD dwThreadID;
        DWORD dwFlags;
    } info;

    info.dwType = 0x1000;
    info.szName = name.toUTF8();
    info.dwThreadID = GetCurrentThreadId();
    info.dwFlags = 0;

    __try
    {
        RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
    }
    __except (EXCEPTION_CONTINUE_EXECUTION)
    {}
   #else
    ignoreUnused (name);
   #endif
}
Example #6
0
//==============================================================================
bool Process::openDocument (const String& fileName, const String& parameters)
{
    String cmdString (fileName.replace (" ", "\\ ",false));
    cmdString << " " << parameters;

    if (URL::isProbablyAWebsiteURL (fileName)
         || cmdString.startsWithIgnoreCase ("file:")
         || URL::isProbablyAnEmailAddress (fileName))
    {
        // create a command that tries to launch a bunch of likely browsers
        const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };

        StringArray cmdLines;

        for (int i = 0; i < numElementsInArray (browserNames); ++i)
            cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());

        cmdString = cmdLines.joinIntoString (" || ");
    }

    const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };

    const int cpid = fork();

    if (cpid == 0)
    {
        setsid();

        // Child process
        execve (argv[0], (char**) argv, environ);
        exit (0);
    }

    return cpid >= 0;
}
Example #7
0
void RecordNode::openFile(Channel* ch)
{
    std::cout << "OPENING FILE: " << ch->filename << std::endl;

    File f = File(ch->filename);
    FILE* chFile;

    bool fileExists = f.exists();

    chFile = fopen(ch->filename.toUTF8(), "ab");

    if (!fileExists)
    {
        // create and write header
        std::cout << "Writing header." << std::endl;
        String header = generateHeader(ch);
        //std::cout << header << std::endl;
        std::cout << "File ID: " << chFile << ", number of bytes: " << header.getNumBytesAsUTF8() << std::endl;

        fwrite(header.toUTF8(), 1, header.getNumBytesAsUTF8(), chFile);

        std::cout << "Wrote header." << std::endl;

    }
    else
    {
        std::cout << "File already exists, just opening." << std::endl;
    }
    //To avoid a race condition resulting on data written before the header,
    //do not assign the channel pointer until the header has been written
    ch->file = chFile;
}
Example #8
0
//==============================================================================
static bool isFileExecutable (const String& filename)
{
    juce_statStruct info;

    return juce_stat (filename, info)
            && S_ISREG (info.st_mode)
            && access (filename.toUTF8(), X_OK) == 0;
}
    //==============================================================================
    static unsigned int calculateHash (const String& s, const unsigned int hashMultiplier)
    {
        const char* t = s.toUTF8();
        unsigned int hash = 0;
        while (*t != 0)
            hash = hashMultiplier * hash + (unsigned int) *t++;

        return hash;
    }
//==============================================================================
String Project::getFileTemplate (const String& templateName)
{
    int dataSize;
    const char* data = BinaryData::getNamedResource (templateName.toUTF8(), dataSize);

    if (data == nullptr)
    {
        jassertfalse;
        return String::empty;
    }

    return String::fromUTF8 (data, dataSize);
}
Example #11
0
bool CodeDocument::writeToStream (OutputStream& stream)
{
    for (int i = 0; i < lines.size(); ++i)
    {
        String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
        const char* utf8 = temp.toUTF8();

        if (! stream.write (utf8, (int) strlen (utf8)))
            return false;
    }

    return true;
}
Example #12
0
	bool TOMLValue::hasMember(const String& name) const
	{
		if (isEmpty())
		{
			return false;
		}

		if (auto&& table = m_detail->ptr->as_table())
		{
			return table->contains(name.toUTF8());
		}

		return false;
	}
Example #13
0
void launcherApplication::runTremulous()
{
    Logger::writeToLog("Running Tremulous...");

    return;

    launcherApplication *app = (launcherApplication *)JUCEApplication::getInstance();

    StringArray commandLineArray;
    commandLineArray.add("+set");
    commandLineArray.add("fs_overpath");
    commandLineArray.add(app->config->getString("general", "overpath"));

    commandLineArray.add("+set");
    commandLineArray.add("fs_basepath");
    commandLineArray.add(app->config->getString("general", "basepath"));

    commandLineArray.add("+set");
    commandLineArray.add("fs_homepath");
    commandLineArray.add(app->config->getString("general", "homepath"));

    File tremulousDir(app->config->getString("general", "overpath"));
#if defined(JUCE_LINUX) || defined(JUCE_BSD)
    File tremulousApp(tremulousDir.getChildFile("tremulous"));
#elif defined(JUCE_WINDOWS)
    File tremulousApp(tremulousDir.getChildFile("tremulous.exe"));
#elif defined(JUCE_MAC)
    // FIXME
    File tremulousApp(tremulousDir.getChildFile("Tremulous.app"));
#endif

#if defined(JUCE_WINDOWS)
    String commandLine;

    for (int i = 0; i < commandLineArray.size(); i++) {
        commandLine += commandLineArray[i].quoted();
        if (i + 1 < commandLineArray.size())
            commandLine += " ";
    }

    SHELLEXECUTEINFO sei = { 0 };
    sei.cbSize = sizeof(SHELLEXECUTEINFO);
    sei.lpVerb = _T("runas");
    sei.lpFile = tremulousApp.getFullPathName().toUTF8();
    sei.lpParameters = commandLine.toUTF8();
    sei.nShow = SW_NORMAL;
    if (ShellExecuteEx(&sei))
        _exit(1);
#endif
}
Example #14
0
String JackClient::open (const String& name, int opts)
{
    String error;

    jack_status_t status;
    client = jack_client_open (name.toUTF8(), (jack_options_t) opts, &status);

    if (0 == client)
    {
        kv_jack_dump_error (status);
        error = "Could not open JACK client";
    }

    return error;
}
int HDF5FileBase::createGroup(String path)
{
    if (!opened) return -1;
    try
    {
        file->createGroup(path.toUTF8());
    }
    catch (FileIException error)
    {
        PROCESS_ERROR;
    }
    catch (GroupIException error)
    {
        PROCESS_ERROR;
    }
    return 0;
}
Example #16
0
void KWIKFileSource::updateActiveRecord()
{
    samplePos=0;
    try
    {
        String path = "/recordings/" + String(availableDataSets[activeRecord]) + "/data";
        dataSet = new DataSet(sourceFile->openDataSet(path.toUTF8()));
    }
    catch (FileIException error)
    {
        PROCESS_ERROR;
    }
    catch (DataSetIException error)
    {
        PROCESS_ERROR;
    }
}
Example #17
0
	PixelShader_GL(const String& source)
	{
		const std::string sourceUTF8 = source.toUTF8();
		
		const char* pSource = sourceUTF8.c_str();
		
		m_psProgram = ::glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &pSource);
		
		GLint status = GL_FALSE;
		
		::glGetProgramiv(m_psProgram, GL_LINK_STATUS, &status);
		
		GLint logLen = 0;
		
		::glGetProgramiv(m_psProgram, GL_INFO_LOG_LENGTH, &logLen);
		
		if (logLen > 4)
		{
			std::string log(logLen + 1, '\0');
			
			::glGetProgramInfoLog(m_psProgram, logLen, &logLen, &log[0]);
			
			LOG_FAIL(U"❌ Pixel shader compilation failed: {0}"_fmt(Unicode::Widen(log)));
		}
		
		if (status == GL_FALSE)
		{
			::glDeleteProgram(m_psProgram);
			
			m_psProgram = 0;
		}
		
		if (m_psProgram)
		{
			const int32 t = ::glGetUniformLocation(m_psProgram, "Tex0");
			
			if (t != -1)
			{
				m_textureIndex = t;
			}
		}
		
		m_initialized = m_psProgram != 0;
	}
Example #18
0
const MLSymbol MLPluginProcessor::XMLAttrToSymbol(const String& str)
{
	std::string strCopy(str.toUTF8());
	
	unsigned len = strCopy.length();
	for(unsigned c = 0; c < len; ++c)
	{
		unsigned char k = strCopy[c];
		if(k == ':')
		{
			strCopy[c] = '#';
		}
		else if(k == 0xB7)
		{
			strCopy[c] = '*';
		}
	}
 	return (MLSymbol(strCopy.c_str()));
}
 int doFTime (CharPointer_UTF32 dest, const size_t maxChars, const String& format, const struct tm* const tm) noexcept
 {
    #if JUCE_ANDROID
     HeapBlock <char> tempDest;
     tempDest.calloc (maxChars + 2);
     const int result = (int) strftime (tempDest, maxChars, format.toUTF8(), tm);
     if (result > 0)
         dest.writeAll (CharPointer_UTF8 (tempDest.getData()));
     return result;
    #elif JUCE_WINDOWS
     HeapBlock <wchar_t> tempDest;
     tempDest.calloc (maxChars + 2);
     const int result = (int) wcsftime (tempDest, maxChars, format.toWideCharPointer(), tm);
     if (result > 0)
         dest.writeAll (CharPointer_UTF16 (tempDest.getData()));
     return result;
    #else
     return (int) wcsftime (dest.getAddress(), maxChars, format.toUTF32(), tm);
    #endif
 }
Example #20
0
//==============================================================================
bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
{
    if (connected)
        close();

    hostName = "listener";
    portNumber = newPortNumber;
    isListener = true;

    struct sockaddr_in servTmpAddr;
    zerostruct (servTmpAddr);

    servTmpAddr.sin_family = PF_INET;
    servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);

	if (localHostName.isNotEmpty())
	{
		inet_pton(PF_INET, localHostName.toUTF8(), &servTmpAddr.sin_addr);
		//servTmpAddr.sin_addr.s_addr = ::inet_addr(localHostName.toUTF8());
	}

    servTmpAddr.sin_port = htons ((uint16) portNumber);

    handle = (int) socket (AF_INET, SOCK_STREAM, 0);

    if (handle < 0)
        return false;

    const int reuse = 1;
    setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));

    if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
         || listen (handle, SOMAXCONN) < 0)
    {
        close();
        return false;
    }

    connected = true;
    return true;
}
Example #21
0
	TOMLValue TOMLValue::operator [](const String& path) const
	{
		if (isEmpty())
		{
			return TOMLValue();
		}

		if (auto&& table = m_detail->ptr->as_table())
		{
			try
			{
				return TOMLValue(detail::TOMLValueDetail(table->get_qualified(path.toUTF8())));
			}
			catch (...)
			{
				return TOMLValue();
			}
		}

		return TOMLValue();
	}
Example #22
0
//-------------------------------------------------------------
//- SaveBone
//- Save an MF1 bone animation file
//- WorkingDir is current Working dir
//- BoneFilename is relative path File name of BoneAnim 
//- BoneFileIndex is the index of split BoneAnim files
// For example, we would save XX.mf1, XX.bf1, XX.bf11, XX.bf12, XX.bf13 ... files
//-------------------------------------------------------------
bool CSGPModelMF1::SaveBone(const String& WorkingDir, const String& BoneFilename, uint16 BoneFileIndex)
{
	bool SaveResult = true;
	s_CurFileOffset = 0;
	s_CollectPtrs.clear();

	Array<uint16> BackupTransFrameNum;
	Array<uint16> BackupRotsFrameNum;
	Array<uint16> BackupScaleFrameNum;
	Array<uint16> BackupVisibleFrameNum;

	uint32 KFStart = 0xFFFFFFFF;
	uint32 KFEnd = 0;

	// get start frame ID and end frame ID from Action list in this bone file
	for(uint32 i=0; i<m_Header.m_iNumActionList; i++)
	{
		if( m_pActionLists[i].m_iBoneFileIndex == BoneFileIndex )
		{
			if( m_pActionLists[i].m_iActionStart < KFStart )
				KFStart = m_pActionLists[i].m_iActionStart;
			if( m_pActionLists[i].m_iActionEnd > KFEnd )
				KFEnd = m_pActionLists[i].m_iActionEnd;
		}
	}


	SGPMF1BoneHeader BF1Header;
	BF1Header.m_iHeaderSize = sizeof(SGPMF1BoneHeader);
	if( BoneFileIndex > 0 )
		strcpy(BF1Header.m_cFilename, String(BoneFilename + String(BoneFileIndex)).toUTF8().getAddress());
	else
		strcpy(BF1Header.m_cFilename, BoneFilename.toUTF8().getAddress());

	BF1Header.m_iNumBones = m_iNumBones;
	BF1Header.m_iNumBoneGroup = m_iNumBoneGroup;

	CollectPointers(&BF1Header, sizeof(SGPMF1BoneHeader));

	BF1Header.m_iBonesOffset = CollectPointers(m_pBones, sizeof(SGPMF1Bone) * m_iNumBones);
	for(uint32 i=0; i<m_iNumBones; i++)
	{
		if( m_pBones[i].m_iNumChildId > 0 )
			m_pBones[i].m_ChildIds = (uint16*)CollectPointers( m_pBones[i].m_ChildIds, sizeof(uint16) * m_pBones[i].m_iNumChildId );

		BackupTransFrameNum.add(m_pBones[i].m_TransKeyFrames->m_iNumber);
		BackupRotsFrameNum.add(m_pBones[i].m_RotsKeyFrames->m_iNumber);
		BackupScaleFrameNum.add(m_pBones[i].m_ScaleKeyFrames->m_iNumber);
		BackupVisibleFrameNum.add(m_pBones[i].m_VisibleKeyFrames->m_iNumber);
		
		uint32 TransKFStartOffset = 0;
		uint16 TransKFNum = 0;
		uint32 RotsKFStartOffset = 0;
		uint16 RotsKFNum = 0;
		uint32 ScaleKFStartOffset = 0;
		uint16 ScaleKFNum = 0;
		uint32 VisibleKFStartOffset = 0;
		uint16 VisibleKFNum = 0;

		for(int j=0; j<m_pBones[i].m_TransKeyFrames->m_iNumber; j++)
		{
			if( m_pBones[i].m_TransKeyFrames->m_KeyFrames[j].m_iFrameID >= KFStart )
			{
				if( m_pBones[i].m_TransKeyFrames->m_KeyFrames[j].m_iFrameID <= KFEnd )
					TransKFNum++;					
			}
			else
				TransKFStartOffset++;				
		}
		for(int j=0; j<m_pBones[i].m_RotsKeyFrames->m_iNumber; j++)
		{
			if( m_pBones[i].m_RotsKeyFrames->m_KeyFrames[j].m_iFrameID >= KFStart )
			{
				if( m_pBones[i].m_RotsKeyFrames->m_KeyFrames[j].m_iFrameID <= KFEnd )
					RotsKFNum++;
			}		
			else
				RotsKFStartOffset++;				
		}
		for(int j=0; j<m_pBones[i].m_ScaleKeyFrames->m_iNumber; j++)
		{
			if( m_pBones[i].m_ScaleKeyFrames->m_KeyFrames[j].m_iFrameID >= KFStart )
			{
				if( m_pBones[i].m_ScaleKeyFrames->m_KeyFrames[j].m_iFrameID <= KFEnd )
					ScaleKFNum++;					
			}
			else
				ScaleKFStartOffset++;				
		}
		for(int j=0; j<m_pBones[i].m_VisibleKeyFrames->m_iNumber; j++)
		{
			if( m_pBones[i].m_VisibleKeyFrames->m_KeyFrames[j].m_iFrameID >= KFStart )
			{
				if( m_pBones[i].m_VisibleKeyFrames->m_KeyFrames[j].m_iFrameID <= KFEnd )
					VisibleKFNum++;
			}
			else
				VisibleKFStartOffset++;				
		}

		if( m_Header.m_iNumActionList == 0 )
		{
			TransKFNum = m_pBones[i].m_TransKeyFrames->m_iNumber;
			TransKFStartOffset = 0;
			RotsKFNum = m_pBones[i].m_RotsKeyFrames->m_iNumber;
			RotsKFStartOffset = 0;
			ScaleKFNum = m_pBones[i].m_ScaleKeyFrames->m_iNumber;
			ScaleKFStartOffset = 0;
			VisibleKFNum = m_pBones[i].m_VisibleKeyFrames->m_iNumber;
			VisibleKFStartOffset = 0;
		}

		KeyFrameBlock* pTransKeyFrames = m_pBones[i].m_TransKeyFrames;
		KeyFrameBlock* pRotsKeyFrames = m_pBones[i].m_RotsKeyFrames;
		ScaleKeyFrameBlock*	pScaleKeyFrames = m_pBones[i].m_ScaleKeyFrames;
		VisibleKeyFrameBlock* pVisibleKeyFrames = m_pBones[i].m_VisibleKeyFrames;

		pTransKeyFrames->m_BoneFileID = BoneFileIndex;
		pRotsKeyFrames->m_BoneFileID = BoneFileIndex;
		pScaleKeyFrames->m_BoneFileID = BoneFileIndex;
		pVisibleKeyFrames->m_BoneFileID = BoneFileIndex;

		pTransKeyFrames->m_iNumber = TransKFNum;
		pRotsKeyFrames->m_iNumber = RotsKFNum;
		pScaleKeyFrames->m_iNumber = ScaleKFNum;
		pVisibleKeyFrames->m_iNumber = VisibleKFNum;

		m_pBones[i].m_TransKeyFrames = (KeyFrameBlock*)CollectPointers( m_pBones[i].m_TransKeyFrames, sizeof(KeyFrameBlock) );
		m_pBones[i].m_RotsKeyFrames = (KeyFrameBlock*)CollectPointers( m_pBones[i].m_RotsKeyFrames, sizeof(KeyFrameBlock) );
		m_pBones[i].m_ScaleKeyFrames = (ScaleKeyFrameBlock*)CollectPointers( m_pBones[i].m_ScaleKeyFrames, sizeof(ScaleKeyFrameBlock) );
		m_pBones[i].m_VisibleKeyFrames = (VisibleKeyFrameBlock*)CollectPointers( m_pBones[i].m_VisibleKeyFrames, sizeof(VisibleKeyFrameBlock) );

		pTransKeyFrames->m_KeyFrames = (SGPMF1KeyFrame *)CollectPointers( pTransKeyFrames->m_KeyFrames + TransKFStartOffset, sizeof(SGPMF1KeyFrame) * TransKFNum, TransKFStartOffset * sizeof(SGPMF1KeyFrame));
		pRotsKeyFrames->m_KeyFrames = (SGPMF1KeyFrame *)CollectPointers( pRotsKeyFrames->m_KeyFrames + RotsKFStartOffset, sizeof(SGPMF1KeyFrame) * RotsKFNum, RotsKFStartOffset * sizeof(SGPMF1KeyFrame));
		pScaleKeyFrames->m_KeyFrames = (SGPMF1ScaleKeyFrame *)CollectPointers( pScaleKeyFrames->m_KeyFrames + ScaleKFStartOffset, sizeof(SGPMF1ScaleKeyFrame) * ScaleKFNum, ScaleKFStartOffset * sizeof(SGPMF1ScaleKeyFrame));
		pVisibleKeyFrames->m_KeyFrames = (SGPMF1VisibleKeyFrame *)CollectPointers( pVisibleKeyFrames->m_KeyFrames + VisibleKFStartOffset, sizeof(SGPMF1VisibleKeyFrame) * VisibleKFNum, VisibleKFStartOffset * sizeof(SGPMF1VisibleKeyFrame));
	}
	

	BF1Header.m_iBoneGroupOffset = CollectPointers( m_pBoneGroup, sizeof(SGPMF1BoneGroup) * m_iNumBoneGroup );



	//-------------------------------------------------------------
	// Identify it by the absolute filenames if possible.
	String AbsolutePath = BoneFilename;	
	if( !File::isAbsolutePath(AbsolutePath) )
	{
		AbsolutePath = WorkingDir +	File::separatorString + BoneFilename;
	}
	if( BoneFileIndex > 0 )
		AbsolutePath = AbsolutePath + String(BoneFileIndex);


	ScopedPointer<FileOutputStream> fileStream( File(AbsolutePath).createOutputStream() );
	if (fileStream != nullptr && fileStream->openedOk() )
    {
		fileStream->setPosition(0);
		fileStream->truncate();

		for( int i=0; i<s_CollectPtrs.size(); i++ )
		{
			fileStream->write( (const uint8*)s_CollectPtrs[i].pDataPointer, s_CollectPtrs[i].DataSize );
		}

		fileStream->flush();
	}
	else
		SaveResult = false;
	//-------------------------------------------------------------

	// Reset Pointers - For release memory correctly
	RelocateFirstPointers();							//SGPMF1BoneHeader
	(SGPMF1Bone*)RelocateFirstPointers();
	for(uint32 i=0; i<m_iNumBones; i++)
	{
		if( m_pBones[i].m_iNumChildId > 0 )
			m_pBones[i].m_ChildIds = (uint16*)RelocateFirstPointers();

		m_pBones[i].m_TransKeyFrames = (KeyFrameBlock*)RelocateFirstPointers();
		m_pBones[i].m_RotsKeyFrames = (KeyFrameBlock*)RelocateFirstPointers();
		m_pBones[i].m_ScaleKeyFrames = (ScaleKeyFrameBlock*)RelocateFirstPointers();
		m_pBones[i].m_VisibleKeyFrames = (VisibleKeyFrameBlock*)RelocateFirstPointers();

		m_pBones[i].m_TransKeyFrames->m_KeyFrames = (SGPMF1KeyFrame*)RelocateFirstPointers();
		m_pBones[i].m_RotsKeyFrames->m_KeyFrames = (SGPMF1KeyFrame*)RelocateFirstPointers();
		m_pBones[i].m_ScaleKeyFrames->m_KeyFrames = (SGPMF1ScaleKeyFrame*)RelocateFirstPointers();
		m_pBones[i].m_VisibleKeyFrames->m_KeyFrames = (SGPMF1VisibleKeyFrame*)RelocateFirstPointers();
	
		m_pBones[i].m_TransKeyFrames->m_iNumber = BackupTransFrameNum[i];
		m_pBones[i].m_RotsKeyFrames->m_iNumber = BackupRotsFrameNum[i];
		m_pBones[i].m_ScaleKeyFrames->m_iNumber = BackupScaleFrameNum[i];
		m_pBones[i].m_VisibleKeyFrames->m_iNumber = BackupVisibleFrameNum[i];		
	}
	(SGPMF1BoneGroup *)RelocateFirstPointers();

	return SaveResult;
}
Example #23
0
    static bool connectSocket (int volatile& handle,
                               const bool isDatagram,
                               struct addrinfo** const serverAddress,
                               const String& hostName,
                               const int portNumber,
                               const int timeOutMillisecs) noexcept
    {
        struct addrinfo hints;
        zerostruct (hints);

        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = isDatagram ? SOCK_DGRAM : SOCK_STREAM;
        hints.ai_flags = AI_NUMERICSERV;

        struct addrinfo* info = nullptr;
        if (getaddrinfo (hostName.toUTF8(), String (portNumber).toUTF8(), &hints, &info) != 0
             || info == nullptr)
            return false;

        if (handle < 0)
            handle = (int) socket (info->ai_family, info->ai_socktype, 0);

        if (handle < 0)
        {
            freeaddrinfo (info);
            return false;
        }

        if (isDatagram)
        {
            if (*serverAddress != nullptr)
                freeaddrinfo (*serverAddress);

            *serverAddress = info;
            return true;
        }

        setSocketBlockingState (handle, false);
        const int result = ::connect (handle, info->ai_addr, (socklen_t) info->ai_addrlen);
        freeaddrinfo (info);

        if (result < 0)
        {
           #if JUCE_WINDOWS
            if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
           #else
            if (errno == EINPROGRESS)
           #endif
            {
                if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
                {
                    setSocketBlockingState (handle, true);
                    return false;
                }
            }
        }

        setSocketBlockingState (handle, true);
        resetSocketOptions (handle, false, false);

        return true;
    }
Example #24
0
void MLPluginProcessor::setStateFromXML(const XmlElement& xmlState, bool setViewAttributes)
{
	if (!(xmlState.hasTagName (JucePlugin_Name))) return;
	if (!(mEngine.getCompileStatus() == MLProc::OK)) return; // TODO revisit need to compile first
	
	// only the differences between default parameters and the program state are saved in an XML program,
	// so the first step is to set the default parameters.
	setDefaultParameters();
	
	// get program version of saved state
	unsigned blobVersion = xmlState.getIntAttribute ("pluginVersion");
	unsigned pluginVersion = JucePlugin_VersionCode;
	
	if (blobVersion > pluginVersion)
	{
		// TODO show error to user
		MLError() << "MLPluginProcessor::setStateFromXML: saved program version is newer than plugin version!\n";
		return;
	}
    
	// try to load scale if a scale attribute exists
    // TODO auto save all state including this
 	const String scaleDir = xmlState.getStringAttribute ("scaleDir"); // look for old-style dir attribute
	const String scaleName = xmlState.getStringAttribute ("scaleName");
    String fullName;
    if(scaleName != String::empty)
    {
        fullName = scaleName;
        if(scaleDir != String::empty)
        {
            fullName = scaleDir + String("/") + fullName + ".scl";
        }
    }
    else
    {
        fullName = "12-equal";
    }
    std::string fullScaleName(fullName.toUTF8());
	setProperty("key_scale", fullScaleName);
	
	// get preset name saved in blob.  when saving from AU host, name will also be set from RestoreState().
	const String presetName = xmlState.getStringAttribute ("presetName");
	setProperty("preset", std::string(presetName.toUTF8()));
    
	/*
     debug() << "MLPluginProcessor: setStateFromXML: loading program " << presetName << ", version " << std::hex << blobVersion << std::dec << "\n";
     MemoryOutputStream myStream;
     xmlState->writeToStream (myStream, "");
     debug() << myStream.toString();
     */
	
	// get plugin-specific translation table for updating older versions of data
	std::map<MLSymbol, MLSymbol> translationTable;
	
	// TODO move this into Aalto!
	// make translation tables based on program version.
	//
	if (blobVersion <= 0x00010120)
	{
		// translate seq parameters
		for(unsigned n=0; n<16; ++n)
		{
			std::stringstream pName;
			std::stringstream pName2;
			pName << "seq_value" << n;
			pName2 << "seq_pulse" << n;
			MLSymbol oldSym(pName.str());
			MLSymbol newSym = MLSymbol("seq_value#").withFinalNumber(n);
			MLSymbol oldSym2(pName2.str());
			MLSymbol newSym2 = MLSymbol("seq_pulse#").withFinalNumber(n);
			translationTable[oldSym] = newSym;
			translationTable[oldSym2] = newSym2;
		}
	}
	
	if (blobVersion <= 0x00010200)
	{
		MLSymbol oldSym = MLSymbol("seq_value");
		MLSymbol newSym = MLSymbol("seq_value").withFinalNumber(0);
		MLSymbol oldSym2 = MLSymbol("seq_pulse");
		MLSymbol newSym2 = MLSymbol("seq_pulse").withFinalNumber(0);
		translationTable[oldSym] = newSym;
		translationTable[oldSym2] = newSym2;
		
		// translate seq parameters
		for(unsigned n=1; n<16; ++n)
		{
			oldSym = MLSymbol("seq_value#").withFinalNumber(n);
			newSym = MLSymbol("seq_value").withFinalNumber(n);
			oldSym2 = MLSymbol("seq_pulse#").withFinalNumber(n);
			newSym2 = MLSymbol("seq_pulse").withFinalNumber(n);
			translationTable[oldSym] = newSym;
			translationTable[oldSym2] = newSym2;
		}
	}
	
	// get patcher matrix from old-style input params
	String patcherInputStr ("patcher_input_");
	
	// get params from xml
	const unsigned numAttrs = xmlState.getNumAttributes();
	
	for(unsigned i=0; i<numAttrs; ++i)
	{
		// get name / value pair.
		const String& attrName = xmlState.getAttributeName(i);
		const MLParamValue paramVal = xmlState.getDoubleAttribute(attrName);
		
		// if not a patcher input setting,
		if (!attrName.contains(patcherInputStr))
		{
			// see if we have this named parameter in our engine.
			MLSymbol paramSym = XMLAttrToSymbol(attrName);
			const int pIdx = getParameterIndex(paramSym);
			
			if (pIdx >= 0)
			{
				// debug() << "setStateFromXML: <" << paramSym << " = " << paramVal << ">\n";
				setProperty(paramSym, paramVal);
			}
			else // try finding a match through translation table.
			{
				//debug() << "Looking for parameter " << paramSym << " in table...\n";
				std::map<MLSymbol, MLSymbol>::iterator it;
				it = translationTable.find(paramSym);
				if (it != translationTable.end())
				{
					const MLSymbol newSym = translationTable[paramSym];
					const int pNewIdx = getParameterIndex(newSym);
					if (pNewIdx >= 0)
					{
						//debug() << "translated parameter to " << newSym << " .\n";
						setProperty(newSym, paramVal);
					}
					else
					{
						MLError() << "MLPluginProcessor::setStateFromXML: no such parameter! \n";
					}
				}
				else
				{
					// fail silently on unfound params, because we have deprecated some but they may still
					// be around in old presets.
					//debug() << "MLPluginProcessor::setStateFromXML: parameter " << paramSym << " not found!\n";
				}
			}
		}
	}
	
	// get editor state from XML
    if(setViewAttributes)
	{
		int x = xmlState.getIntAttribute("editor_x");
		int y = xmlState.getIntAttribute("editor_y");
		int width = xmlState.getIntAttribute("editor_width");
		int height = xmlState.getIntAttribute("editor_height");
		mEditorRect = MLRect(x, y, width, height);
		mEditorNumbersOn = xmlState.getIntAttribute("editor_num", 1);
		mEditorAnimationsOn = xmlState.getIntAttribute("editor_anim", 1);
	}
}
Example #25
0
 bool overwriteFileWithNewDataIfDifferent (const File& file, const String& newData)
 {
     const char* const utf8 = newData.toUTF8();
     return overwriteFileWithNewDataIfDifferent (file, utf8, strlen (utf8));
 }
Example #26
0
//==============================================================================
String File::parseAbsolutePath (const String& p)
{
    if (p.isEmpty())
        return String::empty;

#if JUCE_WINDOWS
    // Windows..
    String path (p.replaceCharacter ('/', '\\'));

    if (path.startsWithChar (separator))
    {
        if (path[1] != separator)
        {
            /*  When you supply a raw string to the File object constructor, it must be an absolute path.
                If you're trying to parse a string that may be either a relative path or an absolute path,
                you MUST provide a context against which the partial path can be evaluated - you can do
                this by simply using File::getChildFile() instead of the File constructor. E.g. saying
                "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
                path if that's what was supplied, or would evaluate a partial path relative to the CWD.
            */
            jassertfalse;

            path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
        }
    }
    else if (! path.containsChar (':'))
    {
        /*  When you supply a raw string to the File object constructor, it must be an absolute path.
            If you're trying to parse a string that may be either a relative path or an absolute path,
            you MUST provide a context against which the partial path can be evaluated - you can do
            this by simply using File::getChildFile() instead of the File constructor. E.g. saying
            "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
            path if that's what was supplied, or would evaluate a partial path relative to the CWD.
        */
        jassertfalse;

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#else
    // Mac or Linux..

    // Yes, I know it's legal for a unix pathname to contain a backslash, but this assertion is here
    // to catch anyone who's trying to run code that was written on Windows with hard-coded path names.
    // If that's why you've ended up here, use File::getChildFile() to build your paths instead.
    jassert ((! p.containsChar ('\\')) || (p.indexOfChar ('/') >= 0 && p.indexOfChar ('/') < p.indexOfChar ('\\')));

    String path (p);

    if (path.startsWithChar ('~'))
    {
        if (path[1] == separator || path[1] == 0)
        {
            // expand a name of the form "~/abc"
            path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
                    + path.substring (1);
        }
        else
        {
            // expand a name of type "~dave/abc"
            const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));

            if (struct passwd* const pw = getpwnam (userName.toUTF8()))
                path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
        }
    }
    else if (! path.startsWithChar (separator))
    {
       #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS
        if (! (path.startsWith ("./") || path.startsWith ("../")))
        {
            /*  When you supply a raw string to the File object constructor, it must be an absolute path.
                If you're trying to parse a string that may be either a relative path or an absolute path,
                you MUST provide a context against which the partial path can be evaluated - you can do
                this by simply using File::getChildFile() instead of the File constructor. E.g. saying
                "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
                path if that's what was supplied, or would evaluate a partial path relative to the CWD.
            */
            jassertfalse;

           #if JUCE_LOG_ASSERTIONS
            Logger::writeToLog ("Illegal absolute path: " + path);
           #endif
        }
       #endif

        return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
    }
#endif

    while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
        path = path.dropLastCharacters (1);

    return path;
}
int HDF5FileBase::setAttributeArray(DataTypes type, const void* data, int size, String path, String name)
{
    H5Location* loc;
    Group gloc;
    DataSet dloc;
    Attribute attr;
    DataType H5type;
    DataType origType;

    if (!opened) return -1;
    try
    {
        try
        {
            gloc = file->openGroup(path.toUTF8());
            loc = &gloc;
        }
        catch (FileIException error) //If there is no group with that path, try a dataset
        {
            dloc = file->openDataSet(path.toUTF8());
            loc = &dloc;
        }

        H5type = getH5Type(type);
        origType = getNativeType(type);

        if (size > 1)
        {
            hsize_t dims = size;
            H5type = ArrayType(H5type,1,&dims);
            origType = ArrayType(origType,1,&dims);
        }

        if (loc->attrExists(name.toUTF8()))
        {
            attr = loc->openAttribute(name.toUTF8());
        }
        else
        {
            DataSpace attr_dataspace(H5S_SCALAR);
            attr = loc->createAttribute(name.toUTF8(),H5type,attr_dataspace);
        }

        attr.write(origType,data);

    }
    catch (GroupIException error)
    {
        PROCESS_ERROR;
    }
    catch (AttributeIException error)
    {
        PROCESS_ERROR;
    }
    catch (DataSetIException error)
    {
        PROCESS_ERROR;
    }
    catch (FileIException error)
    {
        PROCESS_ERROR;
    }

    return 0;
}
int HDF5FileBase::setAttributeStr(const String& value, String path, String name)
{
	Array<const char*> dataPtrs;
	dataPtrs.add(value.toUTF8());
	return setAttributeStrArray(dataPtrs, value.length(), path, name);
}
int HDF5FileBase::setAttributeStrArray(Array<const char*>& data, int maxSize, String path, String name)
{
	H5Location* loc;
	Group gloc;
	DataSet dloc;
	Attribute attr;
	hsize_t dims[1];

	if (!opened) return -1;

	StrType type(PredType::C_S1, maxSize + 1);
	type.setSize(H5T_VARIABLE);

	try
	{
		try
		{
			gloc = file->openGroup(path.toUTF8());
			loc = &gloc;
		}
		catch (FileIException error) //If there is no group with that path, try a dataset
		{
			dloc = file->openDataSet(path.toUTF8());
			loc = &dloc;
		}

		if (loc->attrExists(name.toUTF8()))
		{
			//attr = loc.openAttribute(name.toUTF8());
			return -1; //string attributes cannot change size easily, better not allow overwritting.
		}
		else
		{
			DataSpace attr_dataspace;
			int nStrings = data.size();
			if (nStrings > 1)
			{
				dims[0] = nStrings;
				attr_dataspace = DataSpace(1, dims);
			}
			else
				attr_dataspace = DataSpace(H5S_SCALAR);
			attr = loc->createAttribute(name.toUTF8(), type, attr_dataspace);
		}
		attr.write(type, data.getRawDataPointer());

	}
	catch (GroupIException error)
	{
		PROCESS_ERROR;
	}
	catch (AttributeIException error)
	{
		PROCESS_ERROR;
	}
	catch (FileIException error)
	{
		PROCESS_ERROR;
	}
	catch (DataSetIException error)
	{
		PROCESS_ERROR;
	}


	return 0;

}
Example #30
0
  bool parseFile (const File& rootFolder,
    const File& newTargetFile,
    OutputStream& dest,
    const File& file,
    StringArray& alreadyIncludedFiles,
    const StringArray& includesToIgnore,
    const StringArray& wildcards,
    int level,
    bool stripCommentBlocks)
  {
    // Make sure the file exists

    if (! file.exists())
    {
      std::cout << "  !! ERROR - file doesn't exist!";
      return false;
    }

    // Load the entire file as an array of individual lines.

    StringArray lines;
    lines.addLines (file.loadFileAsString());

    // Make sure there is something in the file.

    if (lines.size() == 0)
    {
      std::cout << "  !! ERROR - input file was empty: " << file.getFullPathName();
      return false;
    }

    // Produce some descriptive progress.

    if (m_verbose)
    {
      if (level == 0)
        std::cout << "  Processing \"" << file.getFileName () << "\"\n";
      else
        std::cout << "  Inlining " << String::repeatedString (" ", level - 1)
                  << "\"" << file.getFileName () << "\"\n";
    }

    bool lastLineWasBlank = true;

    for (int i = 0; i < lines.size(); ++i)
    {
      String line (lines[i]);
      String trimmed (line.trimStart());

      if ((level != 0) && trimmed.startsWith ("//================================================================"))
        line = String::empty;

      std::string s (line.toUTF8 ());

      if (m_remapTable.processLine (s))
      {
        line = String::empty;
      }
      else
      {
        ParsedInclude parsedInclude = parseInclude (line, trimmed);

        if (parsedInclude.isIncludeLine)
        {
          const File targetFile = findInclude (file, parsedInclude.filename);

          if (targetFile.exists())
          {
            if (matchesWildcard (parsedInclude.filename.replaceCharacter ('\\', '/'))
              && ! includesToIgnore.contains (targetFile.getFileName()))
            {
              String fileNamePart = File (parsedInclude.filename).getFileName ();
              RemapTable::iterator remapTo = m_remapTable.find (std::string (fileNamePart.toUTF8 ()));
              if (level != 0 && remapTo != m_remapTable.end ())
              {
                line = "#include \"";
                line << String(remapTo->second.c_str ()) << "\"" << newLine;

                findAllFilesIncludedIn (targetFile, alreadyIncludedFiles);
              }
              else if (line.containsIgnoreCase("SKIP_AMALGAMATOR_INCLUDE"))
              {
              }
              else if (line.containsIgnoreCase ("FORCE_AMALGAMATOR_INCLUDE")
                || ! alreadyIncludedFiles.contains (targetFile.getFullPathName()))
              {
                if (parsedInclude.preventReinclude)
                {
                  alreadyIncludedFiles.add (targetFile.getFullPathName());
                }
                else if (parsedInclude.forceReinclude)
                {
                }
                else if (! canFileBeReincluded (targetFile))
                {
                  alreadyIncludedFiles.add (targetFile.getFullPathName());
                }

                dest << newLine << "/*** Start of inlined file: " << targetFile.getFileName() << " ***/" << newLine;

                if (! parseFile (rootFolder, newTargetFile,
                  dest, targetFile, alreadyIncludedFiles, includesToIgnore,
                  wildcards, level + 1, stripCommentBlocks))
                {
                  return false;
                }

                dest << "/*** End of inlined file: " << targetFile.getFileName() << " ***/" << newLine << newLine;

                line = parsedInclude.lineAfterInclude;
              }
              else
              {
                line = String::empty;
              }
            }
            else
            {
              line = parsedInclude.lineUpToEndOfInclude.upToFirstOccurrenceOf ("\"", true, false)
                + targetFile.getRelativePathFrom (newTargetFile.getParentDirectory())
                .replaceCharacter ('\\', '/')
                + "\""
                + parsedInclude.lineAfterInclude;
            }
          }
        }
      }

      if ((stripCommentBlocks || i == 0) && trimmed.startsWith ("/*") && (i > 10 || level != 0))
      {
        int originalI = i;
        String originalLine = line;

        for (;;)
        {
          int end = line.indexOf ("*/");

          if (end >= 0)
          {
            line = line.substring (end + 2);

            // If our comment appeared just before an assertion, leave it in, as it
            // might be useful..
            if (lines [i + 1].contains ("assert")
              || lines [i + 2].contains ("assert"))
            {
              i = originalI;
              line = originalLine;
            }

            break;
          }

          line = lines [++i];

          if (i >= lines.size())
            break;
        }

        line = line.trimEnd();
        if (line.isEmpty())
          continue;
      }

      line = line.trimEnd();

      {
        // Turn initial spaces into tabs..
        int numIntialSpaces = 0;
        int len = line.length();
        while (numIntialSpaces < len && line [numIntialSpaces] == ' ')
          ++numIntialSpaces;

        if (numIntialSpaces > 0)
        {
          int tabSize = 4;
          int numTabs = numIntialSpaces / tabSize;
          line = String::repeatedString ("\t", numTabs) + line.substring (numTabs * tabSize);
        }

  #if 0
        if (! line.containsChar ('"'))
        {
          // turn large areas of spaces into tabs - this will mess up alignment a bit, but
          // it's only the amalgamated file, so doesn't matter...
          line = line.replace ("        ", "\t", false);
          line = line.replace ("    ", "\t", false);
        }
  #endif
      }

      if (line.isNotEmpty() || ! lastLineWasBlank)
        dest << line << newLine;

      lastLineWasBlank = line.isEmpty();
    }

    return true;
  }