/***************************************************************************
 *   Copyright (C) 2004 by Juergen Thies                                   *
 *   layout@juergenthies.de                                                *
 *                                                                         *
 *   This program 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.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "setup.h"
#include <qsettings.h>
#include "layout.h"
#include <qnamespace.h>
#include <QRect>
#include "defines.h"
#include "widgets/layertool.h"
#include "widgets/mousehelp.h"
#include "elements/text.h"
#include <QDir>
#include <QStringList>
#include <qmessagebox.h>
#include <QPushButton>
#include <QDesktopServices>
#include <QDesktopWidget>
#include "fileformats/filedialog.h"
#ifdef SCHEMATIC
#include "schematic/schematic.h"
#endif
#ifdef TEXTEDIT
#include "textedit/textedit.h"
#endif

int setup::mouseView=1;
bool setup::showGrid =true;
bool setup::schematicSettingsLoaded=false;

//layout *setup::layout_=NULL;

QColor setup::pinColor=QColor(180,0,0);
QColor setup::textColor=QColor(90,90,90);
QColor setup::deviceColor=QColor(31,0,255);
QColor setup::instanceColor=QColor(30,30,30);

QColor setup::backgroundColor=QColor(0,0,0);
QColor setup::mouseColor=QColor(255,255,255);
QColor setup::gridColor=QColor(100,100,100);
QColor setup::zeroColor=QColor(200,200,200);
QColor setup::selectColor=QColor(255,255,255);
QColor setup::highlightColor=QColor(200,250,255);
QColor setup::wireColor=QColor(128,128,128);
QColor setup::busColor=QColor(44,30,199);
int setup::highlightBrush=0;
bool setup::displayCellName=false;
bool setup::displayCells=true;
bool setup::displayCellOrigin=false;
int setup::showReport;
int setup::layerDockStyle=0;
double setup::circularDefault;
QString setup::font="";
QString setup::documentationDirectory="";
QString setup::macroDirectory="";
int setup::fontIteration=3; 
int setup::fontSize=12;
int setup::defaultPathWidth;
int setup::defaultPathCap;
int setup::defaultTextPresentation;
int setup::defaultTextWidth;
int setup::defaultBezierIteration;
bool setup::cifSaveCircle;
bool setup::cifTopCell;
bool setup::dxfSaveCircle;
int setup::gdsMaxPoints=8191;
bool setup::gdsMultiXYRecord;
bool setup::gdsPad2048;
bool setup::gdsMapLayer;
bool setup::gdsBoxToPolygon;
bool setup::oasisMapLayer;
bool setup::oasisSaveCircle;
bool setup::oasisSaveCtrapezoid;
bool setup::oasisSaveTrapezoid;
bool setup::oasisSaveCBlock;
int setup::depthOfCellrefs; 
bool setup::loaded=false;
bool setup::initDone=false;
bool setup::scrollDirection=true;
bool setup::defaultPolygonRemoveNotNeededPoints=true;
bool setup::defaultPolygonFixSelfintersectingPolygons=true;
bool setup::showMenuIcons=true;
QString setup::windowStyle="layout";
QString setup::version;
int setup::numOpen;
double setup::apLamda=0.20;
double setup::tldLamda=0.20;
QString setup::csvFieldDelimiter=",";
int setup::paintEngine=0;
bool setup::netlistAutotrigger;
QString setup::netlistUnnamedNodes;
QString setup::netlistGlobalNodes;
double setup::sourceDatabase=0.000001;
int setup::lefCellBoundaryLayer=0;
int setup::pixelLayerMap=128;
int setup::pixelResolution=0;
int setup::pixelColorBits=4;
QString setup::language="";
int setup::epsEndOfLine=0;
double setup::epsScale=1.0;
int setup::svgEndOfLine=0;
QMap<QString,QVariant> setup::netlistFormat;
QMap<QString,QVariant> setup::netlistSubFormat;
QMap<QString,QVariant> setup::netlistSubModelFormat;
bool setup::autoDisableUnusedLayers;
bool setup::gdsAutoMapDatatypes;
bool setup::oasisAutoMapDatatypes;
bool setup::updateCheck;
QDate setup::lastUpdateCheck;

QTime setup::centralTimer;
QTranslator setup::t(0);
QTranslator setup::tqt(0);
QTranslator setup::tqsci(0);
QString setup::currentLang="";
QString setup::preferedLanguage="auto";


void setup::setLang(QString lang){
  if (currentLang==lang) return;
      QCoreApplication *a=QCoreApplication::instance();
      if (lang=="german") lang="de";
      else if (lang=="deutsch") lang="de";
      else if (lang=="russian") lang="ru";
      else if (lang=="english") lang="en";
      else if (lang=="us") lang="en";
      else if (lang=="auto") {
	 QLocale locale = QLocale::system();
	 lang=locale.name().left(2);
      }
      if (lang==currentLang) return;
      if (!t.isEmpty()) {a->removeTranslator(&t); }
      if (!tqt.isEmpty()) {a->removeTranslator(&tqt); }
      #ifdef TEXTEDIT
      if (!tqsci.isEmpty()) {a->removeTranslator(&tqsci); }
      #endif
      currentLang=lang;
      if (currentLang=="en") return;
      //printf("lang set %s\n",lang.toAscii().data());
      QStringList sl;
      sl<<".";
      sl<<QCoreApplication::applicationDirPath();
      #ifndef WINDOWS 
	sl<<"/usr/share/layout";
      #else
	sl<<"C:/program files/layout";
	sl<<"C:/Programme/layout"; 
      #endif
        sl<<QCoreApplication::applicationDirPath()+"/../translation";
      bool load=false;
      int i=0;
      while ((!load)&&(i<sl.size())){
	load=t.load(QString("layout_")+currentLang,sl.at(i));
	i++;
      }
      if (load) {
	language=currentLang;
	a->installTranslator(&t);
      }
      load=false;
      i=0;
      while ((!load)&&(i<sl.size())){
	load=tqt.load(QString("qt_")+currentLang,sl.at(i));
	i++;
      }
      if (load) a->installTranslator(&tqt);
      load=false;
      i=0;
      #ifdef TEXTEDIT
      while ((!load)&&(i<sl.size())){
	load=tqsci.load(QString("qscintilla_")+currentLang,sl.at(i));
	i++;
      }
      if (load) {a->installTranslator(&tqsci);}
      #endif
}

setup::setup(QObject *parent, const char *)
 : QObject(parent)
{
}


setup::~setup()
{
}

void setup::loadEarlySettings(){
        //init();

	QSettings se;
	if (!se.contains("setup/paintEngine"))
		setOldOrganization();

	QSettings s;
	preferedLanguage=s.value("preferedLanguage",QString("auto")).toString();
	setLang(preferedLanguage);
	paintEngine=s.value("setup/paintEngine",0).toInt();
	setOrganization();
	showMenuIcons=s.value("setup/showMenuIcons",true).toBool();
   	layers::displayedLayers=s.value("setup/layers/displayedLayers",128).toInt();
}

void setup::loadSettings(){
   QSettings se;
   if (!se.contains("pos"))
	setOldOrganization();
   QSettings s;
   scrollDirection=s.value("setup/scrollDirection",true).toBool();
   mouseView=s.value("setup/mouse",1).toInt(); 
   showReport=s.value("setup/report",1).toInt();
   showGrid=s.value("setup/showgrid",true).toBool();
   displayCellName=s.value("setup/displaycellname",false).toBool();
   displayCells=s.value("setup/displaycells",true).toBool();
   displayCellOrigin=s.value("setup/displaycellorigin",false).toBool(); 
   layerDockStyle=s.value("setup/layerDockStyle",0).toInt();
   depthOfCellrefs=s.value("setup/depthOfCellrefs",0).toInt();
   
   //color
   mouseColor=s.value("setup/mousecolor",QColor(qRgb(255,255,255))).value<QColor>();
   gridColor=s.value("setup/gridcolor",QColor(qRgb(100,100,100))).value<QColor>();
   backgroundColor=s.value("setup/backgroundcolor",QColor(qRgb(0,0,0))).value<QColor>();
   selectColor=s.value("setup/selectcolor",QColor(qRgb(255,255,255))).value<QColor>();
   zeroColor=s.value("setup/zerocolor",QColor(qRgb(200,200,200))).value<QColor>();
   highlightColor=s.value("setup/highlightcolor",QColor(qRgb(200,250,255))).value<QColor>();
   highlightBrush=0;//s.value("setup/highlightbrush",0).toInt();
   loadSchematicSettings(&s);
   
   //font
   fontIteration=s.value("font/iteration",3).toInt();
   fontSize=s.value("font/size",12).toInt();
   font=s.value("font/font",font).toString();
   
   //default
   circularDefault=s.value("default/circular",5.0).toDouble();
   if (circularDefault==0) circularDefault=5;
   defaultPathWidth=abs(s.value("default/path/width",0).toInt());
   defaultPathCap=s.value("default/path/cap",0).toInt();
   defaultTextWidth=s.value("default/text/width",-10).toInt();
   defaultTextPresentation=s.value("default/text/presentation",0).toInt();
   defaultBezierIteration=s.value("default/bezier",4).toInt();
   cifSaveCircle=s.value("setup/fileformat/cifcircle",true).toBool();
   cifTopCell=s.value("setup/fileformat/ciftopcell",false).toBool();
   dxfSaveCircle=s.value("setup/fileformat/dxfcircle",true).toBool();
   gdsMaxPoints=s.value("setup/fileformat/gdsMaxPoints",8191).toInt();
   gdsMultiXYRecord=s.value("setup/fileformat/gdsMultiXYRecord",false).toBool();
   gdsPad2048=s.value("setup/fileformat/gdsPad2048",false).toBool();
   gdsMapLayer=s.value("setup/fileformat/gdsMapLayer",false).toBool();
   gdsBoxToPolygon=s.value("setup/fileformat/gdsBoxToPolygon",false).toBool();
   autoDisableUnusedLayers=s.value("setup/layers/autoDisableUnusedLayers",false).toBool();
   gdsAutoMapDatatypes=s.value("setup/fileformat/gdsAutoMapDatatypes",false).toBool();
   oasisAutoMapDatatypes=s.value("setup/fileformat/oasisAutoMapDatatypes",false).toBool(); 
   oasisMapLayer=s.value("setup/fileformat/oasisMapLayer",false).toBool();
   oasisSaveCircle=s.value("setup/fileformat/oasiscircle",true).toBool();
   oasisSaveCtrapezoid=s.value("setup/fileformat/oasisctrapezoid",true).toBool();
   oasisSaveTrapezoid=s.value("setup/fileformat/oasistrapezoid",true).toBool();
   oasisSaveCBlock=s.value("setup/fileformat/oasiscblock",false).toBool();
   apLamda=s.value("setup/fileformat/apLamda",0.2).toDouble();
   sourceDatabase=s.value("setup/fileformat/sourceDatabase",0.000001).toDouble();
   lefCellBoundaryLayer=s.value("setup/fileformat/lefBoundaryLayer",0).toInt();
   tldLamda=s.value("setup/fileformat/tldLamda",0.2).toDouble();
   pixelLayerMap=s.value("setup/fileformat/pixelLayerMap",128).toInt();
   pixelColorBits=s.value("setup/fileformat/pixelColorBits",4).toInt();
   pixelResolution=s.value("setup/fileformat/pixelResolution",0).toInt();
   csvFieldDelimiter=s.value("setup/fileformat/csvFieldDelimiter",",").toString();
   svgEndOfLine=s.value("setup/fileformat/svgEndOfLine",0).toInt();
   epsEndOfLine=s.value("setup/fileformat/epsEndOfLine",0).toInt();
   epsScale=s.value("setup/fileformat/epsScale",1.0).toDouble();

   defaultPolygonRemoveNotNeededPoints=s.value("default/polygon/removeNotNeededPoints",true).toBool();
   defaultPolygonFixSelfintersectingPolygons=s.value("default/polygon/fixSelfintersecting",true).toBool();
   documentationDirectory=s.value("installation/documentation",documentationDirectory).toString();
   macroDirectory=s.value("installation/macros",macroDirectory).toString();
   //netlist
   netlistUnnamedNodes=s.value("netlist/unnamednodes","Node_").toString();
   netlistGlobalNodes=s.value("netlist/globalnodes","^.{1,50}!$").toString();
   netlistAutotrigger=s.value("netlist/autotrigger",true).toBool();
   QMap<QString,QVariant> m;
   netlistFormat=s.value("netlist/format",QVariant(m)).toMap();
   netlistSubFormat=s.value("netlist/formatSub",QVariant(m)).toMap();
   netlistSubModelFormat=s.value("netlist/formatSubModel",QVariant(m)).toMap();
   if (!netlistFormat.contains("spice")) netlistFormat.insert("spice",QVariant(QString("*spice $filename export from LayoutEditor\r\n$groundnode(0)\r\n*start of netlist\r\n$netlist(spice)\r\n*end of netlist\r\n\r\n\r\n*required models\r\n$model(spice)\r\n")));
   if (!netlistFormat.contains("qucs")) netlistFormat.insert("qucs",QVariant(QString("#qucs $filename export from LayoutEditor\r\n$groundnode(gnd)\r\n#start of netlist\r\n$netlist(qucs)\r\n#end of netlist\r\n\r\n\r\n#required models\r\n$model(qucs)\r\n")));
   if (!netlistSubFormat.contains("spice")) netlistSubFormat.insert("spice",QVariant(QString("X$devicename $ports($node($portname) ) $sheetname\r\n")));
   if (!netlistSubModelFormat.contains("spice")) netlistSubModelFormat.insert("spice",QVariant(QString(".subckt $sheetname $ports($portname )\r\n$netlist(spice)\r\n.ends $sheetname\r\n")));
 
   updateCheck=s.value("installation/updateCheck",true).toBool();
   lastUpdateCheck=s.value("installation/lastUpdateCheck",QDate::currentDate()).toDate();
   QString lastPath=s.value("netlist/lastPath","").toString();
   if (lastPath!="") filedialog::setLastPath(lastPath);
   checkDirs();
   //check update
#ifndef GENISYS
   if (updateCheck){
	if (QDate::currentDate().day()%16==1)
		{
		QString v=VERSION;
		QDate version=QDate(v.left(4).toInt(),v.mid(4,2).toInt(),v.right(2).toInt());
		int age=version.daysTo(QDate::currentDate());
		int last=lastUpdateCheck.daysTo(QDate::currentDate());
		if (last<0) last=10000;
		//printf("%d %d (%d %d %d)\n",age,last,v.left(4).toInt(),v.mid(4,2).toInt(),v.right(2).toInt());
		if (((age>80)&&(last>27))) 
			{
			lastUpdateCheck=QDate::currentDate();
			s.setValue("installation/lastUpdateCheck",lastUpdateCheck);
			QString url="http://www.layouteditor.net/updatecheck.php5?release="+ QString(VERSION)+"&date="+QDate::currentDate().toString("yyyyMMdd");
			QDesktopServices::openUrl(QUrl(url));
			}
		}
	}
#endif
   textRender::reset();
   setOrganization();
}

void setup::loadSettings(layout *l){
   init();
   QSettings se;
   if (!se.contains("pos"))
	setOldOrganization();
   QSettings s;
   //geometry
   //l->setGeometry ( s.value("geometry",QRect(10,45,1000,700)).value<QRect>());
   bool maximized=false;
   QPoint pos = s.value("pos", QPoint(4, 45)).toPoint();
   QSize size = s.value("size", QSize(1018, 700)).toSize();
   if (pos.x()<0) {pos.setX(5);maximized=true;}
   if (pos.y()<0) {pos.setY(25);maximized=true;}
   QRect r= QApplication::desktop ()->screenGeometry();
   if ((r.right()>100)&&(r.right()<=pos.x()+100)){pos.setX(3);maximized=true;}
   if ((r.bottom()>100)&&(r.bottom()<=pos.y()+100)){pos.setY(25);maximized=true;}
   if (r.width()>100)
		if (size.width()>r.width()) {size.setWidth(r.width());maximized=true;}
   if (r.height()>100)
		if (size.height()>r.height()){size.setHeight(r.height());maximized=true;}
   //printf("size: %d/%d is%d/%d\n",r.right(),r.bottom(),pos.x(),pos.y()); 
   l->resize(size);
   l->move(pos);
#ifdef Q_OS_WIN32
 if (maximized) l->showMaximized();
#endif
   //printf("%s\n",language.toAscii().data());
   viewModeType viewMode=(viewModeType)(s.value("viewMode",(int)(defaultmode)).toInt());
   if (viewMode==l->viewMode)
	if (language== s.value("language",QString("en")))
		l->restoreState  ( s.value("toolbars").value<QByteArray>());
   if (loaded&&(l->layerTools!=NULL)) {
	QString string;
   	for (int i=0;i<l->layerTools->initLayers;i++){
		l->layerTools->button[i]->setToolTip(layers::num[i].name);
		l->layerTools->button[i]->changeSetup();}
	return;
	}
 if (!s.value("setup/menu",true).toBool()){l->hideMenuBar();}else{l->showMenuBar();}
   //layer
   QString string;
  QStringList stringList;
  QByteArray byteArray;
  QList<QVariant> list;
  stringList=s.value("layer/stringList",stringList).toStringList();
  byteArray=s.value("layer/byteArray",byteArray).toByteArray();
  list=s.value("layer/list",list).toList();
  int sizeStringList = stringList.size();
  int sizebyteArray =byteArray.size();
  int sizeList= list.size();
  int posStringList=0;
  int posbyteArray=0;
  int posList=0;
  QColor co;
  for (int i=0;i<layersMax;i++){
	string=string.setNum(i);
	if (posStringList<sizeStringList){
		layers::num[i].name=stringList.at(posStringList);
		if (layers::num[i].name=="")layers::num[i].name=string;
		++posStringList;
		}
	else layers::num[i].name=s.value("layer/"+string+"name",string).toString();
	if (l->layerTools!=NULL) 
	  if (i<l->layerTools->initLayers)l->layerTools->button[i]->setToolTip(layers::num[i].name);

	QColor c;
	if (posbyteArray+2<sizebyteArray){
		uchar red=byteArray.at(posbyteArray);
		uchar green=byteArray.at(posbyteArray+1);
		uchar blue=byteArray.at(posbyteArray+2);
		//if (i<10) printf("%d %d %d\n",red,green,blue);
		c.setRgb(red,green,blue);
		posbyteArray+=3;
		}
	else {
		co.setHsv((i*67)%255,170+(i*34)%85,130+(i*87)%110);
		c=s.value("layer/"+string+"color",co).value<QColor>();
		}
	layers::num[i].pen.setColor(c);

	if (posbyteArray<sizebyteArray){
		layers::num[i].setStyle(byteArray.at(posbyteArray));
		++posbyteArray;
		}
	else layers::num[i].setStyle(s.value("layer/"+string+"style",(i%(layerStyle-1))).toInt());

	if (posStringList<sizeStringList){
		layers::num[i].shortkey=stringList.at(posStringList);
		++posStringList;
		}
	else layers::num[i].shortkey=s.value("layer/"+string+"shortkey","").toString();

	if (posbyteArray<sizebyteArray){
		if ((l->viewMode==fullmode)||(l->viewMode==custommode)||(l->viewMode==puremode)){
		  if (byteArray.at(posbyteArray)>0) layers::num[i].disable();
		  else layers::num[i].enable();
		} else layers::num[i].enable();
		++posbyteArray;
		}
	else {
		bool le=s.value("layer/"+string+"enable",true).toBool();
		if ((l->viewMode!=fullmode)&&(l->viewMode!=custommode)&&(l->viewMode!=puremode)) le=true;
		if (le) layers::num[i].enable();
		else layers::num[i].disable();
	}
	if (l->layerTools!=NULL) 
	   if (i<l->layerTools->initLayers) l->layerTools->button[i]->changeSetup();

	int level3d,thickness3d;
	if (posList+1<sizeList){
		level3d=list.at(posList).toInt();
		thickness3d=list.at(posList+1).toInt();
		++posList;++posList;
		}
	else {
		level3d=s.value("layer/"+string+"level3d",0).toInt(); 
		thickness3d=s.value("layer/"+string+"thickness3d",0).toInt();
	}
	layers::num[i].set3dView(level3d,thickness3d);

	if (posList+1<sizeList){
		layers::num[i].mapToLayer=list.at(posList).toInt();
		layers::num[i].mapToDatatype=list.at(posList+1).toInt();
		++posList;++posList;
		}
	else {
		layers::num[i].mapToLayer=s.value("layer/"+string+"mapToLayer",i).toInt();
		layers::num[i].mapToDatatype=s.value("layer/"+string+"mapToDatatype",-1).toInt();
	}


 }
   setOrganization();
   loaded=true;
}

void setup::saveSettings(layout *l){
   QSettings s;
   //s.setValue("geometry", l->geometry());
   if (s.value("setup/newviewmode",false).toBool()) {s.remove("setup/newviewmode");}
   else {
		s.setValue("pos",l->pos());
		s.setValue("size",l->size());
		s.setValue("toolbars", l->saveState());
		s.setValue("viewMode",(int)(l->viewMode));
   }
   s.setValue("language",language);
   s.setValue("setup/menu", l->isMenuBarVisible());
   s.setValue("setup/showMenuIcons",showMenuIcons);
   s.setValue("setup/scrollDirection", setup::scrollDirection);
   s.setValue("setup/mouse",mouseView);
   s.setValue("setup/report",showReport);
   s.setValue("setup/showgrid",showGrid);
   s.setValue("setup/displaycellname",displayCellName);
   s.setValue("setup/displaycells",displayCells);
   s.setValue("setup/displaycellorigin",displayCellOrigin);
   s.setValue("setup/layerDockStyle",layerDockStyle);
   s.setValue("setup/depthOfCellrefs",depthOfCellrefs);
   s.setValue("setup/paintEngine",paintEngine);
   s.setValue("preferedLanguage",preferedLanguage);
   QString string;
//printf("start time2: %d ms\n", setup::centralTimer.elapsed());
  QStringList stringList;
  QByteArray byteArray;
  QList<QVariant> list;
  for (int i=0;i<layersMax;i++){
	stringList<<layers::num[i].name;
	QColor c=layers::num[i].pen.color();
	byteArray.append(c.red());
	byteArray.append(c.green());
	byteArray.append(c.blue());
	//if (i<10) printf("%d %d %d\n",c.red(),c.green(),c.blue());
	byteArray.append(layers::num[i].getStyle());
	byteArray.append(layers::num[i].use?0:1);
	stringList<<layers::num[i].shortkey;
	list<<QVariant(layers::num[i].level3d)<<QVariant(layers::num[i].thickness3d);
	list<<QVariant(layers::num[i].mapToLayer)<<QVariant(layers::num[i].mapToDatatype);
 }
 s.setValue("layer/stringList",stringList);
 s.setValue("layer/byteArray",byteArray);
 s.setValue("layer/list",list);
/*
   for (int i=0;i<layersMax;i++){
	string=string.setNum(i);
	s.setValue("layer/"+string+"name",layers::num[i].name);
	s.setValue("layer/"+string+"color",layers::num[i].pen.color());
	//s.setValue("layer/"+string+"style",QVariant(layer->nr[i].brush));
	s.setValue("layer/"+string+"style",layers::num[i].getStyle());
	s.setValue("layer/"+string+"enable",layers::num[i].use);
	s.setValue("layer/"+string+"level3d",layers::num[i].level3d);
	s.setValue("layer/"+string+"thickness3d",layers::num[i].thickness3d);
	s.setValue("layer/"+string+"shortkey",layers::num[i].shortkey);
	s.setValue("layer/"+string+"mapToLayer",layers::num[i].mapToLayer);
	s.setValue("layer/"+string+"mapToDatatype",layers::num[i].mapToDatatype);
   }
*/
//printf("start time2: %d ms\n", setup::centralTimer.elapsed());
   s.setValue("setup/layers/autoDisableUnusedLayers", autoDisableUnusedLayers);
   s.setValue("setup/layers/displayedLayers", layers::displayedLayers);
   s.setValue("setup/mousecolor",mouseColor);
   s.setValue("setup/gridcolor",gridColor);
   s.setValue("setup/backgroundcolor",backgroundColor);
   s.setValue("setup/selectcolor",selectColor);
   s.setValue("setup/zerocolor",zeroColor);
   s.setValue("setup/highlightcolor",highlightColor);
   s.setValue("setup/highlightbrush",highlightBrush);
   s.setValue("font/iteration",fontIteration);
   s.setValue("font/size",fontSize);
   s.setValue("font/font",font);
   s.setValue("default/circular",circularDefault);
   s.setValue("default/path/width",defaultPathWidth);
   s.setValue("default/path/cap",defaultPathCap);
   s.setValue("default/text/width",defaultTextWidth);
   s.setValue("default/text/presentation",defaultTextPresentation);
   s.setValue("default/bezier",defaultBezierIteration);
   s.setValue("setup/fileformat/cifcircle",cifSaveCircle);
   s.setValue("setup/fileformat/ciftopcell",cifTopCell);
   s.setValue("setup/fileformat/dxfcircle",dxfSaveCircle);
   s.setValue("setup/fileformat/oasiscircle",oasisSaveCircle);
   s.setValue("setup/fileformat/oasisctrapezoid",oasisSaveCtrapezoid);
   s.setValue("setup/fileformat/oasistrapezoid",oasisSaveTrapezoid);
   s.setValue("setup/fileformat/oasisMapLayer",oasisMapLayer);
   s.setValue("setup/fileformat/oasiscblock",oasisSaveCBlock);
   s.setValue("setup/fileformat/oasisAutoMapDatatypes",oasisAutoMapDatatypes);
   s.setValue("setup/fileformat/gdsAutoMapDatatypes", gdsAutoMapDatatypes);
   s.setValue("setup/fileformat/gdsMapLayer",gdsMapLayer);
   s.setValue("setup/fileformat/gdsBoxToPolygon",gdsBoxToPolygon);
   s.setValue("setup/fileformat/gdsMaxPoints",gdsMaxPoints);
   s.setValue("setup/fileformat/gdsMultiXYRecord",gdsMultiXYRecord);
   s.setValue("setup/fileformat/gdsPad2048",gdsPad2048);
   s.setValue("setup/fileformat/csvFieldDelimiter",csvFieldDelimiter);
   s.setValue("setup/fileformat/lefBoundaryLayer",lefCellBoundaryLayer);
   s.setValue("setup/fileformat/sourceDatabase",sourceDatabase);
   s.setValue("setup/fileformat/pixelLayerMap",pixelLayerMap);
   s.setValue("setup/fileformat/pixelColorBits",pixelColorBits);
   s.setValue("setup/fileformat/pixelResolution",pixelResolution);
   s.setValue("setup/fileformat/svgEndOfLine",svgEndOfLine);
   s.setValue("setup/fileformat/epsEndOfLine",epsEndOfLine);
   s.setValue("setup/fileformat/epsScale",epsScale);
   s.setValue("default/polygon/removeNotNeededPoints",defaultPolygonRemoveNotNeededPoints);
   s.setValue("default/polygon/fixSelfintersecting",defaultPolygonFixSelfintersectingPolygons);
   s.setValue("installation/documentation",documentationDirectory);
   s.setValue("installation/macros",macroDirectory);
   s.setValue("installation/updateCheck",updateCheck);
   s.setValue("installation/lastUpdateCheck",lastUpdateCheck);
   s.setValue("setup/style",windowStyle);
   s.setValue("setup/fileformat/apLamda",apLamda);
   s.setValue("setup/fileformat/tldLamda",tldLamda);
   //netlist
   s.setValue("netlist/unnamednodes",netlistUnnamedNodes);
   s.setValue("netlist/globalnodes",netlistGlobalNodes);
   s.setValue("netlist/autotrigger",netlistAutotrigger);
   s.setValue("netlist/format",netlistFormat);
   s.setValue("netlist/formatSub",netlistSubFormat);
   s.setValue("netlist/formatSubModel",netlistSubModelFormat);

   QString lastPath=filedialog::getLastPath();
   if (lastPath!="") s.setValue("netlist/lastPath",lastPath);
  
}

QString setup::readStyle(){

	QSettings se;
	if (!se.contains("setup/style"))
		setOldOrganization();
	QSettings s;
	numOpen=s.value("layout/open",1).toInt();
	se.setValue("layout/open",numOpen+1);
	windowStyle=s.value("setup/style",windowStyle).toString();
	setOrganization();
        if ((!se.contains("layout/offset"))) {
		int off=numOpen;
		if (numOpen>100) off-=20;
		else if (numOpen>80) off-=18;
		else if (numOpen>50) off-=15;
		else if (numOpen>30) off-=10;
		se.setValue("layout/offset",off);;
		}
	return windowStyle;
}

//void setup::repaint(){
//if (layout_!=NULL) {layout_->drawing->paint();}
//}

void setup::setBackgroundColor(int red, int green, int blue){
 backgroundColor.setRgb(red,green,blue);
}

void setup::setMouseColor(int red, int green, int blue){
 mouseColor.setRgb(red,green,blue);
}

void setup::setGridColor(int red, int green, int blue){
 gridColor.setRgb(red,green,blue);
}

void setup::setZeroColor(int red, int green, int blue){
 zeroColor.setRgb(red,green,blue);
}

void setup::setSelectColor(int red, int green, int blue){
 selectColor.setRgb(red,green,blue);
}

void setup::setHighlightColor(int red, int green, int blue){
 highlightColor.setRgb(red,green,blue);
}

void setup::setHighlightBrush(int brush){
highlightBrush=brush;
}

void setup::setWireColor(int red, int green, int blue){
wireColor.setRgb(red,green,blue);
}

void setup::setBusColor(int red, int green, int blue){
busColor.setRgb(red,green,blue);
}

void setup::setTextColor(int red, int green, int blue){
textColor.setRgb(red,green,blue);
}

void setup::setDeviceColor(int red, int green, int blue){
deviceColor.setRgb(red,green,blue);
}

void setup::setInstanceColor(int red, int green, int blue){
instanceColor.setRgb(red,green,blue);
}

void setup::setPinColor(int red, int green, int blue){
pinColor.setRgb(red,green,blue);
}



void setup::checkDirs(){
QStringList macroDirs,helpDirs,fontDirs,fontFiles;
macroDirs<<QApplication::applicationDirPath()+"/../macros";
helpDirs<<QApplication::applicationDirPath()+"/../doc";
macroDirs<<(QDir::currentPath()+"/macros");
helpDirs<<(QDir::currentPath()+"/doc");
fontDirs<<(QDir::currentPath()+"/font");
fontDirs<<(QDir::currentPath()+"/fonts");
macroDirs<<(QDir::currentPath()+"/../macros");
helpDirs<<(QDir::currentPath()+"/../doc");
fontDirs<<(QDir::currentPath()+"/../font");
fontDirs<<(QDir::currentPath()+"/../fonts");
macroDirs<<(QDir::currentPath()+"/../../macros");
helpDirs<<(QDir::currentPath()+"/../../doc");
fontDirs<<(QDir::currentPath()+"/../../font");
fontDirs<<(QDir::currentPath()+"/../../fonts");
macroDirs<<(QDir::currentPath()+"/layout/macros");
helpDirs<<(QDir::currentPath()+"/layout/doc");
fontDirs<<(QDir::currentPath()+"/layout/font");
fontDirs<<(QDir::currentPath()+"/layout/fonts");
fontFiles<<"arial.ttf";
#ifdef Q_OS_WIN32
// windows

helpDirs<<("C:/program files/layout/doc");
helpDirs<<("C:/Programme/layout/doc");
macroDirs<<("C:/program files/layout/macros");
macroDirs<<("C:/Programme/layout/macros");
/*
fontFiles<<"arial.ttf";
fontDirs<<("C:/winnt/fonts");
fontDirs<<("C:/WINDOWS/fonts");
fontFiles<<"times.ttf";
*/
#else
#ifdef Q_WS_MAC
//mac
macroDirs<<(QDir::currentPath()+"/layout.app/macros");
helpDirs<<(QDir::currentPath()+"/layout.app/doc");
macroDirs<<(QDir::currentPath()+"/LayoutEditor.app/macros");
helpDirs<<(QDir::currentPath()+"/LayoutEditor.app/doc");
helpDirs<<("/usr/share/layout/doc");
helpDirs<<("/usr/local/share/layout/doc");
macroDirs<<("/usr/share/layout/macros");
macroDirs<<("/usr/local/share/layout/macros");
macroDirs<<("/Applications/layout.app/macros");
helpDirs<<("/Applications/layout.app/doc");
/*
fontDirs<<("/Library/Fonts");
fontDirs<<("/System/Library/Fonts");
fontFiles<<"arial.ttf";
fontFiles<<"Arial.ttf";
fontFiles<<"times.ttf";
fontFiles<<"Vera.ttf";
fontFiles<<"vera.ttf";
fontFiles<<"luxisr.ttf";
fontFiles<<"Helvetica.ttf";
fontFiles<<"helvetica.ttf";
fontFiles<<"times.ttf";
fontFiles<<"verdana.ttf";
fontFiles<<"l048016t.pfa";
fontFiles<<"l048036t.pfa";
fontFiles<<"l048013t.pfa";
fontFiles<<"c0611bt_.pfb";
*/
#else
// linux
helpDirs<<("/usr/share/layout/doc");
helpDirs<<("/usr/local/share/layout/doc");
macroDirs<<("/usr/share/layout/macros");
macroDirs<<("/usr/local/share/layout/macros");
/*
fontDirs<<("/usr/share/fonts/TTF/");
fontDirs<<("/usr/local/share/fonts/TTF/");
fontDirs<<("/usr/share/fonts/");
fontDirs<<("/usr/local/share/fonts/");
fontDirs<<("/usr/X11R6/lib/X11/fonts/Type1");
fontDirs<<("/usr/X11R6/lib/X11/fonts/truetype");
fontDirs<<("/usr/X11R6/lib/X11/fonts/TTF");
fontDirs<<("/usr/X11R6/lib/X11/fonts/corefonts");
fontDirs<<("/usr/X11R7/lib/X11/fonts/Type1");
fontDirs<<("/usr/X11R7/lib/X11/fonts/truetype");
fontDirs<<("/usr/X11R7/lib/X11/fonts/TTF");
fontFiles<<"arial.ttf";
fontFiles<<"times.ttf";
fontFiles<<"Vera.ttf";
fontFiles<<"vera.ttf";
fontFiles<<"luxisr.ttf";
fontFiles<<"Helvetica.ttf";
fontFiles<<"helvetica.ttf";
fontFiles<<"times.ttf";
fontFiles<<"verdana.ttf";
fontFiles<<"l048016t.pfa";
fontFiles<<"l048036t.pfa";
fontFiles<<"l048013t.pfa";
fontFiles<<"c0611bt_.pfb";
*/
#endif
#endif
//printf("ist dicDir (%s)\n",setup::documentationDirectory.toAscii().data());
QFile f(setup::documentationDirectory+"/index.html");
if (!f.exists())
	for (int i = 0; i < helpDirs.size(); i++){
        f.setFileName( helpDirs.at(i)+"/index.html");
	//printf("dicDir (%s)\n",helpDirs.at(i).toAscii().data());
	if (f.exists()) {
		setup::documentationDirectory=helpDirs.at(i);
		break;
		}
	}
//printf("ist macroDir (%s)\n",setup::macroDirectory.toAscii().data());
QDir d(setup::macroDirectory);
if ((!d.exists())||(setup::macroDirectory==""))
	for (int i = 0; i < macroDirs.size(); i++){
        d.setPath( macroDirs.at(i));
	//printf("macroDir (%s)\n",macroDirs.at(i).toAscii().data());
	if (d.exists()) {
		setup::macroDirectory=macroDirs.at(i);
		break;
		}
	}
//printf("ist font (%s)\n",setup::font.toAscii().data());
/*f.setFileName(setup::font);
if (!f.exists())
	for (int i = 0; i < fontDirs.size(); i++){
        d.setPath( fontDirs.at(i));
		for (int l=0;l<fontFiles.size();l++){
		//printf("font (%s,%s)\n",fontDirs.at(i).toAscii().data(),fontFiles.at(l).toAscii().data());
		if (d.exists(fontFiles.at(l))) {
			setup::font=fontDirs.at(i)+"/"+fontFiles.at(l);
			break;
			}
	}}
*/
}


int setup::getViewMode(){
	QSettings se;
	if (!se.contains("setup/defaultviewmode"))
		setOldOrganization();
	QSettings s;
	int i=s.value("setup/defaultviewmode",1).toInt();
	setOrganization();
	  return i;
}

void setup::setViewMode(int mode){
   QSettings s;
   s.setValue("setup/defaultviewmode",mode);
   s.setValue("setup/newviewmode",true);
   s.setValue("pos",QPoint(10, 45));
   s.remove("size");
   s.remove("toolbars");
 
}

QString setup::getLicenseType(){
	QSettings s;
	return s.value("license/type","").toString();
}
void setup::setLicenseType(QString mode){
	QSettings s;
	s.setValue("license/type",mode);
}
int setup::getNumOpen(){
	QSettings s;
	return s.value("layout/open",1).toInt();
}

void setup::releaseNotes(){
#ifdef GENISYS
        return ;
#endif
QString s;
QString s1;
	//s="LayoutEditor"+(QString)(QChar(0x2122))+"\r\n";
	//s+="\r\n";
	//s+=(QString)("Full Version ")+QString(VERSION)+"\r\n";
	s=QString("<TT><FONT SIZE=+3><b>Release Notes:</b></FONT></TT><br><TT><FONT SIZE=+0>LayoutEditor is available in tree different versions. The <a href='http://www.juspertor.com/buylicense.html'>full version</a> is needed to enable all features. See <a href='http://www.juspertor.com/lefeatures.html'>homepage</a> for details.</FONT></TT><br>");
	s1=QString("<b>Major new features/improvements in this release:</b><br>");
	s1+=QString("- improved usability by more contents menus and advanced dialogs,<br>");
	s1+=QString("- previous cell and snap shape feature,<br>");
	s1+=QString("- extension of the shape library,<br>");
	s1+=QString("- support of local encoding in macros,<br>");
	s1+=QString("- a couple smaller improvements,<br>");
	s1+=QString("- fixed some smaller bugs.<br>");
	//s1+=QString("<br>overall 32 new features/fixes within the last 3 month.");

		QMessageBox msgBox;
		QPushButton *donateButton = msgBox.addButton(tr("Buy License"),
		QMessageBox::ActionRole);
		QPushButton *nodonateButton = msgBox.addButton(tr("OK"),
		QMessageBox::ActionRole);
		msgBox.setText(s);
		msgBox.setInformativeText(s1);
		msgBox.setWindowTitle(tr("LayoutEditor"));
		msgBox.setIconPixmap(QPixmap(":/layout130logo"));
		msgBox.setMinimumWidth(800);
		msgBox.exec();
		
		if (msgBox.clickedButton() == donateButton) {
		QUrl url;
		url=QUrl(HOMEPAGE_BUY);
		QDesktopServices::openUrl(url);
		} else if (msgBox.clickedButton() == nodonateButton) {
		}
}

void setup::preShowMessage(){
QSettings se;
//#ifdef FULL_ VERSION
//#ifdef Q_WS_MAC
if (!se.contains(QString("message/releaseNotes")+VERSION)){
	se.setValue(QString("message/releaseNotes")+VERSION,true);
	releaseNotes();
	}
/*#el se
   numOpen=se.value("layout/open",1).toInt();
   if (numOpen>500) if (!se.contains("message/full")){
	se.setValue("message/full",true);
	QString s;
	s="LayoutEditor"+(QString)(QChar(0x2122))+"\r\n";
	s+="\r\n";
	s+=(QString)("Full Version ")+QString(VERSION)+"\r\n";
	s+=QString("\r\n");
	s+=QString("You are using the Full Version of the LayoutEditor.\r\n\r\n");
	s+=QString("Please remember:\r\n");
	s+=QString("The commercial use of the full version is exclusive \r\n");
	s+=QString("for supporters to this project.\r\n");
	s+=QString("IF YOU USE THIS PROGRAM IN A COMMERCIAL WAY AND\r\n");
	s+=QString("IF YOU HAVEN'T SUPPORT THE LAYOUTEDITOR YET,\r\n");
	s+=QString("USE THE GPL-VERSION OR MAKE A DONATION NOW!\r\n");
	s+="\r\n\r\n";
		QMessageBox msgBox;
		QPushButton *donateButton = msgBox.addButton(tr("Donate now"),
		QMessageBox::ActionRole);
		QPushButton *nodonateButton = msgBox.addButton(tr("Donation already done/non commercial use"),
		QMessageBox::ActionRole);
		msgBox.setText(s);
		msgBox.setWindowTitle(tr("LayoutEditor"));
		msgBox.setIconPixmap(QPixmap(":/layoutIcon"));
		msgBox.exec();
		
		if (msgBox.clickedButton() == donateButton) {
		QUrl url;
		url=QUrl("http://layout.sourceforge.net/donate.html" );
		QDesktopServices::openUrl(url);
		} else if (msgBox.clickedButton() == nodonateButton) {
		}
	}
#en dif
#en dif*/
}

void setup::setOrganization(){
   QCoreApplication::setOrganizationName("juspertor");
   QCoreApplication::setOrganizationDomain("juspertor.com");
   QCoreApplication::setApplicationName("layout");
}

void setup::setOldOrganization(){
   QCoreApplication::setOrganizationName("freeSoftware");
   QCoreApplication::setOrganizationDomain("layout.sourceforge.net");
   QCoreApplication::setApplicationName("layout");
}

#ifdef SCHEMATIC
void setup::saveSettings(schematic *l){
   init();
   QSettings s;
   s.setValue("schematic/pos",l->pos());
   s.setValue("schematic/size",l->size());
   s.setValue("schematic/toolbars", l->saveState());
   s.setValue("schematic/language",language);
   s.setValue("schematic/wirecolor",wireColor);
   s.setValue("schematic/buscolor",busColor);
   s.setValue("schematic/textcolor",textColor);
   s.setValue("schematic/pincolor",pinColor);
   s.setValue("schematic/devicecolor",deviceColor);
   s.setValue("schematic/instancecolor",instanceColor);
}
void setup::loadSettings(schematic *l){
 QSettings s;
   //geometry
   //l->setGeometry ( s.value("geometry",QRect(10,45,1000,700)).value<QRect>());
   QPoint pos = s.value("schematic/pos", QPoint(10, 45)).toPoint();
   QSize size = s.value("schematic/size", QSize(1000, 700)).toSize();
   if (pos.x()<0)pos.setX(45);
   if (pos.y()<0)pos.setY(45);
   QRect r= QApplication::desktop ()->screenGeometry();
   if (r.right()<=pos.x()+100)pos.setX(45);
   if (r.bottom()<=pos.y()+100)pos.setY(45);
   if (r.width()>100)
		if (size.width()>r.width())size.setWidth(r.width());
   if (r.height()>100)
		if (size.height()>r.height())size.setHeight(r.height());
   //printf("size: %d/%d is%d/%d\n",r.right(),r.bottom(),pos.x(),pos.y()); 
   l->resize(size);
   l->move(pos);
   if (language== s.value("schematic/language",QString("en")))
	l->restoreState  ( s.value("schematic/toolbars").value<QByteArray>());

   loadSchematicSettings(&s);
}
#endif

void setup::loadSchematicSettings(QSettings *s){
  #ifdef SCHEMATIC
  if (!schematicSettingsLoaded){
    schematicSettingsLoaded=true;
   wireColor=s->value("schematic/wirecolor",QColor(qRgb(128,128,128))).value<QColor>();
   busColor=s->value("schematic/buscolor",QColor(qRgb(44,30,199))).value<QColor>();
   textColor=s->value("schematic/textcolor",QColor(qRgb(90,90,90))).value<QColor>();
   pinColor=s->value("schematic/pincolor",QColor(qRgb(180,0,0))).value<QColor>();
   deviceColor=s->value("schematic/devicecolor",QColor(qRgb(31,0,255))).value<QColor>();
   instanceColor=s->value("schematic/instancecolor",QColor(qRgb(30,30,30))).value<QColor>();
  }
  #endif
}

#ifdef TEXTEDIT
void setup::saveSettings(textEdit *l){
  init();
   QSettings s;
   s.setValue("textedit/pos",l->pos());
   s.setValue("textedit/size",l->size());
   s.setValue("textedit/toolbars", l->saveState());
   s.setValue("textedit/language",language);
}
void setup::loadSettings(textEdit *l){
   QSettings s;
   //geometry
   //l->setGeometry ( s.value("geometry",QRect(10,45,1000,700)).value<QRect>());
   QPoint pos = s.value("textedit/pos", QPoint(10, 45)).toPoint();
   QSize size = s.value("textedit/size", QSize(600, 400)).toSize();
   if (pos.x()<0)pos.setX(45);
   if (pos.y()<0)pos.setY(45);
   QRect r= QApplication::desktop ()->screenGeometry();
   if (r.right()<=pos.x()+100)pos.setX(45);
   if (r.bottom()<=pos.y()+100)pos.setY(45);
   if (r.width()>100)
		if (size.width()>r.width())size.setWidth(r.width());
   if (r.height()>100)
		if (size.height()>r.height())size.setHeight(r.height());
   //printf("size: %d/%d is%d/%d\n",r.right(),r.bottom(),pos.x(),pos.y()); 
   l->resize(size);
   l->move(pos);
   if (language== s.value("textedit/language",QString("en")))
   l->restoreState  ( s.value("texteditc/toolbars").value<QByteArray>());

  
}
#endif

void setup::setNetlistFormat(QString type, QString value){
netlistFormat.insert(type,QVariant(value));
}

QString setup::getNetlistFormat(QString type){
return netlistFormat.value(type).toString();
}

QStringList setup::netlistFormats(){
 return netlistFormat.keys();
}

void setup::setNetlistSubFormat(QString type, QString value){
netlistSubFormat.insert(type,QVariant(value));
}
QString setup::getNetlistSubFormat(QString type){
return netlistSubFormat.value(type).toString();
}
void setup::setNetlistSubModelFormat(QString type, QString value){
netlistSubModelFormat.insert(type,QVariant(value));
}
QString setup::getNetlistSubModelFormat(QString type){
return netlistSubModelFormat.value(type).toString();
}


#ifdef Q_OS_MAC
void qt_mac_set_menubar_icons (bool);
#endif

#include "../styles.cpp"

#ifdef QT_STATIC
#ifndef QT_MAC_USE_COCOA
Q_IMPORT_PLUGIN(qjpeg)
Q_IMPORT_PLUGIN(qgif)
Q_IMPORT_PLUGIN(qmng)
#endif
#endif

/*#ifdef IMAGEPLUGINS
//Q_IMPORT_PLUGIN(qjpeg)
//Q_IMPORT_PLUGIN(qgif)
//Q_IMPORT_PLUGIN(qmng)
//Q_IMPORT_PLUGIN(qico)
#endif*/

void setup::init(){
  if (initDone) return;
#ifdef QT_MAC_USE_COCOA
	QDir dir(QApplication::applicationDirPath());
	dir.cdUp();
	dir.cd("plugins");
	QApplication::setLibraryPaths(QStringList(dir.absolutePath()));
#endif
#ifdef WINDOWS
QStringList dirList;
dirList<<"C:/Python26/Lib/site-packages/PyQt4";
dirList<<"C:/Python26/Lib/site-packages";
dirList<<"C:/Python25/Lib/site-packages/PyQt4";
dirList<<"C:/Python25/Lib/site-packages";
dirList<<"C:/Python27/Lib/site-packages/PyQt4";
dirList<<"C:/Python27/Lib/site-packages";
for (int n=0;n<dirList.size();n++){
  QDir dir(dirList.at(n));
  if (dir.exists()) QApplication::addLibraryPath(dirList.at(n));
}
#endif
    Q_INIT_RESOURCE(layout_rc);
    Q_INIT_RESOURCE(whatsthis);
#ifdef layout_style
    Q_INIT_RESOURCE(images);
#endif
    QApplication::setWindowIcon(QIcon(":/layoutIcon"));
    setup::setOrganization();

//#ifndef QT_MAC_USE_COCOA
    QApplication::setStyle(mystyles::createStyle(setup::readStyle()));
//#endif
	{
	//init layers
	layers l;
	}
 loadEarlySettings();
 if (!setup::showMenuIcons){
 		#ifdef Q_OS_MAC
 		qt_mac_set_menubar_icons (false);
 		#endif
}
qRegisterMetaType<elementCount>("elementCount");
loadSettings();
initDone=true;
}
