asciidoc.C 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "asciidoc.h"
  2. #include <fstream>
  3. #include <signal.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <boost/scoped_array.hpp>
  7. #include "Wt/WString"
  8. using namespace Wt;
  9. namespace {
  10. std::string tempFileName()
  11. {
  12. #ifndef WT_WIN32
  13. char spool[20];
  14. strcpy(spool, "/tmp/wtXXXXXX");
  15. int i = mkstemp(spool);
  16. close(i);
  17. #else
  18. char spool[2 * L_tmpnam];
  19. tmpnam(spool);
  20. #endif
  21. return std::string(spool);
  22. }
  23. std::string readFileToString(const std::string& fileName)
  24. {
  25. std::fstream file (fileName.c_str(), std::ios::in | std::ios::binary);
  26. file.seekg(0, std::ios::end);
  27. int length = file.tellg();
  28. file.seekg(0, std::ios::beg);
  29. boost::scoped_array<char> buf(new char[length]);
  30. file.read(buf.get(), length);
  31. file.close();
  32. return std::string(buf.get(), length);
  33. }
  34. }
  35. WString asciidoc(const Wt::WString& src)
  36. {
  37. std::string srcFileName = tempFileName();
  38. std::string htmlFileName = tempFileName();
  39. {
  40. std::ofstream srcFile(srcFileName.c_str(), std::ios::out);
  41. std::string ssrc = src.toUTF8();
  42. srcFile.write(ssrc.c_str(), (std::streamsize)ssrc.length());
  43. srcFile.close();
  44. }
  45. #if defined(ASCIIDOC_EXECUTABLE)
  46. #define xstr(s) str(s)
  47. #define str(s) #s
  48. std::string cmd = xstr(ASCIIDOC_EXECUTABLE);
  49. #else
  50. std::string cmd = "asciidoc";
  51. #endif
  52. std::string command = cmd + " -o " + htmlFileName + " -s " + srcFileName;
  53. #ifndef WT_WIN32
  54. /*
  55. * So, asciidoc apparently sends a SIGINT which is caught by its parent
  56. * process.. So we have to temporarily ignore it.
  57. */
  58. struct sigaction newAction, oldAction;
  59. newAction.sa_handler = SIG_IGN;
  60. newAction.sa_flags = 0;
  61. sigemptyset(&newAction.sa_mask);
  62. sigaction(SIGINT, &newAction, &oldAction);
  63. #endif
  64. bool ok = system(command.c_str()) == 0;
  65. #ifndef WT_WIN32
  66. sigaction(SIGINT, &oldAction, 0);
  67. #endif
  68. WString result;
  69. if (ok) {
  70. result = WString::fromUTF8(readFileToString(htmlFileName));
  71. } else
  72. result = WString::fromUTF8("<i>Could not execute asciidoc</i>");
  73. unlink(srcFileName.c_str());
  74. unlink(htmlFileName.c_str());
  75. return result;
  76. }