Skip to content
Snippets Groups Projects
ApplicationWindow.cpp 579 KiB
Newer Older
/***************************************************************************
	File                 : ApplicationWindow.cpp
	Project              : QtiPlot
--------------------------------------------------------------------
	Copyright            : (C) 2006 by Ion Vasilief,
	                       Tilman Hoener zu Siederdissen,
                           Knut Franke
	Email (use @ for *)  : ion_vasilief*yahoo.fr, thzs*gmx.net,
	                       knut.franke*gmx.de
	Description          : QtiPlot's main window

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *  This program is free software; you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation; either version 2 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the Free Software           *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor,                    *
 *   Boston, MA  02110-1301  USA                                           *
 *                                                                         *
 ***************************************************************************/
#include "globals.h"
#include "ApplicationWindow.h"
#include "pixmaps.h"
#include "CurvesDialog.h"
#include "PlotDialog.h"
#include "AxesDialog.h"
#include "LineDialog.h"
#include "TextDialog.h"
#include "ExportDialog.h"
#include "TableDialog.h"
#include "SetColValuesDialog.h"
#include "ErrDialog.h"
#include "LegendWidget.h"
#include "ArrowMarker.h"
#include "ImageMarker.h"
#include "Graph.h"
#include "Plot.h"
#include "Grid.h"
#include "PlotWizard.h"
#include "PolynomFitDialog.h"
#include "ExpDecayDialog.h"
#include "FunctionDialog.h"
#include "FitDialog.h"
#include "SurfaceDialog.h"
#include "Graph3D.h"
#include "Plot3DDialog.h"
#include "ImageDialog.h"
#include "MultiLayer.h"
#include "LayerDialog.h"
#include "DataSetDialog.h"
#include "IntDialog.h"
#include "ConfigDialog.h"
#include "MatrixDialog.h"
#include "MatrixSizeDialog.h"
#include "MatrixValuesDialog.h"
#include "MatrixModel.h"
#include "MatrixCommand.h"
#include "importOPJ.h"
#include "AssociationsDialog.h"
#include "RenameWindowDialog.h"
#include "QwtErrorPlotCurve.h"
#include "InterpolationDialog.h"
#include "ImportASCIIDialog.h"
#include "ImageExportDialog.h"
#include "SmoothCurveDialog.h"
#include "FilterDialog.h"
#include "FFTDialog.h"
#include "Note.h"
#include "Folder.h"
#include "FindDialog.h"
#include "ScaleDraw.h"
#include "plot2D/ScaleEngine.h"
#include "ScriptingLangDialog.h"
#include "ScriptingWindow.h"
#include "ScriptFileInterpreter.h"
#include "TableStatistics.h"
#include "Fit.h"
#include "MultiPeakFit.h"
#include "PolynomialFit.h"
#include "SigmoidalFit.h"
#include "LogisticFit.h"
#include "NonLinearFit.h"
#include "FunctionCurve.h"
#include "QwtPieCurve.h"
#include "Spectrogram.h"
#include "Integration.h"
#include "Differentiation.h"
#include "SmoothFilter.h"
#include "FFTFilter.h"
#include "Convolution.h"
#include "Correlation.h"
#include "CurveRangeDialog.h"
#include "ColorBox.h"
#include "QwtHistogram.h"
#include "OpenProjectDialog.h"
#include "ColorMapDialog.h"
#include "TextEditor.h"
#include "SymbolDialog.h"
#include "CustomActionDialog.h"
#include "MdiSubWindow.h"
#include "FloatingWindow.h"
#include "DataPickerTool.h"

// TODO: move tool-specific code to an extension manager
#include "ScreenPickerTool.h"
#include "TranslateCurveTool.h"
#include "MultiPeakFitTool.h"
#include "LineProfileTool.h"
#include "RangeSelectorTool.h"
#include "PlotToolInterface.h"
#include "Mantid/MantidMatrix.h"
#include "Mantid/MantidTable.h"
#include "Mantid/MantidMatrixCurve.h"
#include "ContourLinesEditor.h"
#include "Mantid/InstrumentWidget/InstrumentWindow.h"
#include "Mantid/RemoveErrorsDialog.h"

#include <stdio.h>
#include <stdlib.h>

#include <qwt_scale_engine.h>
#include <QFileDialog>
#include <QInputDialog>
#include <QProgressDialog>
#include <QPrintDialog>
#include <QPixmapCache>
#include <QMenuBar>
#include <QClipboard>
#include <QTranslator>
#include <QSplitter>
#include <QSettings>
#include <QApplication>
#include <QMessageBox>
#include <QPrinter>
#include <QPrinterInfo>
#include <QActionGroup>
#include <QAction>
#include <QToolBar>
#include <QKeySequence>
#include <QImageReader>
#include <QImageWriter>
#include <QDateTime>
#include <QShortcut>
#include <QDockWidget>
#include <QTextStream>
#include <QVarLengthArray>
#include <QList>
#include <QUrl>
#include <QFontComboBox>
#include <QSpinBox>
#include <QMdiArea>
#include <QMdiSubWindow>
#include <QUndoStack>
#include <QUndoView>
#include <QSignalMapper>
#include <QDesktopWidget>

#include <zlib.h>

#include <gsl/gsl_sort.h>

#include <boost/regex.hpp>

//Mantid
#include "ScriptingWindow.h"

#include "Mantid/MantidUI.h"
#include "Mantid/MantidAbout.h"
#include "Mantid/PeakPickerTool.h"
#include "Mantid/ManageCustomMenus.h"
#include "Mantid/FirstTimeSetup.h"
#include "Mantid/SetUpParaview.h"

#include "MantidQtAPI/InterfaceManager.h"
#include "MantidQtAPI/UserSubWindow.h"
#include "MantidQtAPI/AlgorithmInputHistory.h"
#include "MantidQtAPI/ManageUserDirectories.h"

#include "MantidQtMantidWidgets/ICatSearch.h"
#include "MantidQtMantidWidgets/ICatMyDataSearch.h"
#include "MantidQtMantidWidgets/ICatAdvancedSearch.h"
#include "MantidQtMantidWidgets/FitPropertyBrowser.h"
#include "MantidQtMantidWidgets/MuonFitPropertyBrowser.h"

#include "MantidKernel/ConfigService.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/MantidVersion.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/AlgorithmFactory.h"
#include "MantidAPI/ITableWorkspace.h"
#include "MantidAPI/AnalysisDataService.h"

#include "MantidQtAPI/ScriptRepositoryView.h"

using namespace Qwt3D;
using namespace MantidQt::API;

extern "C"
{
void file_compress(const char  *file, const char  *mode);
void file_uncompress(const char  *file);
}

ApplicationWindow::ApplicationWindow(bool factorySettings)
: QMainWindow(), 
Scripted(ScriptingLangManager::newEnv(this)),
blockWindowActivation(false),
m_enableQtiPlotFitting(false),
m_exitCode(0),
#ifdef Q_OS_MAC // Mac
  settings(QSettings::IniFormat,QSettings::UserScope, "ISIS", "MantidPlot")
#else
  settings("ISIS", "MantidPlot")
#endif
{
  QStringList empty;
  init(factorySettings, empty);
}

ApplicationWindow::ApplicationWindow(bool factorySettings, const QStringList& args)
: QMainWindow(), 
Scripted(ScriptingLangManager::newEnv(this)),
blockWindowActivation(false),
m_enableQtiPlotFitting(false),
m_exitCode(0),
#ifdef Q_OS_MAC // Mac
  settings(QSettings::IniFormat,QSettings::UserScope, "ISIS", "MantidPlot")
#else
  settings("ISIS", "MantidPlot")
#endif
{
  init(factorySettings, args);
}

/**
 * Calls QCoreApplication::exit(m_exitCode)
 */
void ApplicationWindow::exitWithPresetCode()
{
  QCoreApplication::exit(m_exitCode);
}

void ApplicationWindow::init(bool factorySettings, const QStringList& args)
  QCoreApplication::setOrganizationName("ISIS");
  QCoreApplication::setApplicationName("MantidPlot");
#ifdef SHARED_MENUBAR
  m_sharedMenuBar = new QMenuBar(NULL);
  //setMenuBar(m_sharedMenuBar);
  m_sharedMenuBar->setNativeMenuBar(true);
#endif
  mantidUI = new MantidUI(this);
  setAttribute(Qt::WA_DeleteOnClose);

  setWindowTitle(tr("MantidPlot - untitled"));//Mantid
  setObjectName("main application");
  initGlobalConstants();
  QPixmapCache::setCacheLimit(20*QPixmapCache::cacheLimit ());

  tablesDepend = new QMenu(this);

  explorerWindow = new QDockWidget( this );
  explorerWindow->setWindowTitle(tr("Project Explorer"));
  explorerWindow->setObjectName("explorerWindow"); // this is needed for QMainWindow::restoreState()
  explorerWindow->setMinimumHeight(150);
  addDockWidget( Qt::BottomDockWidgetArea, explorerWindow );

  actionSaveFile=NULL;
  actionSaveProject=NULL;
  folders = new FolderListView(this);
  folders->header()->setClickEnabled( false );
  folders->addColumn( tr("Folder") );
  folders->setRootIsDecorated( true );
  folders->setResizeMode(Q3ListView::LastColumn);
  folders->header()->hide();
  folders->setSelectionMode(Q3ListView::Single);

  connect(folders, SIGNAL(currentChanged(Q3ListViewItem *)),
      this, SLOT(folderItemChanged(Q3ListViewItem *)));
  connect(folders, SIGNAL(itemRenamed(Q3ListViewItem *, int, const QString &)),
      this, SLOT(renameFolder(Q3ListViewItem *, int, const QString &)));
  connect(folders, SIGNAL(contextMenuRequested(Q3ListViewItem *, const QPoint &, int)),
      this, SLOT(showFolderPopupMenu(Q3ListViewItem *, const QPoint &, int)));
  connect(folders, SIGNAL(dragItems(QList<Q3ListViewItem *>)),
      this, SLOT(dragFolderItems(QList<Q3ListViewItem *>)));
  connect(folders, SIGNAL(dropItems(Q3ListViewItem *)),
      this, SLOT(dropFolderItems(Q3ListViewItem *)));
  connect(folders, SIGNAL(renameItem(Q3ListViewItem *)),
      this, SLOT(startRenameFolder(Q3ListViewItem *)));
  connect(folders, SIGNAL(addFolderItem()), this, SLOT(addFolder()));
  connect(folders, SIGNAL(deleteSelection()), this, SLOT(deleteSelectedItems()));

  current_folder = new Folder( 0, tr("UNTITLED"));
  FolderListItem *fli = new FolderListItem(folders, current_folder);
  current_folder->setFolderListItem(fli);
  fli->setOpen( true );

  lv = new FolderListView();
  lv->addColumn (tr("Name"),-1 );
  lv->addColumn (tr("Type"),-1 );
  lv->addColumn (tr("View"),-1 );
  lv->addColumn (tr("Size"),-1 );
  lv->addColumn (tr("Created"),-1);
  lv->addColumn (tr("Label"),-1);
  lv->setResizeMode(Q3ListView::LastColumn);
  lv->setMinimumHeight(80);
  lv->setSelectionMode(Q3ListView::Extended);
  lv->setDefaultRenameAction (Q3ListView::Accept);

  explorerSplitter = new QSplitter(Qt::Horizontal, explorerWindow);
  explorerSplitter->addWidget(folders);
  explorerSplitter->addWidget(lv);
  explorerWindow->setWidget(explorerSplitter);

  QList<int> splitterSizes;
  explorerSplitter->setSizes( splitterSizes << 45 << 45);
  explorerWindow->hide();

  logWindow = new QDockWidget(this);
  logWindow->setObjectName("logWindow"); // this is needed for QMainWindow::restoreState()
  logWindow->setWindowTitle(tr("Results Log"));
  addDockWidget( Qt::TopDockWidgetArea, logWindow );

  results=new QTextEdit(logWindow);
  results->setReadOnly (true);
  results->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(results, SIGNAL(customContextMenuRequested(const QPoint &)), this, 
	  SLOT(showLogWindowContextMenu(const QPoint &)));
  logWindow->setWidget(results);
  logWindow->hide();

  consoleWindow = new QDockWidget(this);
  consoleWindow->setObjectName("consoleWindow"); // this is needed for QMainWindow::restoreState()
  consoleWindow->setWindowTitle(tr("Scripting Console"));
  addDockWidget( Qt::TopDockWidgetArea, consoleWindow );
  console = new QTextEdit(consoleWindow);
  console->setReadOnly(true);
  console->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(console, SIGNAL(customContextMenuRequested(const QPoint &)), this,
	  SLOT(showScriptConsoleContextMenu(const QPoint &)));
  consoleWindow->setWidget(console);
  consoleWindow->hide();
  m_interpreterDock = new QDockWidget(this);
  m_interpreterDock->setObjectName("interpreterDock"); // this is needed for QMainWindow::restoreState()
  m_interpreterDock->setWindowTitle("Script Interpreter");
  addDockWidget( Qt::BottomDockWidgetArea, m_interpreterDock );
  // This is a temporary widget so that when the settings are read the dock's visible state is correct.
  // It gets replaced with the script widget after the scripting language has been read and set
  m_interpreterDock->setWidget(new QTextEdit);
  m_interpreterDock->hide();

  undoStackWindow = new QDockWidget(this);
  undoStackWindow->setObjectName("undoStackWindow"); // this is needed for QMainWindow::restoreState()
  undoStackWindow->setWindowTitle(tr("Undo Stack"));
  addDockWidget(Qt::RightDockWidgetArea, undoStackWindow);

  d_undo_view = new QUndoView(undoStackWindow);
  d_undo_view->setCleanIcon(QIcon(getQPixmap("filesave_xpm")));
  undoStackWindow->setWidget(d_undo_view);
  undoStackWindow->hide();

  /*
  If applicable, set the Paraview path BEFORE libaries are loaded. Doing it here, before the call to MantidUI::init() prevents 
  the logs being poluted with library loading errors.
Owen Arnold's avatar
Owen Arnold committed
  trySetParaviewPath(args);
  //Initialize Mantid
  // MG: 01/02/2009 - Moved this to before scripting so that the logging is connected when
  // we register Python algorithms
  mantidUI->init();

  // Needs to be done after initialization of dock windows,
  // because we now use QDockWidget::toggleViewAction()
  createActions();
  initToolBars();
  initMainMenu();

  d_workspace = new QMdiArea();
  d_workspace->setOption(QMdiArea::DontMaximizeSubWindowOnActivation);
  d_workspace->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  d_workspace->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  setCentralWidget(d_workspace);

  setAcceptDrops(true);

  hiddenWindows = new QList<QWidget*>();

  scriptingWindow = NULL;
  d_text_editor = NULL;

  // List of registered PyQt interfaces
  QString pyqt_interfaces_as_str = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("mantidqt.python_interfaces"));
  pyqt_interfaces = QStringList::split(" ", pyqt_interfaces_as_str);

  renamedTables = QStringList();
  if (!factorySettings)
    readSettings();
  createLanguagesList();
  insertTranslatedStrings();
  disableToolbars();

//  assistant = new QAssistantClient( QString(), this );

  actionNextWindow = new QAction(QIcon(getQPixmap("next_xpm")), tr("&Next","next window"), this);
  actionNextWindow->setShortcut( tr("F5","next window shortcut") );
  connect(actionNextWindow, SIGNAL(activated()), d_workspace, SLOT(activateNextSubWindow()));

  actionPrevWindow = new QAction(QIcon(getQPixmap("prev_xpm")), tr("&Previous","previous window"), this);
  actionPrevWindow->setShortcut( tr("F6","previous window shortcut") );
  connect(actionPrevWindow, SIGNAL(activated()), d_workspace, SLOT(activatePreviousSubWindow()));

  connect(tablesDepend, SIGNAL(activated(int)), this, SLOT(showTable(int)));

  connect(this, SIGNAL(modified()),this, SLOT(modifiedProject()));
  connect(d_workspace, SIGNAL(subWindowActivated(QMdiSubWindow *)),
      this, SLOT(windowActivated(QMdiSubWindow*)));
  connect(lv, SIGNAL(doubleClicked(Q3ListViewItem *)),
      this, SLOT(activateWindow(Q3ListViewItem *)));
  connect(lv, SIGNAL(doubleClicked(Q3ListViewItem *)),
      this, SLOT(folderItemDoubleClicked(Q3ListViewItem *)));
  connect(lv, SIGNAL(contextMenuRequested(Q3ListViewItem *, const QPoint &, int)),
      this, SLOT(showWindowPopupMenu(Q3ListViewItem *, const QPoint &, int)));
  connect(lv, SIGNAL(dragItems(QList<Q3ListViewItem *>)),
      this, SLOT(dragFolderItems(QList<Q3ListViewItem *>)));
  connect(lv, SIGNAL(dropItems(Q3ListViewItem *)),
      this, SLOT(dropFolderItems(Q3ListViewItem *)));
  connect(lv, SIGNAL(renameItem(Q3ListViewItem *)),
      this, SLOT(startRenameFolder(Q3ListViewItem *)));
  connect(lv, SIGNAL(addFolderItem()), this, SLOT(addFolder()));
  connect(lv, SIGNAL(deleteSelection()), this, SLOT(deleteSelectedItems()));
  connect(lv, SIGNAL(itemRenamed(Q3ListViewItem *, int, const QString &)),
      this, SLOT(renameWindow(Q3ListViewItem *, int, const QString &)));

  connect(recent, SIGNAL(activated(int)), this, SLOT(openRecentProject(int)));
  //connect(&http, SIGNAL(done(bool)), this, SLOT(receivedVersionFile(bool)));

  //apply user settings
  updateAppFonts();
  setAppColors(workspaceColor, panelsColor, panelsTextColor, true);

  //Scripting
  m_script_envs = QHash<QString, ScriptingEnv*>();
  setScriptingLanguage(defaultScriptingLang);
  m_scriptInterpreter = new CommandLineInterpreter(*scriptingEnv(), m_interpreterDock);
  delete m_interpreterDock->widget();
  m_interpreterDock->setWidget(m_scriptInterpreter);
  m_iface_script = NULL;
  loadCustomActions();

  // Print a warning message if the scripting language is set to muParser
  if (defaultScriptingLang == "muParser")
  {
    logWindow->show();
    results->setTextColor(Qt::blue);
    results->insertPlainText("The scripting language is set to muParser. This is probably not what you want! Change the default in View->Preferences.");
    results->setTextColor(Qt::black);
  }

  actionIPythonConsole->setVisible(testForIPython());

  // Need to show first time setup dialog?
  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
  std::string facility = config.getString("default.facility");
  std::string instrument = config.getString("default.instrument");
  if ( facility.empty() || instrument.empty() )
  {
    showFirstTimeSetup();
  }
  using namespace Mantid::API;
  // Do this as late as possible to avoid unnecessary updates
  AlgorithmFactory::Instance().enableNotifications();
  AlgorithmFactory::Instance().notificationCenter.postNotification(new AlgorithmFactoryUpdateNotification);

/*
Function tries to set the paraview path.

Owen Arnold's avatar
Owen Arnold committed
This is a windows only feature. the PATH enviromental variable can be set at runtime on windows.

- Abort if Vates libraries do not seem to be present.
- Othwerise, if the paraview.path is already in the properties file, use it.
- Otherwise, if the user is not using executeandquit command arguments launch the Setup gui.

@param commandArguments : all command line arguments.
*/
void ApplicationWindow::trySetParaviewPath(const QStringList& commandArguments)
{
Owen Arnold's avatar
Owen Arnold committed
#ifdef _WIN32
  if(this->hasVatesAvailable())//TODO: This condition is redundant since Vates will be shipped by default.
    Mantid::Kernel::ConfigServiceImpl& confService = Mantid::Kernel::ConfigService::Instance();
    //Early check of execute and quit command arguments used by system tests.
    QString str;
    bool b_skipDialog = false;
Owen Arnold's avatar
Owen Arnold committed
    foreach(str, commandArguments)
    {
      if(this->shouldExecuteAndQuit(str))
      {
        b_skipDialog = true;
        break;
      }
    }

    //ONLY If skipping is not already selected
    if(!b_skipDialog)
    {
      //If the ignore property exists and is set to true, then skip the dialog.
      const std::string paraviewIgnoreProperty = "paraview.ignore";
      b_skipDialog = confService.hasProperty(paraviewIgnoreProperty) && QString(confService.getString(paraviewIgnoreProperty).c_str()).toInt() > 0;
    if(this->hasParaviewPath())
    {
      //Already have a path in the properties file, just apply it.
      std::string path = confService.getString("paraview.path");
      confService.setParaviewLibraryPath(path);
    }
    else
    {
      //Only run the following if skipping is not implied.
      if(!b_skipDialog)
      {
        //Launch the dialog to set the PV path.
        SetUpParaview pv(SetUpParaview::FirstLaunch);
Owen Arnold's avatar
Owen Arnold committed
#else
  UNUSED_ARG(commandArguments)
#endif
/*
Getter to determine if the vates paraview plugins are available.

The code below may be used before MantidUI::init is called and therefore the implementation
must not rely on the Vates Libraries to be loaded in order to determine whether Vates is available.

@return TRUE if vates is available
*/
bool ApplicationWindow::hasVatesAvailable() const
{
  return Mantid::Kernel::ConfigService::Instance().quickVatesCheck();
}

/*
Getter to determine if the paraview path has been set.
*/
bool ApplicationWindow::hasParaviewPath() const
{
  Mantid::Kernel::ConfigServiceImpl& config = Mantid::Kernel::ConfigService::Instance();
  return config.hasProperty("paraview.path");
}

void ApplicationWindow::showLogWindowContextMenu(const QPoint & p)
{
  (void)p; //Avoid compiler warning
  QMenu *menu = results->createStandardContextMenu();
  if(!menu) return;
  if(results->text().isEmpty())
  {
    actionClearLogInfo->setEnabled(false);
  }
  else
  {
    actionClearLogInfo->setEnabled(true);
  }

  menu->addAction(actionClearLogInfo);
  //Mantid log level changes
  QMenu *logLevelMenu = menu->addMenu("&Log Level");
  logLevelMenu->addAction(actionLogLevelError);
  logLevelMenu->addAction(actionLogLevelWarning);
  logLevelMenu->addAction(actionLogLevelNotice);
  logLevelMenu->addAction(actionLogLevelInformation);
  logLevelMenu->addAction(actionLogLevelDebug);

  //check the right level
  int level = Mantid::Kernel::Logger::get("").getLevel(); //get the root logger logging level
  if (level == Poco::Message::PRIO_ERROR)
    actionLogLevelError->setChecked(true);
  if (level == Poco::Message::PRIO_WARNING)
    actionLogLevelWarning->setChecked(true);
  if (level == Poco::Message::PRIO_NOTICE)
    actionLogLevelNotice->setChecked(true);
  if (level == Poco::Message::PRIO_INFORMATION)
    actionLogLevelInformation->setChecked(true);
  if (level == Poco::Message::PRIO_DEBUG)
    actionLogLevelDebug->setChecked(true);

  //Mantid log level changes
  menu->popup(QCursor::pos());
}

void ApplicationWindow::setLogLevel(int level)
{
  //set the log level
  Mantid::Kernel::Logger::setLevelForAll(level);
}

void ApplicationWindow::showScriptConsoleContextMenu(const QPoint &p)
{
  (void)p;
  QMenu *menu = results->createStandardContextMenu();
  menu->addAction(actionClearConsole);
  menu->popup(QCursor::pos());
}

void ApplicationWindow::initWindow()
{
  switch(d_init_window_type){
  case TableWindow:
    newTable();
    break;
  case MatrixWindow:
    newMatrix();
    break;
  case MultiLayerWindow:
    newGraph();
    break;
  case NoteWindow:
    newNote();
    break;
  default:
    break;
  }
}

void ApplicationWindow::initGlobalConstants()
{
  d_auto_update_table_values = true;
  d_active_window = NULL;
  d_matrix_undo_stack_size = 10;

  d_opening_file = false;
  d_in_place_editing = true;

  d_matrix_tool_bar = true;
  d_file_tool_bar = true;
  d_column_tool_bar = true;
  d_edit_tool_bar = true;
  d_plot_tool_bar = true;
  d_plot3D_tool_bar = true;
  d_display_tool_bar = false;
  d_format_tool_bar = true;

  appStyle = qApp->style()->objectName();
  d_app_rect = QRect();
  projectname = "untitled";
  lastCopiedLayer = 0;
  d_text_copy = NULL;
  d_arrow_copy = NULL;
  d_image_copy = NULL;

  savingTimerId = 0;

  autoSearchUpdatesRequest = false;

  show_windows_policy = ActiveFolder;
  d_init_window_type = NoWindow;

  QString aux = qApp->applicationDirPath();
  workingDir = aux;

  d_translations_folder = aux + "/translations";
  helpFilePath = aux + "/manual/index.html";
  d_python_config_folder = aux;

  fitPluginsPath = aux + "fitPlugins";
  fitModelsPath = QString::null;
  templatesDir = aux;
  asciiDirPath = aux;
  imagesDirPath = aux;
  scriptsDirPath = aux;
  customActionsDirPath = QString::null;

  appFont = QFont();
  QString family = appFont.family();
  int pointSize = appFont.pointSize();
  tableTextFont = appFont;
  tableHeaderFont = appFont;
  plotAxesFont = QFont(family, pointSize, QFont::Bold, false);
  plotNumbersFont = QFont(family, pointSize );
  plotLegendFont = appFont;
  plotTitleFont = QFont(family, pointSize + 2, QFont::Bold,false);

  plot3DAxesFont = QFont(family, pointSize, QFont::Bold, false );
  plot3DNumbersFont = QFont(family, pointSize);
  plot3DTitleFont = QFont(family, pointSize + 2, QFont::Bold,false);

  autoSearchUpdates = false;
  appLanguage = QLocale::system().name().section('_',0,0);
  show_windows_policy = ApplicationWindow::ActiveFolder;

  workspaceColor = QColor("darkGray");
  panelsColor = QColor("#ffffff");
  panelsTextColor = QColor("#000000");
  tableBkgdColor = QColor("#ffffff");
  tableTextColor = QColor("#000000");
  tableHeaderColor = QColor("#000000");

  plot3DColors = QStringList();
  plot3DColors << "blue";
  plot3DColors << "#000000";
  plot3DColors << "#000000";
  plot3DColors << "#000000";
  plot3DColors << "red";
  plot3DColors << "#000000";
  plot3DColors << "#000000";
  plot3DColors << "#ffffff";

  d_graph_tick_labels_dist = 4;
  d_graph_axes_labels_dist = 2;

  autoSave = false;
  autoSaveTime = 15;
  d_backup_files = true;
  defaultScriptingLang = "Python";  //Mantid M. Gigg
  // Scripting window geometry
  d_script_win_pos = QPoint(250,200);
  d_script_win_size = QSize(600,660);
  d_thousands_sep = true;
  d_locale = QLocale::system().name();
  if (!d_thousands_sep)
    d_locale.setNumberOptions(QLocale::OmitGroupSeparator);

  d_decimal_digits = 13;

  d_extended_open_dialog = true;
  d_extended_export_dialog = true;
  d_extended_import_ASCII_dialog = true;
  d_extended_plot_dialog = true;

  d_add_curves_dialog_size = QSize(700, 400);
  d_show_current_folder = false;

  confirmCloseFolder = false;
  confirmCloseTable = false;
  confirmCloseMatrix = false;
  confirmClosePlot2D = false;
  confirmClosePlot3D = false;
  confirmCloseNotes = false;
  d_inform_rename_table = false;
  confirmCloseInstrWindow=false;

  d_show_table_comments = false;

  titleOn = true;
  d_show_axes = QVector<bool> (QwtPlot::axisCnt, true);
  // 'Factory' default is to not show top & right axes
  d_show_axes[1] = false;
  d_show_axes[3] = false;
  d_show_axes_labels = QVector<bool> (QwtPlot::axisCnt, true);
  canvasFrameWidth = 0;
  defaultPlotMargin = 0;
  drawBackbones = true;

  //these settings are overridden, but the default axes scales are linear
  d_axes_scales = QVector<QString> (QwtPlot::axisCnt, "linear");

  axesLineWidth = 1;
  autoscale2DPlots = true;
  autoScaleFonts = true;
  autoResizeLayers = true;
  antialiasing2DPlots = false; //Mantid
  fixedAspectRatio2DPlots = false; //Mantid
  d_scale_plots_on_print = false;
  d_print_cropmarks = false;
  d_synchronize_graph_scales = true;

  defaultCurveStyle = static_cast<int>(Graph::Line);
  defaultCurveLineWidth = 1;
  defaultSymbolSize = 7;

  majTicksStyle = static_cast<int>(ScaleDraw::Out);
  minTicksStyle = static_cast<int>(ScaleDraw::Out);
  minTicksLength = 5;
  majTicksLength = 9;

  legendFrameStyle = static_cast<int>(LegendWidget::Line);
  legendTextColor = Qt::black;
  legendBackground = Qt::white;
  legendBackground.setAlpha(0); // transparent by default;

  defaultArrowLineWidth = 1;
  defaultArrowColor = Qt::black;
  defaultArrowHeadLength = 4;
  defaultArrowHeadAngle = 45;
  defaultArrowHeadFill = true;
  defaultArrowLineStyle = Graph::getPenStyle("SolidLine");

  showPlot3DLegend = true;
  showPlot3DProjection = false;
  smooth3DMesh = false;
  plot3DResolution = 1;
  orthogonal3DPlots = false;
  autoscale3DPlots = true;

  fit_output_precision = 13;
  pasteFitResultsToPlot = false;
  writeFitResultsToLog = true;
  generateUniformFitPoints = true;
  fitPoints = 100;
  generatePeakCurves = true;
  peakCurvesColor = 2;
  fit_scale_errors = true;
  d_2_linear_fit_points = true;

  columnSeparator = "\t";
  ignoredLines = 0;
  renameColumns = true;
  strip_spaces = false;
  simplify_spaces = false;
  d_ASCII_file_filter = "*";
  d_ASCII_import_locale = QLocale::system().name();
  d_import_dec_separators = true;
  d_ASCII_import_mode = static_cast<int>(ImportASCIIDialog::NewTables);
  d_ASCII_comment_string = "#";
  d_ASCII_import_comments = false;
  d_ASCII_import_read_only = false;
  d_ASCII_import_preview = true;
  d_preview_lines = 100;
  d_ASCII_end_line = LF;
  d_eol = LF;
#ifdef Q_OS_MAC
  d_ASCII_end_line = CR;
  d_eol = CR;
#endif

  d_export_col_separator = "\t";
  d_export_col_names = false;
  d_export_col_comment = false;
  d_export_table_selection = false;

  d_image_export_filter = ".png";
  d_export_transparency = false;
  d_export_quality = 100;

  // MG: On Linux, if cups defines a printer queue that cannot be contact, the
  // QPrinter constructor hangs and doesn't timeout.

  //	QPrinterInfo::availablePrinters();


  //	d_export_resolution = QPrinter().resolution();
  d_export_color = true;
  d_export_vector_size = static_cast<int>(QPrinter::Custom);
  d_keep_plot_aspect = true;
}

QMenuBar* ApplicationWindow::myMenuBar()
{
#ifdef SHARED_MENUBAR
  return m_sharedMenuBar == NULL ? menuBar() : m_sharedMenuBar;
#else
  return menuBar();
#endif
}

void ApplicationWindow::initToolBars()
{
  initPlot3DToolBar();

  //	setWindowIcon(QIcon(getQPixmap("logo_xpm")));
  setWindowIcon(QIcon(":/MantidPlot_Icon_32offset.png"));
  QPixmap openIcon, saveIcon;

  fileTools = new QToolBar(tr( "File" ), this);
  fileTools->setObjectName("fileTools"); // this is needed for QMainWindow::restoreState()
  fileTools->setIconSize( QSize(18,20) );
  addToolBar( Qt::TopToolBarArea, fileTools );

  fileTools->addAction(actionNewProject);
  fileTools->addSeparator ();
  fileTools->addAction(actionManageDirs);
  fileTools->addSeparator ();
  
  fileTools->addAction(actionOpenProj);
  fileTools->addAction(actionLoadFile);
  fileTools->addAction(actionSaveProject);
  fileTools->addSeparator ();
  fileTools->addAction(actionShowLog);
#ifdef SCRIPTING_PYTHON
  fileTools->addAction(actionShowScriptWindow);
#endif

  editTools = new QToolBar(tr("Edit"), this);
  editTools->setObjectName("editTools"); // this is needed for QMainWindow::restoreState()
  editTools->setIconSize( QSize(18,20) );
  addToolBar( editTools );

  editTools->addAction(actionCutSelection);
  editTools->addAction(actionCopySelection);
  editTools->addAction(actionPasteSelection);

  plotTools = new QToolBar(tr("Plot"), this);
  plotTools->setObjectName("plotTools"); // this is needed for QMainWindow::restoreState()
  plotTools->setIconSize( QSize(16,20) );
  addToolBar( plotTools );

  plotTools->addAction(actionAddFunctionCurve);
  plotTools->addAction(actionNewLegend);
  plotTools->addSeparator ();
  plotTools->addAction(actionUnzoom);

  dataTools = new QActionGroup( this );
  dataTools->setExclusive( true );

  btnPointer = new QAction(tr("Disable &Tools"), this);
  btnPointer->setActionGroup(dataTools);
  btnPointer->setCheckable( true );
  btnPointer->setIcon(QIcon(getQPixmap("pointer_xpm")) );
  btnPointer->setChecked(true);
  plotTools->addAction(btnPointer);


  actionMagnify->setActionGroup(dataTools);
  actionMagnify->setCheckable( true );
  plotTools->addAction(actionMagnify);

  btnZoomIn = new QAction(tr("&Zoom In"), this);
  btnZoomIn->setShortcut( tr("Ctrl++") );
  btnZoomIn->setActionGroup(dataTools);
  btnZoomIn->setCheckable( true );
  btnZoomIn->setIcon(QIcon(getQPixmap("zoom_xpm")) );
  plotTools->addAction(btnZoomIn);

  btnZoomOut = new QAction(tr("&Zoom Out"), this);
  btnZoomOut->setShortcut( tr("Ctrl+-") );
  btnZoomOut->setActionGroup(dataTools);
  btnZoomOut->setCheckable( true );
  btnZoomOut->setIcon(QIcon(getQPixmap("zoomOut_xpm")) );
  plotTools->addAction(btnZoomOut);


  btnCursor = new QAction(tr("&Data Reader"), this);
  btnCursor->setShortcut( tr("CTRL+D") );
  btnCursor->setActionGroup(dataTools);
  btnCursor->setCheckable( true );
  btnCursor->setIcon(QIcon(getQPixmap("select_xpm")) );
  //plotTools->addAction(btnCursor); disabled until fixed (#2783)

  btnSelect = new QAction(tr("&Select Data Range"), this);
  btnSelect->setShortcut( tr("ALT+S") );
  btnSelect->setActionGroup(dataTools);
  btnSelect->setCheckable( true );
  btnSelect->setIcon(QIcon(getQPixmap("cursors_xpm")) );
  //plotTools->addAction(btnSelect); disabled until fixed (#2783)

  btnPicker = new QAction(tr("S&creen Reader"), this);
  btnPicker->setActionGroup(dataTools);
  btnPicker->setCheckable( true );
  btnPicker->setIcon(QIcon(getQPixmap("cursor_16_xpm")) );
  plotTools->addAction(btnPicker); //disabled until fixed (#2783)

  btnLabel = new QAction(tr("Label &Tool"), this);
  btnLabel->setShortcut( tr("ALT+T") );
  btnLabel->setActionGroup(dataTools);
  btnLabel->setIcon(QIcon(getQPixmap("text_xpm")));
  btnLabel->setCheckable(true);
  plotTools->addAction(btnLabel); //disabled until fixed (#2783)
  
  actionDrawPoints = new QAction(tr("&Draw Data Points"), this);
  actionDrawPoints->setActionGroup(dataTools);
  actionDrawPoints->setCheckable( true );
  actionDrawPoints->setIcon(QIcon(getQPixmap("draw_points_xpm")) );
  //plotTools->addAction(actionDrawPoints); disabled until fixed (#2783)

  btnMovePoints = new QAction(tr("&Move Data Points..."), this);
  btnMovePoints->setShortcut( tr("Ctrl+ALT+M") );
  btnMovePoints->setActionGroup(dataTools);
  btnMovePoints->setCheckable( true );
  btnMovePoints->setIcon(QIcon(getQPixmap("hand_xpm")) );
  //plotTools->addAction(btnMovePoints); disabled until fixed (#2783)

  btnRemovePoints = new QAction(tr("Remove &Bad Data Points..."), this);
  btnRemovePoints->setShortcut( tr("Alt+B") );
  btnRemovePoints->setActionGroup(dataTools);
  btnRemovePoints->setCheckable( true );
  btnRemovePoints->setIcon(QIcon(getQPixmap("gomme_xpm")));
  //plotTools->addAction(btnRemovePoints); disabled until fixed (#2783)

  if (mantidUI->fitFunctionBrowser())
  {
    btnMultiPeakPick = new QAction(tr("Select Multiple Peaks..."), this);
    btnMultiPeakPick->setActionGroup(dataTools);
    btnMultiPeakPick->setCheckable( true );
    btnMultiPeakPick->setIcon(QIcon(getQPixmap("Fit_xpm")));
    plotTools->addAction(btnMultiPeakPick);
  }
  else
  {
    btnMultiPeakPick = NULL;
  }

  connect( dataTools, SIGNAL( triggered( QAction* ) ), this, SLOT( pickDataTool( QAction* ) ) );
  plotTools->addSeparator ();

  btnArrow = new QAction(tr("Draw &Arrow"), this);
  btnArrow->setShortcut( tr("CTRL+ALT+A") );
  btnArrow->setActionGroup(dataTools);
  btnArrow->setCheckable( true );
  btnArrow->setIcon(QIcon(getQPixmap("arrow_xpm")) );
  plotTools->addAction(btnArrow);

  btnLine = new QAction(tr("Draw &Line"), this);
  btnLine->setShortcut( tr("CTRL+ALT+L") );
  btnLine->setActionGroup(dataTools);
  btnLine->setCheckable( true );
  btnLine->setIcon(QIcon(getQPixmap("lPlot_xpm")) );
  plotTools->addAction(btnLine);

  plotTools->hide();

  displayBar = new QToolBar( tr( "Data Display" ), this );
  displayBar->setAllowedAreas( Qt::TopToolBarArea | Qt::BottomToolBarArea );
  displayBar->setObjectName("displayBar"); // this is needed for QMainWindow::restoreState()
  info = new QLineEdit( this );
  displayBar->addWidget( info );
  info->setReadOnly(true);
  QPalette palette;
  palette.setColor(QPalette::Text, QColor(Qt::green));
  palette.setColor(QPalette::HighlightedText, QColor(Qt::darkGreen));
  palette.setColor(QPalette::Base, QColor(Qt::black));
  info->setPalette(palette);

  addToolBar( Qt::TopToolBarArea, displayBar );
  displayBar->hide();

  insertToolBarBreak (displayBar);

  formatToolBar = new QToolBar(tr( "Format" ), this);
  formatToolBar->setObjectName("formatToolBar");
  addToolBar(Qt::TopToolBarArea, formatToolBar);

  QFontComboBox *fb = new QFontComboBox();
  connect(fb, SIGNAL(currentFontChanged(const QFont &)), this, SLOT(setFontFamily(const QFont &)));
  actionFontBox = formatToolBar->addWidget(fb);

  QSpinBox *sb = new QSpinBox();
  connect(sb, SIGNAL(valueChanged(int)), this, SLOT(setFontSize(int)));
  actionFontSize = formatToolBar->addWidget(sb);

  actionFontBold->addTo(formatToolBar);
  actionFontItalic->addTo(formatToolBar);

  actionUnderline->addTo(formatToolBar);
  actionSuperscript->addTo(formatToolBar);
  actionSubscript->addTo(formatToolBar);
  actionGreekSymbol->addTo(formatToolBar);
  actionGreekMajSymbol->addTo(formatToolBar);
  actionMathSymbol->addTo(formatToolBar);

  formatToolBar->setEnabled(false);
  formatToolBar->hide();



}

void ApplicationWindow::insertTranslatedStrings()
{
  if (projectname == "untitled")
    setWindowTitle(tr("MantidPlot - untitled"));//Mantid

  lv->setColumnText (0, tr("Name"));
  lv->setColumnText (1, tr("Type"));
  lv->setColumnText (2, tr("View"));
  lv->setColumnText (3, tr("Size"));
  lv->setColumnText (4, tr("Created"));
  lv->setColumnText (5, tr("Label"));

  explorerWindow->setWindowTitle(tr("Project Explorer"));
  logWindow->setWindowTitle(tr("Results Log"));
  undoStackWindow->setWindowTitle(tr("Undo Stack"));
  consoleWindow->setWindowTitle(tr("Scripting Console"));
  displayBar->setWindowTitle(tr("Data Display"));
  plotTools->setWindowTitle(tr("Plot"));
  fileTools->setWindowTitle(tr("File"));
  editTools->setWindowTitle(tr("Edit"));
  plot3DTools->setWindowTitle(tr("3D Surface"));
  formatToolBar->setWindowTitle(tr("Format"));

  fileMenu->changeItem(recentMenuID, tr("&Recent Projects"));

  translateActionsStrings();
  customMenu(activeWindow());
}

void ApplicationWindow::initMainMenu()
{
  fileMenu = new QMenu(this);
  fileMenu->setObjectName("fileMenu");
  connect(fileMenu, SIGNAL(aboutToShow()), this, SLOT(fileMenuAboutToShow()));

  recent = new QMenu(this);
  newMenu = new QMenu(this);
  newMenu->setObjectName("newMenu");
  exportPlotMenu = new QMenu(this);
  exportPlotMenu->setObjectName("exportPlotMenu");

  edit = new QMenu(this);
  edit->setObjectName("editMenu");

  edit->insertSeparator();
  edit->addAction(actionCopySelection);
  edit->addAction(actionPasteSelection);
  edit->insertSeparator();
  edit->addAction(actionDeleteFitTables);

  connect(edit, SIGNAL(aboutToShow()), this, SLOT(editMenuAboutToShow()));

  view = new QMenu(this);
  view->setObjectName("viewMenu");

  view->setCheckable(true);

  //view->addAction(actionShowPlotWizard);
  view->addAction(actionShowExplorer);
  view->addAction(actionShowLog);
  //view->addAction(actionShowUndoStack);
  view->addAction(actionShowConsole);

  view->insertSeparator();
  view->addAction(actionShowScriptWindow);//Mantid
  view->addAction(actionShowScriptInterpreter);
  view->addAction(actionIPythonConsole);
  view->insertSeparator();

  mantidUI->addMenuItems(view);

  view->insertSeparator();
  view->addAction(actionToolBars);
  view->addAction(actionShowConfigureDialog);
  view->insertSeparator();
  view->addAction(actionCustomActionDialog);

  graph = new QMenu(this);
  graph->setObjectName("graphMenu");
  graph->setCheckable(true);
  graph->addAction(actionAddErrorBars);
  graph->addAction(actionRemoveErrorBars);
  graph->addAction(actionShowCurvesDialog);
  graph->addAction(actionAddFunctionCurve);
  graph->addAction(actionNewLegend);
  graph->insertSeparator();
  graph->addAction(btnLabel);
  graph->addAction(btnArrow);
  graph->addAction(btnLine);
  graph->addAction(actionTimeStamp);
  graph->addAction(actionAddImage);
  graph->insertSeparator();//layers section
  graph->addAction(actionAddLayer);
  graph->addAction(actionDeleteLayer);
  graph->addAction(actionShowLayerDialog);

  plot3DMenu = new QMenu(this);
  plot3DMenu->setObjectName("plot3DMenu");
  plot3DMenu->addAction(actionPlot3DWireFrame);
  plot3DMenu->addAction(actionPlot3DHiddenLine);
  plot3DMenu->addAction(actionPlot3DPolygons);
  plot3DMenu->addAction(actionPlot3DWireSurface);
  plot3DMenu->insertSeparator();
  plot3DMenu->addAction(actionPlot3DBars);
  plot3DMenu->addAction(actionPlot3DScatter);
  plot3DMenu->insertSeparator();
  plot3DMenu->addAction(actionImagePlot);
  plot3DMenu->addAction(actionColorMap);
  plot3DMenu->addAction(actionNoContourColorMap);
  plot3DMenu->addAction(actionContourMap);
  plot3DMenu->addAction(actionGrayMap);
  plot3DMenu->insertSeparator();
  //plot3DMenu->addAction(actionPlotHistogram);

  matrixMenu = new QMenu(this);
  matrixMenu->setObjectName("matrixMenu");
  connect(matrixMenu, SIGNAL(aboutToShow()), this, SLOT(matrixMenuAboutToShow()));

  plot2DMenu = new QMenu(this);
  plot2DMenu->setObjectName("plot2DMenu");
  connect(plot2DMenu, SIGNAL(aboutToShow()), this, SLOT(plotMenuAboutToShow()));

  plotDataMenu = new QMenu(this);
  plotDataMenu->setObjectName("plotDataMenu");
  plotDataMenu->setCheckable(true);
  connect(plotDataMenu, SIGNAL(aboutToShow()), this, SLOT(plotDataMenuAboutToShow()));

  normMenu = new QMenu(this);
  normMenu->setObjectName("normMenu");

  fillMenu = new QMenu(this);
  fillMenu->setObjectName("fillMenu");

  tableMenu = new QMenu(this);
  tableMenu->setObjectName("tableMenu");
  connect(tableMenu, SIGNAL(aboutToShow()), this, SLOT(tableMenuAboutToShow()));

  smoothMenu = new QMenu(this);
  smoothMenu->setObjectName("smoothMenu");

  filterMenu = new QMenu(this);
  filterMenu->setObjectName("filterMenu");

  decayMenu = new QMenu(this);
  decayMenu->setObjectName("decayMenu");

  multiPeakMenu = new QMenu(this);
  multiPeakMenu->setObjectName("multiPeakMenu");

  analysisMenu = new QMenu(this);
  analysisMenu->setObjectName("analysisMenu");
  connect(analysisMenu, SIGNAL(aboutToShow()), this, SLOT(analysisMenuAboutToShow()));

  format = new QMenu(this);
  format->setObjectName("formatMenu");

  windowsMenu = new QMenu(this);
  windowsMenu->setObjectName("windowsMenu");
  windowsMenu->setCheckable(true);
  connect(windowsMenu, SIGNAL(aboutToShow()), this, SLOT(windowsMenuAboutToShow()));

  foldersMenu = new QMenu(this);
  foldersMenu->setCheckable(true);

  help = new QMenu(this);
  help->setObjectName("helpMenu");

  help->addAction(actionHomePage);
  help->addAction(actionMantidConcepts);
  help->addAction(actionMantidAlgorithms);
  help->addAction(actionmantidplotHelp);
  help->insertSeparator();
  help->addAction(actionHelpBugReports);
  help->insertSeparator();
  help->addAction(actionFirstTimeSetup);
  help->insertSeparator();
Owen Arnold's avatar
Owen Arnold committed

  ///The paraview action should only be available on windows
#ifdef _WIN32
  help->addAction(actionSetupParaview);
Owen Arnold's avatar
Owen Arnold committed
  help->insertSeparator(); 
#endif
  help->addAction(actionAbout);

  icat = new QMenu(this);
  icat->setObjectName("CatalogMenu");
  icat->addAction(actionICatLogin);//Login menu item
  icat->addAction(actionMydataSearch);// my data search menu item
  icat->addAction(actionICatSearch);//search menu item
  icat->addAction(actionAdvancedSearch); //advanced search menu item
  icat->addAction(actionICatLogout);//logout menu item
  disableActions();
}

void ApplicationWindow::tableMenuAboutToShow()
{
  tableMenu->clear();
  fillMenu->clear();

  MdiSubWindow* t = activeWindow();

  QMenu *setAsMenu = tableMenu->addMenu(tr("Set Columns &As"));
  setAsMenu->addAction(actionSetXCol);
  setAsMenu->addAction(actionSetYCol);
  setAsMenu->addAction(actionSetZCol);
  setAsMenu->insertSeparator();
  setAsMenu->addAction(actionSetLabelCol);
  setAsMenu->addAction(actionDisregardCol);
  setAsMenu->insertSeparator();
  setAsMenu->addAction(actionSetXErrCol);
  setAsMenu->addAction(actionSetYErrCol);
  setAsMenu->insertSeparator();
  setAsMenu->addAction(tr("&Read-only"), this, SLOT(setReadOnlyColumns()));
  setAsMenu->addAction(tr("Read/&Write"), this, SLOT(setReadWriteColumns()));

  tableMenu->addAction(actionShowColumnOptionsDialog);
  tableMenu->insertSeparator();

  tableMenu->addAction(actionShowColumnValuesDialog);
  tableMenu->addAction(actionTableRecalculate);

  fillMenu = tableMenu->addMenu (tr("&Fill Columns With"));
  fillMenu->addAction(actionSetAscValues);
  fillMenu->addAction(actionSetRandomValues);

  tableMenu->addAction(actionClearTable);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionAddColToTable);
  tableMenu->addAction(actionShowColsDialog);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionHideSelectedColumns);
  tableMenu->addAction(actionShowAllColumns);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionMoveColFirst);
  tableMenu->addAction(actionMoveColLeft);
  tableMenu->addAction(actionMoveColRight);
  tableMenu->addAction(actionMoveColLast);
  tableMenu->addAction(actionSwapColumns);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionShowRowsDialog);
  tableMenu->addAction(actionDeleteRows);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionGoToRow);
  tableMenu->addAction(actionGoToColumn);
  tableMenu->insertSeparator();
  tableMenu->addAction(actionConvertTable);
  if (t->isA("Table")) // but not MantidTable
  {
    tableMenu->addAction(actionConvertTableToWorkspace);
  }
  tableMenu->addAction(actionConvertTableToMatrixWorkspace);

  tableMenu->insertSeparator();
  tableMenu->addAction(actionShowPlotWizard);

  reloadCustomActions();
}

void ApplicationWindow::plotDataMenuAboutToShow()
{
  plotDataMenu->clear();
  plotDataMenu->addAction(btnPointer);
  plotDataMenu->addAction(btnZoomIn);
  plotDataMenu->addAction(btnZoomOut);
  plotDataMenu->addAction(actionMagnify);
  plotDataMenu->addAction(actionUnzoom);
  plotDataMenu->insertSeparator();
  plotDataMenu->addAction(btnCursor);
  plotDataMenu->addAction(btnSelect);
  plotDataMenu->addAction(btnPicker);
  plotDataMenu->insertSeparator();
  plotDataMenu->addAction(actionDrawPoints);
  plotDataMenu->addAction(btnMovePoints);
  plotDataMenu->addAction(btnRemovePoints);


  reloadCustomActions();
}

void ApplicationWindow::plotMenuAboutToShow()
{
  plot2DMenu->clear();

  plot2DMenu->addAction(actionPlotL);
  plot2DMenu->addAction(actionPlotP);
  plot2DMenu->addAction(actionPlotLP);

  QMenu *specialPlotMenu = plot2DMenu->addMenu (tr("Special Line/Symb&ol"));
  specialPlotMenu->addAction(actionWaterfallPlot);
  specialPlotMenu->addAction(actionPlotVerticalDropLines);
  specialPlotMenu->addAction(actionPlotSpline);
  specialPlotMenu->addAction(actionPlotVertSteps);
  specialPlotMenu->addAction(actionPlotHorSteps);
  plot2DMenu->insertSeparator();
  plot2DMenu->addAction(actionPlotVerticalBars);
  plot2DMenu->addAction(actionPlotHorizontalBars);
  plot2DMenu->addAction(actionPlotArea);
  plot2DMenu->addAction(actionPlotPie);
  plot2DMenu->addAction(actionPlotVectXYXY);
  plot2DMenu->addAction(actionPlotVectXYAM);
  plot2DMenu->insertSeparator();

  QMenu *statMenu = plot2DMenu->addMenu (tr("Statistical &Graphs"));
  statMenu->addAction(actionBoxPlot);
  statMenu->addAction(actionPlotHistogram);
  statMenu->addAction(actionPlotStackedHistograms);
  statMenu->insertSeparator();
  statMenu->addAction(actionStemPlot);

  QMenu *panelsMenu = plot2DMenu->addMenu (tr("Pa&nel"));
  panelsMenu->addAction(actionPlot2VerticalLayers);
  panelsMenu->addAction(actionPlot2HorizontalLayers);
  panelsMenu->addAction(actionPlot4Layers);
  panelsMenu->addAction(actionPlotStackedLayers);

  QMenu *plot3D = plot2DMenu->addMenu (tr("3&D Plot"));
  plot3D->addAction(actionPlot3DRibbon);
  plot3D->addAction(actionPlot3DBars);
  plot3D->addAction(actionPlot3DScatter);
  plot3D->addAction(actionPlot3DTrajectory);

  reloadCustomActions();
}

void ApplicationWindow::customMenu(MdiSubWindow* w)
{
  myMenuBar()->clear();
  myMenuBar()->insertItem(tr("&File"), fileMenu);
  fileMenuAboutToShow();
  myMenuBar()->insertItem(tr("&Edit"), edit);
  editMenuAboutToShow();
  myMenuBar()->insertItem(tr("&View"), view);

  // these use the same keyboard shortcut (Ctrl+Return) and should not be enabled at the same time
  actionTableRecalculate->setEnabled(false);

  // clear undo stack view (in case window is not a matrix)
  d_undo_view->setStack(0);
  actionUndo->setEnabled(false);
  actionRedo->setEnabled(false);

  if(w){
    actionPrintAllPlots->setEnabled(projectHas2DPlots());
    actionPrint->setEnabled(true);
    actionCutSelection->setEnabled(true);
    actionCopySelection->setEnabled(true);
    actionPasteSelection->setEnabled(true);
    actionClearSelection->setEnabled(true);
    actionSaveTemplate->setEnabled(true);
    QStringList tables = tableNames() + matrixNames();
    if (!tables.isEmpty())
      actionShowExportASCIIDialog->setEnabled(true);
    else
      actionShowExportASCIIDialog->setEnabled(false);

    if (w->isA("MultiLayer")) {
      myMenuBar()->insertItem(tr("&Graph"), graph);
      myMenuBar()->insertItem(tr("&Data"), plotDataMenu);
      plotDataMenuAboutToShow();
      if (m_enableQtiPlotFitting)
      {
        myMenuBar()->insertItem(tr("&Analysis"), analysisMenu);
        analysisMenuAboutToShow();
      }
      myMenuBar()->insertItem(tr("For&mat"), format);

      format->clear();
      format->addAction(actionShowPlotDialog);
      format->insertSeparator();
      format->addAction(actionShowScaleDialog);
      format->addAction(actionShowAxisDialog);
      actionShowAxisDialog->setEnabled(true);
      format->insertSeparator();
      format->addAction(actionShowGridDialog);
      format->addAction(actionShowTitleDialog);
  
    } else if (w->isA("Graph3D")) {
      disableActions();

      myMenuBar()->insertItem(tr("For&mat"), format);

      actionPrint->setEnabled(true);
      actionSaveTemplate->setEnabled(true);

      format->clear();
      format->addAction(actionShowPlotDialog);
      format->addAction(actionShowScaleDialog);
      format->addAction(actionShowAxisDialog);
      format->addAction(actionShowTitleDialog);
      if (dynamic_cast<Graph3D*>(w)->coordStyle() == Qwt3D::NOCOORD)
        actionShowAxisDialog->setEnabled(false);
    } else if (w->inherits("Table")) {
      myMenuBar()->insertItem(tr("&Plot"), plot2DMenu);
      myMenuBar()->insertItem(tr("&Analysis"), analysisMenu);
      analysisMenuAboutToShow();
      myMenuBar()->insertItem(tr("&Table"), tableMenu);
      tableMenuAboutToShow();
      actionTableRecalculate->setEnabled(true);

    } else if (w->isA("Matrix")){
      actionTableRecalculate->setEnabled(true);
      myMenuBar()->insertItem(tr("3D &Plot"), plot3DMenu);
      myMenuBar()->insertItem(tr("&Matrix"), matrixMenu);
      matrixMenuAboutToShow();
      myMenuBar()->insertItem(tr("&Analysis"), analysisMenu);
      analysisMenuAboutToShow();
      d_undo_view->setEmptyLabel(w->objectName() + ": " + tr("Empty Stack"));
      QUndoStack *stack = dynamic_cast<Matrix *>(w)->undoStack();
      d_undo_view->setStack(stack);

    } else if (w->isA("Note")) {
      actionSaveTemplate->setEnabled(false);

    } else if (!mantidUI->menuAboutToShow(w)) // Note that this call has a side-effect (it enables menus)
        disableActions();
   
  } else
    disableActions();

  myMenuBar()->insertItem(tr("&Windows"), windowsMenu);
  windowsMenuAboutToShow();
  // -- Mantid: add script actions, if any exist --
  QListIterator<QMenu*> mIter(d_user_menus);
  while( mIter.hasNext() )
  {
    QMenu* item = mIter.next();
    myMenuBar()->insertItem(tr(item->title()), item);

  }

  myMenuBar()->insertItem(tr("&Catalog"),icat);

  // Interface menu. Build the interface from the user sub windows list.
  // Modifications will be done through the ManageCustomMenus dialog and
  // remembered through QSettings.
  QStringList user_windows = MantidQt::API::InterfaceManager::Instance().getUserSubWindowKeys();
  QStringListIterator itr(user_windows);
  QString menuName = "&Interfaces";
  addUserMenu(menuName);
  while( itr.hasNext() )
  {
      QString itemName = itr.next();
      // Check whether the menu item was flagged in the QSettings.
      if (getMenuSettingsFlag(itemName))
          addUserMenuAction( menuName, itemName, itemName);
  }

  // Go through PyQt interfaces
  QString scriptsDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("mantidqt.python_interfaces_directory"));
  QStringListIterator pyqt_itr(pyqt_interfaces);
  while( pyqt_itr.hasNext() )
  {
    QString itemName = pyqt_itr.next();
    QString scriptPath = scriptsDir + '/' + itemName;

    if( QFileInfo(scriptPath).exists() ) {
      QString baseName = QFileInfo(scriptPath).baseName();
      // Need to use "nice" name to check if scripts has been removed by user.
      QString niceName = baseName.replace("_", " ");
      if (getMenuSettingsFlag(niceName))
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 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
        addUserMenuAction(menuName, baseName, scriptPath);
    }
    else
    {
      Mantid::Kernel::Logger& g_log = Mantid::Kernel::Logger::get("ConfigService");
      g_log.warning() << "Could not find interface script: " << scriptPath.ascii() << "\n";
    }
  }

  myMenuBar()->insertItem(tr("&Help"), help );

  reloadCustomActions();
}

/**
 * Returns whether a custom interface should be added to the Interfaces menu.
 * @param menu_item: name of the custom interface
 */
bool ApplicationWindow::getMenuSettingsFlag(const QString & menu_item)
{
  // Look for the interface in the user menu list
  // If we found the item in the user menu list, return true
  QMenu *menu = NULL;
  foreach(menu, d_user_menus)
  {
    if( menu->title() == menu_item ) return true;
  }

  // If we didn't find it, check whether is was manually removed
  if( removed_interfaces.contains(menu_item) ) return false;
  return true;
}

void ApplicationWindow::disableActions()
{
  actionSaveTemplate->setEnabled(false);
  actionPrintAllPlots->setEnabled(false);
  actionPrint->setEnabled(false);

  actionCutSelection->setEnabled(false);
  actionCopySelection->setEnabled(false);
  actionPasteSelection->setEnabled(false);
  actionClearSelection->setEnabled(false);
}

void ApplicationWindow::customColumnActions()
{
  actionMoveColFirst->setEnabled(false);
  actionMoveColLeft->setEnabled(false);
  actionMoveColRight->setEnabled(false);
  actionMoveColLast->setEnabled(false);
  actionSetXCol->setEnabled(false);
  actionSetYCol->setEnabled(false);
  actionSetZCol->setEnabled(false);
  actionSetLabelCol->setEnabled(false);
  actionSetYErrCol->setEnabled(false);
  actionDisregardCol->setEnabled(false);
  actionSwapColumns->setEnabled(false);
  actionSetAscValues->setEnabled(false);
  actionSetRandomValues->setEnabled(false);

  Table *t = dynamic_cast<Table*>(activeWindow(TableWindow));
  if (!t)
    return;

  int selectedCols = t->selectedColsNumber();
  if (selectedCols == 1){
    int col = t->selectedColumn();
    if (col > 0){
      actionMoveColFirst->setEnabled(true);
      actionMoveColLeft->setEnabled(true);
    }

    if (col < t->numCols() - 1){
      actionMoveColRight->setEnabled(true);
      actionMoveColLast->setEnabled(true);
    }
  }

  if (selectedCols >= 1){
    actionSetAscValues->setEnabled(true);
    actionSetRandomValues->setEnabled(true);
    actionSetXCol->setEnabled(true);
    actionSetYCol->setEnabled(true);
    actionSetZCol->setEnabled(true);
    actionSetYErrCol->setEnabled(true);
    actionSetLabelCol->setEnabled(true);
    actionDisregardCol->setEnabled(true);
  }

  if (selectedCols == 2)
    actionSwapColumns->setEnabled(true);
}


/** Set the exit code to be returned by the application at
 * exit. Used by MantidPlot unit tests to signal failure.
 *
 * @param code :: int code, non-zero for failure
 */
void ApplicationWindow::setExitCode(int code)
{
  m_exitCode = code;
}

/** Get the exit code to be returned by the application at
 * exit. Used by MantidPlot unit tests to signal failure.
 *
 * @return code :: int code, non-zero for failure
 */
int ApplicationWindow::getExitCode()
{
  return m_exitCode;
}


void ApplicationWindow::customToolBars(MdiSubWindow* w)
{
  disableToolbars();
  if (!w)
    return;

  if (w->isA("MultiLayer") && d_plot_tool_bar){
    if(!plotTools->isVisible())
      plotTools->show();
    plotTools->setEnabled (true);
    customMultilayerToolButtons(dynamic_cast<MultiLayer*>(w));
    if(d_format_tool_bar && !formatToolBar->isVisible()){
      formatToolBar->setEnabled (true);
      formatToolBar->show();
    }
  } else if (w->isA("Graph3D") && d_plot3D_tool_bar){
    if(!plot3DTools->isVisible())
      plot3DTools->show();

    if (dynamic_cast<Graph3D*>(w)->plotStyle() == Qwt3D::NOPLOT)
      plot3DTools->setEnabled(false);
    else
      plot3DTools->setEnabled(true);
    custom3DActions(w);
  }
}

void ApplicationWindow::disableToolbars()
{
  plotTools->setEnabled(false);
  plot3DTools->setEnabled(false);
}

void ApplicationWindow::hideToolbars()
{
  fileTools->setVisible(false);
  displayBar->setVisible(false);
  editTools->setVisible(false);
  plotTools->setVisible(false);
  plot3DTools->setVisible(false);
  formatToolBar->setVisible(false);
}

void ApplicationWindow::showToolbars()
{
  fileTools->setVisible(true);
  displayBar->setVisible(true);
  editTools->setVisible(true);
  plotTools->setVisible(true);
  //plot3DTools->setVisible(true);
  formatToolBar->setVisible(true);
}

void ApplicationWindow::plot3DRibbon()
{
  MdiSubWindow *w = activeWindow(TableWindow);
  if (!w)
    return;

  Table *table = static_cast<Table*>(w);
  if(table->selectedColumns().count() == 1){
    if (!validFor3DPlot(table))
      return;
    plotXYZ(table, table->colName(table->selectedColumn()), Graph3D::Ribbon);
  } else
    QMessageBox::warning(this, tr("MantidPLot - Plot error"), tr("You must select exactly one column for plotting!"));
}

void ApplicationWindow::plot3DWireframe()
{
  plot3DMatrix (0, Qwt3D::WIREFRAME);
}

void ApplicationWindow::plot3DHiddenLine()
{
  plot3DMatrix (0, Qwt3D::HIDDENLINE);
}

void ApplicationWindow::plot3DPolygons()
{
  plot3DMatrix (0, Qwt3D::FILLED);
}

void ApplicationWindow::plot3DWireSurface()
{
  plot3DMatrix (0, Qwt3D::FILLEDMESH);
}

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

  if (w->inherits("Table")){
    Table *table = static_cast<Table *>(w);
    if (!validFor3DPlot(table))
      return;

    if(table->selectedColumns().count() == 1)
      plotXYZ(table, table->colName(table->selectedColumn()), Graph3D::Bars);
    else
      QMessageBox::warning(this, tr("MantidPlot - Plot error"),tr("You must select exactly one column for plotting!"));//Mantid
  }
  else if(w->inherits("Matrix"))
    plot3DMatrix(0, Qwt3D::USER);
}

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

  if (w->inherits("Table"))
  {
    Table *table = static_cast<Table *>(w);
    if (!validFor3DPlot(table))
      return;

    if(table->selectedColumns().count() == 1)
      plotXYZ(table, table->colName(table->selectedColumn()), Graph3D::Scatter);
    else
      QMessageBox::warning(this, tr("MantidPlot - Plot error"),tr("You must select exactly one column for plotting!"));//Mantid
  }
  else if(w->inherits("Matrix"))
    plot3DMatrix (0, Qwt3D::POINTS);
}

void ApplicationWindow::plot3DTrajectory()
{
  Table *table = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!table)
    return;
  if (!validFor3DPlot(table))
    return;

  if(table->selectedColumns().count() == 1)
    plotXYZ(table, table->colName(table->selectedColumn()), Graph3D::Trajectory);
  else
    QMessageBox::warning(this, tr("MantidPlot - Plot error"), tr("You must select exactly one column for plotting!"));//Mantid
}

void ApplicationWindow::plotBoxDiagram()
{
  generate2DGraph(Graph::Box);
}

void ApplicationWindow::plotVerticalBars()
{
  generate2DGraph(Graph::VerticalBars);
}

void ApplicationWindow::plotHorizontalBars()
{
  generate2DGraph(Graph::HorizontalBars);
}

MultiLayer* ApplicationWindow::plotHistogram()
{
  return generate2DGraph(Graph::Histogram);
}

MultiLayer* ApplicationWindow::plotHistogram(Matrix *m)
{
  if (!m) {
    m = dynamic_cast<Matrix*>(activeWindow(MatrixWindow));
    if (!m)
      return 0;
  }

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

  MultiLayer* g = new MultiLayer(this);
  initMultilayerPlot(g, generateUniqueName(tr("Graph")));

  Graph* plot = g->activeGraph();
  setPreferences(plot);
  plot->addHistogram(m);

  QApplication::restoreOverrideCursor();
  return g;
}

void ApplicationWindow::plotArea()
{
  generate2DGraph(Graph::Area);
}

void ApplicationWindow::plotPie()
{
  Table *table = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!table)
    return;

  if(table->selectedColumns().count() != 1){
    QMessageBox::warning(this, tr("MantidPlot - Plot error"),//Mantid
        tr("You must select exactly one column for plotting!"));
    return;
  }

  QStringList s = table->selectedColumns();
  if (s.count()>0){
    Q3TableSelection sel = table->getSelection();
    multilayerPlot(table, s, Graph::Pie, sel.topRow(), sel.bottomRow());
  } else
    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select a column to plot!"));//Mantid
}

void ApplicationWindow::plotL()
{
  generate2DGraph(Graph::Line);
}

void ApplicationWindow::plotP()
{
  generate2DGraph(Graph::Scatter);
}

void ApplicationWindow::plotLP()
{
  generate2DGraph(Graph::LineSymbols);
}

void ApplicationWindow::plotVerticalDropLines()
{
  generate2DGraph(Graph::VerticalDropLines);
}

void ApplicationWindow::plotSpline()
{
  generate2DGraph(Graph::Spline);
}

void ApplicationWindow::plotVertSteps()
{
  generate2DGraph(Graph::VerticalSteps);
}

void ApplicationWindow::plotHorSteps()
{
  generate2DGraph(Graph::HorizontalSteps);
}

void ApplicationWindow::plotVectXYXY()
{
  Table *table = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!table)
    return;
  if (!validFor2DPlot(table))
    return;

  QStringList s = table->selectedColumns();
  if (s.count() == 4) {
    Q3TableSelection sel = table->getSelection();
    multilayerPlot(table, s, Graph::VectXYXY, sel.topRow(), sel.bottomRow());
  } else
    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select four columns for this operation!"));//Mantid
}

void ApplicationWindow::plotVectXYAM()
{
  Table *table = dynamic_cast<Table *>(activeWindow(TableWindow));
  if (!table)
    return;
  if (!validFor2DPlot(table))
    return;

  QStringList s = table->selectedColumns();
  if (s.count() == 4){
    Q3TableSelection sel = table->getSelection();
    multilayerPlot(table, s, Graph::VectXYAM, sel.topRow(), sel.bottomRow());
  } else
    QMessageBox::warning(this, tr("MantidPlot - Error"), tr("Please select four columns for this operation!"));//Mantid
}

QString ApplicationWindow::stemPlot(Table *t, const QString& colName, int power, int startRow, int endRow)
{
  if (!t)
    return QString();

  int col = t->colIndex(colName);
  if (col < 0){
    QMessageBox::critical(this, tr("MantidPlot - Error"),
    tr("Data set: %1 doesn't exist!").arg(colName));
    return QString();
  }

  startRow--;
  endRow--;
  if (startRow < 0 || startRow >= t->numRows())
    startRow = 0;
  if (endRow < 0 || endRow >= t->numRows())
    endRow = t->numRows() - 1;

  QString result = tr("Stem and leaf plot of dataset") + ": " + colName + " ";
  result += tr("from row") + ": " + QString::number(startRow + 1) + " ";
  result += tr("to row") + ": " + QString::number(endRow + 1) + "\n";

  int rows = 0;
  for (int j = startRow; j <= endRow; j++){
    if (!t->text(j, col).isEmpty())
       rows++;
  }

  if (rows >= 1){
    double *data = (double *)malloc(rows * sizeof (double));
    if (!data){
      result += tr("Not enough memory for this dataset!") + "\n";
      return result;
    }

    result += "\n" + tr("Stem") + " | " + tr("Leaf");
    result += "\n---------------------\n";

    int row = 0;
    for (int j = startRow; j <= endRow; j++){
      if (!t->text(j, col).isEmpty()){
        data[row] = t->cell(j, col);
        row++;
      }
    }
    gsl_sort (data, 1, rows);

    if (power > 1e3){
      power = static_cast<int>(std::ceil(log10(data[rows - 1] - data[0]) - log10(rows - 1.0)));
      bool ok;
      int input = QInputDialog::getInteger(this, tr("Please confirm the stem unit!"),
                                      tr("Data set") + ": " + colName + ", " + tr("stem unit") + " = 10<sup>n</sup>, n = ",
                                      power, -1000, 1000, 1, &ok);
      if (ok)
        power = input;
    }

    double stem_unit = pow(10.0, power);
    double leaf_unit = stem_unit/10.0;

    int prev_stem = int(data[0]/stem_unit);
    result += "      " + QString::number(prev_stem) + " | ";

    for (int j = 0; j <rows; j++){
      double val = data[j];
      int stem = int(val/stem_unit);
      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();
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
  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)
{
  Table* w = new Table(scriptingEnv(), r, c, legend, this, 0);
  initTable(w, name);
  return w;
}

Table* ApplicationWindow::newTable(const QString& caption, int r, int c, const QString& text)
{
  QStringList lst = caption.split("\t", QString::SkipEmptyParts);
  QString legend = QString();
  if (lst.count() == 2)
    legend = lst[1];

  Table* w = new Table(scriptingEnv(), r, c, legend, this, 0);

  QStringList rows = text.split("\n", QString::SkipEmptyParts);
  QString rlist = rows[0];
  QStringList list = rlist.split("\t");
  w->setHeader(list);

  for (int i=0; i<r; i++)
  {
    rlist=rows[i+1];
    list=rlist.split("\t");
    for (int j=0; j<c; j++)
      w->setText(i, j, list[j]);
  }

  initTable(w, lst[0]);
  w->showNormal();
  return w;
}

Table* ApplicationWindow::newHiddenTable(const QString& name, const QString& label, int r, int c, const QString& text)
{
  Table* w = new Table(scriptingEnv(), r, c, label, this, 0);

  if (!text.isEmpty()) {
    QStringList rows = text.split("\n", QString::SkipEmptyParts);
    QStringList list = rows[0].split("\t");
    w->setHeader(list);

    QString rlist;
    for (int i=0; i<r; i++){
      rlist=rows[i+1];
      list = rlist.split("\t");
      for (int j=0; j<c; j++)
        w->setText(i, j, list[j]);
    }
  }

  initTable(w, name);
  hideWindow(w);
  return w;
}

/* Perfom initialization on a Table?
 * @param w :: table that was created
 * @param caption :: title to set
 */
void ApplicationWindow::initTable(Table* w, const QString& caption)
{
  QString name = caption;
  name = name.replace ("_","-");

  while(name.isEmpty() || alreadyUsedName(name))
    name = generateUniqueName(tr("Table"));

  connectTable(w);
  customTable(w);

  w->setName(name);
  w->setIcon( getQPixmap("worksheet_xpm") );
  w->setSpecifications(w->saveToString(windowGeometryInfo(w)));

  addMdiSubWindow(w);
}

/*
 * !creates a new table with type statistics on target columns/rows of table base
 */
TableStatistics *ApplicationWindow::newTableStatistics(Table *base, int type, QList<int> target, const QString &caption)
{
  TableStatistics* s = new TableStatistics(scriptingEnv(), this, base, (TableStatistics::Type) type, target);
  if (caption.isEmpty())
    initTable(s, s->objectName());
  else
    initTable(s, caption);
  s->showNormal();
  return s;
}

/*
 *creates a new empty note window
 */
Note* ApplicationWindow::newNote(const QString& caption)
{
  Note* m = new Note("", this);

  QString name = caption;
  while(name.isEmpty() || alreadyUsedName(name))
    name = generateUniqueName(tr("Notes"));

  m->setName(name);
  m->setIcon(getQPixmap("note_xpm"));
  m->confirmClose(confirmCloseNotes);

  addMdiSubWindow(m);
  m->showNormal();
  return m;
}

Matrix* ApplicationWindow::newMatrix(int rows, int columns)
{
  Matrix* m = new Matrix(scriptingEnv(), rows, columns, "", this, 0);
  initMatrix(m, generateUniqueName(tr("Matrix")));
  m->showNormal();
  return m;
}

Matrix* ApplicationWindow::newMatrix(const QString& caption, int r, int c)
{
  Matrix* w = new Matrix(scriptingEnv(), r, c, "", this, 0);
  initMatrix(w, caption);
  if (w->objectName() != caption)//the matrix was renamed
    renamedTables << caption << w->objectName();

  w->showNormal();
  return w;
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetViewCommand(m, m->viewType(), Matrix::ImageView, tr("Set Image Mode")));
  m->setViewType(Matrix::ImageView);
  QApplication::restoreOverrideCursor();
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetViewCommand(m, m->viewType(), Matrix::TableView, tr("Set Data Mode")));
  m->setViewType(Matrix::TableView);
  QApplication::restoreOverrideCursor();
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetHeaderViewCommand(m, m->headerViewType(), Matrix::XY, tr("Show X/Y")));
  m->setHeaderViewType(Matrix::XY);
  QApplication::restoreOverrideCursor();
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetHeaderViewCommand(m, m->headerViewType(), Matrix::ColumnRow, tr("Show Column/Row")));
  m->setHeaderViewType(Matrix::ColumnRow);
  QApplication::restoreOverrideCursor();
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetColorMapCommand(m, m->colorMapType(), m->colorMap(),
      Matrix::GrayScale, QwtLinearColorMap(), tr("Set Gray Scale Palette")));
  m->setGrayScale();
  QApplication::restoreOverrideCursor();
}

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

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
  m->undoStack()->push(new MatrixSetColorMapCommand(m, m->colorMapType(), m->colorMap(),
      Matrix::Rainbow, QwtLinearColorMap(), tr("Set Rainbow Palette")));
  m->setRainbowColorMap();
  QApplication::restoreOverrideCursor();
}

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

  ColorMapDialog *cmd = new ColorMapDialog(this);
  cmd->setAttribute(Qt::WA_DeleteOnClose);
  cmd->setMatrix(m);
  cmd->exec();
}

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

  m->transpose();
}

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

  m->flipVertically();
}

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

  m->flipHorizontally();
}

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

  m->rotate90();
}

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

  m->rotate90(false);
}

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

  QDateTime dt = QDateTime::currentDateTime ();
  QString info=dt.toString(Qt::LocalDate);
  info+= "\n" + tr("Determinant of ") + QString(m->objectName()) + ":\t";
  info+= "det = " + QString::number(m->determinant()) + "\n";
  info+="-------------------------------------------------------------\n";

  current_folder->appendLogInfo(info);

  showResults(true);
}

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

  m->invert();
}

Table* ApplicationWindow::convertMatrixToTableDirect()
{
  Matrix* m = dynamic_cast<Matrix*>(activeWindow(MatrixWindow));
  if (!m)
    return 0;

  return matrixToTable(m, Direct);
}

Table* ApplicationWindow::convertMatrixToTableXYZ()
{
  Matrix* m = dynamic_cast<Matrix*>(activeWindow(MatrixWindow));
  if (!m)
    return 0;

  return matrixToTable(m, XYZ);
}

Table* ApplicationWindow::convertMatrixToTableYXZ()
{
  Matrix* m = dynamic_cast<Matrix*>(activeWindow(MatrixWindow));
  if (!m)
    return 0;

  return matrixToTable(m, YXZ);
}

Table* ApplicationWindow::matrixToTable(Matrix* m, MatrixToTableConversion conversionType)
{
  if (!m)
    return 0;

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

  int rows = m->numRows();
  int cols = m->numCols();
  MatrixModel *mModel = m->matrixModel();

  Table* w = NULL;
  if (conversionType == Direct){
    w = new Table(scriptingEnv(), rows, cols, "", this, 0);
    for (int i = 0; i<rows; i++){
      for (int j = 0; j<cols; j++)
        w->setCell(i, j, m->cell(i,j));
    }
  } else if (conversionType == XYZ){
    int tableRows = rows*cols;
    w = new Table(scriptingEnv(), tableRows, 3, "", this, 0);
    for (int i = 0; i<rows; i++){
      for (int j = 0; j<cols; j++){
        int cell = i*cols + j;
        w->setCell(cell, 0, mModel->x(j));
        w->setCell(cell, 1, mModel->y(i));
        w->setCell(cell, 2, mModel->cell(i, j));
      }
    }
  } else if (conversionType == YXZ){
    int tableRows = rows*cols;
    w = new Table(scriptingEnv(), tableRows, 3, "", this, 0);
    for (int i = 0; i<cols; i++){
      for (int j = 0; j<rows; j++){
        int cell = i*rows + j;
        w->setCell(cell, 0, mModel->x(i));
        w->setCell(cell, 1, mModel->y(j));
        w->setCell(cell, 2, mModel->cell(i, j));
      }
    }
  }


  initTable(w, generateUniqueName(tr("Table")));
  w->setWindowLabel(m->windowLabel());
  w->setCaptionPolicy(m->captionPolicy());
  w->resize(m->size());
  w->showNormal();

  QApplication::restoreOverrideCursor();
  return w;
}

void ApplicationWindow::initMatrix(Matrix* m, const QString& caption)
{
  QString name = caption;
  while(alreadyUsedName(name)){name = generateUniqueName(tr("Matrix"));}

  m->setWindowTitle(name);
  m->setName(name);
  m->setIcon( m->matrixIcon() );//Mantid
  m->confirmClose(confirmCloseMatrix);
  m->setNumericPrecision(d_decimal_digits);

  addMdiSubWindow(m);

  QUndoStack *stack = m->undoStack();
  connect(stack, SIGNAL(canUndoChanged(bool)), actionUndo, SLOT(setEnabled(bool)));
  connect(stack, SIGNAL(canRedoChanged(bool)), actionRedo, SLOT(setEnabled(bool)));

  connect(m, SIGNAL(modifiedWindow(MdiSubWindow*)), this, SLOT(updateMatrixPlots(MdiSubWindow *)));

  emit modified();
}

Matrix* ApplicationWindow::convertTableToMatrix()
{
  Table* t = dynamic_cast<Table*>(activeWindow(TableWindow));
  if (!t)
    return 0;

  return tableToMatrix (t);
}

/**
 * Convert Table in the active window to a TableWorkspace
 */
void ApplicationWindow::convertTableToWorkspace()
{
  Table* t = dynamic_cast<Table*>(activeWindow(TableWindow));
  if (!t) return;
  MantidTable* mt = dynamic_cast<MantidTable*>(t);
  if (!mt)
  {
    mt = convertTableToTableWorkspace(t);
  }
}

/**
 * Convert Table in the active window to a TableWorkspace
 */
void ApplicationWindow::convertTableToMatrixWorkspace()
{
  Table* t = dynamic_cast<Table*>(activeWindow(TableWindow));
  if (!t) return;
  MantidTable* mt = dynamic_cast<MantidTable*>(t);
  if (!mt)
  {
    mt = convertTableToTableWorkspace(t);
  }
  //mantidUI->executeAlgorithm("ConvertTableToMatrixWorkspace","InputWorkspace="+QString::fromStdString(mt->getWorkspaceName()));
  QMap<QString,QString> params;
  params["InputWorkspace"] = QString::fromStdString(mt->getWorkspaceName());
  mantidUI->executeAlgorithmDlg("ConvertTableToMatrixWorkspace",params);
}

/**
 * Convert a Table to a TableWorkspace. Columns with plot designations X,Y,Z,xErr,yErr
 * are transformed to doubles, others - to strings.
 * @param t :: The Table to convert.
 */
MantidTable* ApplicationWindow::convertTableToTableWorkspace(Table* t)
{
  if (!t) return NULL;
  Mantid::API::ITableWorkspace_sptr tws = Mantid::API::WorkspaceFactory::Instance().createTable();
  for(int col = 0; col < t->numCols(); ++col)
  {
    Table::PlotDesignation des = (Table::PlotDesignation)t->colPlotDesignation(col);
    QString name = t->colLabel(col);
    std::string type;
    int plotType = 6; // Label
    case Table::X: {plotType = 1; type = "double"; break;}
    case Table::Y: {plotType = 2; type = "double"; break;}
    case Table::Z: {plotType = 3; type = "double"; break;}
    case Table::xErr:  {plotType = 4; type = "double"; break;}
    case Table::yErr: {plotType = 5; type = "double"; break;}
      type = "string"; plotType = 6;
    std::string columnName = name.toStdString();
    tws->addColumn(type,columnName);
    Mantid::API::Column_sptr column = tws->getColumn(columnName);
    column->setPlotType(plotType);
  }
  tws->setRowCount(t->numRows());
  for(int col = 0; col < t->numCols(); ++col)
  {
    Mantid::API::Column_sptr column = tws->getColumn(col);
    for(int row = 0; row < t->numRows(); ++row)
    {
      column->read(row, t->text(row,col).toStdString());
    }
  }
  std::string wsName = t->objectName().toStdString();
  if (Mantid::API::AnalysisDataService::Instance().doesExist(wsName))
  {
    if (QMessageBox::query("MantidPlot","Workspace with name " + t->objectName() + " already exists\n"
      "Do you want to overwrite it?"))
    {
      Mantid::API::AnalysisDataService::Instance().addOrReplace(wsName,tws);
    }
    else
    {
      return NULL;
    }
  }
  else
  {
    Mantid::API::AnalysisDataService::Instance().add(wsName,tws);
  }
  MantidTable* mt = new MantidTable(scriptingEnv(), tws, t->objectName(), this);
  return mt;
}

Matrix* ApplicationWindow::tableToMatrix(Table* t)
{
  if (!t)
    return 0;

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

  int rows = t->numRows();
  int cols = t->numCols();

  QString caption = generateUniqueName(tr("Matrix"));
  Matrix* m = new Matrix(scriptingEnv(), rows, cols, "", this, 0);
  initMatrix(m, caption);

  for (int i = 0; i<rows; i++){
    for (int j = 0; j<cols; j++)
      m->setCell(i, j, t->cell(i, j));
  }

  m->setWindowLabel(m->windowLabel());
  m->setCaptionPolicy(m->captionPolicy());
  m->resize(m->size());
  m->showNormal();

  QApplication::restoreOverrideCursor();
  return m;
}

MdiSubWindow* ApplicationWindow::window(const QString& name)
{
  QList<MdiSubWindow *> windows = windowsList();
  foreach(MdiSubWindow *w, windows){
    if (w->objectName() == name)
      return w;
  }
  return  NULL;
}

Table* ApplicationWindow::table(const QString& name)
{
  int pos = name.find("_", 0);
  QString caption = name.left(pos);

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

  return  0;
}

Matrix* ApplicationWindow::matrix(const QString& name)
{
  QString caption = name;
  if (!renamedTables.isEmpty() && renamedTables.contains(caption)){
    int index = renamedTables.findIndex(caption);
    caption = renamedTables[index+1];
  }

  Folder *f = projectFolder();
  while (f){
    QList<MdiSubWindow *> folderWindows = f->windowsList();
    foreach(MdiSubWindow *w, folderWindows){
      if (w->isA("Matrix") && w->objectName() == caption)
        return dynamic_cast<Matrix*>(w);
    }
    f = f->folderBelow();
  }
  return  0;
}

MdiSubWindow *ApplicationWindow::activeWindow(WindowType type)
{
  MdiSubWindow* active = getActiveWindow();
  if (!active)
    return NULL;

  switch(type){
  case NoWindow:
    break;

  case TableWindow:
    if (active->inherits("Table"))
      return active;
    else
      return NULL;
    break;

  case MatrixWindow:
    if (active->inherits("Matrix"))//Mantid
      return active;
    else
      return NULL;
    break;

  case MultiLayerWindow:
    if (active->isA("MultiLayer"))
      return active;
    else
      return NULL;
    break;

  case NoteWindow:
    if (active->isA("Note"))
      return active;
    else
      return NULL;
    break;

  case Plot3DWindow:
    if (active->isA("Graph3D"))
      return active;
    else
      return NULL;
    break;
  }
  return active;
}

void ApplicationWindow::windowActivated(QMdiSubWindow *w)
{	
  if ( !w ) return;

  MdiSubWindow *qti_subwin = qobject_cast<MdiSubWindow*>(w->widget());
  if( !qti_subwin ) return;

  activateWindow(qti_subwin);

}

void ApplicationWindow::addErrorBars()
{
  MdiSubWindow *w = activeWindow(MultiLayerWindow);
  if (!w)
    return;

  MultiLayer* plot = dynamic_cast<MultiLayer*>(w);
  if (plot->isEmpty()){
    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
        tr("<h4>There are no plot layers available in this window.</h4>"
            "<p><h4>Please add a layer and try again!</h4>"));
    return;
  }

  Graph* g = dynamic_cast<Graph*>(plot->activeGraph());
  if (!g)
    return;

  if (!g->curves()){
    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no curves available on this plot!"));//Mantid
    return;
  }

  if (g->isPiePlot()){
    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
    return;
  }

  ErrDialog* ed = new ErrDialog(this);
  ed->setAttribute(Qt::WA_DeleteOnClose);
  connect (ed,SIGNAL(options(const QString&,int,const QString&,int,bool)),this,SLOT(defineErrorBars(const QString&,int,const QString&,int,bool))); 
  connect (ed,SIGNAL(options(const QString&,const QString&,int)),this,SLOT(defineErrorBars(const QString&,const QString&,int)));

  ed->setCurveNames(g->analysableCurvesList());
  ed->setSrcTables(tableList());
  ed->exec();
}

void ApplicationWindow::removeErrorBars()
{
  MdiSubWindow *w = activeWindow(MultiLayerWindow);
  if (!w)
    return;

  MultiLayer* plot = dynamic_cast<MultiLayer*>(w);
  if (plot->isEmpty()){
    QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid
        tr("<h4>There are no plot layers available in this window.</h4>"
            "<p><h4>Please add a layer and try again!</h4>"));
    return;
  }

  Graph* g = dynamic_cast<Graph*>(plot->activeGraph());
  if (!g)
    return;

  if (!g->curves()){
    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("There are no curves available on this plot!"));//Mantid
    return;
  }

  if (g->isPiePlot()){
    QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid
    return;
  }

  RemoveErrorsDialog* ed = new RemoveErrorsDialog(this);
  connect (ed,SIGNAL(curveName(const QString&)),this,SLOT(removeErrorBars(const QString&)));

  ed->setCurveNames(g->analysableCurvesList());
  ed->exec();
}

void ApplicationWindow::removeErrorBars(const QString& name)
{
  MdiSubWindow *w = activeWindow(MultiLayerWindow);
  if (!w)
    return;

  Graph* g = dynamic_cast<MultiLayer*>(w)->activeGraph();
  if (!g)
    return;

  g->removeMantidErrorBars(name);

}

void ApplicationWindow::defineErrorBars(const QString& name, int type, const QString& percent, int direction, bool drawAll)
{
  MdiSubWindow *w = activeWindow(MultiLayerWindow);
  if (!w)
    return;

  Graph* g = dynamic_cast<MultiLayer*>(w)->activeGraph();
  if (!g)
    return;

  if (type == 2) // A MantidCurve - do all the work in the Graph method
  {
    g->addMantidErrorBars(name, drawAll);
    return;
  }

  Table *t = table(name);
  if (!t){//user defined function
    QMessageBox::critical(this,tr("MantidPlot - Error bars error"),//Mantid
        tr("This feature is not available for user defined function curves!"));
    return;
  }

  DataCurve *master_curve = dynamic_cast<DataCurve *>(g->curve(name));
  QString xColName = master_curve->xColumnName();
  if (xColName.isEmpty())
    return;

  if (direction == QwtErrorPlotCurve::Horizontal)
    t->addCol(Table::xErr);
  else
    t->addCol(Table::yErr);

  int r=t->numRows();
  int c=t->numCols()-1;
  int ycol=t->colIndex(name);
  if (!direction)
    ycol=t->colIndex(xColName);

  QVarLengthArray<double> Y(r);
  Y=t->col(ycol);
  QString errColName=t->colName(c);

  double prc=percent.toDouble();
  if (type==0){
    for (int i=0;i<r;i++){
      if (!t->text(i,ycol).isEmpty())
        t->setText(i, c, QString::number(Y[i]*prc/100.0,'g',15));
    }
  } else if (type==1) {
    int i;
    double dev=0.0;
    double moyenne=0.0;
    for (i=0;i<r;i++)
      moyenne+=Y[i];
    moyenne/=r;
    for (i=0;i<r;i++)
      dev+=(Y[i]-moyenne)*(Y[i]-moyenne);
    dev=sqrt(dev/(r-1));
    for (i=0;i<r;i++){
      if (!t->table()->item(i,ycol)->text().isEmpty())
        t->setText(i, c, QString::number(dev, 'g', 15));
    }
  }
  QwtErrorPlotCurve * errs = g->addErrorBars(xColName, name, t, errColName, direction);
  if ( errs )
  {
    // Error bars should be the same color as the curve line
    errs->setColor(master_curve->pen().color());
    g->updatePlot();
  }
}

void ApplicationWindow::defineErrorBars(const QString& curveName, const QString& errColumnName, int direction)
{
  Table *w=table(curveName);
  if (!w){//user defined function --> no worksheet available
    QMessageBox::critical(this,tr("MantidPlot - Error"),//Mantid
        tr("This feature is not available for user defined function curves!"));
    return;
  }

  Table *errTable=table(errColumnName);
  if (w->numRows() != errTable->numRows()){
    QMessageBox::critical(this,tr("MantidPlot - Error"),//Mantid
        tr("The selected columns have different numbers of rows!"));

    addErrorBars();
    return;
  }

  int errCol=errTable->colIndex(errColumnName);
  if (errTable->isEmptyColumn(errCol)){
    QMessageBox::critical(this, tr("MantidPlot - Error"),//Mantid
        tr("The selected error column is empty!"));
    addErrorBars();
    return;
  }

  MultiLayer *plot = dynamic_cast<MultiLayer*>(activeWindow(MultiLayerWindow));
  if (!plot)
    return;

  Graph* g = plot->activeGraph();
  if (!g)
    return;

  QwtErrorPlotCurve * errs = g->addErrorBars(curveName, errTable, errColumnName, direction);
  if ( errs )
  {
    QwtPlotCurve * master_curve = g->curve(curveName);
    if (master_curve) errs->setColor(master_curve->pen().color());
    g->updatePlot();
  }
  emit modified();
}

void ApplicationWindow::removeCurves(const QString& name)
{
  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  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->removeCurves(name);
    }
    else if (w->isA("Graph3D"))
    {
      if ( (dynamic_cast<Graph3D*>(w)->formula()).contains(name) )
        dynamic_cast<Graph3D*>(w)->clearData();
    }
  }
  QApplication::restoreOverrideCursor();
}

void ApplicationWindow::updateCurves(Table *t, const QString& name)
{
  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->updateCurvesData(t, name);
    } else if (w->isA("Graph3D")){
      Graph3D* g = dynamic_cast<Graph3D*>(w);
      if ((g->formula()).contains(name))
        g->updateData(t);
    }
  }
}

void ApplicationWindow::showPreferencesDialog()
{
  ConfigDialog* cd= new ConfigDialog(this);
  cd->setAttribute(Qt::WA_DeleteOnClose);
  cd->setColumnSeparator(columnSeparator);
  cd->exec();
}

void ApplicationWindow::setSaveSettings(bool autoSaving, int min)
{
  if (autoSave==autoSaving && autoSaveTime==min)
    return;

  autoSave=autoSaving;
  autoSaveTime=min;

  killTimer(savingTimerId);

  if (autoSave)
    savingTimerId=startTimer(autoSaveTime*60000);
  else
    savingTimerId=0;
}

void ApplicationWindow::changeAppStyle(const QString& s)
{
  // style keys are case insensitive
  if (appStyle.toLower() == s.toLower())
    return;

  qApp->setStyle(s);
  appStyle = qApp->style()->objectName();

  QPalette pal = qApp->palette();
  pal.setColor (QPalette::Active, QPalette::Base, QColor(panelsColor));
  qApp->setPalette(pal);

}

void ApplicationWindow::changeAppFont(const QFont& f)
{
  if (appFont == f)
    return;

  appFont = f;
  updateAppFonts();
}

void ApplicationWindow::updateAppFonts()
{
  qApp->setFont(appFont);
  this->setFont(appFont);
  info->setFont(QFont(appFont.family(), 2 + appFont.pointSize(), QFont::Bold,false));
}

void ApplicationWindow::updateConfirmOptions(bool askTables, bool askMatrices, bool askPlots2D,
    bool askPlots3D, bool askNotes,bool askInstrWindow)
{
  QList<MdiSubWindow *> windows = windowsList();


  if (confirmCloseTable != askTables){
    confirmCloseTable=askTables;
    foreach(MdiSubWindow *w, windows){

      if (w->inherits("Table"))
      {w->confirmClose(confirmCloseTable);
      }
    }
  }

  if (confirmCloseMatrix != askMatrices){
    confirmCloseMatrix = askMatrices;
    foreach(MdiSubWindow *w, windows){
      if (w->isA("Matrix"))
      {w->confirmClose(confirmCloseMatrix);
      }
    }
  }

  if (confirmClosePlot2D != askPlots2D){
    confirmClosePlot2D=askPlots2D;
    foreach(MdiSubWindow *w, windows){
      if (w->isA("MultiLayer"))
      {w->confirmClose(confirmClosePlot2D);
      }
    }
  }

  if (confirmClosePlot3D != askPlots3D){
    confirmClosePlot3D=askPlots3D;
    foreach(MdiSubWindow *w, windows){
      if (w->isA("Graph3D"))
        w->confirmClose(confirmClosePlot3D);
    }
  }

  if (confirmCloseNotes != askNotes){
    confirmCloseNotes = askNotes;
    foreach(MdiSubWindow *w, windows){
      if (w->isA("Note"))
        w->confirmClose(confirmCloseNotes);
    }
  }

  if (confirmCloseInstrWindow != askInstrWindow){
    confirmCloseInstrWindow = askInstrWindow;

    foreach(MdiSubWindow *w, windows){
      if (w->isA("InstrumentWindow"))
      {w->confirmClose(confirmCloseInstrWindow);
      }
    }
  }
}

void ApplicationWindow::setGraphDefaultSettings(bool autoscale, bool scaleFonts,
    bool resizeLayers, bool antialiasing, bool fixedAspectRatio)
{
  if (autoscale2DPlots == autoscale &&
      autoScaleFonts == scaleFonts &&
      autoResizeLayers != resizeLayers &&
      antialiasing2DPlots == antialiasing &&
      fixedAspectRatio2DPlots == fixedAspectRatio)
    return;

  autoscale2DPlots = autoscale;
  autoScaleFonts = scaleFonts;
  autoResizeLayers = !resizeLayers;
  antialiasing2DPlots = antialiasing;
  fixedAspectRatio2DPlots = fixedAspectRatio;

  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->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("; "));
Loading
Loading full blame...