From djvanderlaan at gmail.com  Wed Jul 21 16:43:12 2010
From: djvanderlaan at gmail.com (Jan van der Laan)
Date: Wed, 21 Jul 2010 16:43:12 +0200
Subject: [Rd] Plot window does not update in embedded code
Message-ID: <AANLkTilIxmc9rrIs2NXLna_wXzQPLFH4tDHK-FOgk3gZ@mail.gmail.com>

Dear list,

I am trying to embed R into a C++ program. After some tinkering,
reading the documentation and browsing the source code I have this
more or less working. A very very condensed and very simplified
version of the code is included below.

The program can create plots. However, after the plot is initially
drawn it is no longer updated. When scaling or updating the plot the
window becomes blank, and the window also doesn't want to close. I
suspect that my R_ReadConsole routine is the problem. This routine
waits for user input and returns this (which I thought it should). It
seems that this causes the event loop that updates the windows to also
be on hold. I did have a look at 'Rstd_ReadConsole' in
'src/unix/sys-std.c', but I can't figure out what exactly happens in
this routine.

How do I ensure that the windows keep being updated?

Presently I am working under Linux. However, I also want to be able to
run my code under windows, so I hope there is a cross-platform
solution. Thanks in advance.

Regards,

Jan van der Laan


===== The example code =====
#include <iostream>
#include <iomanip>
#include <string>

static void R_WriteConsoleEx (const char *buf, int buflen, int otype) {
  std::string output(buf, buflen);
  std::cout << output;
}

static void R_WriteConsole (const char *buf, int buflen) {
  R_WriteConsoleEx(buf, buflen, 0);
}

static int R_ReadConsole (const char *prompt, unsigned char *buf, int
buflen, int hist) {
  std::cout << prompt;
  std::string input;
  std::cin >> input;
  for (unsigned int i = 0; i < input.length(); ++i) {
    buf[i] = input[i];
    buf[i+1] = '\n';
    buf[i+2] = '\0';
    if ((int)i >= buflen-3) break;
  }
  return input.length();
}

extern "C" {
#define  R_INTERFACE_PTRS
#include <Rinterface.h>
int Rf_initialize_R(int ac, char **av); /* in ../unix/system.c */
extern int R_running_as_main_program;   /* in ../unix/system.c */
}

int main(int ac, char **av)
{
  R_running_as_main_program = 1;
  Rf_initialize_R(ac, av);
  ptr_R_WriteConsoleEx = &R_WriteConsoleEx;
  ptr_R_WriteConsole = &R_WriteConsole;
  ptr_R_ReadConsole = &R_ReadConsole;
  R_Outputfile = NULL;
  R_Consolefile = NULL;
  Rf_mainloop(); /* does not return */
  return 0;
}



[Rd] Plot window does not update in embedded code
Jan van der Laan