/***************************************************************************
 *   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 "filedialog.h"
#include <QStringList>
#include <QFileDialog>
#include <QUrl>
#include <QImageReader>
#include "general/setup.h"
#include "iconprovider.h"

QString filedialog::gdsFilter="GDS II (*.GDS *.gds *.GDS.gz *.gds.gz *.sf *.stm *.stem)";
QString filedialog::dxfFilter="DXF (*.DXF *.dxf)";
QString filedialog::oasisFilter="OASIS (*.OAS *.oas *.OASIS *.oasis *.OAS.gz *.oas.gz)";
QString filedialog::cifFilter="CIF (*.CIF *.cif)";
QString filedialog::svgFilter="SVG (*.SVG *.svg)";
QString filedialog::lefFilter="LEF (*.LEF *.lef)";
QString filedialog::defFilter="DEF (*.DEF *.def)";
QString filedialog::csvFilter="CSV (*.CSV *.csv)";
QString filedialog::psFilter="PS (*.PS *.ps)";
QString filedialog::epsFilter="EPS (*.EPS *.eps)";
QString filedialog::odbFilter="ODB++ ( matrix )";
QString filedialog::oaFilter="OpenAccess ( *.oa )";
QString filedialog::sourceFilter="SOURCE ( *.sou *.SOU *.source *.SOURCE )";
QString filedialog::gerberMacroFilter="Gerber Macro (*.gerber.layout)";
QString filedialog::electromaskFilter="Electromask (*.pat *.PAT *.8?? *.??m)";
QString filedialog::lastPath="";
QStringList filedialog::pixelFilter;


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


filedialog::~filedialog()
{
}


QString filedialog::extension(QString fn){
  int i=0;
  i=fn.lastIndexOf("/");
  //if ((i>1)&&(fn.mid(i+1)=="data.dm")){return (QString)("data.dm");}
  i=fn.lastIndexOf(".");
  if (i<1){return (QString)("");}
  if (fn.mid(i+1)=="layout") {
	 QString pre=fn.left(i);
	int k=pre.lastIndexOf(".");
	if (k>0) return fn.mid(k+1);
  }
  if (fn.mid(i+1)=="gz") {
	QString pre=fn.left(i);
	int k=pre.lastIndexOf(".");
	if (k>0) return fn.mid(k+1);
	}
  return fn.mid(i+1);
}

QString filedialog::getOpenFileName(){
 QFileDialog file;
 file.setIconProvider(new iconProvider());
 file.setAcceptMode ( QFileDialog::AcceptOpen);
 file.setWindowTitle(tr("Open"));
 file.setModal(true);
 QStringList types;
 QString pixelString;
 for (int i=0;i<QImageReader::supportedImageFormats ().count();i++){
	QString f=QImageReader::supportedImageFormats ().at(i);
	pixelString += " *." + f.toLower() + " *." + f.toUpper() + " ";}
 
 types << tr("supported Formats")+"(*.gds *.GDS *.DXF *.dxf *.OAS *.oas *.OASIS *.oasis *.cif *.CIF *.ap *.AP *.tld *.TLD *.tlc *.TLC *.grb *.GRB *.GBR *.gbr *.gerber *.GERBER *.gbx *.GBX *.gerber.layout *.svg *.SVG *.csv *.CSV *.GDS.gz *.gds.gz *.OAS.gz *.oas.gz *.stm *.stem"+pixelString+
#ifdef OPENACCESS
" *.oa "+
#endif
" *.8?? *.pat *.PAT *.??m )"
              << gdsFilter
              << dxfFilter
	      << oasisFilter
	      << cifFilter
#ifdef OPENACCESS
	      << oaFilter
#endif
	      << gerberMacroFilter
	      << svgFilter
	      << csvFilter
	      << electromaskFilter
	      << tr("All Files")+" (*)";
 file.setFilters(types);
 QList<QUrl> urls;//=file.sidebarUrls();
 QStringList sl;
 sl<<""<<QDir::homePath();
 if (setup::macroDirectory!="") sl<< setup::macroDirectory+"/.." <<setup::macroDirectory+"/../example" <<setup::macroDirectory;
 if (setup::documentationDirectory!="") sl<< setup::documentationDirectory<< setup::documentationDirectory+"/.."<< setup::documentationDirectory+"/../example";
#ifdef Q_OS_MAC
 sl << QString("/Volumes") << QString("/home");
#endif
#ifdef Q_WS_X11
 sl <<  QString("/home");
#endif
#ifndef Q_OS_WIN32
 sl<<QString("C:/")<< QString("D:/");
#endif
 for (int i=0;i<sl.size();i++){
    QDir u=QDir(sl[i]);
    if (u.exists())urls<<QUrl::fromLocalFile(u.absolutePath());
 }
 file.setSidebarUrls(urls);
 file.setFileMode(QFileDialog::ExistingFile);
 file.setViewMode(QFileDialog::List);
 if (lastPath!="") file.setDirectory(lastPath);
 else file.setDirectory(QDir::homePath ());
 file.show();
 int i=file.exec();
 if (i==QDialog::Accepted) {
	lastPath= file.directory().absolutePath();
 	QStringList files = file.selectedFiles();
        if (!files.isEmpty()) return files[0];
	else return QString::null;}
 else return QString::null;
}

QString filedialog::getSaveFileName(){
 QFileDialog file;
 file.setIconProvider(new iconProvider());
 file.setAcceptMode ( QFileDialog::AcceptSave);
 file.setWindowTitle(tr("Save"));
 file.setModal(true);
 if (lastPath!="") file.setDirectory(lastPath);
 else file.setDirectory(QDir::homePath ());
 if (pixelFilter.size()==0) setPixelFilter();
 QStringList types;
 types << gdsFilter << dxfFilter << oasisFilter << cifFilter<< gerberMacroFilter << svgFilter<< csvFilter
	;
 types<<pixelFilter;
 types<<tr("All Files")+" (*)";
 file.setFilters(types);
 file.setFileMode(QFileDialog::AnyFile);
 file.setViewMode(QFileDialog::List);
 file.show();
 int i=file.exec();
 if (i==QDialog::Accepted) {
 	QString fn="";
	lastPath= file.directory().absolutePath();
 	QStringList files = file.selectedFiles();
        if (!files.isEmpty()) fn=files[0];
	QString ext=extension(fn);
	//printf("%s\n",file.selectedFilter().toAscii().data());
	if (file.selectedFilter()==gdsFilter){
		if (gdsExtension(ext)){return fn;}
		else return fn+".gds";
	}
	if (file.selectedFilter()==dxfFilter){
		if (dxfExtension(ext)){return fn;}
		else return fn+".dxf";
	}
	if (file.selectedFilter()==oasisFilter){
		if (oasisExtension(ext)){return fn;}
		else return fn+".oas";
	}
	if (file.selectedFilter()==cifFilter){
		if (cifExtension(ext)){return fn;}
		else return fn+".cif";
	}
	if (file.selectedFilter()==svgFilter){
		if (svgExtension(ext)){return fn;}
		else return fn+".svg";
	}
	if (file.selectedFilter()==csvFilter){
		if (csvExtension(ext)){return fn;}
		else return fn+".csv";
	}
	if (file.selectedFilter()==psFilter){
		if (psExtension(ext)){return fn;}
		else return fn+".ps";
	}
	if (file.selectedFilter()==epsFilter){
		if (epsExtension(ext)){return fn;}
		else return fn+".eps";
	}
	if (file.selectedFilter()==sourceFilter){
		if (sourceExtension(ext)){return fn;}
		else return fn+".sou";
	}
	if (file.selectedFilter()==gerberMacroFilter){
		if (gerberMacroExtension(ext)){return fn;}
		else return fn+".gerber.layout";
	}
	if (file.selectedFilter()==odbFilter){
		if (fn.right(14)=="/matrix/matrix"){return fn;}
		else return fn+"/matrix/matrix";
	}
	if (pixelFilter.contains(file.selectedFilter())){
		if (pixelExtension(ext)){return fn;}
		else return fn+"."+file.selectedFilter().left(3).toLower();
	}
 	return fn;
 	}
 else return QString::null;
}

bool filedialog::gdsExtension(QString s){
if (s=="GDS"){return true;}
if (s=="gds"){return true;}
if (s=="GDS.gz"){return true;}
if (s=="gds.gz"){return true;}
if (s=="sf"){return true;}
if (s=="stm"){return true;}
if (s=="stem"){return true;}
return false;
}

bool filedialog::dxfExtension(QString s){
if (s=="DXF"){return true;}
if (s=="dxf"){return true;}
return false;
}
bool filedialog::oasisExtension(QString s){
if (s=="OAS"){return true;}
if (s=="oas"){return true;}
if (s=="OAS.gz"){return true;}
if (s=="oas.gz"){return true;}
if (s=="oasis"){return true;}
if (s=="OASIS"){return true;}
return false;
}
bool filedialog::cifExtension(QString s){
if (s=="CIF"){return true;}
if (s=="cif"){return true;}
return false;
}
bool filedialog::apExtension(QString s){
if (s=="AP"){return true;}
if (s=="ap"){return true;}
return false;
}

bool filedialog::svgExtension(QString s){
if (s=="SVG"){return true;}
if (s=="svg"){return true;}
return false;
}

bool filedialog::csvExtension(QString s){
if (s=="CSV"){return true;}
if (s=="csv"){return true;}
return false;
}

bool filedialog::lefExtension(QString s){
if (s=="LEF"){return true;}
if (s=="lef"){return true;}
return false;
}
bool filedialog::defExtension(QString s){
if (s=="DEF"){return true;}
if (s=="def"){return true;}
return false;
}

bool filedialog::psExtension(QString s){
if (s=="PS"){return true;}
if (s=="ps"){return true;}
return false;
}

bool filedialog::epsExtension(QString s){
if (s=="EPS"){return true;}
if (s=="eps"){return true;}
return false;
}

bool filedialog::tldExtension(QString s){
if (s=="TLD"){return true;}
if (s=="tld"){return true;}
if (s=="TLC"){return true;}
if (s=="tlc"){return true;}
return false;
}

bool filedialog::sourceExtension(QString s){
if (s=="sou"){return true;}
if (s=="SOU"){return true;}
if (s=="source"){return true;}
if (s=="SOURCE"){return true;}
return false;
}

bool filedialog::odbExtension(QString s){
if (s=="/matrix/matrix"){return true;}
return false;
}

bool filedialog::gerberExtension(QString s){
if (s=="grb"){return true;}
if (s=="GRB"){return true;}
if (s=="GBR"){return true;}
if (s=="gbr"){return true;}
if (s=="gbx"){return true;}
if (s=="GBX"){return true;}
if (s=="gerber"){return true;}
if (s=="GERBER"){return true;}
return false;
}

bool filedialog::electromaskExtension(QString s){
if (s=="pat"){return true;}
if (s=="PAT"){return true;}
if (s.length()!=3) return false;
if (s.left(1)=="8"){return true;}
if (s.right(1)=="m"){return true;} 
return false;
}


bool filedialog::oaExtension(QString s){
if (s=="oa"){return true;}
//if (s=="data.dm"){return true;}
return false;
}

bool filedialog::gerberMacroExtension(QString s){
if (s=="gerber.layout"){return true;}
return false;
}

bool filedialog::pixelExtension(QString s){
 for (int i=0;i<QImageReader::supportedImageFormats ().count();i++){
	if (s==QImageReader::supportedImageFormats ().at(i).toLower()){return true;}
	if (s==QImageReader::supportedImageFormats ().at(i).toUpper()){return true;}
	}
return false;
}

QString filedialog::getFileType(QString s){
  QString ex=extension(s);
  
if (gdsExtension(ex)) return "gds";
if (dxfExtension(ex)) return "dxf";
if (cifExtension(ex)) return "cif";
if (oasisExtension(ex)) return "oasis";
if (apExtension(ex)) return "ap";
if (tldExtension(ex)) return "tld";
if (svgExtension(ex)) return "svg";
if (lefExtension(ex)) return "lef";
if (defExtension(ex)) return "def";
if (csvExtension(ex)) return "csv";
if (gerberExtension(ex)) return "gerber";
if (gerberMacroExtension(ex)) return "gerber.layout";
if (odbExtension(s.right(14))) return "odb++";
if (psExtension(ex)) return "ps";
if (sourceExtension(ex)) return "source";
if (epsExtension(ex)) return "eps";
if (pixelExtension(ex)) return "pixel";
#ifdef OPENACCESS
if (oaExtension(ex)) return "oa";
#endif
if (electromaskExtension(ex)) return "emask";
return "";
}

QString filedialog::getLastPath(){return lastPath;}

void filedialog::setLastPath(QString s){lastPath=s;}

void filedialog::setPixelFilter(){
pixelFilter.clear();
QStringList used;
 for (int i=0;i<QImageReader::supportedImageFormats ().count();i++){
	if ((QImageReader::supportedImageFormats ().at(i).toUpper()!="SVG")&& 
	(QImageReader::supportedImageFormats ().at(i).toUpper()!="EPS")&& 
	(( !used.contains(QImageReader::supportedImageFormats ().at(i).toUpper())))){
		//printf("- %s \n",QImageReader::supportedImageFormats ().at(i).toUpper().data());
		QString s=QImageReader::supportedImageFormats ().at(i).toUpper()+" (";
		s+="*."+QImageReader::supportedImageFormats ().at(i).toUpper();
		s+=" *."+QImageReader::supportedImageFormats ().at(i).toLower()+")";
		pixelFilter<<s;
		used<<QImageReader::supportedImageFormats ().at(i).toUpper();
		}
	}
}

