baseWidget.cc 15 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1 2 3
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
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
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
Jan Möbius's avatar
Jan Möbius committed
39 40 41
*                                                                            *
\*===========================================================================*/

Jan Möbius's avatar
Jan Möbius committed
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

//== INCLUDES =================================================================
#include <QVBoxLayout>
#include <QPushButton>
#include <QDialog>
#include <QTextEdit>
#include <QFileDialog>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>

#include <QApplication>
#include <QClipboard>
#include <QScriptEngine>

#include <QDomDocument>

#include <QXmlQuery>
#include <QXmlResultItems>

#include <OpenFlipper/common/GlobalOptions.hh>

#include "baseWidget.hh"
#include "toolBoxElement.hh"
#include "scene/sceneElement.hh"

#include "parser/context.hh"

//== NAMESPACES ===============================================================
namespace VSI {

//=============================================================================
//
//  CLASS BaseWidget - IMPLEMENTATION
//
//=============================================================================

// static variable for singleton
BaseWidget * BaseWidget::base_ = NULL;

//------------------------------------------------------------------------------

// Constructor
BaseWidget::BaseWidget (Context *_ctx, QWidget *_parent) :
  QMainWindow (_parent),
  ctx_ (_ctx),
  fileName_ (),
  changedContent_ (false)
{
  setWindowIcon (OpenFlipper::Options::OpenFlipperIcon ());
  updateTitle ();

  splitter_ = new QSplitter (Qt::Horizontal, this);
  toolbox_ = new QToolBox ();
  views_ = new QStackedWidget ();
 

Jan Möbius's avatar
Jan Möbius committed
100
  toolbox_->setMinimumWidth (275);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

  QVBoxLayout *layout = new QVBoxLayout;

  layout->addWidget (toolbox_);

  QPushButton *execute = new QPushButton ("Execute");
  layout->addWidget (execute);

  QWidget *w = new QWidget;
  w->setLayout (layout);

  mainScene_ = new GraphicsScene (_ctx);
  views_->addWidget(mainScene_->graphicsView ());

  splitter_->addWidget (w);
  splitter_->addWidget (views_);
  QList<int> sizes;
Jan Möbius's avatar
Jan Möbius committed
118
  sizes << 275 << 10000;
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
  splitter_->setSizes (sizes);

  setCentralWidget (splitter_);

  resize (1000, 700);

  setupUi ();

  connect (execute, SIGNAL (clicked (bool)), this, SLOT (executeCode ()));

  connect (mainScene_, SIGNAL (contentChanged()), this, SLOT (contentChanged()));


  QMenu *menu = new QMenu (tr("&File"));
  QIcon icon;

  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"add-empty-object.png");
  menu->addAction (icon, tr("New"), this, SLOT (newFile()), QKeySequence::New);

  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"document-open.png");
  menu->addAction (icon, tr("Open ..."), this, SLOT (load()), QKeySequence::Open);

  menu->addSeparator ();

  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"document-save.png");
  menu->addAction (icon, tr("Save"), this, SLOT (save()), QKeySequence::Save);

  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"document-save-as.png");
  menu->addAction (icon, tr("Save as ..."), this, SLOT (saveAs()), QKeySequence::SaveAs);
  menu->addSeparator ();

  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"window-close.png");
  menu->addAction (icon, tr("Close"), this, SLOT (close()), QKeySequence::Close);

  menuBar()->addMenu (menu);

  menu = new QMenu (tr("&Script"));
  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"scriptEditor.png");
  menu->addAction (icon, tr("Open in script editor"), this, SLOT (codeToScript()));

  menuBar()->addMenu (menu);

  base_ = this;
}

//------------------------------------------------------------------------------

/// Destructor
BaseWidget::~BaseWidget ()
{
  base_ = NULL;
}

//------------------------------------------------------------------------------

/// Adds element widgets to toolbox
void BaseWidget::setupUi ()
{

  foreach (const QString &c, ctx_->categories ())
  {
    QWidget *widget = new QWidget (toolbox_);
    QVBoxLayout *layout = new QVBoxLayout ();
    foreach (Element *e, ctx_->elements (c))
    {
      if (!(e->flags () & ELEMENT_FLAG_SKIP_TOOLBOX))
      {
        ToolBoxElement *t = new ToolBoxElement (e, widget);
        layout->addWidget (t);
      }
    }
    layout->addStretch ();
    widget->setLayout (layout);
    toolbox_->addItem (widget, c);
  }
}

//------------------------------------------------------------------------------

/// Executes current visual script
void BaseWidget::executeCode ()
{
  QString errors = "";

  QString code = mainScene_->generateCode (errors);

  if (errors.isEmpty ())
  {
    ctx_->scriptEngine ()->pushContext ();
    ctx_->scriptEngine ()->evaluate (code);
    ctx_->scriptEngine ()->popContext ();
    return;
  }

  errors = "<h3> " + tr("Following Elements could not be processed:") + "</h3>" + errors;

  QMessageBox::warning (this, tr("Error during code generation"), errors,
                        QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
}

//------------------------------------------------------------------------------

/// signal to open textual script editor with current script
void BaseWidget::codeToScript()
{
  
  QString errors = "";

  QString code = mainScene_->generateCode (errors);

  if (errors.isEmpty ())
  {
    emit codeToScriptEditor (code);
    return;
  }

  errors = "<qt> " + tr("Following Elements could not be processed:") + errors + "</qt>";

  QMessageBox::warning (this, tr("Error during code generation"), errors,
                        QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
}

//------------------------------------------------------------------------------

/// Save to file
bool BaseWidget::saveAs()
{
  return save (true);
}

//------------------------------------------------------------------------------

/// Load file
void VSI::BaseWidget::load()
{
  if (!saveIfChanged ())
    return;

257 258 259
  QString filename = QFileDialog::getOpenFileName (this,
                                                   tr("Load Visual Script"),
                                                   OpenFlipperSettings().value("Core/CurrentDir").toString(),
260 261 262 263 264
                                                   tr("Visual Script File (*.ofvs)"));

  if (filename.isEmpty ())
    return;

265 266 267 268
  // Get the chosen directory and remember it.
  QFileInfo fileInfo(filename);
  OpenFlipperSettings().setValue("Core/CurrentDir", fileInfo.absolutePath() );

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
  QFile f (filename);
  if (!f.open (QFile::ReadOnly))
  {
    QMessageBox msgBox;
    msgBox.setText(tr("Unable to open file."));
    msgBox.setInformativeText(filename);
    msgBox.exec();
    return;
  }

  while (!scenes_.isEmpty())
    scenes_.pop ();
  views_->setCurrentWidget (mainScene_->graphicsView());

  QXmlQuery query;
  query.setFocus (&f);

  query.setQuery ("VisualScript");

  QXmlResultItems root;

  if (query.isValid ())
  {
    query.evaluateTo (&root);

    QXmlItem item (root.next ());
    if (!item.isNull ())
    {
      QXmlQuery q (query);
      q.setFocus (item);
      mainScene_->loadFromXml (q);
    }
  }

  changedContent_ = false;
  fileName_ = filename;
  updateTitle ();
}

//------------------------------------------------------------------------------

/// Save file
bool BaseWidget::save(bool _newName)
{
313

314 315 316 317
  QString filename;

  if (fileName_.isEmpty () || _newName)
  {
318 319
    QFileDialog *d = new QFileDialog (this, tr("Save Visual Script"),
                                            OpenFlipperSettings().value("Core/CurrentDir").toString(),
320 321 322 323 324 325 326 327 328 329 330 331 332 333
                                            tr("Visual Script File (*.ofvs)"));

    d->setAcceptMode (QFileDialog::AcceptSave);
    d->setDefaultSuffix ("ofvs");

    if (QDialog::Accepted == d->exec ())
      filename = d->selectedFiles ()[0];
  }
  else
    filename = fileName_;

  if (filename.isEmpty ())
    return false;

334 335 336 337
  // Get the chosen directory and remember it.
  QFileInfo fileInfo(filename);
  OpenFlipperSettings().setValue("Core/CurrentDir", fileInfo.absolutePath() );

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
  QFile f (filename);
  if (!f.open (QFile::WriteOnly))
  {
    QMessageBox msgBox;
    msgBox.setText(tr("Unable to write file."));
    msgBox.setInformativeText(filename);
    msgBox.exec();
    return false;
  }

  QDomDocument doc("VisualScript");
  QDomElement root = doc.createElement("VisualScript");
  doc.appendChild(root);

  mainScene_->saveToXml (doc, root);

  f.write (doc.toString().toUtf8 ());
  f.close ();

  changedContent_ = false;
  fileName_ = filename;
  updateTitle ();

  return true;
}

//------------------------------------------------------------------------------

/// New empty scene
void BaseWidget::newFile()
{
  if (!saveIfChanged ())
    return;

  while (!scenes_.isEmpty())
    scenes_.pop ();
  views_->setCurrentWidget (mainScene_->graphicsView());

  fileName_ = QString ();
  mainScene_->clearScene ();
  changedContent_ = false;
  updateTitle ();
}

//------------------------------------------------------------------------------

/// Update window title
void BaseWidget::updateTitle()
{
  if (fileName_.isEmpty ())
    setWindowTitle (tr("Untitled") + (changedContent_ ? " [" + tr("Modified") + "] " : "") + " - Visual Script Editor");
  else
    setWindowTitle (fileName_ + (changedContent_ ? " [" + tr("Modified") + "] " : "") + " - Visual Script Editor");
}

//------------------------------------------------------------------------------

/// Called if something it the scene has changed
void BaseWidget::contentChanged()
{
  if (!changedContent_)
  {
    changedContent_ = true;
    updateTitle ();
  }
}

//------------------------------------------------------------------------------

/// Asks the user if he want to save his changes
bool BaseWidget::saveIfChanged()
{
  if (changedContent_)
  {
    QMessageBox msgBox;
    msgBox.setText(tr("The visual script has been modified."));
    msgBox.setInformativeText(tr("Do you want to save your changes?"));
    msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Save);
    int ret = msgBox.exec();
    switch (ret) {
     case QMessageBox::Save:
      // Save was clicked
      if (!save ())
        return false;
      break;
     case QMessageBox::Discard:
      // Don't Save was clicked
      break;
     case QMessageBox::Cancel:
      // Cancel was clicked
      return false;
      break;
     default:
      // should never be reached
      break;
   }
   return true;
  }
  else
    return true;
}

//------------------------------------------------------------------------------

/// Chatch close event
void BaseWidget::closeEvent(QCloseEvent *_event)
{
  if (!saveIfChanged ())
    _event->ignore ();
  else
    _event->accept();
}

//------------------------------------------------------------------------------

/// Singleton constructor
BaseWidget * BaseWidget::createBaseWidget (Context *_ctx, QWidget *_parent)
{
  if (!base_)
    base_ = new BaseWidget (_ctx, _parent);
  return base_;
}

//------------------------------------------------------------------------------

/// Returns singleton
BaseWidget * BaseWidget::getBaseWidget()
{
  return base_;
}

//------------------------------------------------------------------------------

/// Display a new scene (function) in editor
void VSI::BaseWidget::pushScene(GraphicsScene * _scene)
{
  scenes_.push (_scene);
  views_->setCurrentWidget (_scene->graphicsView());
}

//------------------------------------------------------------------------------

/// Go back to previous scene (function)
void VSI::BaseWidget::popScene()
{
  if (!scenes_.isEmpty())
    scenes_.pop ();

  if (!scenes_.isEmpty())
    views_->setCurrentWidget (scenes_.top ()->graphicsView());
  else
    views_->setCurrentWidget (mainScene_->graphicsView());
}

//------------------------------------------------------------------------------

/// Add scene to stack widget
void VSI::BaseWidget::addScene(GraphicsScene * _scene)
{
  views_->addWidget (_scene->graphicsView ());
}

//------------------------------------------------------------------------------

/// Remove scene from stack widget
void VSI::BaseWidget::removeScene(GraphicsScene * _scene)
{
  views_->removeWidget (_scene->graphicsView ());
}

//------------------------------------------------------------------------------
}