// pageSize.cpp
//
// Part of KVIEWSHELL - A framework for multipage text/gfx viewers
//
// (C) 2002-2003 Stefan Kebekus
// Distributed under the GPL

// Add header files alphabetically

#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <math.h>
#include <qstringlist.h>

#include "pageSize.h"
#include "units.h"

struct pageSizeItem 
{
  const char *name;
  float width;         // in mm
  float height;        // in mm
  const char *preferredUnit;
};

// TODO: make default paper size depend on the current locale
// --e.g. use "US Letter" if metric system is "imperial".

#define defaultMetricPaperSize 4 // Default paper size is "DIN A4"
#define defaultImperialPaperSize 8 // Default paper size is "US Letter"

static pageSizeItem staticList[] = { {"DIN A0",    841.0, 1189.0, "mm"}, 
				     {"DIN A1",    594.0, 841.0, "mm"}, 
				     {"DIN A2",    420.0, 594.0, "mm"}, 
				     {"DIN A3",    297.0, 420.0, "mm"}, 
				     {"DIN A4",    210.0, 297.0, "mm"},
				     {"DIN A5",    148.5, 210.0, "mm"}, 
				     {"DIN B4",    250.0, 353.0, "mm"}, 
				     {"DIN B5",    176.0, 250.0, "mm"},
				     {"US Letter", 215.9, 279.4, "in"}, 
				     {"US Legal",  215.9, 355.6, "in"},
				     {0,  0.0, 0.0, 0} // marks the end of the list.
};


pageSize::pageSize(void)
{
  currentSize = defaultPageSize();
  pageWidth  = staticList[currentSize].width;
  pageHeight = staticList[currentSize].height;
}


pageSize::pageSize(simplePageSize s)
{
  pageWidth  = s.width_in_mm();
  pageHeight = s.height_in_mm();
  
  rectifySizes();
  reconstructCurrentSize();
}


bool pageSize::setPageSize(QString name)
{
  // See if we can recognize the string
  QString currentName;
  for(int i=0; staticList[i].name != 0; i++) {
    currentName = staticList[i].name;
    if (currentName == name) {
      currentSize = i;  
      // Set page width/height accordingly
      pageWidth  = staticList[currentSize].width;
      pageHeight = staticList[currentSize].height;
      emit(sizeChanged(*this));
      return true;
    }
  }

  // Check if the string contains 'x'. If yes, we assume it is of type
  // "<number>x<number>". If yes, the first number is interpreted as
  // the width in mm, the second as the height in mm
  if (name.find('x') >= 0) {
    bool wok, hok;
    float pageWidth_tmp  = name.section('x',0,0).toFloat(&wok);
    float pageHeight_tmp = name.section('x',1,1).toFloat(&hok);
    if (wok && hok) {
      pageWidth  = pageWidth_tmp;
      pageHeight = pageHeight_tmp;
      
      rectifySizes();
      reconstructCurrentSize();
      emit(sizeChanged(*this));
      return true;
    }
  }
  
  // Check if the string contains ','. If yes, we assume it is of type
  // "<number><unit>,<number><uni>". The first number is supposed to
  // be the width, the second the height.
  if (name.find(',') >= 0) {
    bool wok, hok;
    float pageWidth_tmp  = distance::convertToMM(name.section(',',0,0), &wok);
    float pageHeight_tmp = distance::convertToMM(name.section(',',1,1), &hok);
    if (wok && hok) {
      pageWidth  = pageWidth_tmp;
      pageHeight = pageHeight_tmp;
      
      rectifySizes();
      reconstructCurrentSize();
      emit(sizeChanged(*this));
      return true;
    } 
  }  
  
  // Last resource. Set the default, in case the string is
  // unintelligible to us.
  currentSize = defaultPageSize();
  pageWidth  = staticList[currentSize].width;
  pageHeight = staticList[currentSize].height;
  kdError(4300) << "pageSize::setPageSize: could not parse '" << name << "'. Using " << staticList[currentSize].name << " as a default." << endl;
  emit(sizeChanged(*this));
  return false;
}


void pageSize::setPageSize(double width, double height)
{
  double oldPageWidth  = pageWidth;
  double oldPageHeight = pageHeight;

  pageWidth  = width;
  pageHeight = height;
  
  rectifySizes();
  reconstructCurrentSize();
  if ( fabs(pageWidth - oldPageWidth) > 2.0 || fabs(pageHeight - oldPageHeight) > 2.0)
    emit(sizeChanged(*this));
}


void pageSize::setPageSize(QString width, QString widthUnits, QString height, QString heightUnits)
{
  double oldPageWidth  = pageWidth;
  double oldPageHeight = pageHeight;
  pageWidth  = width.toFloat();
  pageHeight = height.toFloat();

  if ((widthUnits != "cm") && (widthUnits != "mm") && (widthUnits != "in")) {
    kdDebug(4300) << "Unrecognized page width unit '" << widthUnits << "'. Assuming mm" << endl;
    widthUnits = "mm";
  }
  if (widthUnits == "cm")
    pageWidth *= 10.0;
  if (widthUnits == "in")
    pageWidth *= 25.4;

  if ((heightUnits != "cm") && (heightUnits != "mm") && (heightUnits != "in")) {
    kdDebug(4300) << "Unrecognized page height unit '" << widthUnits << "'. Assuming mm" << endl;
    heightUnits = "mm";
  }
  if (heightUnits == "cm")
    pageHeight *= 10.0;
  if (heightUnits == "in")
    pageHeight *= 25.4;

  rectifySizes();
  reconstructCurrentSize();
  if ( fabs(pageWidth - oldPageWidth) > 2.0 || fabs(pageHeight - oldPageHeight) > 2.0)
    emit(sizeChanged(*this));
}


pageSize &pageSize::operator= (const pageSize &src)
{
  double oldPageWidth  = pageWidth;
  double oldPageHeight = pageHeight;

  currentSize = src.currentSize;
  pageWidth   = src.pageWidth;
  pageHeight  = src.pageHeight;

  if ( fabs(pageWidth - oldPageWidth) > 2.0 || fabs(pageHeight - oldPageHeight) > 2.0)
    emit(sizeChanged(*this));
  return *this;
}


void pageSize::rectifySizes(void)
{
  // Now do some sanity checks to make sure that values are not
  // outrageous. We allow values between 5cm and 50cm.
  if (pageWidth < 50)
    pageWidth = 50;
  if (pageWidth > 1200)
    pageWidth = 1200;
  if (pageHeight < 50)
    pageHeight = 50;
  if (pageHeight > 1200)
    pageHeight = 1200;
  return;
}


QString pageSize::preferredUnit(void) const
{
  if (currentSize >= 0)
    return staticList[currentSize].preferredUnit;

  // User-defined size. Give a preferred unit depening on the locale.
  if (KGlobal::locale()-> measureSystem() == KLocale::Metric)
    return "mm";
  else
    return "in";
}


QString pageSize::widthString(QString unit) const
{
  QString answer = "--";

  if (unit == "cm")
    answer.setNum(pageWidth/10.0);
  if (unit == "mm")
    answer.setNum(pageWidth);
  if (unit == "in")
    answer.setNum(pageWidth/25.4);

  return answer;
}


QString pageSize::heightString(QString unit) const
{
  QString answer = "--";

  if (unit == "cm")
    answer.setNum(pageHeight/10.0);
  if (unit == "mm")
    answer.setNum(pageHeight);
  if (unit == "in")
    answer.setNum(pageHeight/25.4);

  return answer;
}


QStringList pageSize::pageSizeNames(void) 
{
  QStringList names;
  
  for(int i=0; staticList[i].name != 0; i++) 
    names << staticList[i].name;

  return names;
}


QString pageSize::formatName(void) const
{
  if (currentSize >= 0)
    return staticList[currentSize].name;
  else 
    return QString::null;
}


int pageSize::getOrientation(void) const
{
  if (currentSize == -1) {
    kdError(4300) << "pageSize::getOrientation: getOrientation called for page format that does not have a name." << endl;
    return 0;
  }

  if (pageWidth == staticList[currentSize].width)
    return 0;
  else
    return 1;
}


void pageSize::setOrientation(int orient)
{
  if (currentSize == -1) {
    kdError(4300) << "pageSize::setOrientation: setOrientation called for page format that does not have a name." << endl;
    return;
  }
  
  if (orient == 1) {
    pageWidth  = staticList[currentSize].height;
    pageHeight = staticList[currentSize].width;
  } else {
    pageWidth  = staticList[currentSize].width;
    pageHeight = staticList[currentSize].height;
  }
  emit(sizeChanged(*this));
}


QString pageSize::serialize(void) const
{
  if ((currentSize >= 0) && (fabs(staticList[currentSize].height-pageHeight) <= 0.5))
    return staticList[currentSize].name;
  else 
    return QString("%1x%2").arg(pageWidth).arg(pageHeight);
}


void pageSize::reconstructCurrentSize(void)
{
  for(int i=0; staticList[i].name != 0; i++) {
    if ((fabs(staticList[i].width - pageWidth) <= 2) && (fabs(staticList[i].height - pageHeight) <= 2)) {
      currentSize = i;
      pageWidth  = staticList[currentSize].width;
      pageHeight = staticList[currentSize].height;
      return;
    }
    if ((fabs(staticList[i].height - pageWidth) <= 2) && (fabs(staticList[i].width - pageHeight) <= 2)) {
      currentSize = i;
      pageWidth  = staticList[currentSize].height;
      pageHeight = staticList[currentSize].width;
      return;
    }
  }
  currentSize = -1;
  return;
}

int pageSize::defaultPageSize(void)
{
  // FIXME: static_cast<QPrinter::PageSize>(KGlobal::locale()->pageSize())
  //        is the proper solution here.  Then you can determine the values
  //        without using your hardcoded table too!
  if (KGlobal::locale()-> measureSystem() == KLocale::Metric)
    return defaultMetricPaperSize;
  else
    return defaultImperialPaperSize;
}

#include "pageSize.moc"

