R-matrix theory of driven electromagnetic cavities.