// --------------------------------------------------------------------
// ipetopng
// --------------------------------------------------------------------
/*

    This file is part of the extensible drawing editor Ipe.
    Copyright (C) 1993-2004  Otfried Cheong

    Ipe is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    As a special exception, you have permission to link Ipe with the
    CGAL library and distribute executables, as long as you follow the
    requirements of the Gnu General Public License in regard to all of
    the software in the executable aside from CGAL.

    Ipe is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License
    along with Ipe; if not, you can find it at
    "http://www.gnu.org/copyleft/gpl.html", or write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include "ipeq.h"
#include "ipemodel.h"
#include "ipeprefs.h"

#include <qapplication.h>
#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qtextcodec.h>

#include <cstdio>
#include <cstdlib>

using namespace std;

#ifdef WIN32
#include <windows.h>
#endif

#ifdef __BORLANDC__
#ifdef main
#undef main
#endif
#endif

extern QPixmap toPng(const IpeDocument *doc, const IpePage *page,
		     int view, double zoom);

#ifdef WIN32
static void ipeDebugImpl(const char *msg)
{
  OutputDebugStringA(msg);
}
#else
static void ipeDebugImpl(const char *)
{
  // fprintf(stderr, "%s\n", msg);
  // nothing
}
#endif

static int runlatex(IpeDocument *doc)
{
  QString logFile;
  switch (IpeModel::RunLatex(doc, true, QDir::currentDirPath(), logFile)) {
  case IpeModel::ErrNoText:
    fprintf(stderr, "No text objects in document, no need to run Pdflatex\n");
    return 0;
  case IpeModel::ErrNoDir:
    fprintf(stderr, "Directory '%s' does not exist and cannot be created\n",
	    ((const char *) IpePreferences::Static()->iLatexDir.local8Bit()));
    return 1;
  case IpeModel::ErrWritingSource:
    fprintf(stderr, "Error writing Latex source.\n");
    return 1;
  case IpeModel::ErrOldPdfLatex:
    fprintf(stderr, "Your installed version of Pdflatex is too old.\n");
    return 1;
  case IpeModel::ErrLatex:
    fprintf(stderr, "There were errors trying to run Pdflatex\n");
    return 1;
  case IpeModel::ErrNone:
  default:
    fprintf(stderr, "Pdflatex was run sucessfully.\n");
    return 0;
  }
}

static int topng(const char *src, const char *dst, int pageNum, double zoom)
{
  int reason;
  IpeDocument *doc = IpeDocument::New(src, reason);

  if (!doc) {
    fprintf(stderr, "Could not read Ipe file '%s' (reason %d)\n",
	    src, reason);
    return 1;
  }
  if (pageNum < 1 || pageNum > int(doc->size())) {
    fprintf(stderr,
	    "The document contains %d pages, cannot convert page %d.\n",
	    doc->size(), pageNum);
    delete doc;
    return 1;
  }

  if (runlatex(doc)) {
    delete doc;
    return 1;
  }

  const IpePage *page = (*doc)[pageNum - 1];
  QPixmap pixmap = toPng(doc, page, 0, zoom);
  delete doc;

  if (!pixmap.save(dst, "PNG")) {
    fprintf(stderr, "Error saving bitmap '%s'\n", dst);
    return 1;
  }
  return 0;
}

static void usage()
{
  fprintf(stderr,
	  "Usage:\n (1) ipetopng <page> <resolution> infile outfile.png\n");
  fprintf(stderr,
	  "ipetopng saves a single page of the Ipe document as a bitmap.\n");
  fprintf(stderr,
	  "(<resolution> is the number of pixels per inch.)\n");
  exit(1);
}

int main(int argc, char *argv[])
{
  // Check Ipelib version mismatch
  if (IpelibVersion() != IPELIB_VERSION) {
    fprintf(stderr,
	    "Ipe has been compiled with header files for Ipelib %d\n"
	    "but is dynamically linked against libipe %d.\n"
	    "Check with 'ldd ipe' which libipe is being loaded, and either "
	    "replace it by the correct version or set LD_LIBRARY_PATH.\n",
	    IPELIB_VERSION, IpelibVersion());
    exit(99);
  }

  // set ipeDebug handler
  ipeDebugHandler = ipeDebugImpl;

  // ensure exactly four arguments (handles -help as well :-)
  if (argc != 5)
    usage();

  int pageNum = IpeLex(IpeString(argv[1])).GetInt();
  double dpi = IpeLex(IpeString(argv[2])).GetDouble();
  const char *src = argv[3];
  const char *dst = argv[4];

  // Need a QApplication! (we create a pixmap)
  QApplication a(argc, argv);
  return topng(src, dst, pageNum, dpi / 72.0);
}

// --------------------------------------------------------------------
