/***************************************************************************
                          projectprivate.cpp  -  description
                             -------------------
    begin                : Mon Oct 4 20:49:39 2004
    copyright            : (C) 2000 by Yacovlev Alexander & Dmitry Poplavsky <pdima@mail.univ.kiev.ua>
                           (C) 2001-2004 by Andras Mantia <amantia@kde.org>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "projectprivate.h"

//qt includes
#include <tqcheckbox.h>
#include <tqdir.h>
#include <tqfile.h>
#include <tqradiobutton.h>
#include <tqwidgetstack.h>
#include <tqwizard.h>
#include <tqeventloop.h>

//kde includes
#include <tdeaction.h>
#include <tdeapplication.h>
#include <kcharsets.h>
#include <tdeconfig.h>
#include <kdirwatch.h>
#include <tdefiledialog.h>
#include <kinputdialog.h>
#include <tdeio/netaccess.h>
#include <klineedit.h>
#include <tdelocale.h>
#include <tdemainwindow.h>
#include <tdemessagebox.h>
#include <tdeparts/componentfactory.h>
#include <kprogress.h>
#include <kstandarddirs.h>
#include <tdetempfile.h>
#include <kurl.h>
#include <kurlrequester.h>
#include <kurlrequesterdlg.h>

//app includes
#include "copyto.h"
#include "debuggerclient.h"
#include "dtds.h"
#include "project.h"
#include "projectnewgeneral.h"
#include "projectnewlocal.h"
#include "projectnewweb.h"
#include "projectnewfinal.h"
#include "qpevents.h"
#include "quantacommon.h"
#include "resource.h"
#include "uploadprofiles.h"
#include "viewmanager.h"

ProjectPrivate::ProjectPrivate(Project *p)
          : TQObject(), config(0L), m_dirWatch(0L), tempFile(0L), sessionTempFile(0L)
{
  parent = p;
  m_projectFiles.setAutoDelete(true);
  m_showUploadTreeviews = true;
  m_eventsEnabled = true;
  m_events = new EventActions();
  init();
  m_wizTitle = i18n("<b>Insert Files in Project</b>");
}

ProjectPrivate::~ProjectPrivate()
{
  delete m_events;
}

/** setup of the actions */
void ProjectPrivate::initActions(TDEActionCollection *ac)
{
  (void) new TDEAction( i18n( "&New Project..." ), "window-new", 0,
                        this, TQ_SLOT( slotNewProject() ),
                        ac, "project_new" );

  (void) new TDEAction( i18n( "&Open Project..." ), "project_open", 0,
                        this, TQ_SLOT( slotOpenProject() ),
                        ac, "project_open" );
  m_projectRecent =
      KStdAction::openRecent(parent, TQ_SLOT(slotOpenProject(const KURL&)),
                            ac, "project_open_recent");
  m_projectRecent->setText(i18n("Open Recent Project"));
  m_projectRecent->setIcon("project_open");
  m_projectRecent->setToolTip(i18n("Open/Open recent project"));
  connect(m_projectRecent, TQ_SIGNAL(activated()), this, TQ_SLOT(slotOpenProject()));

  closeprjAction =  new TDEAction( i18n( "&Close Project" ), "window-close", 0,
                        this, TQ_SLOT( slotCloseProject() ),
                        ac, "project_close" );


  openPrjViewAction = new TDESelectAction( i18n( "Open Project &View..." ), 0,
                        ac, "project_view_open" );
  connect(openPrjViewAction, TQ_SIGNAL(activated(const TQString &)),
          this, TQ_SLOT(slotOpenProjectView(const TQString &)));
  openPrjViewAction->setToolTip(i18n("Open project view"));

  savePrjViewAction = new TDEAction( i18n( "&Save Project View" ), "document-save", 0,
                        this, TQ_SLOT( slotSaveProjectView() ),
                        ac, "project_view_save" );
  saveAsPrjViewAction = new TDEAction( i18n( "Save Project View &As..." ), "document-save-as", 0,
                        this, TQ_SLOT( slotSaveAsProjectView() ),
                        ac, "project_view_save_as" );
  deletePrjViewAction = new TDESelectAction( i18n( "&Delete Project View" ), "edit-delete", 0,
                        ac, "project_view_delete" );
  connect(deletePrjViewAction, TQ_SIGNAL(activated(const TQString &)),
          this, TQ_SLOT(slotDeleteProjectView(const TQString &)));
  deletePrjViewAction->setToolTip(i18n("Close project view"));



  insertFileAction = new TDEAction( i18n( "&Insert Files..." ), 0,
                        this, TQ_SLOT( slotAddFiles() ),
                        ac, "project_insert_file" );

  insertDirAction = new TDEAction( i18n( "Inser&t Folder..." ), 0,
                        this, TQ_SLOT( slotAddDirectory() ),
                        ac, "project_insert_directory" );

  rescanPrjDirAction = new TDEAction( i18n( "&Rescan Project Folder..." ), "reload", 0,
                        parent, TQ_SLOT( slotRescanPrjDir() ),
                        ac, "project_rescan" );

  uploadProjectAction = new TDEAction( i18n( "&Upload Project..." ), "go-up", Key_F8,
                        parent, TQ_SLOT( slotUpload() ),
                        ac, "project_upload" );

  projectOptionAction = new TDEAction( i18n( "&Project Properties" ), "configure", SHIFT + Key_F7,
                        parent, TQ_SLOT( slotOptions() ),
                        ac, "project_options" );

  saveAsProjectTemplateAction =
            new TDEAction( i18n( "Save as Project Template..." ), 0,
                        m_mainWindow, TQ_SLOT( slotFileSaveAsProjectTemplate() ),
                        ac, "save_project_template" );

  saveSelectionAsProjectTemplateAction =
                        new TDEAction( i18n( "Save Selection to Project Template File..." ), 0,
                                    m_mainWindow, TQ_SLOT( slotFileSaveSelectionAsProjectTemplate() ),
                                    ac, "save_selection_project_template" );
  adjustActions();
}


void ProjectPrivate::adjustActions()
{
  bool projectExists = parent->hasProject();
  closeprjAction->setEnabled(projectExists);
  openPrjViewAction->setEnabled(projectExists);
  savePrjViewAction->setEnabled(projectExists);
  saveAsPrjViewAction->setEnabled(projectExists);
  deletePrjViewAction->setEnabled(projectExists);

  insertFileAction->setEnabled(projectExists);
  insertDirAction->setEnabled(projectExists);
  rescanPrjDirAction->setEnabled(projectExists);
  uploadProjectAction->setEnabled(projectExists);
  projectOptionAction->setEnabled(projectExists);
  saveAsProjectTemplateAction->setEnabled(projectExists);
  saveSelectionAsProjectTemplateAction->setEnabled(projectExists);

  adjustViewActions();
  parent->slotShowProjectToolbar(projectExists);
}


void ProjectPrivate::adjustViewActions()
{
  TQStringList viewList = projectViewList();
  TQString oldItem = openPrjViewAction->currentText();
  openPrjViewAction->clear();
  openPrjViewAction->setItems(viewList);
  int i = viewList.findIndex(oldItem);
  if (i > -1)
    openPrjViewAction->setCurrentItem(i);
  deletePrjViewAction->clear();
  deletePrjViewAction->setItems(viewList);
  bool hasView = !currentProjectView.isEmpty();
  savePrjViewAction->setEnabled(hasView);
}


TQStringList ProjectPrivate::projectViewList()
{
  TQStringList list;
  TQDomNodeList nl = dom.elementsByTagName("projectview");
  TQDomElement el;
  for (uint i = 0; i < nl.count(); i++)
  {
    el = nl.item(i).cloneNode().toElement();
    list += el.attribute("name");
  }
  list.sort();
  return list;
}

void ProjectPrivate::init()
{
  projectURL  = KURL();
  templateURL = KURL();
  projectName = TQString();
  m_modified = false;
  m_defaultDTD = qConfig.defaultDocType;
  excludeRx.setPattern(".*~$");
  excludeList.clear();
  excludeList.append("*~");
  usePreviewPrefix = false;
  previewPrefix = KURL();
  m_persistentBookmarks = false;
  m_debuggerPersistentBreakpoints = false;
  m_debuggerPersistentWatches = false;
  m_excludeCvsignore = false;
  currentProjectView = TQString();
  m_projectFiles.clear();
  m_mailingList = TQString();
  m_teamLeader.name = TQString();
  m_teamLeader.email = TQString();
  m_taskLeaders.clear();
  m_subprojectLeaders.clear();
  m_subprojects.clear();
  m_simpleMembers.clear();
  UploadProfiles::ref()->clear();
}


void ProjectPrivate::openCurrentView()
{
  if (currentProjectView.isEmpty())
    return;
  KURL::List urlsToOpen, urlsInView;
  TQDomNodeList nl = dom.elementsByTagName("projectview");
  TQDomElement el;
  for (uint i = 0; i < nl.count(); i++)
  {
    el = nl.item(i).cloneNode().toElement();
    if (el.attribute("name") == currentProjectView)
    {
      TQDomNodeList itemNodes = el.childNodes();
      for (uint j = 0; j < itemNodes.count(); j++)
      {
        TQDomElement el2 = itemNodes.item(j).cloneNode().toElement();
        KURL url = baseURL;
        QuantaCommon::setUrl(url,el2.attribute("url"));
        url = QExtFileInfo::toAbsolute(url, baseURL);
        if (el2.nodeName() == "viewitem")
        {
          urlsInView.append(url);
          if (!ViewManager::ref()->isOpened(url) && QExtFileInfo::exists(url, true, m_mainWindow))
            urlsToOpen.append(url);
        } else {
          if (el2.nodeName() == "viewtoolbar")
          {
            parent->loadToolbarFile(url);
          }
        }
      }
      // first we open what we want, might be that a wanted file is already open!
      parent->openFiles(urlsToOpen, m_defaultEncoding);
      // second we close what we don't want
      KURL::List openURLs = ViewManager::ref()->openedFiles(true); // get open urls
      KURL::List::Iterator it;
      for ( it = openURLs.begin(); it != openURLs.end(); ++it )
      {
        if (urlsInView.findIndex( *it ) == -1)
          parent->closeFile (*it);
      }
      break;
    }
  }
  TQStringList viewList = projectViewList();
  int i = viewList.findIndex(currentProjectView);
  if (i > -1)
    openPrjViewAction->setCurrentItem(i);
  adjustViewActions();
}

/** Opens a project view (toolbars & files). */
void ProjectPrivate::slotOpenProjectView(const TQString &view)
{
  currentProjectView = view;
  openCurrentView();
}

/** insert files */
void ProjectPrivate::insertFiles( KURL::List files )
{
  TQDomElement  el;
  TQDomNodeList nl = dom.elementsByTagName("item");
  parent->statusMsg( i18n("Adding files to the project...") );
  progressBar->setTotalSteps(2 * files.count() - 2);
  progressBar->setValue(0);
  progressBar->setTextEnabled(true);

  KURL::List::Iterator it;
  for ( it = files.begin(); it != files.end(); ++it )
  {
    if (m_projectFiles.contains(*it))
    {
        it = files.erase(it);
        --it;
    }
    progressBar->advance(1);
  }
  for ( it = files.begin(); it != files.end(); ++it )
  {
    if (! (*it).isEmpty())
    {
      KURL url = *it;
      url.setPath(url.directory(false));
      while ( baseURL.isParentOf(url) )
      {
        if (!m_projectFiles.contains(url))
        {
          el = dom.createElement("item");
          el.setAttribute("url", QuantaCommon::qUrl(QExtFileInfo::toRelative(url, baseURL, false)));
          dom.firstChild().firstChild().appendChild(el);
          m_projectFiles.insert( new ProjectURL(url, "", 1, false, el) );
          emit eventHappened("after_project_add", url.url(), TQString());
          m_modified = true;
        }
        url.setPath(url.directory(false));
      }
      el = dom.createElement("item");
      url = *it;
      if (!excludeRx.exactMatch(url.path()))
      {
        el.setAttribute("url", QuantaCommon::qUrl(QExtFileInfo::toRelative(url, baseURL, false)));
        dom.firstChild().firstChild().appendChild(el);
        m_projectFiles.insert( new ProjectURL(url, "", 1, false, el) );
        emit eventHappened("after_project_add", url.url(), TQString());
        m_modified = true;
      }
    }
    progressBar->advance(1);
  }
  progressBar->setTotalSteps(1);
  progressBar->setValue(0);
  progressBar->setTextEnabled(false);

  parent->reloadTree(&(m_projectFiles), false, TQStringList());
  parent->newStatus();
  parent->statusMsg(TQString());
}


/** insert files from dir recursive */
void ProjectPrivate::insertFiles(const KURL& pathURL, const TQString& mask )
{
  KURL::List list;

  list.append(pathURL);
  list += QExtFileInfo::allFiles(pathURL, mask, m_mainWindow);
  insertFiles(list);
}


void ProjectPrivate::loadProjectXML()
{
//TODO: Optimize reading. For example iterate through all the nodes and handle them
//according to the found node type
  parent->statusMsg( i18n("Reading the project file...") );
  TQDomNode    no;
  TQDomElement el;
  KURL url;
  TQDomNode projectNode = dom.firstChild().firstChild();
  projectName = projectNode.toElement().attribute("name");

  if ( projectNode.isNull() || projectName.isEmpty() )
  {
    parent->hideSplash();
    KMessageBox::sorry(m_mainWindow, i18n("Invalid project file.") );
    adjustActions();
    return;
  }

  m_modified = false;
  TQString tmpString;
  TQDomNode sessionNode;

  if (!m_createSessionDom)
  {
    sessionNode = m_sessionDom.firstChild().firstChild();
    tmpString = sessionNode.toElement().attribute("previewPrefix");
    if ( !tmpString.isEmpty())
    {
      previewPrefix = KURL::fromPathOrURL(tmpString);
    }
    usePreviewPrefix = ( sessionNode.toElement().attribute("usePreviewPrefix") == "1");
    m_persistentBookmarks = (sessionNode.toElement().attribute("usePersistentBookmarks") == "1");
  } else //TODO: Remove when upgrade from 3.4 is not supported
  {
    tmpString = projectNode.toElement().attribute("previewPrefix");
    if ( !tmpString.isEmpty())
    {
      previewPrefix = KURL::fromPathOrURL(tmpString);
    }
    usePreviewPrefix = ( projectNode.toElement().attribute("usePreviewPrefix") == "1");
    m_persistentBookmarks = (projectNode.toElement().attribute("usePersistentBookmarks") == "1");

    sessionNode = m_sessionDom.firstChild().firstChild();
    sessionNode.toElement().setAttribute("usePreviewPrefix", usePreviewPrefix ? "1" : "0");
    sessionNode.toElement().setAttribute("previewPrefix", previewPrefix.url());
    sessionNode.toElement().setAttribute("usePersistentBookmarks", m_persistentBookmarks ? "1" : "0");
  }
  no = sessionNode.namedItem("itemcursorpositions");
  if (no.isNull())
  {
    el = m_sessionDom.createElement("itemcursorpositions");
    sessionNode.appendChild(el);
  }
  m_eventsEnabled = projectNode.toElement().attribute("enableEvents", "true") == "true";
  m_defaultEncoding = projectNode.toElement().attribute("encoding");
  if (m_defaultEncoding.isEmpty())
  {
    m_defaultEncoding = qConfig.defaultEncoding;
  }
  no = projectNode.namedItem("author");
  author = no.firstChild().nodeValue();
  no = projectNode.namedItem("email");
  email = no.firstChild().nodeValue();
  no = projectNode.namedItem("defaultDTD");
  m_defaultDTD = no.firstChild().nodeValue();
  if (m_defaultDTD.isEmpty()) m_defaultDTD = qConfig.defaultDocType;

  no = projectNode.namedItem("autoload");
  currentProjectView = no.toElement().attribute("projectview");
  if (currentProjectView.isEmpty())
  {
    TQStringList list = projectViewList();
    if (list.count() > 0)
      currentProjectView = list[0];
  }
  // Debugger
  no = projectNode.namedItem("debuggerclient");
  debuggerClient = no.firstChild().nodeValue();
  m_debuggerPersistentBreakpoints = (no.toElement().attribute("persistentBreakpoints") == "1");
  m_debuggerPersistentWatches = (no.toElement().attribute("persistentWatches") == "1");

  no = projectNode.namedItem("templates");
  tmpString = no.firstChild().nodeValue();
  templateURL = baseURL;
  if(no.isNull()) // compatability
  {
    templateURL.setPath("templates/");
    m_modified = true;
  }
  else
  {
    QuantaCommon::setUrl(templateURL, tmpString);
  }
  if (tmpString != QuantaCommon::qUrl(templateURL) )
  {
    el = no.toElement();
    url = QExtFileInfo::toRelative(templateURL, baseURL);
    if(el.isNull())
    {
      el = dom.createElement("templates");
      dom.firstChild().firstChild().appendChild(el);
      el.appendChild(dom.createTextNode(QuantaCommon::qUrl(url)));
    }
    else
    {
      el.firstChild().setNodeValue(QuantaCommon::qUrl(url));
    }
  }
  templateURL = QExtFileInfo::toAbsolute(templateURL, baseURL);

  no = projectNode.namedItem("toolbars");
  toolbarURL = baseURL;
  if (no.isNull()) // compatability
  {
    toolbarURL.setPath(baseURL.path(1) + "toolbars/");
    m_modified = true;
  }
  else
  {
    QuantaCommon::setUrl(toolbarURL,no.firstChild().nodeValue());
  }
  if (tmpString != QuantaCommon::qUrl(toolbarURL))
  {
    el = no.toElement();
    url = QExtFileInfo::toRelative(toolbarURL, baseURL);
    if(el.isNull())
    {
      el = dom.createElement("toolbars");
      dom.firstChild().firstChild().appendChild(el);
      el.appendChild(dom.createTextNode(QuantaCommon::qUrl(url)));
    }
    else
    {
      el.firstChild().setNodeValue(QuantaCommon::qUrl(url));
    }
  }
  toolbarURL = QExtFileInfo::toAbsolute(toolbarURL, baseURL);

  no = projectNode.namedItem("exclude");
  m_excludeCvsignore = (no.toElement().attribute("cvsignore", "false") == "true");
  TQString excludeStr = no.firstChild().nodeValue();
  TQString regExpStr = "";
  excludeList = TQStringList::split(';', excludeStr);
  for (uint i = 0; i < excludeList.count(); i++)
  {
    excludeStr = excludeList[i].stripWhiteSpace();
    TQString str = excludeStr;
    if (!excludeStr.startsWith("*"))
    {
      if (!excludeStr.endsWith("*"))
        str += "|^" + excludeStr + "/*|*/" + excludeStr + "/*|*/" + excludeStr + "$";
      else
        str += "|^" + excludeStr + "|*/" + excludeStr + "$";
    } else
    if (!excludeStr.endsWith("*"))
      str = excludeStr + "/*|"+ excludeStr + "$";
    str.replace(".","\\.");
    str.replace("*",".*");
    str.replace("?",".");
    regExpStr.append(str);
    if (i+1 < excludeList.count())
      regExpStr.append("|");
  }
  TQDomNodeList nl = dom.firstChild().firstChild().childNodes();
  if (m_excludeCvsignore && projectURL.isLocalFile())
  {
    TQStringList cvsIgnoreList;
    uint nlCount = nl.count();
    for ( uint i = 0; i < nlCount; i++ )
    {
      el = nl.item(i).toElement();
      tmpString = el.attribute("url");
      if (!tmpString.endsWith("/")) continue;
      cvsIgnoreList.append(tmpString);
    }
    cvsIgnoreList.append("");
    for (TQStringList::ConstIterator it = cvsIgnoreList.constBegin(); it != cvsIgnoreList.constEnd(); ++it)
    {
      tmpString = *it;
      TQString rxStr;
      KURL cvsIgnoreURL;
      cvsIgnoreURL.setPath(baseURL.path(1) + tmpString + ".cvsignore");
      TQFile f(cvsIgnoreURL.path());
      if (f.open(IO_ReadOnly))
      {
        TQTextStream stream(&f);
        stream.setEncoding(TQTextStream::UnicodeUTF8);
        TQString line;
        while (!stream.atEnd())
        {
            line = stream.readLine().stripWhiteSpace();
            line.prepend(tmpString);
            if (!line.endsWith("*"))
              line = line + "/*|"+ line + "$";
            if (!line.startsWith("*"))
              line.prepend("^");
            line.replace(".","\\.");
            line.replace("*",".*");
            line.replace("?",".");
            rxStr += line + "|";
        }
        regExpStr.prepend(rxStr);
        f.close();
      }
    }
  }
  excludeRx.setPattern(regExpStr);

  m_events->clear();
  nl = projectNode.toElement().elementsByTagName("event");
  uint nlCount = nl.count();
  for ( uint i = 0; i < nlCount; i++ )
  {
    el = nl.item(i).toElement();
    EventAction ev;
    if (el.attribute("type", "internal") == "internal")
      ev.type = EventAction::Internal;
    else
      ev.type = EventAction::External;
    ev.action = el.attribute("action");
    TQDomNodeList nl2 = el.elementsByTagName("argument");
    for (uint j = 0; j < nl2.count(); j++)
    {
      TQString s = nl2.item(j).toElement().text();
      if (s != "--not set--" && !s.isEmpty())
          ev.arguments << s;
    }
    if (m_events->contains(el.attribute("name")))
    {
      (*m_events)[el.attribute("name")].append(ev);
    } else
    {
      TQValueList<EventAction> evList;
      evList.append(ev);
      m_events->insert(el.attribute("name"), evList);
    }
  }

  TQDomNode teamNode = projectNode.namedItem("teamdata");
  no = teamNode.namedItem("leader");
  if (!no.isNull())
  {
     m_teamLeader.name = no.namedItem("name").toElement().text();
     m_teamLeader.nickName = no.namedItem("nickName").toElement().text();
     m_teamLeader.email = no.namedItem("email").toElement().text();
  }

  m_subprojects.clear();
  m_subprojectLeaders.clear();
  no = teamNode.namedItem("subprojectleaders");
  nl = no.toElement().elementsByTagName("subproject");
  for (uint i = 0; i < nl.count(); i++)
  {
     el = nl.item(i).toElement();
     TQDomElement el2 = el.namedItem("subprojectleader").toElement();
     TeamMember member;
     member.name = el2.attribute("name");
     member.nickName = el2.attribute("nickName");
     member.email = el2.attribute("email");
     SubProject subproject;
     subproject.name = el.attribute("name");
     subproject.location = el.attribute("location");
     m_subprojects.append(subproject);
     m_subprojectLeaders[subproject.name] = member;
  }

  m_taskLeaders.clear();
  no = teamNode.namedItem("taskleaders");
  nl = no.toElement().elementsByTagName("projecttask");
  for (uint i = 0; i < nl.count(); i++)
  {
     el = nl.item(i).toElement();
     TeamMember member;
     member.name = el.attribute("tasklead");
     member.nickName = el.attribute("nickName");
     member.email = el.attribute("email");
     m_taskLeaders[el.attribute("task")] = member;
  }

  m_simpleMembers.clear();
  nl = teamNode.toElement().elementsByTagName("member");
  for (uint i = 0; i < nl.count(); i++)
  {
     el = nl.item(i).toElement();
     TeamMember member;
     member.name = el.namedItem("name").toElement().text();
     member.nickName = el.namedItem("nickName").toElement().text();
     member.email = el.namedItem("email").toElement().text();
     member.task = el.attribute("task");
     m_simpleMembers.append(member);
  }

  no = teamNode.namedItem("mailinglist");
  m_mailingList = no.toElement().attribute("address");
  teamNode = m_sessionDom.firstChild().namedItem("teamdata");
  m_yourself = teamNode.toElement().attribute("yourself");

  if (m_projectFiles.readFromXML(dom, baseURL, templateURL, excludeRx))
   m_modified = true;
  TQDomNode uploadNode;
  if (!m_createSessionDom)
  {
    uploadNode = sessionNode.namedItem("uploadprofiles");
  } else
  {
    uploadNode = projectNode.namedItem("uploadprofiles").cloneNode(true);
    sessionNode.appendChild(uploadNode);
  }

  TQDomElement uploadEl = uploadNode.toElement();
  m_showUploadTreeviews = uploadEl.attribute("showtreeviews", "true") == "true";
  if (m_showUploadTreeviews)
  {
    // read the profiles and create treeviews for them
    UploadProfiles::ref()->readFromXML(m_sessionDom);
  } else
    UploadProfiles::ref()->clear();

  if (m_createSessionDom)
  {
    TQDomNode node;
    node = projectNode.namedItem("treestatus").cloneNode(true);
    sessionNode.appendChild(node);
    node = projectNode.namedItem("debuggers").cloneNode(true);
    sessionNode.appendChild(node);
  }


  parent->statusMsg(TQString());
  parent->newProjectLoaded(projectName, baseURL, templateURL);
  parent->reloadTree(&(m_projectFiles), true, treeStatusFromXML());
  parent->newStatus();
  adjustActions();
}

void ProjectPrivate::slotAcceptCreateProject()
{
  bool errorOccured = false;

  projectName = png->linePrjName->text();
  TQString basePath = png->linePrjDir ->text();

  KURL oldBaseURL = baseURL;
  baseURL = KURL::fromPathOrURL(basePath);
  if (baseURL.isLocalFile())
  {
    TQString path = TQDir(baseURL.path()).canonicalPath();
    if (baseURL.path().endsWith("/"))
      path.append("/");
    if (!path.isEmpty())
      baseURL.setPath(path);
  }
  /*
    it is important to set the fields only if there is some input
    otherwise you set them to an empty string and the treeview will
    not recognize it as parent url because:
                TQString::Null != ""
  */
  if (!png->lineHost->text().isEmpty())
    baseURL.setHost(png->lineHost->text());
  if (!png->lineUser->text().isEmpty())
    baseURL.setUser(png->lineUser->text());
  if (!png->linePasswd->text().isEmpty())
    baseURL.setPass(png->linePasswd->text());
  if (!png->linePort->text().isEmpty())
    baseURL.setPort(png->linePort->text().toInt());
  if (!png->comboProtocol->currentText().isEmpty())
    baseURL.setProtocol(png->comboProtocol->currentText());
  if (baseURL.protocol() == i18n("Local")) baseURL.setProtocol("file");
  baseURL.adjustPath(1);
  if (!baseURL.path().startsWith("/")) baseURL.setPath("/"+ baseURL.path());
  if (!QExtFileInfo::createDir(baseURL, m_mainWindow))
  {
    QuantaCommon::dirCreationError(m_mainWindow, baseURL);
    baseURL = oldBaseURL;
  } else
  {
    projectURL = baseURL;
    projectURL.setPath(baseURL.path(1) + png->linePrjFile->text());

    errorOccured = !createEmptyDom();
    if (!errorOccured)
    {
      email = pnf->lineEmail->text();
      author = pnf->lineAuthor->text();
      m_defaultDTD = DTDs::ref()->getDTDNameFromNickName(pnf->dtdCombo->currentText());
      m_defaultEncoding  = pnf->encodingCombo->currentText();

      previewPrefix = KURL::fromPathOrURL( pnf->linePrefix->text() );
      usePreviewPrefix = pnf->checkPrefix->isChecked();

      TQDomElement el;
      KURL url;

      el = dom.firstChild().firstChild().toElement();
      el.setAttribute("type", png->type());
      el.setAttribute("name", projectName );
      el.setAttribute("encoding", m_defaultEncoding);

      el = m_sessionDom.firstChild().firstChild().toElement();
      el.setAttribute("previewPrefix", previewPrefix.url() );
      el.setAttribute("usePreviewPrefix",usePreviewPrefix);

      el = dom.createElement("author");
      dom.firstChild().firstChild().appendChild( el );
      el.appendChild( dom.createTextNode( author ) );

      el = dom.createElement("email");
      dom.firstChild().firstChild().appendChild( el );
      el.appendChild( dom.createTextNode( email ) );

      el = dom.createElement("defaultDTD");
      dom.firstChild().firstChild().appendChild(el);
      el.appendChild(dom.createTextNode(m_defaultDTD));

      KURL::List list;
      if ( png->type() == "Local" ) list = pnl->files();
      if ( png->type() == "Web"   ) list = pnw->files();

      for ( KURL::List::Iterator it = list.begin(); it != list.end(); ++it )
      {
        url = *it;//QExtFileInfo::toRelative(*it, baseURL );
        el = dom.createElement("item");
        el.setAttribute("url",QuantaCommon::qUrl(url));
        dom.firstChild().firstChild().appendChild( el );
      }

    // el = dom.createElement("item");
    // el.setAttribute("url","templates/");
    // dom.firstChild().firstChild().appendChild(el);

    //setup the templates directory
      templateURL = baseURL;
      bool createTemplateDir = true;
      if (pnf->insertGlobalTemplates->isChecked())
      {
        KURL url;
        QuantaCommon::setUrl(url, qConfig.globalDataDir + resourceDir + "templates/");
        parent->slotAddDirectory(url, false);
        QuantaCommon::setUrl(templateURL, "templates/");
        createTemplateDir = false;
      }
      if (pnf->insertLocalTemplates->isChecked())
      {
        KURL url;
        QuantaCommon::setUrl(url, locateLocal("data", resourceDir + "templates/"));
        parent->slotAddDirectory(url, false);
        QuantaCommon::setUrl(templateURL, "templates/");
        createTemplateDir = false;
      }

    if (createTemplateDir)
    {
      QuantaCommon::setUrl(templateURL, png->linePrjTmpl->text());
      templateURL.adjustPath(1);
      templateURL = QExtFileInfo::toAbsolute(templateURL, baseURL);
      if (!QExtFileInfo::createDir(templateURL, m_mainWindow))
      {
        QuantaCommon::dirCreationError(m_mainWindow, templateURL);
      }
    }
    //the nodes are already created in loadProjectXML() called from createEmptyDom()
    el = dom.firstChild().firstChild().namedItem("templates").toElement();
    url = QExtFileInfo::toRelative(templateURL, baseURL);
    el.firstChild().setNodeValue(QuantaCommon::qUrl(url));

    //setup the toolbars directory
    toolbarURL = baseURL;
    QuantaCommon::setUrl(toolbarURL,png->linePrjToolbar->text());
    toolbarURL.adjustPath(1);
    toolbarURL = QExtFileInfo::toAbsolute(toolbarURL, baseURL);
    if (!QExtFileInfo::createDir(toolbarURL, m_mainWindow))
    {
      QuantaCommon::dirCreationError(m_mainWindow, toolbarURL);
    }
    el = dom.firstChild().firstChild().namedItem("toolbars").toElement();
    url = QExtFileInfo::toRelative(toolbarURL, baseURL);
    el.firstChild().setNodeValue(QuantaCommon::qUrl(url));

#if KDE_IS_VERSION(3,4,89)
    m_projectRecent->addURL(projectURL, projectName);
#else
    m_projectRecent->addURL(projectURL);
#endif
    m_projectRecent->setCurrentItem(0);
    // remember the project in config
    writeConfig();

//workaround to load the newly created project items in the treeview
    KURL u = projectURL;
    slotCloseProject();
    loadProject(u);
  }
}
if (errorOccured)
{
  slotCloseProject();
}
}


/** Saves a project view (group of files & toolbars) without asking for a name. */
void ProjectPrivate::slotSaveProjectView()
{
  slotSaveAsProjectView(currentProjectView.isEmpty());
}


/** Deletes a project view */
void ProjectPrivate::slotDeleteProjectView(const TQString &view)
{
  TQDomNodeList nl = dom.elementsByTagName("projectview");
  TQDomElement el;
  for (uint i = 0; i < nl.count(); i++)
  {
    TQDomNode node = nl.item(i);
    el = node.cloneNode().toElement();
    if (el.attribute("name") == view)
    {
      node.parentNode().removeChild(node);
      if (currentProjectView == view)
        currentProjectView = "";
      parent->setModified();
      adjustViewActions();
      break;
    }
  }
}

/** Saves a project view (group of files & toolbars) asking for a name. */
void ProjectPrivate::slotSaveAsProjectView(bool askForName)
{
  if (askForName)
  {
    bool ok;
    TQString newProjectView = KInputDialog::getText(i18n("Save Project View As"),
                                                        i18n("Enter the name of the view:"), "", &ok, m_mainWindow).lower();
    if (!ok)
      return;
    currentProjectView = newProjectView;
  }
  TQDomNodeList nl = dom.elementsByTagName("projectview");
  for (uint i = 0 ;i < nl.count(); i++)
  {
    TQDomNode node = nl.item(i);
    if (node.toElement().attribute("name") == currentProjectView)
    {
      if (!askForName ||
          KMessageBox::warningContinueCancel(m_mainWindow, i18n("<qt>A project view named <b>%1</b> already exists.<br>Do you want to overwrite it?</qt>")
                                            .arg(currentProjectView), TQString(), i18n("Overwrite")) == KMessageBox::Continue)
      {
        node.parentNode().removeChild(node);
        break;
      } else
      {
        return;
      }
    }
  }

  TQDomElement el = dom.createElement("projectview");
  el.setAttribute("name", currentProjectView);
  TQDomElement item;
  KURL::List openURLs = ViewManager::ref()->openedFiles(true); // get open urls
  KURL::List::Iterator it;
  for ( it = openURLs.begin(); it != openURLs.end(); ++it )
  {
    KURL url = (*it);
    if (m_projectFiles.contains(url))
    {
      item = dom.createElement("viewitem");
      item.setAttribute("url", QuantaCommon::qUrl(QExtFileInfo::toRelative(url, baseURL)) );
      el.appendChild(item);
    }
  }

  KURL::List toolbarList;
  parent->getUserToolbarFiles(&toolbarList);
  for (uint i =0 ; i < toolbarList.count(); i++)
  {
    item = dom.createElement("viewtoolbar");
    KURL url = toolbarList[i];
    url = QExtFileInfo::toRelative(url, baseURL);
    item.setAttribute("url", QuantaCommon::qUrl(url) );
    el.appendChild(item);
  }

  dom.firstChild().firstChild().appendChild( el );
  parent->setModified();
  adjustViewActions();
}


void ProjectPrivate::slotSelectProjectType(const TQString &title)
{
  if ( png->radioLocal->isChecked() ) stack->raiseWidget( 0 );
  if ( png->radioWeb  ->isChecked() ) stack->raiseWidget( 1 );
  if ( title == m_wizTitle )
    emit setLocalFiles( pnl->checkInsert->isChecked() );
}


bool ProjectPrivate::createEmptyDom()
{
  TQString str;
  TQTextStream stream(&str, IO_WriteOnly);
  stream.setEncoding(TQTextStream::UnicodeUTF8);

  stream << "<!DOCTYPE webproject ><webproject>" << endl;
  stream << "\t<project name=\"" << projectName << "\">" << endl;
  stream << "\t\t<upload />" << endl;
  stream << "\t</project>" << endl;
  stream << "</webproject>" << endl;

  TQString sessionStr;
  TQTextStream sessionStream(&sessionStr, IO_WriteOnly);
  sessionStream.setEncoding(TQTextStream::UnicodeUTF8);

  sessionStream << "<!DOCTYPE webprojectsession ><webprojectsession>" << endl;
  sessionStream << "\t<session>" << endl;
  sessionStream << "\t</session>" << endl;
  sessionStream << "</webprojectsession>" << endl;

  KURL sessionURL = projectURL;
  TQString fileName = projectURL.fileName();
  if (fileName.endsWith(".webprj"))
    fileName.replace(".webprj", ".session");
  else
    fileName += ".session";
  sessionURL.setFileName(fileName);

  bool result = true;

  if (!projectURL.isLocalFile())
  {
    tempFile = new KTempFile(tmpDir); // tempFile will get deleted in slotProjectClose()
    tempFile->setAutoDelete(true);
    tempFile->textStream()->setEncoding(TQTextStream::UnicodeUTF8);
    *(tempFile->textStream()) << str;
    tempFile->close();
    result = QExtFileInfo::createDir(baseURL, m_mainWindow);
    if (result)
      result = TDEIO::NetAccess::upload(tempFile->name(), projectURL, m_mainWindow);
    if (result)
      m_tmpProjectFile = tempFile->name();

    sessionTempFile = new KTempFile(tmpDir); // sessionTempFile will get deleted in slotProjectClose()
    sessionTempFile->setAutoDelete(true);
    sessionTempFile->textStream()->setEncoding(TQTextStream::UnicodeUTF8);
    *(sessionTempFile->textStream()) << sessionStr;
    sessionTempFile->close();
    result = TDEIO::NetAccess::upload(sessionTempFile->name(), sessionURL, m_mainWindow);
    if (result)
      m_tmpSessionFile= sessionTempFile->name();
  } else
  {
    TQFile f(projectURL.path());
    if (f.open( IO_WriteOnly ))
    {
      TQTextStream fstream(&f);
      fstream.setEncoding(TQTextStream::UnicodeUTF8);
      fstream << str;
      m_tmpProjectFile = projectURL.path();  // we are local: the temp file and the projectURL are the same
    } else
    {
      result = false;
    }
    f.close();
    if (result)
    {
      f.setName(sessionURL.path());
      if (f.open(IO_WriteOnly))
      {
        TQTextStream fstream(&f);
        fstream.setEncoding(TQTextStream::UnicodeUTF8);
        fstream << sessionStr;
        m_tmpSessionFile = sessionURL.path();  // we are local: the temp file and the projectURL are the same
      } else
      {
        result = false;
      }
      f.close();
    }
  }

  if (!result)
  {
    parent->hideSplash();
    KMessageBox::sorry(m_mainWindow, i18n("<qt>Cannot open file <b>%1</b> for writing.</qt>").arg(projectURL.prettyURL(0, KURL::StripFileProtocol)));
    delete tempFile;
    tempFile = 0L;
    delete sessionTempFile;
    sessionTempFile = 0L;
    return false;
  }

  dom.setContent(str);
  m_sessionDom.setContent(sessionStr);
  m_projectFiles.clear();
  return true;
}


TQStringList ProjectPrivate::treeStatusFromXML()
{
  TQStringList folderList;
  TQDomNodeList nl = m_sessionDom.elementsByTagName("treestatus");
  if (nl.count() > 0) {
    nl = nl.item(0).childNodes();
    for ( unsigned int i = 0; i < nl.count(); i++ )
    {
      TQString urlString = nl.item(i).toElement().attribute("url");
      folderList.append( baseURL.url(1) + urlString);
    }
  }
  return folderList;
}


void ProjectPrivate::getStatusFromTree()
{
  // remove old status
  TQDomNodeList nl = m_sessionDom.elementsByTagName("treestatus");
  TQDomElement  el;
  for ( unsigned int i = 0; i < nl.count(); i++ )
  {
    el = nl.item(i).toElement();
    el.parentNode().removeChild( el );
    i--;
  }
  TQStringList folderList;
  parent->getTreeStatus( &folderList );
  // toplevel folder is always open in a project and QExtFileInfo::toRelative
  // creates strange output -> we remove the toplevel folder
  if (folderList.count() > 0)
     folderList.remove(folderList.begin());
  if (folderList.count() > 0) {
    // create the root element
    TQDomElement root = m_sessionDom.createElement("treestatus");
    m_sessionDom.firstChild().firstChild().appendChild(root);
    for (TQStringList::Iterator it = folderList.begin(); it != folderList.end(); ++it) {
      el = m_sessionDom.createElement("openfolder");
      el.setAttribute("url", QuantaCommon::qUrl( QExtFileInfo::toRelative(KURL(*it), baseURL) ) );
      root.appendChild( el );
    }
  }
}


/** create new project */
void ProjectPrivate::slotNewProject()
{
  TQWizard *wiz = new TQWizard(m_mainWindow, "new", true);
  wiz->setCaption(i18n("New Project Wizard"));
  wiz->setSizePolicy(TQSizePolicy::Minimum, TQSizePolicy::Minimum);

  png = new ProjectNewGeneral(0L);

  stack = new TQWidgetStack(0L);

  pnl = new ProjectNewLocal(stack);
  pnw = new ProjectNewWeb(stack);
  pnf = new ProjectNewFinal(0L);

  stack->addWidget( pnl, 0);
  stack->addWidget( pnw, 1 );

  wiz->addPage( png,   i18n("<b>General Project Settings</b>"));
  wiz->addPage( stack, m_wizTitle );
  wiz->addPage( pnf,   i18n("<b>More Project Settings</b>"));

  wiz->setNextEnabled  ( png,   false );
  wiz->setBackEnabled  ( stack, true  );
  wiz->setNextEnabled  ( stack, true  );
  wiz->setNextEnabled  ( pnf,   false );
  wiz->setFinishEnabled( pnf,   true  );

  connect( png, TQ_SIGNAL(enableNextButton(TQWidget *,bool)),
           wiz, TQ_SLOT(setNextEnabled(TQWidget*,bool)));
  connect( png, TQ_SIGNAL(setBaseURL(const KURL&)),
          pnl, TQ_SLOT(  setBaseURL(const KURL&)));
  connect( png, TQ_SIGNAL(setBaseURL(const KURL&)),
          pnw, TQ_SLOT(  setBaseURL(const KURL&)));
  connect( this,TQ_SIGNAL(setLocalFiles(bool)),
          pnl, TQ_SLOT(slotSetFiles(bool)));
  
  connect(wiz, TQ_SIGNAL(selected(const TQString &)),
          this, TQ_SLOT  (slotSelectProjectType(const TQString &)));
  connect(wiz, TQ_SIGNAL(helpClicked()), TQ_SLOT(slotNewProjectHelpClicked()));

  connect( pnw, TQ_SIGNAL(enableMessagesWidget()),
          parent, TQ_SIGNAL(enableMessageWidget()));
  connect( pnw, TQ_SIGNAL(messages(const TQString&)),
          parent, TQ_SLOT  (slotGetMessages(const TQString&)));
  connect( pnw, TQ_SIGNAL(enableNextButton(TQWidget *,bool)),
           wiz, TQ_SLOT(setNextEnabled(TQWidget*,bool)));
  connect( pnw, TQ_SIGNAL(enableNextButton(TQWidget *,bool)),
           wiz, TQ_SLOT(setBackEnabled(TQWidget*,bool)));

  TQStringList lst = DTDs::ref()->nickNameList(true);
  pnf->dtdCombo->insertStringList(lst);
  TQString defaultDTDName = DTDs::ref()->getDTDNickNameFromName(qConfig.defaultDocType.lower());
  int pos = lst.findIndex(defaultDTDName);
  if (pos >= 0)
    pnf->dtdCombo->setCurrentItem(pos);

  TQStringList availableEncodingNames(TDEGlobal::charsets()->availableEncodingNames());
  pnf->encodingCombo->insertStringList( availableEncodingNames );
  TQStringList::ConstIterator iter;
  int iIndex = -1;
  for (iter = availableEncodingNames.begin(); iter != availableEncodingNames.end(); ++iter)
  {
    ++iIndex;
    if ((*iter).lower() == qConfig.defaultEncoding.lower())
    {
      pnf->encodingCombo->setCurrentItem(iIndex);
      break;
    }
  }

  png->linePrjName->setFocus();
  if (wiz->exec())
  {
    slotCloseProject();
    slotAcceptCreateProject();
  }
  delete wiz;

  adjustActions();
  parent->newStatus();
}

/** close project and edited files */
void ProjectPrivate::slotCloseProject()
{
  if (!parent->hasProject()) return;
  connect(ViewManager::ref(), TQ_SIGNAL(filesClosed(bool)), this, TQ_SLOT(slotProceedWithCloseProject(bool)));
  parent->closeFiles();
}

void ProjectPrivate::slotProceedWithCloseProject(bool success)
{
  disconnect(ViewManager::ref(), TQ_SIGNAL(filesClosed(bool)), this, TQ_SLOT(slotProceedWithCloseProject(bool)));
  if (!success) return;
  emit eventHappened("before_project_close", baseURL.url(), TQString());
  if (!uploadProjectFile())
  {
    if (KMessageBox::warningContinueCancel(m_mainWindow, i18n("Saving of project failed. Do you want to continue with closing (might cause data loss)?"), i18n("Project Saving Error"), KStdGuiItem::close()) == KMessageBox::Cancel)
      return;
  }
  emit eventHappened("after_project_close", baseURL.url(), TQString());
  // empty dom tree
  dom.clear();
  m_sessionDom.clear();
  m_events->clear();
  config->setGroup("Projects");
  config->writePathEntry("Last Project", TQString());
  init();
  parent->newProjectLoaded(projectName, baseURL, templateURL);
  parent->reloadTree( &(m_projectFiles), true, TQStringList());
  adjustActions();
  m_projectRecent->setCurrentItem(-1);
  parent->newStatus();
  kapp->processEvents(TQEventLoop::ExcludeUserInput | TQEventLoop::ExcludeSocketNotifiers);
}


/** open project file */
void ProjectPrivate::slotOpenProject()
{
  KURL url = KFileDialog::getOpenURL( TQString(),
                      "*.wpj *.webprj"+i18n("|Project Files\n*|All Files"), m_mainWindow,
                      i18n("Open Project"));

  if( !url.isEmpty() )
  {
    loadProject ( url );
  }
}


/* save project file */
bool ProjectPrivate::saveProject()
{
  if ( !parent->hasProject() ) return false;
  bool result = true;
  // remove old opened files
  TQDomElement  el;
  TQDomNodeList nl = dom.firstChild().firstChild().childNodes();

  for ( unsigned int i = 0; i < nl.count(); i++ )
  {
    el = nl.item(i).toElement();
    if ( el.nodeName() == "openfile" )
    {
      el.parentNode().removeChild( el );
      i--;
    }
  }
  getStatusFromTree();
  TQFile f(m_tmpProjectFile);
  if (f.open(IO_WriteOnly))
  {
    TQTextStream stream( &f );
    stream.setEncoding(TQTextStream::UnicodeUTF8);
    dom.save(stream, 2);
    f.close();
    f.setName(m_tmpSessionFile);
    if (f.open(IO_WriteOnly))
    {
      TQTextStream stream(&f);
      stream.setEncoding(TQTextStream::UnicodeUTF8);
      m_sessionDom.save(stream, 2);
      f.close();
    }
    m_modified = false;
    parent->statusMsg(i18n( "Wrote project file %1" ).arg(m_tmpProjectFile));
  } else
  {
    parent->hideSplash();
    KMessageBox::error(m_mainWindow, i18n("<qt>Cannot open the file <b>%1</b> for writing.</qt>").arg(m_tmpProjectFile));
    result = false;
  }
  return result;
}


void ProjectPrivate::loadProjectFromTemp(const KURL &url, const TQString &tempFile, const TQString &sessionTempFile)
{
  m_createSessionDom = true;
  m_tmpProjectFile = tempFile;
  if (!sessionTempFile.isEmpty())
    m_tmpSessionFile = sessionTempFile;
  projectURL = url;
  TQFile f(tempFile);
  if (f.open(IO_ReadOnly))
  {
    baseURL = url;
    baseURL.setPath(url.directory(true, true));
    if (baseURL.isLocalFile())
    {
      TQDir dir(baseURL.path());
      baseURL.setPath(dir.canonicalPath());
      baseURL.adjustPath(-1);
    }
    dom.setContent(&f);
    f.close();
    if (!sessionTempFile.isEmpty())
    {
      f.setName(sessionTempFile);
      if (f.open(IO_ReadOnly))
      {
        m_sessionDom.setContent(&f);
        m_createSessionDom = false;
        f.close();
      }
    }
    loadProjectXML();
    openCurrentView();
#if KDE_IS_VERSION(3,4,89)
    kdDebug(24000) << "Add recent project: " << url << " : projectName= " << projectName << endl;
    m_projectRecent->addURL(url, projectName);
#else
    m_projectRecent->addURL( url );
#endif
    m_projectRecent->setCurrentItem(0);
    // remember the project in config
    writeConfig();
  } else
  {
    parent->hideSplash();
    KMessageBox::error(m_mainWindow, i18n("<qt>Cannot open the file <b>%1</b> for reading.</qt>").arg(tempFile));
  }
}

/** load project from file: url */
bool ProjectPrivate::loadProject(const KURL &url)
{
  if (projectURL == url)
    return true;
  if (!url.isValid())
  {
    parent->hideSplash();
    KMessageBox::sorry(m_mainWindow, i18n("<qt>Malformed URL: <b>%1</b></qt>").arg(url.prettyURL()));
    return false;
  }
  if ( projectAlreadyOpen(url.url()) )
  {
    parent->hideSplash();
    if (KMessageBox::warningContinueCancel(m_mainWindow, i18n("<qt>The project<br><b>%1</b><br> seems to be used by another Quanta instance.<br>You may end up with data loss if you open the same project in two instances, modify and save them in both.<br><br>Do you want to proceed with open?</qt>").arg(url.prettyURL()), TQString(), KStdGuiItem::open()) == KMessageBox::Cancel)
      return false;
  }
  TQString projectTmpFile;
  TQString sessionTmpFile;

  // test if url is writeable and download to local file
  if (TDEIO::NetAccess::exists(url, false, m_mainWindow) &&
      TDEIO::NetAccess::download(url, projectTmpFile, m_mainWindow))
  {
    if (parent->hasProject())
    {
      slotCloseProject();
    }
    KURL sessionURL = url;
    TQString fileName = url.fileName();
    if (fileName.endsWith(".webprj"))
      fileName.replace(".webprj", ".session");
    else
      fileName += ".session";
    sessionURL.setFileName(fileName);
    if (TDEIO::NetAccess::exists(sessionURL, false, m_mainWindow))
     TDEIO::NetAccess::download(sessionURL, sessionTmpFile, m_mainWindow);
    else
    {
      TQString sessionStr;
      TQTextStream sessionStream(&sessionStr, IO_WriteOnly);
      sessionStream.setEncoding(TQTextStream::UnicodeUTF8);

      sessionStream << "<!DOCTYPE webprojectsession ><webprojectsession>" << endl;
      sessionStream << "\t<session>" << endl;
      sessionStream << "\t</session>" << endl;
      sessionStream << "</webprojectsession>" << endl;
      if (!sessionURL.isLocalFile())
      {
        sessionTempFile = new KTempFile(tmpDir); // sessionTempFile will get deleted in slotProjectClose()
        sessionTempFile->setAutoDelete(true);
        sessionTempFile->textStream()->setEncoding(TQTextStream::UnicodeUTF8);
        *(sessionTempFile->textStream()) << sessionStr;
        sessionTempFile->close();
        m_tmpSessionFile = sessionTempFile->name();
      } else
      {
        TQFile f(sessionURL.path());
        if (f.open(IO_WriteOnly))
        {
          TQTextStream fstream(&f);
          fstream.setEncoding(TQTextStream::UnicodeUTF8);
          fstream << sessionStr;
          m_tmpSessionFile = sessionURL.path();  // we are local: the temp file and the projectURL are the same
        }
        f.close();
      }
      m_sessionDom.setContent(sessionStr);
    }
    loadProjectFromTemp(url, projectTmpFile, sessionTmpFile);
  } else
  {
    parent->hideSplash();
    KMessageBox::error(m_mainWindow, i18n("<qt>Cannot access the project file <b>%1</b>.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)));
    return false;
  }
  return true;
}


/** dialog for add files */
void ProjectPrivate::slotAddFiles()
{
  KURL::List list = KFileDialog::getOpenURLs(
    baseURL.url(),  i18n("*"), m_mainWindow, i18n("Insert Files in Project"));

  if ( !list.isEmpty() )
  {
    KURL firstURL = list.first();
    firstURL = QExtFileInfo::toRelative( firstURL, baseURL );

    if ( firstURL.path().startsWith("/") || firstURL.path().startsWith("."))
    {
      KURLRequesterDlg *urlRequesterDlg = new KURLRequesterDlg( baseURL.prettyURL(), m_mainWindow, "");
      urlRequesterDlg->setCaption(i18n("Files: Copy to Project"));
      urlRequesterDlg->urlRequester()->setMode( KFile::Directory | KFile::ExistingOnly);
      urlRequesterDlg->exec();
      KURL destination = urlRequesterDlg->selectedURL();
      delete urlRequesterDlg;

      if ( !destination.isEmpty())
      {
        CopyTo *dlg = new CopyTo( baseURL);
        connect(dlg, TQ_SIGNAL(deleteDialog(CopyTo*)),
                    TQ_SLOT  (slotDeleteCopytoDlg(CopyTo*)));
        connect(dlg, TQ_SIGNAL(addFilesToProject(const KURL::List&)), parent,
                    TQ_SLOT  (slotInsertFilesAfterCopying(const KURL::List&)));
        list = dlg->copy( list, destination );
        return;
      }
      else {
        return;
      }
    }

    insertFiles( list );
    //Take care also of the selected dirs
    KURL dirURL;
    for (uint i = 0; i < list.count(); i++)
    {
      dirURL = list[i];
      if (dirURL.path().endsWith("/"))
      {
        insertFiles( dirURL, "*" );
      }
    }

    parent->reloadTree( &(m_projectFiles), false, TQStringList());
  }
}


void ProjectPrivate::slotDeleteCopytoDlg(CopyTo *dlg)
{
//The CopyTo dlg is deleted only here!!
  delete dlg;
}


void ProjectPrivate::slotAddDirectory()
{
  KURL url = KURL();
  url = KFileDialog::getExistingURL(baseURL.prettyURL(), m_mainWindow,
                  i18n("Insert Folder in Project"));
  parent->slotAddDirectory(url);
}


void ProjectPrivate::slotDebuggerOptions()
{
  // Debuggers Combo
  TDETrader::OfferList offers = TDETrader::self()->query("Quanta/Debugger");
  TDETrader::OfferList::ConstIterator iterDbg;
  for(iterDbg = offers.begin(); iterDbg != offers.end(); ++iterDbg)
  {
    KService::Ptr service = *iterDbg;
    if(m_debuggerClientEdit == service->name())
    {
      DebuggerClient *dbg = 0L;
      int errCode = 0;
//Workaround for dynamic_cast not working correctly on SUSE 10, gcc 4.0.2
//The correct way should be a simple:
// DebuggerClient *dbg = KParts::ComponentFactory::createInstanceFromService<DebuggerClient>(service, this, 0, TQStringList(), &errCode);
      TQObject* obj = KParts::ComponentFactory::createInstanceFromService<TQObject>(service, this, 0, TQStringList(), &errCode);
      if (obj && obj->inherits("DebuggerClient"))
        dbg = static_cast<DebuggerClient *>(obj);
      if (dbg)
      {
        TQDomNode projectNode = m_sessionDom.firstChild().firstChild();
        TQDomNode nodeThisDbg;
        TQDomNode nodeDbg  = projectNode.namedItem("debuggers");
        if(nodeDbg.isNull())
        {
          nodeDbg = m_sessionDom.createElement("debuggers");
          projectNode.appendChild(nodeDbg);
        }

        nodeThisDbg = nodeDbg.namedItem(service->name());
        if(nodeThisDbg.isNull())
        {
          nodeThisDbg = m_sessionDom.createElement(service->name());
          nodeDbg.appendChild(nodeThisDbg);
        }
        dbg->showConfig(nodeThisDbg);
        delete dbg;
      }
      else
      {
        parent->hideSplash();
        KMessageBox::error(NULL, i18n("<qt>Unable to load the debugger plugin, error code %1 was returned: <b>%2</b>.</qt>").arg(errCode).arg(KLibLoader::self()->lastErrorMessage()), i18n("Debugger Error"));
      }
    }
  }
}

void ProjectPrivate::slotDebuggerChanged(const TQString &debugger)
{
  m_debuggerClientEdit = debugger;
}


void ProjectPrivate::writeConfig()
{
  config->reparseConfiguration();
  config->setGroup("Projects");
  // remember the last project in config
  KURL url = projectURL.url();
  url.setPass("");
  config->writePathEntry("Last Project", url.url());
  // add project to list
  if (!projectURL.isEmpty())
  {
    TQStringList projectList = QuantaCommon::readPathListEntry(config, "OpenProjects");
    if (projectList.contains( projectURL.url() ) == 0)
    {
      projectList.append( projectURL.url() );
      config->writePathEntry("OpenProjects", projectList);
      // add the temp file to list
      projectList = QuantaCommon::readPathListEntry(config, "ProjectTempFiles");
      projectList.append(KURL::fromPathOrURL(m_tmpProjectFile).url());
      config->writePathEntry("ProjectTempFiles", projectList);
      projectList = QuantaCommon::readPathListEntry(config, "ProjectSessionTempFiles");
      projectList.append(KURL::fromPathOrURL(m_tmpSessionFile).url());
      config->writePathEntry("ProjectSessionTempFiles", projectList);
    }
  }
  // save recent projects
  config->deleteGroup("RecentProjects");
  m_projectRecent->saveEntries(config, "RecentProjects");
  config->sync();
}


void ProjectPrivate::removeFromConfig(const TQString & urlStr)
{
  config->reparseConfiguration();
  config->setGroup("Projects");
  TQStringList projectList = QuantaCommon::readPathListEntry(config, "OpenProjects");
  int i = projectList.findIndex( urlStr );
  if ( i > -1)
  {
    projectList.remove(projectList.at(i));
    config->writePathEntry("OpenProjects", projectList);
    // remove the temp file from list
    projectList = QuantaCommon::readPathListEntry(config, "ProjectTempFiles");
    projectList.remove(projectList.at(i));
    config->writePathEntry("ProjectTempFiles", projectList);
    projectList = QuantaCommon::readPathListEntry(config, "ProjectSessionTempFiles");
    if (projectList.count() > (uint)i)
    {
      projectList.remove(projectList.at(i));
      config->writePathEntry("ProjectSessionTempFiles", projectList);
    }
  }
  config->sync();
}


bool ProjectPrivate::projectAlreadyOpen(const TQString & urlStr)
{
  config->reparseConfiguration();
  config->setGroup("Projects");
  TQStringList projectList = QuantaCommon::readPathListEntry(config, "OpenProjects");
  return (projectList.contains(urlStr) != 0);
}


/* uploads project file */
bool ProjectPrivate::uploadProjectFile()
{
  if (m_tmpProjectFile.isNull() || !saveProject())
    return false;
  KURL sessionURL = projectURL;
  TQString fileName = projectURL.fileName();
  if (fileName.endsWith(".webprj"))
    fileName.replace(".webprj", ".session");
  else
    fileName += ".session";
  sessionURL.setFileName(fileName);

  // no need to upload a local file because it is the same as the tempFile
  if (projectURL.isLocalFile())
  {
    removeFromConfig( projectURL.url() );    // remove the project from the list of open projects
    // delete all temp files we used
    delete tempFile;
    tempFile = 0L;
    delete sessionTempFile;
    sessionTempFile = 0L;
    m_tmpProjectFile = TQString();
    return true;
  }
  if (TDEIO::NetAccess::upload(m_tmpProjectFile, projectURL, m_mainWindow) && TDEIO::NetAccess::upload(m_tmpSessionFile, sessionURL, m_mainWindow))
  {
    removeFromConfig(projectURL.url());    // remove the project from the list of open projects
    if (quantaApp)
      parent->statusMsg(i18n( "Uploaded project file %1" ).arg( projectURL.prettyURL()));
    // delete all temp files we used
    // first the one from creating a new project
    delete tempFile;
    tempFile = 0L;
    delete sessionTempFile;
    sessionTempFile = 0L;
    // second the one from downloading a project
    TDEIO::NetAccess::removeTempFile(m_tmpProjectFile);
    TDEIO::NetAccess::removeTempFile(m_tmpSessionFile);
    // third if we recovered after crash
    TDEIO::NetAccess::del(KURL().fromPathOrURL(m_tmpProjectFile), m_mainWindow);
    TDEIO::NetAccess::del(KURL().fromPathOrURL(m_tmpSessionFile), m_mainWindow);
    m_tmpProjectFile = "";
    m_tmpSessionFile = "";
  }
  else
  {
    if (quantaApp)
    {
      parent->statusMsg(TQString() );
      KMessageBox::error(m_mainWindow, TDEIO::NetAccess::lastErrorString());
    }
    return false;
  }
  return true;
}

void ProjectPrivate::slotNewProjectHelpClicked()
{
  kapp->invokeHelp("create-new-project-3-2", "quanta");
}

#include "projectprivate.moc"
