Skip to content
Snippets Groups Projects
ApplicationWindow.cpp 579 KiB
Newer Older
4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383
    if (w->isA("MultiLayer"))
    {
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers)
      {
        g->enableAutoscaling(autoscale2DPlots);
        g->updateScale();
        g->setIgnoreResizeEvents(!autoResizeLayers);
        g->setAutoscaleFonts(autoScaleFonts);
        g->setAntialiasing(antialiasing2DPlots);
        g->enableFixedAspectRatio(fixedAspectRatio2DPlots);
      }
    }
  }
}

void ApplicationWindow::setLegendDefaultSettings(int frame, const QFont& font,
    const QColor& textCol, const QColor& backgroundCol)
{
  if (legendFrameStyle == frame &&
      legendTextColor == textCol &&
      legendBackground == backgroundCol &&
      plotLegendFont == font)
    return;

  legendFrameStyle = frame;
  legendTextColor = textCol;
  legendBackground = backgroundCol;
  plotLegendFont = font;
  saveSettings();
}

void ApplicationWindow::setArrowDefaultSettings(double lineWidth,  const QColor& c, Qt::PenStyle style,
    int headLength, int headAngle, bool fillHead)
{
  if (defaultArrowLineWidth == lineWidth &&
      defaultArrowColor == c &&
      defaultArrowLineStyle == style &&
      defaultArrowHeadLength == headLength &&
      defaultArrowHeadAngle == headAngle &&
      defaultArrowHeadFill == fillHead)
    return;

  defaultArrowLineWidth = lineWidth;
  defaultArrowColor = c;
  defaultArrowLineStyle = style;
  defaultArrowHeadLength = headLength;
  defaultArrowHeadAngle = headAngle;
  defaultArrowHeadFill = fillHead;
  saveSettings();
}

ApplicationWindow * ApplicationWindow::plotFile(const QString& fn)
{
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  ApplicationWindow *app = new ApplicationWindow();
  app->restoreApplicationGeometry();

  Table* t = app->newTable();
  if (!t)
    return NULL;

  t->importASCII(fn, app->columnSeparator, 0, app->renameColumns, app->strip_spaces, app->simplify_spaces,
      app->d_ASCII_import_comments, app->d_ASCII_comment_string,
      app->d_ASCII_import_read_only, Table::Overwrite, app->d_ASCII_end_line);
  t->setCaptionPolicy(MdiSubWindow::Both);
  app->multilayerPlot(t, t->YColumns(),Graph::LineSymbols);
  QApplication::restoreOverrideCursor();
  return 0;
}

void ApplicationWindow::importASCII()
{
  ImportASCIIDialog *import_dialog = new ImportASCIIDialog(!activeWindow(TableWindow) && !activeWindow(MatrixWindow), this, d_extended_import_ASCII_dialog);
  import_dialog->setDir(asciiDirPath);
  import_dialog->selectFilter(d_ASCII_file_filter);
  if (import_dialog->exec() != QDialog::Accepted)
    return;
  asciiDirPath = import_dialog->directory().path();
  d_ASCII_import_mode = import_dialog->importMode();
  columnSeparator = import_dialog->columnSeparator();
  ignoredLines = import_dialog->ignoredLines();
  renameColumns = import_dialog->renameColumns();
  strip_spaces = import_dialog->stripSpaces();
  simplify_spaces = import_dialog->simplifySpaces();
  d_ASCII_import_locale = import_dialog->decimalSeparators();
  d_import_dec_separators = import_dialog->updateDecimalSeparators();
  d_ASCII_comment_string = import_dialog->commentString();
  d_ASCII_import_comments = import_dialog->importComments();
  d_ASCII_import_read_only = import_dialog->readOnly();
  d_ASCII_end_line = (EndLineChar)import_dialog->endLineChar();
  saveSettings();

  importASCII(import_dialog->selectedFiles(),
      import_dialog->importMode(),
      import_dialog->columnSeparator(),
      import_dialog->ignoredLines(),
      import_dialog->renameColumns(),
      import_dialog->stripSpaces(),
      import_dialog->simplifySpaces(),
      import_dialog->importComments(),
      import_dialog->updateDecimalSeparators(),
      import_dialog->decimalSeparators(),
      import_dialog->commentString(),
      import_dialog->readOnly(),
      import_dialog->endLineChar(),import_dialog->getselectedColumnSeparator());
}

void ApplicationWindow::importASCII(const QStringList& files, int import_mode, const QString& local_column_separator,
    int local_ignored_lines, bool local_rename_columns, bool local_strip_spaces, bool local_simplify_spaces,
    bool local_import_comments, bool update_dec_separators, QLocale local_separators, const QString& local_comment_string,
    bool import_read_only, int endLineChar,const QString& sepforloadAscii)
{
  if (files.isEmpty())
    return;
  switch(import_mode) {
  case ImportASCIIDialog::NewTables:
  {
    int dx = 0, dy = 0;
    QStringList sorted_files = files;
    sorted_files.sort();
    int filesCount = sorted_files.size();
    for (int i=0; i<filesCount; i++){
      Table *w = newTable();
      if (!w)
        continue;

      w->importASCII(sorted_files[i], local_column_separator, local_ignored_lines,
          local_rename_columns, local_strip_spaces, local_simplify_spaces,
          local_import_comments, local_comment_string, import_read_only,
          Table::Overwrite, endLineChar);
      if (!w) continue;
      w->setWindowLabel(sorted_files[i]);
      w->setCaptionPolicy(MdiSubWindow::Both);
      if (i == 0){
        dx = w->verticalHeaderWidth();
        dy = w->frameGeometry().height() - w->widget()->height();
      }
      if (filesCount > 1)
        w->move(QPoint(i*dx, i*dy));

      if (update_dec_separators)
        w->updateDecimalSeparators(local_separators);
    }
    modifiedProject();
    break;
  }
  case ImportASCIIDialog::NewMatrices:
  {
    int dx = 0, dy = 0;
    QStringList sorted_files = files;
    sorted_files.sort();
    int filesCount = sorted_files.size();
    for (int i=0; i<filesCount; i++){
      Matrix *w = newMatrix();
      if (!w)
        continue;
      w->importASCII(sorted_files[i], local_column_separator, local_ignored_lines,
          local_strip_spaces, local_simplify_spaces, local_comment_string,
          Matrix::Overwrite, local_separators, endLineChar);
      w->setWindowLabel(sorted_files[i]);
      w->setCaptionPolicy(MdiSubWindow::Both);
      if (i == 0){
        dx = w->verticalHeaderWidth();
        dy = w->frameGeometry().height() - w->widget()->height();
      }
      if (filesCount > 1)
        w->move(QPoint(i*dx,i*dy));
    }
    modifiedProject();
    break;
  }

  case ImportASCIIDialog::NewColumns:
  case ImportASCIIDialog::NewRows:
  {
    MdiSubWindow *w = activeWindow();
    if (!w)
      return;

    if (w->inherits("Table")){
      Table *t = dynamic_cast<Table*>(w);
      for (int i=0; i<files.size(); i++)
        t->importASCII(files[i], local_column_separator, local_ignored_lines, local_rename_columns,
            local_strip_spaces, local_simplify_spaces, local_import_comments,
            local_comment_string, import_read_only, (Table::ImportMode)(import_mode - 2), endLineChar);

      if (update_dec_separators)
        t->updateDecimalSeparators(local_separators);
      t->notifyChanges();
      emit modifiedProject(t);
    } else if (w->isA("Matrix")){
      Matrix *m = dynamic_cast<Matrix*>(w);
      for (int i=0; i<files.size(); i++){
        m->importASCII(files[i], local_column_separator, local_ignored_lines,
            local_strip_spaces, local_simplify_spaces, local_comment_string,
            (Matrix::ImportMode)(import_mode - 2), local_separators, endLineChar);
      }
    }
    w->setWindowLabel(files.join("; "));
    w->setCaptionPolicy(MdiSubWindow::Name);
    break;
  }
  case ImportASCIIDialog::Overwrite:
  {
    MdiSubWindow *w = activeWindow();
    if (!w)
      return;

    if (w->inherits("Table")){
      Table *t = dynamic_cast<Table*>(w);
      t->importASCII(files[0], local_column_separator, local_ignored_lines, local_rename_columns,
          local_strip_spaces, local_simplify_spaces, local_import_comments,
          local_comment_string, import_read_only, Table::Overwrite, endLineChar);
      if (update_dec_separators)
        t->updateDecimalSeparators(local_separators);
      t->notifyChanges();
    } else if (w->isA("Matrix")){
      Matrix *m = dynamic_cast<Matrix*>(w);
      m->importASCII(files[0], local_column_separator, local_ignored_lines,
          local_strip_spaces, local_simplify_spaces, local_comment_string,
          Matrix::Overwrite, local_separators, endLineChar);
    }

    w->setWindowLabel(files[0]);
    w->setCaptionPolicy(MdiSubWindow::Both);
    modifiedProject();
    break;
  }
  case ImportASCIIDialog::NewWorkspace:
  {
    try
    {
      Mantid::API::IAlgorithm_sptr alg =mantidUI->createAlgorithm("LoadAscii");
      QStringList sorted_files = files;
      sorted_files.sort();
      for (int i=0; i<sorted_files.size(); i++){
        QStringList ws=sorted_files[i].split(".",QString::SkipEmptyParts);
        QString temp=ws[0];
        int index=temp.lastIndexOf("\\");
        if(index==-1) return;
        QString wsName=temp.right(temp.size()-(index+1));
        alg->setPropertyValue("Filename",sorted_files[i].toStdString());
        alg->setPropertyValue("OutputWorkspace",wsName.toStdString());
        alg->setPropertyValue("Separator",sepforloadAscii.toStdString());
        alg->execute();
      }

    }
    catch(...)
    {
      throw std::runtime_error("LoadAscii failed when importing the file as workspace");
    }
    break;
  }
  }
}

void ApplicationWindow::open()
{
  OpenProjectDialog *open_dialog = new OpenProjectDialog(this, d_extended_open_dialog);
  open_dialog->setDirectory(workingDir);
  if (open_dialog->exec() != QDialog::Accepted || open_dialog->selectedFiles().isEmpty())
    return;
  workingDir = open_dialog->directory().path();

  switch(open_dialog->openMode()) {
  case OpenProjectDialog::NewProject:
  {
    QString fn = open_dialog->selectedFiles()[0];
    QFileInfo fi(fn);

    if (projectname != "untitled"){
      QFileInfo fi(projectname);
      QString pn = fi.absFilePath();
      if (fn == pn){
        QMessageBox::warning(this, tr("MantidPlot - File openning error"),//Mantid
            tr("The file: <b>%1</b> is the current file!").arg(fn));
        return;
      }
    }

    if (fn.endsWith(".qti",Qt::CaseInsensitive) || fn.endsWith(".qti~",Qt::CaseInsensitive) ||
        fn.endsWith(".opj",Qt::CaseInsensitive) || fn.endsWith(".ogm",Qt::CaseInsensitive) ||
        fn.endsWith(".ogw",Qt::CaseInsensitive) || fn.endsWith(".ogg",Qt::CaseInsensitive) ||
        fn.endsWith(".qti.gz",Qt::CaseInsensitive)||fn.endsWith(".mantid",Qt::CaseInsensitive)||
        fn.endsWith(".mantid~",Qt::CaseInsensitive))
    {
      if (!fi.exists ()){
        QMessageBox::critical(this, tr("MantidPlot - File openning error"),//Mantid
            tr("The file: <b>%1</b> doesn't exist!").arg(fn));
        return;
      }

      saveSettings();//the recent projects must be saved

      ApplicationWindow *a = open (fn,false,false);
      if (a){
        a->workingDir = workingDir;
        if (fn.endsWith(".qti",Qt::CaseInsensitive) || fn.endsWith(".qti~",Qt::CaseInsensitive) ||
            fn.endsWith(".opj",Qt::CaseInsensitive) || fn.endsWith(".ogg", Qt::CaseInsensitive) ||
            fn.endsWith(".qti.gz",Qt::CaseInsensitive))
        {// this->close();
        }
      }
    } else {
      QMessageBox::critical(this,tr("MantidPlot - File openning error"),//Mantid
          tr("The file: <b>%1</b> is not a MantidPlot or Origin project file!").arg(fn));
      return;
    }
    break;
  }
  case OpenProjectDialog::NewFolder:
    appendProject(open_dialog->selectedFiles()[0]);
    break;
  }
}

ApplicationWindow* ApplicationWindow::open(const QString& fn, bool factorySettings, bool newProject)
{
  if (fn.endsWith(".opj", Qt::CaseInsensitive) || fn.endsWith(".ogm", Qt::CaseInsensitive) ||
      fn.endsWith(".ogw", Qt::CaseInsensitive) || fn.endsWith(".ogg", Qt::CaseInsensitive))
    return importOPJ(fn, factorySettings, newProject);
  else if (fn.endsWith(".py", Qt::CaseInsensitive))
    return loadScript(fn);
  else if (!( fn.endsWith(".qti",Qt::CaseInsensitive) || fn.endsWith(".qti.gz",Qt::CaseInsensitive) ||
      fn.endsWith(".qti~",Qt::CaseInsensitive)||fn.endsWith(".mantid",Qt::CaseInsensitive)||fn.endsWith(".mantid~",Qt::CaseInsensitive)  ))
  {return plotFile(fn);
  }

  QString fname = fn;
  if (fn.endsWith(".qti.gz", Qt::CaseInsensitive)||fn.endsWith(".mantid.gz",Qt::CaseInsensitive)){//decompress using zlib
    file_uncompress(fname.ascii());
    fname = fname.left(fname.size() - 3);
  }

  QFile f(fname);
  QTextStream t( &f );
  f.open(QIODevice::ReadOnly);
  QString s = t.readLine();
  QStringList list = s.split(QRegExp("\\s"), QString::SkipEmptyParts);
  if (list.count() < 2 || list[0] != "MantidPlot"){
    f.close();
    if (QFile::exists(fname + "~")){
      int choice = QMessageBox::question(this, tr("MantidPlot - File opening error"),//Mantid
          tr("The file <b>%1</b> is corrupted, but there exists a backup copy.<br>Do you want to open the backup instead?").arg(fn),
          QMessageBox::Yes|QMessageBox::Default, QMessageBox::No|QMessageBox::Escape);
      if (choice == QMessageBox::Yes)
        return open(fname + "~");
      else
        QMessageBox::critical(this, tr("MantidPlot - File opening error"),  tr("The file: <b> %1 </b> was not created using MantidPlot!").arg(fn));//Mantid
      return 0;
    }
  }

  QStringList vl = list[1].split(".", QString::SkipEmptyParts);
  d_file_version = 100*(vl[0]).toInt()+10*(vl[1]).toInt()+(vl[2]).toInt();
  ApplicationWindow* app = openProject(fname, factorySettings, newProject);
  f.close();
  return app;
}

void ApplicationWindow::openRecentProject(int index)
{
  QString fn = recent->text(index);
  int pos = fn.find(" ",0);
  fn = fn.right(fn.length()-pos-1);

  QFile f(fn);
  if (!f.exists()){
    QMessageBox::critical(this, tr("MantidPlot - File Open Error"),//Mantid
        tr("The file: <b> %1 </b> <p>does not exist anymore!"
            "<p>It will be removed from the list.").arg(fn));

    recentProjects.remove(fn);
    updateRecentProjectsList();
    return;
  }

  if (projectname != "untitled"){
    QFileInfo fi(projectname);
    QString pn = fi.absFilePath();
    if (fn == pn){
      QMessageBox::warning(this, tr("MantidPlot - File open error"),//Mantid
          tr("The file: <p><b> %1 </b><p> is the current file!").arg(fn));
      return;
    }
  }

  if (!fn.isEmpty()){
    saveSettings();//the recent projects must be saved
    bool isSaved = saved;
    // Have to change the working directory here because that is used when finding the nexus files to load
    workingDir = QFileInfo(f).absolutePath();
    ApplicationWindow * a = open (fn,false,false);
    if (a && (fn.endsWith(".qti",Qt::CaseInsensitive) || fn.endsWith(".qti~",Qt::CaseInsensitive) ||
        fn.endsWith(".opj",Qt::CaseInsensitive) || fn.endsWith(".ogg", Qt::CaseInsensitive)))
      if (isSaved)
        savedProject();//force saved state
    //close();
  }
}

ApplicationWindow* ApplicationWindow::openProject(const QString& fn, bool factorySettings, bool newProject)
{	
  ApplicationWindow *app = this;

  //if the current project is not saved prompt to save and close all windows opened
  mantidUI->saveProject(saved);
  if (newProject)
  { 	app = new ApplicationWindow(factorySettings);
  }
  // the matrix window list
  m_mantidmatrixWindows.clear();
  app->projectname = fn;
  app->d_file_version = d_file_version;
  app->setWindowTitle(tr("MantidPlot") + " - " + fn);
  app->d_opening_file = true;
  app->d_workspace->blockSignals(true);
  QFile f(fn);
  QTextStream t( &f );
  t.setEncoding(QTextStream::UnicodeUTF8);
  f.open(QIODevice::ReadOnly);

  QFileInfo fi(fn);
  QString baseName = fi.fileName();

  t.readLine();
  if (d_file_version < 73)
    t.readLine();
  QString s = t.readLine();
  QStringList list=s.split("\t", QString::SkipEmptyParts);
  if (list[0] == "<scripting-lang>")
  {
    if (!app->setScriptingLanguage(list[1]))
      QMessageBox::warning(app, tr("MantidPlot - File opening error"),//Mantid
          tr("The file \"%1\" was created using \"%2\" as scripting language.\n\n"\
              "Initializing support for this language FAILED; I'm using \"%3\" instead.\n"\
              "Various parts of this file may not be displayed as expected.")\
              .arg(fn).arg(list[1]).arg(scriptingEnv()->name()));

    s = t.readLine();
    list=s.split("\t", QString::SkipEmptyParts);
  }
  int aux=0,widgets=list[1].toInt();

  QString titleBase = tr("Window") + ": ";
  QString title = titleBase + "1/"+QString::number(widgets)+"  ";

  QProgressDialog progress(this);
  progress.setWindowModality(Qt::WindowModal);
  progress.setRange(0, widgets);
  progress.setMinimumWidth(app->width()/2);
  progress.setWindowTitle(tr("MantidPlot - Opening file") + ": " + baseName);//Mantid
  progress.setLabelText(title);

  Folder *cf = app->projectFolder();
  app->folders->blockSignals (true);
  app->blockSignals (true);

  //rename project folder item
  FolderListItem *item = dynamic_cast<FolderListItem *>(app->folders->firstChild());
  item->setText(0, fi.baseName());
  item->folder()->setObjectName(fi.baseName());

  //process tables and matrix information
  while ( !t.atEnd() && !progress.wasCanceled()){
    s = t.readLine();
    list.clear();
    if  (s.left(8) == "<folder>"){
      list = s.split("\t");
      Folder *f = new Folder(app->current_folder, list[1]);
      f->setBirthDate(list[2]);
      f->setModificationDate(list[3]);
      if(list.count() > 4)
        if (list[4] == "current")
          cf = f;

      FolderListItem *fli = new FolderListItem(app->current_folder->folderListItem(), f);
      f->setFolderListItem(fli);

      app->current_folder = f;
    } else if  (s.contains("<open>")) {
      app->current_folder->folderListItem()->setOpen(s.remove("<open>").remove("</open>").toInt());
    } else if  (s == "<table>") {
      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s!="</table>" ){
        s=t.readLine();
        lst<<s;
      }
      lst.pop_back();
      openTable(app,lst);
      progress.setValue(aux);
    } else if (s.left(17)=="<TableStatistics>") {
      QStringList lst;
      while ( s!="</TableStatistics>" ){
        s=t.readLine();
        lst<<s;
      }
      lst.pop_back();
      app->openTableStatistics(lst);
    } else if  (s == "<matrix>") {
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s != "</matrix>" ) {
        s=t.readLine();
        lst<<s;
      }
      lst.pop_back();
      openMatrix(app, lst);
      progress.setValue(aux);
    } else if  (s == "<note>") {
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      for (int i=0; i<3; i++){
        s = t.readLine();
        list << s;
      }
      Note* m = openNote(app,list);
      QStringList cont;
      while ( s != "</note>" ){
        s=t.readLine();
        cont << s;
      }
      cont.pop_back();
      m->restore(cont);
      progress.setValue(aux);
    } else if  (s == "</folder>") {
      Folder *parent = dynamic_cast<Folder *>(app->current_folder->parent());
      if (!parent)
        app->current_folder = app->projectFolder();
      else
        app->current_folder = parent;
    }else if(s=="<mantidmatrix>"){
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s != "</mantidmatrix>" ){
        s=t.readLine();
        lst<<s;
      }
      lst.pop_back();
      openMantidMatrix(lst);
      progress.setValue(aux);
    }
    else if(s=="<mantidworkspaces>"){
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s != "</mantidworkspaces>" ) {
        s=t.readLine();
        lst<<s;
      }
      lst.pop_back();
      s=lst[0];
      populateMantidTreeWdiget(s);
      progress.setValue(aux);
    }
    else if (s=="<scriptwindow>"){
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s != "</scriptwindow>" ) {
        s=t.readLine();
        lst<<s;
      }
      openScriptWindow(lst);
      progress.setValue(aux);
    }
    else if (s=="<instrumentwindow>"){
      title= titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      QStringList lst;
      while ( s != "</instrumentwindow>" ) {
        s=t.readLine();
        lst<<s;
      }
      openInstrumentWindow(lst);
      progress.setValue(aux);
    }
  }
  f.close();

  if (progress.wasCanceled()){
    app->saved = true;
    app->close();
    return 0;
  }

  //process the rest
  f.open(QIODevice::ReadOnly);
  MultiLayer *plot=0;
  while ( !t.atEnd() && !progress.wasCanceled()){
    s=t.readLine();
    if  (s.left(8) == "<folder>"){
      list = s.split("\t");
      app->current_folder = app->current_folder->findSubfolder(list[1]);
    } else if  (s == "<multiLayer>"){//process multilayers information
      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);

      s=t.readLine();
      QStringList graph=s.split("\t");
      QString caption=graph[0];
      plot =multilayerPlot(caption, 0,  graph[2].toInt(), graph[1].toInt());
      app->setListViewDate(caption, graph[3]);
      plot->setBirthDate(graph[3]);

      restoreWindowGeometry(app, plot, t.readLine());

      plot->blockSignals(true);

      if (d_file_version > 71)
      {
        QStringList lst=t.readLine().split("\t");
        plot->setWindowLabel(lst[1]);
        plot->setCaptionPolicy((MdiSubWindow::CaptionPolicy)lst[2].toInt());
      }
      if (d_file_version > 83)
      {
        QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
        plot->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
        lst=t.readLine().split("\t", QString::SkipEmptyParts);
        plot->setSpacing(lst[1].toInt(),lst[2].toInt());
        lst=t.readLine().split("\t", QString::SkipEmptyParts);
        plot->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
        lst=t.readLine().split("\t", QString::SkipEmptyParts);
        plot->setAlignement(lst[1].toInt(),lst[2].toInt());
      }

      while ( s!="</multiLayer>" )
      {//open layers
        s = t.readLine();

        if (s.contains("<waterfall>")){
          QStringList lst = s.trimmed().remove("<waterfall>").remove("</waterfall>").split(",");
          Graph *ag = plot->activeGraph();
          if (ag && lst.size() >= 2){
            ag->setWaterfallOffset(lst[0].toInt(), lst[1].toInt());
            if (lst.size() >= 3)
              ag->setWaterfallSideLines(lst[2].toInt());
          }
          plot->setWaterfallLayout();
        }

        if (s.left(7)=="<graph>")
        {	list.clear();
        while ( s!="</graph>" )
        {
          s=t.readLine();
          list<<s;
        }
        openGraph(app, plot, list);
        }
      }
      if(plot) plot->blockSignals(false);
      progress.setValue(aux);
    }
    else if  (s == "<SurfacePlot>")
    {//process 3D plots information
      list.clear();
      title = titleBase + QString::number(++aux)+"/"+QString::number(widgets);
      progress.setLabelText(title);
      while ( s!="</SurfacePlot>" )
      {
        s=t.readLine();
        list<<s;
      }
      openSurfacePlot(app,list);
      progress.setValue(aux);
    }
    else if (s == "</folder>")
    {
      Folder *parent = dynamic_cast<Folder*>(app->current_folder->parent());
      if (!parent)
        app->current_folder = projectFolder();
      else
        app->current_folder = parent;
    }
    else if (s == "<log>")
    {//process analysis information
      s = t.readLine();
      QString log = s + "\n";
      while(s != "</log>"){
        s = t.readLine();
        log += s + "\n";
      }
      app->current_folder->appendLogInfo(log.remove("</log>"));
    }
  }
  f.close();

  if (progress.wasCanceled())
  {
    app->saved = true;
    app->close();
    return 0;
  }

  QFileInfo fi2(f);
  QString fileName = fi2.absFilePath();
  app->recentProjects.remove(fileName);
  app->recentProjects.push_front(fileName);
  app->updateRecentProjectsList();

  app->folders->setCurrentItem(cf->folderListItem());
  app->folders->blockSignals (false);
  //change folder to user defined current folder
  app->changeFolder(cf, true);

  app->blockSignals (false);
  app->renamedTables.clear();

  app->restoreApplicationGeometry();

  app->savedProject();
  app->d_opening_file = false;
  app->d_workspace->blockSignals(false);
  return app;
}

void ApplicationWindow::scriptPrint(const QString &msg, bool error, bool timestamp)
{
  if( error || msg.contains("error",Qt::CaseInsensitive) )
  {
    console->setTextColor(Qt::red);
    consoleWindow->show();
  }
  else
  {
    console->setTextColor(Qt::black);
  }
  QString msg_to_print = msg;

  if( error || timestamp )
  {
    if( timestamp )
    {
      QString separator(100, '-'); 
      msg_to_print  = separator + "\n" + QDateTime::currentDateTime().toString() 
	    + ": " + msg.trimmed() + "\n" + separator + '\n';
    }

    // Check for last character being a new line character unless we are at the start of the 
    // scroll area
    if( !console->text().endsWith('\n') && console->textCursor().position() != 0 )
    {
      console->textCursor().insertText("\n");    
    }
  }

  console->textCursor().insertText(msg_to_print);
  console->moveCursor(QTextCursor::End);
}

bool ApplicationWindow::setScriptingLanguage(const QString &lang)
{
  if ( lang.isEmpty() ) return false;
  if( scriptingEnv() && lang == scriptingEnv()->name() ) return true;

  if( m_bad_script_envs.contains(lang) ) 
  {
    this->writeErrorToLogWindow("Previous initialization of " + lang + " failed, cannot retry.");
    return false;
  }

  ScriptingEnv* newEnv(NULL);
  if( m_script_envs.contains(lang) )
  {
    newEnv = m_script_envs.value(lang);
  }
  else
  {
    newEnv = ScriptingLangManager::newEnv(lang, this);
    connect(newEnv, SIGNAL(print(const QString&)), this, SLOT(scriptPrint(const QString&)));

    // The following is already part of executeScript
    // This call could be uncommented if mantidsimple is folded into Mantid such that the
    // algorithm call signature could also be updated.
    //connect(mantidUI, SIGNAL(algorithmAboutToBeCreated()), newEnv, SLOT(refreshAlgorithms()));

    if( newEnv->initialize() )
    {   
      m_script_envs.insert(lang, newEnv);
    }
    else
    {
      delete newEnv;
      m_bad_script_envs.insert(lang);
      QMessageBox::information(this, "MantidPlot", QString("Failed to initialize ") + lang + ". Please contact support.");
      return false;
    }
  }

  // notify everyone who might be interested
  ScriptingChangeEvent *sce = new ScriptingChangeEvent(newEnv);
  QApplication::sendEvent(this, sce);
  delete sce;

  foreach(QObject *i, findChildren<QObject*>())
  QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));

  if (scriptingWindow)
  {
    //Mantid - This is so that the title of the script window reflects the current scripting language
    QApplication::postEvent(scriptingWindow, new ScriptingChangeEvent(newEnv));

    foreach(QObject *i, scriptingWindow->findChildren<QObject*>())
    QApplication::postEvent(i, new ScriptingChangeEvent(newEnv));
  }

  return true;
}

void ApplicationWindow::showScriptingLangDialog()
{
  // If a script is currently active, don't let a new one be selected
  if( scriptingWindow->isExecuting() )
  {
    QMessageBox msg_box;
    msg_box.setText("Cannot change scripting language, a script is still running.");
    msg_box.exec();
    return;
  }
  ScriptingLangDialog* d = new ScriptingLangDialog(scriptingEnv(), this);
  d->exec();
}

void ApplicationWindow::openTemplate()
{
  QString filter = "MantidPlot 2D Graph Template (*.qpt);;";
  filter += "MantidPlot 3D Surface Template (*.qst);;";
  filter += "MantidPlot Table Template (*.qtt);;";
  filter += "MantidPlot Matrix Template (*.qmt);;";

  QString fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Open Template File"), templatesDir, filter);//Mantid
  if (!fn.isEmpty()){
    QFileInfo fi(fn);
    templatesDir = fi.dirPath(true);
    if (fn.contains(".qmt") || fn.contains(".qpt") || fn.contains(".qtt") || fn.contains(".qst"))
      openTemplate(fn);
    else {
      QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
          tr("The file: <b>%1</b> is not a MantidPlot template file!").arg(fn));
      return;
    }
  }
}

MdiSubWindow* ApplicationWindow::openTemplate(const QString& fn)
{
  if (fn.isEmpty() || !QFile::exists(fn)){
    QMessageBox::critical(this, tr("MantidPlot - File opening error"),//Mantid
        tr("The file: <b>%1</b> doesn't exist!").arg(fn));
    return 0;
  }

  QFile f(fn);
  QTextStream t(&f);
  t.setEncoding(QTextStream::UnicodeUTF8);
  f.open(QIODevice::ReadOnly);
  QStringList l=t.readLine().split(QRegExp("\\s"), QString::SkipEmptyParts);
  QString fileType=l[0];
  if (fileType != "MantidPlot"){
    QMessageBox::critical(this,tr("MantidPlot - File opening error"),//Mantid
        tr("The file: <b> %1 </b> was not created using MantidPlot!").arg(fn));
    return 0;
  }

  QStringList vl = l[1].split(".", QString::SkipEmptyParts);
  d_file_version = 100*(vl[0]).toInt()+10*(vl[1]).toInt()+(vl[2]).toInt();

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  MdiSubWindow *w = 0;
  QString templateType;
  t>>templateType;

  if (templateType == "<SurfacePlot>") {
    t.skipWhiteSpace();
    QStringList lst;
    while (!t.atEnd())
      lst << t.readLine();
    w = openSurfacePlot(this,lst);
    if (w)
      dynamic_cast<Graph3D*>(w)->clearData();
  } else {
    int rows, cols;
    t>>rows; t>>cols;
    t.skipWhiteSpace();
    QString geometry = t.readLine();

    if (templateType == "<multiLayer>"){
      w = multilayerPlot(generateUniqueName(tr("Graph")));
      if (w){
        MultiLayer *ml = qobject_cast<MultiLayer *>(w);
        dynamic_cast<MultiLayer*>(w)->setCols(cols);
        dynamic_cast<MultiLayer*>(w)->setRows(rows);
        //restoreWindowGeometry(this, w, geometry);
        if (d_file_version > 83){
          QStringList lst=t.readLine().split("\t", QString::SkipEmptyParts);
          dynamic_cast<MultiLayer*>(w)->setMargins(lst[1].toInt(),lst[2].toInt(),lst[3].toInt(),lst[4].toInt());
          lst=t.readLine().split("\t", QString::SkipEmptyParts);
          dynamic_cast<MultiLayer*>(w)->setSpacing(lst[1].toInt(),lst[2].toInt());
          lst=t.readLine().split("\t", QString::SkipEmptyParts);
          dynamic_cast<MultiLayer*>(w)->setLayerCanvasSize(lst[1].toInt(),lst[2].toInt());
          lst=t.readLine().split("\t", QString::SkipEmptyParts);
          dynamic_cast<MultiLayer*>(w)->setAlignement(lst[1].toInt(),lst[2].toInt());
        }
        while (!t.atEnd()){//open layers
          QString s=t.readLine();
          if (s.contains("<waterfall>")){
            QStringList lst = s.trimmed().remove("<waterfall>").remove("</waterfall>").split(",");
            Graph *ag = ml->activeGraph();
            if (ag && lst.size() >= 2){
              ag->setWaterfallOffset(lst[0].toInt(), lst[1].toInt());
              if (lst.size() >= 3)
                ag->setWaterfallSideLines(lst[2].toInt());
            }
            ml->setWaterfallLayout();
          }
          if (s.left(7)=="<graph>"){
            QStringList lst;
            while ( s!="</graph>" ){
              s = t.readLine();
              lst << s;
            }
            openGraph(this, dynamic_cast<MultiLayer*>(w), lst);
          }
        }
      }
    } else {
      if (templateType == "<table>")
        w = newTable(tr("Table1"), rows, cols);
      else if (templateType == "<matrix>")
        w = newMatrix(rows, cols);
      if (w){
        QStringList lst;
        while (!t.atEnd())
          lst << t.readLine();
        w->restore(lst);
        //restoreWindowGeometry(this, w, geometry);
      }
    }
  }

  f.close();
  if (w){
    customMenu(w);
    customToolBars(w);
  }

  QApplication::restoreOverrideCursor();
  return w;
}

void ApplicationWindow::readSettings()
{
#ifdef Q_OS_MAC // Mac
  QSettings settings(QSettings::IniFormat,QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
#else
  QSettings settings;
#endif

  /* ---------------- group General --------------- */
  settings.beginGroup("/General");
  settings.beginGroup("/ApplicationGeometry");//main window geometry
  d_app_rect = QRect(settings.value("/x", 0).toInt(), settings.value("/y", 0).toInt(),
      settings.value("/width", 0).toInt(), settings.value("/height", 0).toInt());
  settings.endGroup();

  autoSearchUpdates = settings.value("/AutoSearchUpdates", false).toBool();
  appLanguage = settings.value("/Language", QLocale::system().name().section('_',0,0)).toString();
  show_windows_policy = (ShowWindowsPolicy)settings.value("/ShowWindowsPolicy", ApplicationWindow::ActiveFolder).toInt();

  recentProjects = settings.value("/RecentProjects").toStringList();
  //Follows an ugly hack added by Ion in order to fix Qt4 porting issues
  //(only needed on Windows due to a Qt bug?)
#ifdef Q_OS_WIN
  if (!recentProjects.isEmpty() && recentProjects[0].contains("^e"))
    recentProjects = recentProjects[0].split("^e", QString::SkipEmptyParts);
  else if (recentProjects.count() == 1){
    QString s = recentProjects[0];
    if (s.remove(QRegExp("\\s")).isEmpty())
      recentProjects = QStringList();
  }
#endif

  updateRecentProjectsList();

  changeAppStyle(settings.value("/Style", appStyle).toString());
  autoSave = settings.value("/AutoSave", false).toBool();
  autoSaveTime = settings.value("/AutoSaveTime",15).toInt();
  d_backup_files = settings.value("/BackupProjects", true).toBool();
  d_init_window_type = (WindowType)settings.value("/InitWindow", NoWindow).toInt();
  defaultScriptingLang = settings.value("/ScriptingLang","Python").toString();    //Mantid M. Gigg
  d_thousands_sep = settings.value("/ThousandsSeparator", true).toBool();
  d_locale = QLocale(settings.value("/Locale", QLocale::system().name()).toString());