// --------------------------------------------------------------------
// Main function
// --------------------------------------------------------------------
/*

    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 "appui.h"
#include "ipeq.h"
#include "ipeversion.h"

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

#ifdef IPE_KDE
#include <kcmdlineargs.h>
#include <kapplication.h>
#endif

#include <cstdio>
#include <cstdlib>

using namespace std;

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

static bool showDebug = false;

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

// used from appui.cpp
void StartManual(QString url)
{
#if defined(WIN32)
  ShellExecute(0, "open", url.local8Bit(), 0, 0, 0);
#elif defined(IPE_KDE)
  KApplication::kApplication()->invokeBrowser(url);
#else
  QString browser = IpePreferences::Static()->iBrowser;
  QString s = browser + " " + url;
  system((s + " &").local8Bit());
#endif
}

int saveKeys(int argc, char **argv, const char *fname)
{
  QApplication a(argc, argv);
  AppUi *appui = new AppUi;
  appui->SaveKeys(QString::fromLocal8Bit(fname));
  return 0;
}

#ifdef IPE_KDE

static const KCmdLineOptions options[] = {
  { "debug", "Display debug information on stderr.", 0 },
  { "sheet <stylesheet>", "Add style sheet to all newly created documents.",
    0 },
  { "!geom <WxH+X+Y>", "Set geometry of main window.", 0 },
  { "+[file]", "Load document from file.", 0 },
  KCmdLineLastOption // End of options.
};

#else

static void usage()
{
  fprintf(stderr,
	  "Usage:\n ipe [ Qt options ] [-debug] [-geom wxh+x+y] "
	  "[-sheet stylesheet][ filename ]\n");
  exit(1);
}

#endif

// The main function just starts the QApplication
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 (probably 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;

  if (argc == 3 && !qstrcmp(argv[1], "-savekeys"))
    return saveKeys(argc, argv, argv[2]);

#ifdef IPE_KDE

  KCmdLineArgs::init(argc, argv, "ipe", "Ipe",
		     "Ipe drawing editor", IPE_VERSION);
  KCmdLineArgs::addCmdLineOptions(options);
  KApplication::addCmdLineOptions();
  KApplication a;

#else

  if (argc >= 2 && (!qstrcmp(argv[1], "-help") ||
		    !qstrcmp(argv[1], "--help")))
    usage();

  QApplication a( argc, argv );

#endif

  // must create QApplication before first call to IpePreferences::Static.
  IpePreferences *prefs = IpePreferences::Static();

  QApplication::setFont(prefs->iFont, true);

  QString lang = IpePreferences::Static()->iLanguage;
  ipeDebug("Current locale is '%s'", QTextCodec::locale());
  ipeDebug("Current directory is '%s'", QDir::current().path().latin1());

  QTranslator qt(0);
  QTranslator qt1(0);
  if (!lang.isNull()) {
    if (qt.load("ipe-" + lang, prefs->iLangDir))
      a.installTranslator(&qt);
    if (qt1.load("keys-" + lang, prefs->iLangDir))
      a.installTranslator(&qt1);
  }

  QTranslator qt2(0);
  if (qt2.load(prefs->iKeysFileName)) {
    qDebug("Loaded personal key definitions from '%s'",
	   prefs->iKeysFileName.latin1());
    a.installTranslator(&qt2);
  }

  bool geom = false;
  int w, h, x, y;
  QCString load;

#ifdef IPE_KDE

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  QCString sheet = args->getOption("sheet");
  if (!sheet.isEmpty())
    prefs->iStyleSheet2 = sheet.data();

  QCString geoms = args->getOption("geom");
  if (!geoms.isEmpty() &&
      sscanf(geoms.data(), "%dx%d+%d+%d", &w, &h, &x, &y) == 4) {
    geom = true;
    ipeDebug("Geometry: %dx%d at (%d,%d)", w, h, x, y);
  }

  // File to open
  if (args->count() > 0)
    load = args->arg(0);

  args->clear(); // Free up some memory.

#else

  int i = 1;
  if (a.argc() >= i+2 && !qstrcmp(a.argv()[i], "-geom")) {
    if (sscanf(a.argv()[i+1], "%dx%d+%d+%d", &w, &h, &x, &y) == 4)
      geom = true;
    ipeDebug("Geometry: %dx%d at (%d,%d)", w, h, x, y);
    i += 2;
  }
  if (a.argc() >= i+2 && !qstrcmp(a.argv()[i], "-sheet")) {
    prefs->iStyleSheet2 = a.argv()[i+1];
    i += 2;
  }
  if (a.argc() >= i+1 && !qstrcmp(a.argv()[i], "-debug")) {
    showDebug = true;
    ++i;
  }
  if (a.argc() == i + 1) {
    load = a.argv()[i];
  } else if (a.argc() > i + 1)
    usage();

#endif

  AppUi *appui = new AppUi;

  if (load.isEmpty() || !appui->Load(load))
    appui->NewDoc();

  if (prefs->iMaximize) {
    appui->showMaximized();
  } else {
    if (geom)
      appui->setGeometry(x, y, w, h);
    appui->show();
  }

  appui->DefaultZoom();

  QObject::connect(&a, SIGNAL(lastWindowClosed()),
		   &a, SLOT(quit()));
  return a.exec();
}

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