Skip to content
Snippets Groups Projects
QReflTableView.cpp 18.4 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
#include "MantidQtCustomInterfaces/Reflectometry/QReflTableView.h"
#include "MantidAPI/ITableWorkspace.h"
#include "MantidQtAPI/FileDialogHandler.h"
#include "MantidQtAPI/HelpWindow.h"
#include "MantidQtAPI/MantidWidget.h"
#include "MantidQtCustomInterfaces/Reflectometry/QReflTableModel.h"
#include "MantidQtCustomInterfaces/Reflectometry/ReflTableViewPresenter.h"
#include "MantidQtMantidWidgets/HintingLineEditFactory.h"

#include <QWidget>
namespace {
const QString ReflSettingsGroup = "Mantid/CustomInterfaces/ISISReflectometry";
}

namespace MantidQt {
namespace CustomInterfaces {
using namespace Mantid::API;

//----------------------------------------------------------------------------------------------
/** Constructor
*/
QReflTableView::QReflTableView(QWidget *parent) : MantidWidget(parent) {

  createTable();
}

//----------------------------------------------------------------------------------------------
/** Destructor
*/
QReflTableView::~QReflTableView() {}

/**
Initialise the Interface
*/
void QReflTableView::createTable() {
  ui.setupUi(this);

  ui.buttonProcess->setDefaultAction(ui.actionProcess);

  // Create a whats this button
  ui.rowToolBar->addAction(QWhatsThis::createAction(this));

  // Allow rows and columns to be reordered
  ui.viewTable->verticalHeader()->setMovable(true);
  ui.viewTable->horizontalHeader()->setMovable(true);

  // Custom context menu for table
  connect(ui.viewTable, SIGNAL(customContextMenuRequested(const QPoint &)),
          this, SLOT(showContextMenu(const QPoint &)));
  // Finally, create the presenters to do the thinking for us
  m_tablePresenter = boost::make_shared<ReflTableViewPresenter>(
      this /*table view*/,
      this /*currently this concrete view is also responsibile for prog reporting*/);
}

/**
This slot loads a table workspace model and changes to a LoadedMainView
presenter
@param name : the string name of the workspace to be grabbed
*/
void QReflTableView::setModel(QString name) {
  m_toOpen = name.toStdString();
  m_tablePresenter->notify(IReflTablePresenter::OpenTableFlag);
}

/**
Set a new model in the tableview
@param model : the model to be attached to the tableview
*/
void QReflTableView::showTable(QReflTableModel_sptr model) {
  m_model = model;
  // So we can notify the presenter when the user updates the table
  connect(m_model.get(),
          SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), this,
          SLOT(tableUpdated(const QModelIndex &, const QModelIndex &)));
  ui.viewTable->setModel(m_model.get());
  ui.viewTable->resizeColumnsToContents();
  std::string windowTitle = "ISIS Reflectometry (Polref) - " + m_toOpen;
  auto mainWindowWidget = this->topLevelWidget();
  mainWindowWidget->setWindowTitle(QString::fromStdString(windowTitle + "[*]"));
  this->setWindowModified(false);
}

/**
Set the list of tables the user is offered to open
@param tables : the names of the tables in the ADS
*/
void QReflTableView::setTableList(const std::set<std::string> &tables) {
  ui.menuOpenTable->clear();
  for (auto it = tables.begin(); it != tables.end(); ++it) {
    QAction *openTable =
        ui.menuOpenTable->addAction(QString::fromStdString(*it));
    openTable->setIcon(QIcon("://worksheet.png"));

    // Map this action to the table name
    m_openMap->setMapping(openTable, QString::fromStdString(*it));
    // When repeated corrections happen the QMessageBox from openTable()
    // method in ReflMainViewPresenter will be called multiple times
    // when 'no' is clicked.
    // ConnectionType = UniqueConnection ensures that
    // each object has only one of these signals.
    connect(openTable, SIGNAL(triggered()), m_openMap, SLOT(map()),
            Qt::UniqueConnection);
    connect(m_openMap, SIGNAL(mapped(QString)), this, SLOT(setModel(QString)),
            Qt::UniqueConnection);
  }
}

/**
This slot notifies the presenter that the "save" button has been pressed
*/
void QReflTableView::on_actionSaveTable_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::SaveFlag);
}

/**
This slot notifies the presenter that the "save as" button has been pressed
*/
void QReflTableView::on_actionSaveTableAs_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::SaveAsFlag);
}

/**
This slot notifies the presenter that the "append row" button has been pressed
*/
void QReflTableView::on_actionAppendRow_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::AppendRowFlag);
}

/**
This slot notifies the presenter that the "prepend row" button has been pressed
*/
void QReflTableView::on_actionPrependRow_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::PrependRowFlag);
}

/**
This slot notifies the presenter that the "delete" button has been pressed
*/
void QReflTableView::on_actionDeleteRow_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::DeleteRowFlag);
}

/**
This slot notifies the presenter that the "process" button has been pressed
*/
void QReflTableView::on_actionProcess_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::ProcessFlag);
}

/**
This slot notifies the presenter that the "group rows" button has been pressed
*/
void QReflTableView::on_actionGroupRows_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::GroupRowsFlag);
}

/**
This slot notifies the presenter that the "clear selected" button has been
pressed
*/
void QReflTableView::on_actionClearSelected_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::ClearSelectedFlag);
}

/**
This slot notifies the presenter that the "copy selection" button has been
pressed
*/
void QReflTableView::on_actionCopySelected_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::CopySelectedFlag);
}

/**
This slot notifies the presenter that the "cut selection" button has been
pressed
*/
void QReflTableView::on_actionCutSelected_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::CutSelectedFlag);
}

/**
This slot notifies the presenter that the "paste selection" button has been
pressed
*/
void QReflTableView::on_actionPasteSelected_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::PasteSelectedFlag);
}

/**
This slot notifies the presenter that the "new table" button has been pressed
*/
void QReflTableView::on_actionNewTable_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::NewTableFlag);
}

/**
This slot notifies the presenter that the "expand selection" button has been
pressed
*/
void QReflTableView::on_actionExpandSelection_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::ExpandSelectionFlag);
}

/**
This slot notifies the presenter that the "options..." button has been pressed
*/
void QReflTableView::on_actionOptionsDialog_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::OptionsDialogFlag);
}

/**
This slot requests the list of runs to transfer to ReflMainViewPresenter
Then updates ReflTableViewPresenter
*/
// TODO: see below
// void QtReflMainView::on_actionTransfer_triggered() {
//  // m_presenter->notify(IReflPresenter::TransferFlag);
//  auto runs = m_presenter->getRunsToTransfer();
//  m_tablePresenter->transfer(runs);
//}

/**
This slot notifies the presenter that the "export table" button has been pressed
*/
void QReflTableView::on_actionExportTable_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::ExportTableFlag);
}

/**
This slot notifies the presenter that the "import table" button has been pressed
*/
void QReflTableView::on_actionImportTable_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::ImportTableFlag);
}

/**
This slot opens the documentation when the "help" button has been pressed
*/
void QReflTableView::on_actionHelp_triggered() {
  MantidQt::API::HelpWindow::showPage(
      this,
      QString(
          "qthelp://org.mantidproject/doc/interfaces/ISIS_Reflectometry.html"));
}

/**
This slot notifies the presenter that the "plot selected rows" button has been
pressed
*/
void QReflTableView::on_actionPlotRow_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::PlotRowFlag);
}

/**
This slot notifies the presenter that the "plot selected groups" button has been
pressed
*/
void QReflTableView::on_actionPlotGroup_triggered() {
  m_tablePresenter->notify(IReflTablePresenter::PlotGroupFlag);
}

/**
This slot notifies the presenter that the table has been updated/changed by the
user
*/
void QReflTableView::tableUpdated(const QModelIndex &topLeft,
                                  const QModelIndex &bottomRight) {
  Q_UNUSED(topLeft);
  Q_UNUSED(bottomRight);
  m_tablePresenter->notify(IReflTablePresenter::TableUpdatedFlag);
}

/**
This slot is triggered when the user right clicks on the table
@param pos : The position of the right click within the table
*/
void QReflTableView::showContextMenu(const QPoint &pos) {
  // If the user didn't right-click on anything, don't show a context menu.
  if (!ui.viewTable->indexAt(pos).isValid())
    return;

  // parent widget takes ownership of QMenu
  QMenu *menu = new QMenu(this);
  menu->addAction(ui.actionProcess);
  menu->addAction(ui.actionExpandSelection);
  menu->addSeparator();
  menu->addAction(ui.actionPlotRow);
  menu->addAction(ui.actionPlotGroup);
  menu->addSeparator();
  menu->addAction(ui.actionPrependRow);
  menu->addAction(ui.actionAppendRow);
  menu->addSeparator();
  menu->addAction(ui.actionGroupRows);
  menu->addAction(ui.actionCopySelected);
  menu->addAction(ui.actionCutSelected);
  menu->addAction(ui.actionPasteSelected);
  menu->addAction(ui.actionClearSelected);
  menu->addSeparator();
  menu->addAction(ui.actionDeleteRow);

  menu->popup(ui.viewTable->viewport()->mapToGlobal(pos));
}

/**
Show an critical error dialog
@param prompt : The prompt to appear on the dialog
@param title : The text for the title bar of the dialog
*/
void QReflTableView::giveUserCritical(std::string prompt, std::string title) {
  QMessageBox::critical(this, QString(title.c_str()), QString(prompt.c_str()),
                        QMessageBox::Ok, QMessageBox::Ok);
}

/**
Show a warning dialog
@param prompt : The prompt to appear on the dialog
@param title : The text for the title bar of the dialog
*/
void QReflTableView::giveUserWarning(std::string prompt, std::string title) {
  QMessageBox::warning(this, QString(title.c_str()), QString(prompt.c_str()),
                       QMessageBox::Ok, QMessageBox::Ok);
}

/**
Ask the user a Yes/No question
@param prompt : The prompt to appear on the dialog
@param title : The text for the title bar of the dialog
@returns a boolean true if Yes, false if No
*/
bool QReflTableView::askUserYesNo(std::string prompt, std::string title) {
  auto response = QMessageBox::question(
      this, QString(title.c_str()), QString(prompt.c_str()),
      QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
  if (response == QMessageBox::Yes) {
    return true;
  }
  return false;
}

/**
Ask the user to enter a string.
@param prompt : The prompt to appear on the dialog
@param title : The text for the title bar of the dialog
@param defaultValue : The default value entered.
@returns The user's string if submitted, or an empty string
*/
std::string QReflTableView::askUserString(const std::string &prompt,
                                          const std::string &title,
                                          const std::string &defaultValue) {
  bool ok;
  QString text = QInputDialog::getText(
      QString::fromStdString(title), QString::fromStdString(prompt),
      QLineEdit::Normal, QString::fromStdString(defaultValue), &ok);
  if (ok)
    return text.toStdString();
  return "";
}

/**
Show the user the dialog for an algorithm
*/
void QReflTableView::showAlgorithmDialog(const std::string &algorithm) {
  std::stringstream pythonSrc;
  pythonSrc << "try:\n";
  pythonSrc << "  algm = " << algorithm << "Dialog()\n";
  pythonSrc << "except:\n";
  pythonSrc << "  pass\n";
  runPythonCode(QString::fromStdString(pythonSrc.str()), false);
}

void QReflTableView::showImportDialog() {
  std::stringstream pythonSrc;
  pythonSrc << "try:\n";
  pythonSrc << "  algm = "
            << "LoadReflTBL"
            << "Dialog()\n";
  pythonSrc << "  print algm.getPropertyValue(\"OutputWorkspace\")\n";
  pythonSrc << "except:\n";
  pythonSrc << "  pass\n";
  // outputWorkspaceName will hold the name of the workspace
  // otherwise this should be an empty string.
  QString outputWorkspaceName =
      runPythonCode(QString::fromStdString(pythonSrc.str()), false);
  m_toOpen = outputWorkspaceName.trimmed().toStdString();
  // notifying the presenter that a new table should be opened
  // The presenter will ask about any unsaved changes etc
  // before opening the new table
  m_tablePresenter->notify(IReflTablePresenter::OpenTableFlag);
}

/**
Show the user file dialog to choose save location of notebook
*/
std::string QReflTableView::requestNotebookPath() {

  // We won't use QFileDialog directly here as using the NativeDialog option
  // causes problems on MacOS.
  QString qfilename = API::FileDialogHandler::getSaveFileName(
      this, "Save notebook file", QDir::currentPath(),
      "IPython Notebook files (*.ipynb);;All files (*.*)",
      new QString("IPython Notebook files (*.ipynb)"));

  // There is a Qt bug (QTBUG-27186) which means the filename returned
  // from the dialog doesn't always the file extension appended.
  // So we'll have to ensure this ourselves.
  // Important, notebooks can't be loaded without this extension.
  std::string filename = qfilename.toStdString();
  if (filename.size() > 6) {
    if (filename.substr(filename.size() - 6) != ".ipynb") {
      filename.append(".ipynb");
    }
  } else {
    filename.append(".ipynb");
  }

  return filename;
}

/**
Save settings
@param options : map of user options to save
*/
void QReflTableView::saveSettings(
    const std::map<std::string, QVariant> &options) {
  QSettings settings;
  settings.beginGroup(ReflSettingsGroup);
  for (auto it = options.begin(); it != options.end(); ++it)
    settings.setValue(QString::fromStdString(it->first), it->second);
  settings.endGroup();
}

/**
Load settings
@param options : map of user options to load into
*/
void QReflTableView::loadSettings(std::map<std::string, QVariant> &options) {
  QSettings settings;
  settings.beginGroup(ReflSettingsGroup);
  QStringList keys = settings.childKeys();
  for (auto it = keys.begin(); it != keys.end(); ++it)
    options[it->toStdString()] = settings.value(*it);
  settings.endGroup();
}

/**
Plot a workspace
*/
void QReflTableView::plotWorkspaces(const std::set<std::string> &workspaces) {
  if (workspaces.empty())
    return;

  std::stringstream pythonSrc;
  pythonSrc << "base_graph = None\n";
  for (auto ws = workspaces.begin(); ws != workspaces.end(); ++ws)
    pythonSrc << "base_graph = plotSpectrum(\"" << *ws
              << "\", 0, True, window = base_graph)\n";

  pythonSrc << "base_graph.activeLayer().logLogAxes()\n";

  runPythonCode(QString::fromStdString(pythonSrc.str()));
}

/**
Set the range of the progress bar
@param min : The minimum value of the bar
@param max : The maxmimum value of the bar
*/
void QReflTableView::setProgressRange(int min, int max) {
  ui.progressBar->setRange(min, max);
}

/**
Set the status of the progress bar
@param progress : The current value of the bar
*/
void QReflTableView::setProgress(int progress) {
  ui.progressBar->setValue(progress);
}

/**
Get status of checkbox which determines whether an ipython notebook is produced
@return true if a notebook should be output on process, false otherwise
*/
bool QReflTableView::getEnableNotebook() {
  return ui.checkEnableNotebook->isChecked();
}

/**
Set which rows are selected
@param rows : The set of rows to select
*/
void QReflTableView::setSelection(const std::set<int> &rows) {
  ui.viewTable->clearSelection();
  auto selectionModel = ui.viewTable->selectionModel();

  for (auto row = rows.begin(); row != rows.end(); ++row)
    selectionModel->select(ui.viewTable->model()->index((*row), 0),
                           QItemSelectionModel::Select |
                               QItemSelectionModel::Rows);
}

/**
Set the list of available instruments to search and process for
@param instruments : The list of instruments available
@param defaultInstrument : The instrument to have selected by default
*/
void QReflTableView::setInstrumentList(
    const std::vector<std::string> &instruments,
    const std::string &defaultInstrument) {
  ui.comboProcessInstrument->clear();

  for (auto it = instruments.begin(); it != instruments.end(); ++it) {
    QString instrument = QString::fromStdString(*it);
    ui.comboProcessInstrument->addItem(instrument);
  }

  int index = ui.comboProcessInstrument->findData(
      QString::fromStdString(defaultInstrument), Qt::DisplayRole);
  ui.comboProcessInstrument->setCurrentIndex(index);
}

/**
Set the strategy used for generating hints for the autocompletion in the options
column.
@param hintStrategy The hinting strategy to use
*/
void QReflTableView::setOptionsHintStrategy(HintStrategy *hintStrategy) {
  ui.viewTable->setItemDelegateForColumn(
      ReflTableSchema::COL_OPTIONS, new HintingLineEditFactory(hintStrategy));
}

/**
Sets the contents of the system's clipboard
@param text The contents of the clipboard
*/
void QReflTableView::setClipboard(const std::string &text) {
  QApplication::clipboard()->setText(QString::fromStdString(text));
}

/**
Get the selected instrument for processing
@returns the selected instrument to process with
*/
std::string QReflTableView::getProcessInstrument() const {
  return ui.comboProcessInstrument->currentText().toStdString();
}

/**
Get the indices of the highlighted rows
@returns a set of ints containing the highlighted row numbers
*/
std::set<int> QReflTableView::getSelectedRows() const {
  std::set<int> rows;
  auto selectionModel = ui.viewTable->selectionModel();
  if (selectionModel) {
    auto selectedRows = selectionModel->selectedRows();
    for (auto it = selectedRows.begin(); it != selectedRows.end(); ++it)
      rows.insert(it->row());
  }
  return rows;
}

/**
Get the name of the workspace that the user wishes to open as a table
@returns The name of the workspace to open
*/
std::string QReflTableView::getWorkspaceToOpen() const { return m_toOpen; }

/**
Get a pointer to the presenter that's currently controlling this view.
@returns A pointer to the presenter
*/
boost::shared_ptr<IReflTablePresenter>
QReflTableView::getTablePresenter() const {
  return m_tablePresenter;
}

/**
Gets the contents of the system's clipboard
@returns The contents of the clipboard
*/
std::string QReflTableView::getClipboard() const {
  return QApplication::clipboard()->text().toStdString();
}

/**
* Clear the progress
*/
void QReflTableView::clearProgress() { ui.progressBar->reset(); }

} // namespace CustomInterfaces
} // namespace Mantid