Skip to content
Snippets Groups Projects
ApplicationWindow.cpp 579 KiB
Newer Older
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
      int leaf = int(qRound((val - stem*stem_unit)/leaf_unit));
      for (int k = prev_stem + 1; k < stem + 1; k++)
        result += "\n      " + QString::number(k) + " | ";
      result += QString::number(leaf);
      prev_stem = stem;
    }

    result += "\n---------------------\n";
    result += tr("Stem unit") + ": " + locale().toString(stem_unit) + "\n";
    result += tr("Leaf unit") + ": " + locale().toString(leaf_unit) + "\n";

    QString legend = tr("Key") + ": " + QString::number(prev_stem) + " | ";
    int leaf = int(qRound((data[rows - 1] - prev_stem*stem_unit)/leaf_unit));
    legend += QString::number(leaf);
    legend += " " + tr("means") + ": " + locale().toString(prev_stem*stem_unit + leaf*leaf_unit) + "\n";

    result += legend + "---------------------\n";
    free(data);
  } else
    result += "\t" + tr("Input error: empty data set!") + "\n";
  return result;
}

Note * ApplicationWindow::newStemPlot()
{
  Table *t = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!t)
    return NULL;

  int ts = t->table()->currentSelection();
  if (ts < 0)
    return NULL;

  Note *n = newNote();
  if (!n)
    return NULL;
  n->hide();

  QStringList lst = t->selectedColumns();
  if (lst.isEmpty()){
    Q3TableSelection sel = t->table()->selection(ts);
    for (int i = sel.leftCol(); i <= sel.rightCol(); i++)
      n->setText(n->text() + stemPlot(t, t->colName(i), 1001, sel.topRow() + 1, sel.bottomRow() + 1) + "\n");
  } else {
    for (int i = 0; i < lst.count(); i++)
      n->setText(n->text() + stemPlot(t, lst[i], 1001) + "\n");
  }

  n->show();
  return n;
}

void ApplicationWindow::renameListViewItem(const QString& oldName,const QString& newName)
{
  Q3ListViewItem *it=lv->findItem (oldName,0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    it->setText(0,newName);
}

void ApplicationWindow::setListViewLabel(const QString& caption,const QString& label)
{
  Q3ListViewItem *it=lv->findItem ( caption, 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    it->setText(5,label);
}

void ApplicationWindow::setListViewDate(const QString& caption,const QString& date)
{
  Q3ListViewItem *it=lv->findItem ( caption, 0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    it->setText(4,date);
}

void ApplicationWindow::setListView(const QString& caption,const QString& view)
{
  Q3ListViewItem *it=lv->findItem ( caption,0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    it->setText(2,view);
}

void ApplicationWindow::setListViewSize(const QString& caption,const QString& size)
{
  Q3ListViewItem *it=lv->findItem ( caption,0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    it->setText(3,size);
}

QString ApplicationWindow::listViewDate(const QString& caption)
{
  Q3ListViewItem *it=lv->findItem (caption,0, Q3ListView::ExactMatch | Qt::CaseSensitive );
  if (it)
    return it->text(4);
  else
    return "";
}

void ApplicationWindow::updateTableNames(const QString& oldName, const QString& newName)
{
  QList<MdiSubWindow *> windows = windowsList();
  foreach (MdiSubWindow *w, windows) {
    if (w->isA("MultiLayer")) {
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers)
      g->updateCurveNames(oldName, newName);
    } else if (w->isA("Graph3D")) {
      QString name = dynamic_cast<Graph3D*>(w)->formula();
      if (name.contains(oldName, true)) {
        name.replace(oldName,newName);
        dynamic_cast<Graph3D*>(w)->setPlotAssociation(name);
      }
    }
  }
}

void ApplicationWindow::updateColNames(const QString& oldName, const QString& newName)
{
  QList<MdiSubWindow *> windows = windowsList();
  foreach (MdiSubWindow *w, windows){
    if (w->isA("MultiLayer")){
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers)
      g->updateCurveNames(oldName, newName, false);
    }
    else if (w->isA("Graph3D")){
      QString name = dynamic_cast<Graph3D*>(w)->formula();
      if (name.contains(oldName)){
        name.replace(oldName,newName);
        dynamic_cast<Graph3D*>(w)->setPlotAssociation(name);
      }
    }
  }
}

void ApplicationWindow::changeMatrixName(const QString& oldName, const QString& newName)
{
  QList<MdiSubWindow *> windows = windowsList();
  foreach(MdiSubWindow *w, windows){
    if (w->isA("Graph3D"))
    {
      QString s = dynamic_cast<Graph3D*>(w)->formula();
      if (s.contains(oldName))
      {
        s.replace(oldName, newName);
        dynamic_cast<Graph3D*>(w)->setPlotAssociation(s);
      }
    }
    else if (w->isA("MultiLayer"))
    {
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers){
        for (int i=0; i<g->curves(); i++){
          QwtPlotItem *sp = dynamic_cast<QwtPlotItem*>(g->plotItem(i));
          if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram && sp->title().text() == oldName)
            sp->setTitle(newName);
        }
      }
    }
  }
}

void ApplicationWindow::remove3DMatrixPlots(Matrix *m)
{
  if (!m)
    return;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  QList<MdiSubWindow *> windows = windowsList();
  foreach(MdiSubWindow *w, windows){
    if (w->isA("Graph3D") && dynamic_cast<Graph3D*>(w)->matrix() == m)
      dynamic_cast<Graph3D*>(w)->clearData();
    else if (w->isA("MultiLayer")){
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers){
        for (int i=0; i<g->curves(); i++){
          if (g->curveType(i) == Graph::Histogram){
            QwtHistogram *h = dynamic_cast<QwtHistogram*>(g->plotItem(i));
            if (h && h->matrix() == m)
              g->removeCurve(i);
          } else {
            Spectrogram *sp = dynamic_cast<Spectrogram*>(g->plotItem(i));
            if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram && sp->matrix() == m)
              g->removeCurve(i);
          }
        }
      }
    }
  }
  QApplication::restoreOverrideCursor();
}

void ApplicationWindow::updateMatrixPlots(MdiSubWindow *window)
{
  Matrix *m = dynamic_cast<Matrix *>(window);
  if (!m)
    return;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  QList<MdiSubWindow *> windows = windowsList();
  foreach(MdiSubWindow *w, windows){
    if (w->isA("Graph3D") && dynamic_cast<Graph3D*>(w)->matrix() == m)
      dynamic_cast<Graph3D*>(w)->updateMatrixData(m);
    else if (w->isA("MultiLayer")){
      QList<Graph *> layers = dynamic_cast<MultiLayer*>(w)->layersList();
      foreach(Graph *g, layers){
        for (int i=0; i<g->curves(); i++){
          if (g->curveType(i) == Graph::Histogram){
            QwtHistogram *h = dynamic_cast<QwtHistogram*>(g->plotItem(i));
            if (h && h->matrix() == m)
              h->loadData();
          } else {
            Spectrogram *sp = dynamic_cast<Spectrogram*>(g->plotItem(i));
            if (sp && sp->rtti() == QwtPlotItem::Rtti_PlotSpectrogram && sp->matrix() == m)
              sp->updateData(m);
          }
        }
        g->updatePlot();
      }
    }
  }
  QApplication::restoreOverrideCursor();
}

void ApplicationWindow::add3DData()
{
  if (!hasTable()){
    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
        tr("<h4>There are no tables available in this project.</h4>"
            "<p><h4>Please create a table and try again!</h4>"));
    return;
  }

  QStringList zColumns = columnsList(Table::Z);
  if ((int)zColumns.count() <= 0)
  {
    QMessageBox::critical(this,tr("MantidPlot - Warning"),//Mantid
        tr("There are no available columns with plot designation set to Z!"));
    return;
  }

  DataSetDialog *ad = new DataSetDialog(tr("Column") + " : ", this);
  ad->setAttribute(Qt::WA_DeleteOnClose);
  connect (ad,SIGNAL(options(const QString&)), this, SLOT(insertNew3DData(const QString&)));
  ad->setWindowTitle(tr("MantidPlot - Choose data set"));//Mantid
  ad->setCurveNames(zColumns);
  ad->exec();
}

void ApplicationWindow::change3DData()
{
  DataSetDialog *ad = new DataSetDialog(tr("Column") + " : ", this);
  ad->setAttribute(Qt::WA_DeleteOnClose);
  connect (ad,SIGNAL(options(const QString&)), this, SLOT(change3DData(const QString&)));

  ad->setWindowTitle(tr("MantidPlot - Choose data set"));//Mantid
  ad->setCurveNames(columnsList(Table::Z));
  ad->exec();
}

void ApplicationWindow::change3DMatrix()
{
  DataSetDialog *ad = new DataSetDialog(tr("Matrix") + " : ", this);
  ad->setAttribute(Qt::WA_DeleteOnClose);
  connect (ad, SIGNAL(options(const QString&)), this, SLOT(change3DMatrix(const QString&)));

  ad->setWindowTitle(tr("MantidPlot - Choose matrix to plot"));//Mantid
  ad->setCurveNames(matrixNames());

  Graph3D* g = dynamic_cast<Graph3D*>(activeWindow(Plot3DWindow));
  if (g && g->matrix())
    ad->setCurentDataSet(g->matrix()->objectName());
  ad->exec();
}

void ApplicationWindow::change3DMatrix(const QString& matrix_name)
{
  MdiSubWindow *w = activeWindow(Plot3DWindow);
  if (!w)
    return;

  Graph3D* g = dynamic_cast<Graph3D*>(w);
  Matrix *m = matrix(matrix_name);
  if (m && g)
    g->addMatrixData(m);

  emit modified();
}

void ApplicationWindow::add3DMatrixPlot()
{
  QStringList matrices = matrixNames();
  if (static_cast<int>(matrices.count()) <= 0)
  {
    QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid
        tr("<h4>There are no matrices available in this project.</h4>"
            "<p><h4>Please create a matrix and try again!</h4>"));
    return;
  }

  DataSetDialog *ad = new DataSetDialog(tr("Matrix") + " :", this);
  ad->setAttribute(Qt::WA_DeleteOnClose);
  connect (ad,SIGNAL(options(const QString&)), this, SLOT(insert3DMatrixPlot(const QString&)));

  ad->setWindowTitle(tr("MantidPlot - Choose matrix to plot"));//Mantid
  ad->setCurveNames(matrices);
  ad->exec();
}

void ApplicationWindow::insert3DMatrixPlot(const QString& matrix_name)
{
  MdiSubWindow *w = activeWindow(Plot3DWindow);
  if (!w)
    return;

  dynamic_cast<Graph3D*>(w)->addMatrixData(matrix(matrix_name));
  emit modified();
}

void ApplicationWindow::insertNew3DData(const QString& colName)
{
  MdiSubWindow *w = activeWindow(Plot3DWindow);
  if (!w)
    return;

  dynamic_cast<Graph3D*>(w)->insertNewData(table(colName),colName);
  emit modified();
}

void ApplicationWindow::change3DData(const QString& colName)
{
  MdiSubWindow *w = activeWindow(Plot3DWindow);
  if (!w)
    return;

  dynamic_cast<Graph3D*>(w)->changeDataColumn(table(colName), colName);
  emit modified();
}

void ApplicationWindow::editSurfacePlot()
{
  MdiSubWindow *w = activeWindow(Plot3DWindow);
  if (!w)
    return;

  Graph3D* g = dynamic_cast<Graph3D*>(w);
  SurfaceDialog* sd = new SurfaceDialog(this);
  sd->setAttribute(Qt::WA_DeleteOnClose);

  if (g->hasData() && g->userFunction())
    sd->setFunction(g);
  else if (g->hasData() && g->parametricSurface())
    sd->setParametricSurface(g);
  sd->exec();
}

void ApplicationWindow::newSurfacePlot()
{
  SurfaceDialog* sd = new SurfaceDialog(this);
  sd->setAttribute(Qt::WA_DeleteOnClose);
  sd->exec();
}

Graph3D* ApplicationWindow::plotSurface(const QString& formula, double xl, double xr,
    double yl, double yr, double zl, double zr, int columns, int rows)
{
  QString label = generateUniqueName(tr("Graph"));

  Graph3D *plot = new Graph3D("", this);
  plot->resize(500,400);
  plot->setWindowTitle(label);
  plot->setName(label);
  customPlot3D(plot);
  plot->addFunction(formula, xl, xr, yl, yr, zl, zr, columns, rows);

  initPlot3D(plot);

  emit modified();
  return plot;
}

Graph3D* ApplicationWindow::plotParametricSurface(const QString& xFormula, const QString& yFormula,
    const QString& zFormula, double ul, double ur, double vl, double vr,
    int columns, int rows, bool uPeriodic, bool vPeriodic)
{
  QString label = generateUniqueName(tr("Graph"));

  Graph3D *plot = new Graph3D("", this);
  plot->resize(500, 400);
  plot->setWindowTitle(label);
  plot->setName(label);
  customPlot3D(plot);
  plot->addParametricSurface(xFormula, yFormula, zFormula, ul, ur, vl, vr,
      columns, rows, uPeriodic, vPeriodic);
  initPlot3D(plot);
  emit modified();
  return plot;
}

void ApplicationWindow::updateSurfaceFuncList(const QString& s)
{
  surfaceFunc.remove(s);
  surfaceFunc.push_front(s);
  while ((int)surfaceFunc.size() > 10)
    surfaceFunc.pop_back();
}

Graph3D* ApplicationWindow::dataPlot3D(const QString& caption,const QString& formula,
    double xl, double xr, double yl, double yr, double zl, double zr)
{
  int pos=formula.find("_",0);
  QString wCaption=formula.left(pos);

  Table* w=table(wCaption);
  if (!w)
    return 0;

  int posX=formula.find("(",pos);
  QString xCol=formula.mid(pos+1,posX-pos-1);

  pos=formula.find(",",posX);
  posX=formula.find("(",pos);
  QString yCol=formula.mid(pos+1,posX-pos-1);

  Graph3D *plot = new Graph3D("", this, 0);
  plot->addData(w, xCol, yCol, xl, xr, yl, yr, zl, zr);
  plot->update();

  QString label=caption;
  while(alreadyUsedName(label))
    label = generateUniqueName(tr("Graph"));

  plot->setWindowTitle(label);
  plot->setName(label);
  initPlot3D(plot);

  return plot;
}

Graph3D* ApplicationWindow::newPlot3D()
{
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  QString label = generateUniqueName(tr("Graph"));

  Graph3D *plot = new Graph3D("", this, 0);
  plot->setWindowTitle(label);
  plot->setName(label);

  customPlot3D(plot);
  initPlot3D(plot);

  emit modified();
  QApplication::restoreOverrideCursor();
  return plot;
}

Graph3D* ApplicationWindow::plotXYZ(Table* table, const QString& zColName, int type)
{
  int zCol = table->colIndex(zColName);
  if (zCol < 0)
    return 0;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  Graph3D *plot = new Graph3D("", this, 0);
  QString label = generateUniqueName(tr("Graph"));
  plot->setWindowTitle(label);
  plot->setName(label);

  customPlot3D(plot);
  if (type == Graph3D::Ribbon) {
    int ycol = table->colIndex(zColName);
    plot->addData(table, table->colName(table->colX(ycol)), zColName);
  } else
    plot->addData(table, table->colX(zCol), table->colY(zCol), zCol, type);
  initPlot3D(plot);

  emit modified();
  QApplication::restoreOverrideCursor();
  return plot;
}

Graph3D* ApplicationWindow::openPlotXYZ(const QString& caption,const QString& formula,
    double xl, double xr, double yl, double yr, double zl, double zr)
{
  int pos=formula.find("_",0);
  QString wCaption=formula.left(pos);

  Table* w=table(wCaption);
  if (!w)
    return 0;

  int posX=formula.find("(X)",pos);
  QString xColName=formula.mid(pos+1,posX-pos-1);

  pos=formula.find(",",posX);

  posX=formula.find("(Y)",pos);
  QString yColName=formula.mid(pos+1,posX-pos-1);

  pos=formula.find(",",posX);
  posX=formula.find("(Z)",pos);
  QString zColName=formula.mid(pos+1,posX-pos-1);

  int xCol=w->colIndex(xColName);
  int yCol=w->colIndex(yColName);
  int zCol=w->colIndex(zColName);

  Graph3D *plot=new Graph3D("", this, 0);
  plot->loadData(w, xCol, yCol, zCol, xl, xr, yl, yr, zl, zr);

  QString label = caption;
  if (alreadyUsedName(label))
    label = generateUniqueName(tr("Graph"));

  plot->setWindowTitle(label);
  plot->setName(label);
  initPlot3D(plot);
  return plot;
}

void ApplicationWindow::customPlot3D(Graph3D *plot)
{
  plot->setDataColors(QColor(plot3DColors[4]), QColor(plot3DColors[0]));
  plot->setMeshColor(QColor(plot3DColors[2]));
  plot->setAxesColor(QColor(plot3DColors[6]));
  plot->setNumbersColor(QColor(plot3DColors[5]));
  plot->setLabelsColor(QColor(plot3DColors[1]));
  plot->setBackgroundColor(QColor(plot3DColors[7]));
  plot->setGridColor(QColor(plot3DColors[3]));
  plot->setResolution(plot3DResolution);
  plot->showColorLegend(showPlot3DLegend);
  plot->setAntialiasing(smooth3DMesh);
  plot->setOrthogonal(orthogonal3DPlots);
  if (showPlot3DProjection)
    plot->setFloorData();
  plot->setNumbersFont(plot3DNumbersFont);
  plot->setXAxisLabelFont(plot3DAxesFont);
  plot->setYAxisLabelFont(plot3DAxesFont);
  plot->setZAxisLabelFont(plot3DAxesFont);
  plot->setTitleFont(plot3DTitleFont);
}

void ApplicationWindow::initPlot3D(Graph3D *plot)
{
  addMdiSubWindow(plot);
  connectSurfacePlot(plot);

  plot->setIcon(getQPixmap("trajectory_xpm"));
  plot->show();
  plot->setFocus();

  if (!plot3DTools->isVisible())
    plot3DTools->show();

  if (!plot3DTools->isEnabled())
    plot3DTools->setEnabled(true);

  customMenu(plot);
  customToolBars(plot);
}

void ApplicationWindow::exportMatrix()
{
  Matrix* m = dynamic_cast<Matrix*>(activeWindow(MatrixWindow));
  if (!m)
    return;

  ImageExportDialog *ied = new ImageExportDialog(this, m!=NULL, d_extended_export_dialog);
  ied->setDir(workingDir);
  ied->selectFilter(d_image_export_filter);
  if ( ied->exec() != QDialog::Accepted )
    return;
  workingDir = ied->directory().path();
  if (ied->selectedFiles().isEmpty())
    return;

  QString selected_filter = ied->selectedFilter();
  QString file_name = ied->selectedFiles()[0];
  QFileInfo file_info(file_name);
  if (!file_info.fileName().contains("."))
    file_name.append(selected_filter.remove("*"));

  QFile file(file_name);
  if (!file.open( QIODevice::WriteOnly )){
    QMessageBox::critical(this, tr("MantidPlot - Export error"),//Mantid
        tr("Could not write to file: <br><h4> %1 </h4><p>Please verify that you have the right to write to this location!").arg(file_name));
    return;
  }

  if (selected_filter.contains(".eps") || selected_filter.contains(".pdf") || selected_filter.contains(".ps"))
    m->exportVector(file_name, ied->resolution(), ied->color(), ied->keepAspect(), ied->pageSize());
  else {
    QList<QByteArray> list = QImageWriter::supportedImageFormats();
    for (int i=0; i<(int)list.count(); i++){
      if (selected_filter.contains("." + (list[i]).lower()))
        m->image().save(file_name, list[i], ied->quality());
    }
  }
}

Matrix* ApplicationWindow::importImage(const QString& fileName)
{
  QString fn = fileName;
  if (fn.isEmpty()){
    QList<QByteArray> list = QImageReader::supportedImageFormats();
    QString filter = tr("Images") + " (", aux1, aux2;
    for (int i=0; i<(int)list.count(); i++){
      aux1 = " *."+list[i]+" ";
      aux2 += " *."+list[i]+";;";
      filter += aux1;
    }
    filter+=");;" + aux2;

    fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Import image from file"), imagesDirPath, filter);//Mantid
    if ( !fn.isEmpty() ){
      QFileInfo fi(fn);
      imagesDirPath = fi.dirPath(true);
    }
  }

  QImage image(fn);
  if (image.isNull())
    return 0;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  MdiSubWindow *w = activeWindow(MatrixWindow);
  Matrix* m = NULL;
  if (w){
    m = dynamic_cast<Matrix*>(w);
    m->importImage(fn);
  } else {
    m = new Matrix(scriptingEnv(), image, "", this);
    initMatrix(m, generateUniqueName(tr("Matrix")));
    m->show();
    m->setWindowLabel(fn);
    m->setCaptionPolicy(MdiSubWindow::Both);
  }

  QApplication::restoreOverrideCursor();
  return m;
}

void ApplicationWindow::loadImage()
{
  QList<QByteArray> list = QImageReader::supportedImageFormats();
  QString filter = tr("Images") + " (", aux1, aux2;
  for (int i=0; i<(int)list.count(); i++){
    aux1 = " *."+list[i]+" ";
    aux2 += " *."+list[i]+";;";
    filter += aux1;
  }
  filter+=");;" + aux2;

  QString fn = QFileDialog::getOpenFileName(this, tr("MantidPlot - Load image from file"), imagesDirPath, filter);//Mantid
  if ( !fn.isEmpty() ){
    loadImage(fn);
    QFileInfo fi(fn);
    imagesDirPath = fi.dirPath(true);
  }
}

void ApplicationWindow::loadImage(const QString& fn)
{
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  MultiLayer *plot = multilayerPlot(generateUniqueName(tr("Graph")));
  plot->setWindowLabel(fn);
  plot->setCaptionPolicy(MdiSubWindow::Both);

  Graph *g = plot->activeGraph();
  g->setTitle("");
  for (int i=0; i<4; i++)
    g->enableAxis(i, false);
  g->removeLegend();
  g->addImage(fn);
  QApplication::restoreOverrideCursor();
}

void ApplicationWindow::loadScriptRepo(){
   MantidQt::API::ScriptRepositoryView *ad = new MantidQt::API::ScriptRepositoryView(this);
   connect(ad, SIGNAL(loadScript(const QString)),this,SLOT(loadScript(const QString& )));
  ad->setAttribute(Qt::WA_DeleteOnClose);
  ad->show();
  ad->setFocus();
}

void ApplicationWindow::polishGraph(Graph *g, int style)
{
  if (style == Graph::VerticalBars || style == Graph::HorizontalBars ||style == Graph::Histogram)
  {
    QList<int> ticksList;
    int ticksStyle = ScaleDraw::Out;
    ticksList<<ticksStyle<<ticksStyle<<ticksStyle<<ticksStyle;
    g->setMajorTicksType(ticksList);
    g->setMinorTicksType(ticksList);
  }
  if (style == Graph::HorizontalBars){
    g->setAxisTitle(QwtPlot::xBottom, tr("X Axis Title"));
    g->setAxisTitle(QwtPlot::yLeft, tr("Y Axis Title"));
  }
}

MultiLayer* ApplicationWindow::multilayerPlot(const QString& caption, int layers, int rows, int cols)
{
  MultiLayer* ml = new MultiLayer(this, layers, rows, cols);
  QString label = caption;
  initMultilayerPlot(ml, label.replace(QRegExp("_"), "-"));
  return ml;
}

MultiLayer* ApplicationWindow::newGraph(const QString& caption)
{
  MultiLayer *ml = multilayerPlot(generateUniqueName(caption));
  if (ml){
    Graph *g = ml->activeGraph();
    setPreferences(g);
    g->newLegend();
  }
  return ml;
}

MultiLayer* ApplicationWindow::multilayerPlot(Table* w, const QStringList& colList, int style, int startRow, int endRow)
{//used when plotting selected columns
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  MultiLayer* g = multilayerPlot(generateUniqueName(tr("Graph")));
  Graph *ag = g->activeGraph();
  if (!ag)
    return 0;

  setPreferences(ag);
  ag->addCurves(w, colList, style, defaultCurveLineWidth, defaultSymbolSize, startRow, endRow);

  polishGraph(ag, style);
  ag->newLegend();

  ag->setAutoScale();//Mantid
  /* The 'setAutoScale' above is needed to make sure that the plot initially encompasses all the
   * data points. However, this has the side-effect suggested by its name: all the axes become
   * auto-scaling if the data changes. If, in the plot preferences, autoscaling has been disabled
   * the the next line re-fixes the axes
   */
  if ( ! autoscale2DPlots ) ag->enableAutoscaling(false);

  QApplication::restoreOverrideCursor();
  return g;
}

MultiLayer* ApplicationWindow::multilayerPlot(int c, int r, int style)
{//used when plotting from the panel menu
  Table *t = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!t)
    return 0;

  if (!validFor2DPlot(t))
    return 0;

  QStringList list = t->selectedYColumns();
  if((int)list.count() < 1) {
    QMessageBox::warning(this, tr("MantidPlot - Plot error"), tr("Please select a Y column to plot!"));//Mantid
    return 0;
  }

  int curves = list.count();
  if (r < 0)
    r = curves;

  int layers = c*r;
  MultiLayer* g = multilayerPlot(generateUniqueName(tr("Graph")), layers, r, c);
  QList<Graph *> layersList = g->layersList();
  int i = 0;
  foreach(Graph *ag, layersList){
    setPreferences(ag);
    if (i < curves)
      ag->addCurves(t, QStringList(list[i]), style, defaultCurveLineWidth, defaultSymbolSize);
    ag->newLegend();
    polishGraph(ag, style);
    i++;
  }
  g->arrangeLayers(false, false);
  return g;
}

MultiLayer* ApplicationWindow::multilayerPlot(const QStringList& colList)
{//used when plotting from wizard
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  MultiLayer* g = multilayerPlot(generateUniqueName(tr("Graph")));
  Graph *ag = g->activeGraph();
  setPreferences(ag);
  polishGraph(ag, defaultCurveStyle);
  int curves = (int)colList.count();
  int errorBars = 0;
  for (int i=0; i<curves; i++) {
    if (colList[i].contains("(yErr)") || colList[i].contains("(xErr)"))
      errorBars++;
  }

  for (int i=0; i<curves; i++){
    QString s = colList[i];
    int pos = s.find(":", 0);
    QString caption = s.left(pos) + "_";
    Table *w = dynamic_cast<Table *>(table(caption));

    int posX = s.find("(X)", pos);
    QString xColName = caption+s.mid(pos+2, posX-pos-2);
    int xCol=w->colIndex(xColName);

    posX = s.find(",", posX);
    int posY = s.find("(Y)", posX);
    QString yColName = caption+s.mid(posX+2, posY-posX-2);

    PlotCurve *c = NULL;
    if (s.contains("(yErr)") || s.contains("(xErr)")){
      posY = s.find(",", posY);
      int posErr, errType;
      if (s.contains("(yErr)")){
        errType = QwtErrorPlotCurve::Vertical;
        posErr = s.find("(yErr)", posY);
      } else {
        errType = QwtErrorPlotCurve::Horizontal;
        posErr = s.find("(xErr)",posY);
      }

      QString errColName = caption+s.mid(posY+2, posErr-posY-2);
      c = dynamic_cast<PlotCurve *>(ag->addErrorBars(xColName, yColName, w, errColName, errType));
    } else
      c = dynamic_cast<PlotCurve *>(ag->insertCurve(w, xCol, yColName, defaultCurveStyle));

    CurveLayout cl = ag->initCurveLayout(defaultCurveStyle, curves - errorBars);
    cl.lWidth = float(defaultCurveLineWidth);
    cl.sSize = defaultSymbolSize;
    ag->updateCurveLayout(c, &cl);
  }
  ag->newLegend();
  ag->initScaleLimits();
  QApplication::restoreOverrideCursor();
  return g;
}

void ApplicationWindow::initMultilayerPlot(MultiLayer* g, const QString& name)
{
  QString label = name;
  while(alreadyUsedName(label))
    label = generateUniqueName(tr("Graph"));

  g->setWindowTitle(label);
  g->setName(label);
  g->setIcon(getQPixmap("graph_xpm"));
  g->setScaleLayersOnPrint(d_scale_plots_on_print);
  g->printCropmarks(d_print_cropmarks);

  connectMultilayerPlot(g);

  addMdiSubWindow(g);
}

void ApplicationWindow::customizeTables(const QColor& bgColor,const QColor& textColor,
    const QColor& headerColor,const QFont& textFont, const QFont& headerFont, bool showComments)
{
  tableBkgdColor = bgColor;
  tableTextColor = textColor;
  tableHeaderColor = headerColor;
  tableTextFont = textFont;
  tableHeaderFont = headerFont;
  d_show_table_comments = showComments;

  QList<MdiSubWindow *> windows = windowsList();
  foreach(MdiSubWindow *w, windows){
    if (w->inherits("Table"))
      customTable(dynamic_cast<Table*>(w));
  }
}

void ApplicationWindow::setAutoUpdateTableValues(bool on)
{
  if (d_auto_update_table_values == on)
    return;

  d_auto_update_table_values = on;

  Folder *f = projectFolder();
  while (f){
    QList<MdiSubWindow *> folderWindows = f->windowsList();
    foreach(MdiSubWindow *w, folderWindows){
      if (w->inherits("Table"))
        dynamic_cast<Table*>(w)->setAutoUpdateValues(d_auto_update_table_values);
    }
    f = f->folderBelow();
  }
}

void ApplicationWindow::customTable(Table* w)
{
  QColorGroup cg;
  cg.setColor(QColorGroup::Base, QColor(tableBkgdColor));
  cg.setColor(QColorGroup::Text, QColor(tableTextColor));
  w->setPalette(QPalette(cg, cg, cg));

  w->setHeaderColor(tableHeaderColor);
  w->setTextFont(tableTextFont);
  w->setHeaderFont(tableHeaderFont);
  w->showComments(d_show_table_comments);
  w->setNumericPrecision(d_decimal_digits);
}

void ApplicationWindow::setPreferences(Graph* g)
{
  if (!g->isPiePlot())
  {
    for (int i = 0; i < QwtPlot::axisCnt; i++)
    {
      bool show = d_show_axes[i];
      g->enableAxis(i, show);
      if (show)
      {
        ScaleDraw *sd = (ScaleDraw *)g->plotWidget()->axisScaleDraw (i);
        sd->enableComponent(QwtAbstractScaleDraw::Labels, d_show_axes_labels[i]);
        sd->setSpacing(d_graph_tick_labels_dist);
        if (i == QwtPlot::yRight && !d_show_axes_labels[i])
          g->setAxisTitle(i, tr(" "));
      }
    }
    //set the scale type i.e. log or linear
    g->setScale(QwtPlot::yLeft, d_axes_scales[0]);
    g->setScale(QwtPlot::yRight, d_axes_scales[1]);
    g->setScale(QwtPlot::xBottom, d_axes_scales[2]);
    g->setScale(QwtPlot::xTop, d_axes_scales[3]);

    // QtiPlot makes these calls here (as of 26/6/12), but they spoil color fill plots for us.
    //   Losing them seems to have no detrimental effect. Perhaps we need to update our updateSecondaryAxis code to match QtiPlot's.
    //g->updateSecondaryAxis(QwtPlot::xTop);
    //g->updateSecondaryAxis(QwtPlot::yRight);

    QList<int> ticksList;
    ticksList<<majTicksStyle<<majTicksStyle<<majTicksStyle<<majTicksStyle;
    g->setMajorTicksType(ticksList);
    ticksList.clear();
    ticksList<<minTicksStyle<<minTicksStyle<<minTicksStyle<<minTicksStyle;
    g->setMinorTicksType(ticksList);

    g->setTicksLength (minTicksLength, majTicksLength);
    g->setAxesLinewidth(axesLineWidth);
    g->drawAxesBackbones(drawBackbones);
    for (int i = 0; i < QwtPlot::axisCnt; i++)
      g->setAxisTitleDistance(i, d_graph_axes_labels_dist);
    //    need to call the plot functions for log/linear, errorbars and distribution stuff
  }

  g->setSynchronizedScaleDivisions(d_synchronize_graph_scales);
  g->initFonts(plotAxesFont, plotNumbersFont);
  g->initTitle(titleOn, plotTitleFont);
  g->setCanvasFrame(canvasFrameWidth);
  g->plotWidget()->setMargin(defaultPlotMargin);


  g->enableAutoscaling(autoscale2DPlots);
  g->setAutoscaleFonts(autoScaleFonts);
  g->setIgnoreResizeEvents(!autoResizeLayers);
  g->setAntialiasing(antialiasing2DPlots);
  g->enableFixedAspectRatio(fixedAspectRatio2DPlots);

}

/*
 *creates a new empty table
 */
Table* ApplicationWindow::newTable()
{
  Table* w = new Table(scriptingEnv(), 30, 2, "", this, 0);
  initTable(w, generateUniqueName(tr("Table")));
  w->showNormal();
  return w;
}

/*
 *used when opening a project file
 */
Table* ApplicationWindow::newTable(const QString& caption, int r, int c)
{
  Table* w = new Table(scriptingEnv(), r, c, "", this, 0);
  initTable(w, caption);
  if (w->objectName() != caption){//the table was renamed
    renamedTables << caption << w->objectName();
    if (d_inform_rename_table){
      QMessageBox:: warning(this, tr("MantidPlot - Renamed Window"),//Mantid
          tr("The table '%1' already exists. It has been renamed '%2'.").arg(caption).arg(w->objectName()));
    }
  }
  w->showNormal();
  return w;
}

Table* ApplicationWindow::newTable(int r, int c, const QString& name, const QString& legend)
{