context('Capture plots')

options(device = function(file = NULL, ...) {
  pdf(file, ...)
  dev.control('enable')  # important! otherwise plots get discarded
})

test_that('remove blank plots', {
  # remove the a blank plot
  res = evaluate('layout(t(1:2))')
  expect_identical(sapply(rm_blank_plot(res), class), 'source')
})

test_that('plots generated by par(), palette() or layout() are removed', {

  res = evaluate('par(mfrow = c(1, 2))\npie(islands)\nbarplot(islands)')
  res = rm_blank_plot(res)
  expect_identical(sapply(res, class), rep(c('source', 'recordedplot'), c(3, 1)))

  res = evaluate('layout(t(1:2))\npie(islands)\nbarplot(islands)')
  res1 = rm_blank_plot(res)
  expect_identical(sapply(res1, class), rep(c('source', 'recordedplot'), c(3, 1)))

  res = evaluate('pie(islands)\nbarplot(islands)\npar(mfrow = c(1, 2))')
  res = merge_low_plot(res)
  expect_identical(sapply(res, class), rep(c('source', 'recordedplot'), length = 5))

  res = evaluate('pie(islands)\npar(cex.main=1.2)\nbarplot(islands)')
  res = merge_low_plot(res)
  expect_identical(sapply(res, class), c('source', 'recordedplot')[c(1, 2, 1, 1, 2)])

  res = evaluate('par(cex.main=1.2)\npalette(c("red","black"))\nbarplot(islands)')
  res = rm_blank_plot(res)
  expect_identical(sapply(res, class), rep(c('source', 'recordedplot'), c(3, 1)))

})

test_that('merge low-level changes', {
  res = evaluate('plot(1)\npoints(1.1, 1.1)')
  expect_identical(sapply(merge_low_plot(res), class),
                   rep(c('source', 'recordedplot'), c(2, 1)))
})

test_that('captures grid graphics', {
  res = evaluate('library(grid)
    grid.newpage()
    grid.rect(gp=gpar(fill="grey"))
    grid.rect(gp=gpar(fill="red"))')
  res = rm_blank_plot(res)
  expect_identical(sapply(res, class), c('source', 'recordedplot')[c(1, 1, 1, 2, 1, 2)])
  res = merge_low_plot(res)
  expect_identical(sapply(res, class), rep(c('source', 'recordedplot'), c(4, 1)))
})
