#
# This illustrates a variety of different ways
# of embedding graphics devices within a GUI.
# We create a notebook with three different pages
# Then within the first page (Single Device),
# we create a regular single graphics device.
# The second page (Scrolled) shows a graphics
# device that is bigger than the window and
# uses a scrolled window to allow the user to see the different
# parts of the `canvas'. This is different from any of the graphics
# devices available in R or S-Plus.
# Finally, the third page (Panes) contains 4 graphics devices
# and the user can dynamically drag handles to apportion the space
# for each of them.
#
# To render plots, call showPlots() with the result from
# multiDevices(), i.e.
# d <- multiDevices()
# showPlots(d)
# Be sure to do this differently

# This requires some modifications to R to support
# using Gtk widgets as graphics devices. These will
# probably be added to R soon. In the meantime, they are available
# from  http://www.omegahat.org/RGtk/RGtkPatches.tar.gz
# Now they are done via the gtk or gtkDev package by Martyn Plummer
# and myself. This works without patching R at all.

multiDevices <-
function()
{
  devices <- list()
  w <- gtkWindow(show = FALSE)
  w$SetUsize(500, 500)

  book <- gtkNotebook()
  
  v <- gtkVPaned()  

  h <- gtkHPaned()
  dev1 <- gtkDrawingArea()
  h$Add(dev1)

  dev2 <- gtkDrawingArea()
  h$Add2(dev2)

  h$SetPosition(250)
  
  v$Add(h)

  h <- gtkHPaned()
  dev3 <- gtkDrawingArea()
  h$Add(dev3)

  dev4 <- gtkDrawingArea()
  h$Add2(dev4)
  v$Add2(h)

  h$SetPosition(250)  

  v$SetPosition(250)
  
  devs <- list(dev1,dev2,dev3,dev4)
  index <- integer(length(devs))
  for(i in 1:length(devs)) {
      asGtkDevice(devs[[i]])
      index[i] <- dev.cur()
  }
  devices[["Panes"]] <- index

  single <- gtkDrawingArea()
  book$AppendPage(single, gtkLabel("Single Device"))
  asGtkDevice(single)
  devices[["Single"]] <- dev.cur()

  sw <- gtkScrolledWindow()
  scrolledDevice <- gtkDrawingArea()
  scrolledDevice$SetUsize(1000, 1000)
  sw$AddWithViewport(scrolledDevice)
  asGtkDevice(scrolledDevice)
  devices[["Scrolled"]] <- dev.cur()

  book$AppendPage(sw, gtkLabel("Scrolled"))
  
  book$AppendPage(v, gtkLabel("Panes"))

  w$Add(book)

  book$AddCallback("switch-page",
                   function(x, arg, index) {
                     which <- c("Single", "Scrolled", "Panes")[index+1]
#                    cat("Switching device to", index, " ", which, "\n")
                     dev.set(as.numeric(devices[[which]])[1])
                   })
  
  w$Show()
  list(win = w, devices = devices)
}



showPlots <-
function(d)
{
 dev.set(d$devices$Single[1])
 persp(matrix(rnorm(300),100,3), theta = 35, phi = 25, col="red")
 
 dev.set(d$devices$Panes[2])
 plot(1:10)
 dev.set(d$devices$Panes[3])
 hist(rnorm(100))
 dev.set(d$devices$Panes[4])
 boxplot(rnorm(100), rnorm(100))
 dev.set(d$devices$Scrolled)
 pairs(matrix(rnorm(200), 100, 2))
}