ScriptingPlugin.cc 18.1 KB
Newer Older
1
/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
2
3
*                                                                            *
*                              OpenFlipper                                   *
Jan Möbius's avatar
Jan Möbius committed
4
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen       *
Jan Möbius's avatar
Jan Möbius committed
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
*                           www.openflipper.org                              *
*                                                                            *
*--------------------------------------------------------------------------- *
*  This file is part of OpenFlipper.                                         *
*                                                                            *
*  OpenFlipper is free software: you can redistribute it and/or modify       *
*  it under the terms of the GNU Lesser General Public License as            *
*  published by the Free Software Foundation, either version 3 of            *
*  the License, or (at your option) any later version with the               *
*  following exceptions:                                                     *
*                                                                            *
*  If other files instantiate templates or use macros                        *
*  or inline functions from this file, or you compile this file and          *
*  link it with other files to produce an executable, this file does         *
*  not by itself cause the resulting executable to be covered by the         *
*  GNU Lesser General Public License. This exception does not however        *
*  invalidate any other reasons why the executable file might be             *
*  covered by the GNU Lesser General Public License.                         *
*                                                                            *
*  OpenFlipper 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 Lesser General Public License for more details.                       *
*                                                                            *
*  You should have received a copy of the GNU LesserGeneral Public           *
*  License along with OpenFlipper. If not,                                   *
*  see <http://www.gnu.org/licenses/>.                                       *
*                                                                            *
33
34
35
\*===========================================================================*/

/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
36
37
38
39
40
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
41
42
\*===========================================================================*/

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

#include <QtGui>

#include "ScriptingPlugin.hh"

#include <iostream>
#include <ACG/GL/GLState.hh>

#include <OpenFlipper/BasePlugin/PluginFunctions.hh>

#include "OpenFlipper/common/GlobalOptions.hh"

#include <QFileDialog>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QSyntaxHighlighter>

ScriptingPlugin::ScriptingPlugin() {

}

void ScriptingPlugin::pluginsInitialized() {

  if ( OpenFlipper::Options::nogui() )
    return;

  ///@todo register objectid variable

  // Scriping Menu
73
  QMenu *scriptingMenu;
Jan Möbius's avatar
 
Jan Möbius committed
74

75
  emit getMenubarMenu(tr("&Scripting"), scriptingMenu, true );
Jan Möbius's avatar
 
Jan Möbius committed
76
77

  QIcon icon;
Dirk Wilden's avatar
Dirk Wilden committed
78
  QAction* showWidget = scriptingMenu->addAction( tr("Show script editor") );
Jan Möbius's avatar
 
Jan Möbius committed
79
80
81
82
83
84
85
  icon.addFile(OpenFlipper::Options::iconDirStr()+OpenFlipper::Options::dirSeparator()+"scriptEditor.png");
  showWidget->setIcon(icon);
  connect( showWidget, SIGNAL( triggered() ) ,
           this      , SLOT( showScriptWidget() ));

  scriptWidget_ = new ScriptWidget();

Jan Möbius's avatar
Jan Möbius committed
86
87
88

  QString iconPath = OpenFlipper::Options::iconDirStr() + OpenFlipper::Options::dirSeparator();

Jan Möbius's avatar
 
Jan Möbius committed
89
90
  scriptWidget_->setWindowIcon( OpenFlipper::Options::OpenFlipperIcon() );

Jan Möbius's avatar
Jan Möbius committed
91
  icon.addFile(iconPath+"document-open.png");
Jan Möbius's avatar
 
Jan Möbius committed
92
93
  scriptWidget_->actionLoad_Script->setIcon(icon);

Jan Möbius's avatar
Jan Möbius committed
94
  icon.addFile(iconPath+"document-save.png");
Jan Möbius's avatar
 
Jan Möbius committed
95
96
  scriptWidget_->actionSave_Script->setIcon(icon);

Jan Möbius's avatar
Jan Möbius committed
97
  icon.addFile(iconPath+"document-save-as.png");
Jan Möbius's avatar
 
Jan Möbius committed
98
99
  scriptWidget_->actionSave_Script_As->setIcon(icon);

Jan Möbius's avatar
Jan Möbius committed
100
  icon.addFile(iconPath+"window-close.png");
Jan Möbius's avatar
 
Jan Möbius committed
101
102
  scriptWidget_->actionClose->setIcon(icon);

103
104
105
106
107
  // ==================================================================
  // Add a toolbar
  // ==================================================================

  QToolBar* toolBar = new QToolBar(tr("Scripting Toolbar"));
Jan Möbius's avatar
Jan Möbius committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129


  QAction* openButton = new QAction(QIcon(iconPath + "document-open.png"), "Open", toolBar);
  toolBar->addAction(openButton);
  connect (openButton, SIGNAL( triggered() ), this, SLOT( slotLoadScript() ) );

  QAction* saveButton = new QAction(QIcon(iconPath + "document-save.png"), "Save", toolBar);
  toolBar->addAction(saveButton);
  connect (saveButton, SIGNAL( triggered() ), this, SLOT( slotSaveScript() ) );

  QAction* saveAsButton = new QAction(QIcon(iconPath + "document-save-as.png"), "Save as", toolBar);
  toolBar->addAction(saveAsButton);
  connect (saveAsButton, SIGNAL( triggered() ), this, SLOT( slotSaveScriptAs() ) );

  toolBar->addSeparator();

  QAction* executeButton = new QAction(QIcon(iconPath + "arrow-right.png"), "Execute", toolBar);
  toolBar->addAction(executeButton);
  connect (executeButton, SIGNAL( triggered() ), this, SLOT( slotExecuteScriptButton() ) );

  scriptWidget_->addToolBar(toolBar);

130
131
132
133
134
135
136
137
138
139
  // ==================================================================
  // Create a status bar
  // ==================================================================

  statusBar_ = new QStatusBar();

  scriptWidget_->setStatusBar( statusBar_ );

  // ==================================================================

Jan Möbius's avatar
 
Jan Möbius committed
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
  scriptWidget_->hide();

  scriptWidget_->resize(scriptWidget_->width() , std::min(QApplication::desktop()->screenGeometry().height() - 150 , 800) );

  connect (scriptWidget_->actionLoad_Script, SIGNAL( triggered() ), this, SLOT( slotLoadScript() ) );
  scriptWidget_->actionLoad_Script->setShortcut( QKeySequence(Qt::CTRL + Qt::Key_O) );
  connect (scriptWidget_->actionSave_Script, SIGNAL( triggered() ), this, SLOT( slotSaveScript() ) );
  scriptWidget_->actionSave_Script->setShortcut( QKeySequence(Qt::CTRL + Qt::Key_S) );
  connect (scriptWidget_->actionSave_Script_As, SIGNAL( triggered() ), this, SLOT( slotSaveScriptAs() ) );
  connect (scriptWidget_->actionClose, SIGNAL( triggered() ), scriptWidget_, SLOT( close() ) );

  connect (scriptWidget_->currentScript, SIGNAL( textChanged() ), this, SLOT( slotEnableSave() ) );

  connect (scriptWidget_->functionList, SIGNAL( itemClicked(QListWidgetItem*) ),
           this,                          SLOT( slotFunctionClicked(QListWidgetItem*) ));
  connect (scriptWidget_->functionList, SIGNAL( itemDoubleClicked(QListWidgetItem*) ),
           this,                          SLOT( slotFunctionDoubleClicked(QListWidgetItem*) ));

  //filter
  connect (scriptWidget_->filterButton, SIGNAL( clicked() ),
           this,                          SLOT( slotApplyFilter() ));
  connect (scriptWidget_->resetButton, SIGNAL( clicked() ),
           scriptWidget_->functionList,  SLOT( reset() ));
  connect (scriptWidget_->resetButton, SIGNAL( clicked() ),
           scriptWidget_->filterEdit,  SLOT( clear() ));
  connect (scriptWidget_->functionList, SIGNAL(getDescription(QString,QString&,QStringList&,QStringList&)),
           this                       , SIGNAL(getDescription(QString,QString&,QStringList&,QStringList&)));

  scriptWidget_->description->setVisible( false );

  highlighterCurrent_ = new Highlighter( scriptWidget_->currentScript );
  highlighterLive_    = new Highlighter( scriptWidget_->liveEdit );
//   highlighterList_    = new Highlighter( scriptWidget_->functionList  );
  frameTime_.start();
}

void ScriptingPlugin::slotApplyFilter(){
  scriptWidget_->functionList->filter( scriptWidget_->filterEdit->text() );
}

void ScriptingPlugin::slotEnableSave(){
  scriptWidget_->actionSave_Script->setEnabled( true );
}

void ScriptingPlugin::showScriptWidget( ) {
  if ( OpenFlipper::Options::nogui() )
    return;

  scriptWidget_->show();

  // Update list of available functions
  QStringList completeList;
  emit getAvailableFunctions( completeList  );

  QStringList plugins;
  QStringList functions;

  scriptWidget_->functionList->clear( );

  //Update Highlighters
  for ( int i = 0  ; i <  completeList.size() ; ++i) {

    QString plugin   = completeList[i].section('.',0,0);
    if ( ! plugins.contains( plugin ) )
      plugins.push_back( plugin );


    QString function = completeList[i].section('.',1,1);
    function         = function.section('(',0,0);
    if ( ! functions.contains( function ) )
      functions.push_back( function );

    scriptWidget_->functionList->addItem( completeList[i] );

  }

  highlighterCurrent_->pluginPatterns_   = plugins;
  highlighterCurrent_->functionPatterns_ = functions;
  highlighterCurrent_->update();
  highlighterCurrent_->rehighlight();

  highlighterLive_->pluginPatterns_      = plugins;
  highlighterLive_->functionPatterns_    = functions;
  highlighterLive_->update();
  highlighterLive_->rehighlight();

//   highlighterList_->pluginPatterns_      = plugins;
//   highlighterList_->functionPatterns_    = functions;
//   highlighterList_->update();
//   highlighterList_->rehighlight();

}

void ScriptingPlugin::hideScriptWidget( ) {
  if ( OpenFlipper::Options::nogui() )
    return;

  scriptWidget_->hide();
}

void ScriptingPlugin::slotScriptInfo( QString _pluginName , QString _functionName  ) {

  if ( OpenFlipper::Options::scripting() || OpenFlipper::Options::nogui()  )
    return;

  scriptWidget_->liveEdit->append( _pluginName + "." + _functionName );

  QScrollBar* bar = scriptWidget_->liveEdit->verticalScrollBar();
  bar->setValue(bar->maximum());
}

void ScriptingPlugin::slotExecuteScript( QString _script ) {
252
253
254
255

  if ( OpenFlipper::Options::gui())
    statusBar_->showMessage(tr("Executing Script"));

Jan Möbius's avatar
 
Jan Möbius committed
256
257
258
259
260
261
262
263
264
265
  QScriptEngine* engine;
  emit getScriptingEngine( engine  );

  /// Switch scripting mode on
  OpenFlipper::Options::scripting(true);


  // Get the filename of the script and set it in the scripting environment
  engine->globalObject().setProperty("ScriptPath",QScriptValue(engine,lastFile_.section(OpenFlipper::Options::dirSeparator(), 0, -2)));

266
  // Execute the script
Jan Möbius's avatar
 
Jan Möbius committed
267
  engine->evaluate( _script );
268
269
270

  // Catch errors and print some reasonable error message to log and statusbar
  bool error = false;
Jan Möbius's avatar
 
Jan Möbius committed
271
  if ( engine->hasUncaughtException() ) {
272
    error = true;
Jan Möbius's avatar
 
Jan Möbius committed
273
274
    QScriptValue result = engine->uncaughtException();
    QString exception = result.toString();
275
276
277
278
279
    int lineNumber = engine->uncaughtExceptionLineNumber();
    emit log( LOGERR , tr("Script execution failed at line %1, with : %2 ").arg(lineNumber).arg(exception) );

    if ( OpenFlipper::Options::gui())
        statusBar_->showMessage(tr("Script execution failed at line %1, with : %2 ").arg(lineNumber).arg(exception));
Jan Möbius's avatar
 
Jan Möbius committed
280
281
  }

282
283
284
  if ( OpenFlipper::Options::gui() && !error)
    statusBar_->clearMessage();

Jan Möbius's avatar
 
Jan Möbius committed
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
  /// Switch scripting mode off
  OpenFlipper::Options::scripting(false);
}

void ScriptingPlugin::slotExecuteFileScript( QString _filename ) {
  QString script;

  QFile data(_filename);
  if (data.open(QFile::ReadOnly)) {
    QTextStream input(&data);
    do {
      script.append(input.readLine() + "\n");
    } while (!input.atEnd());

    if ( OpenFlipper::Options::gui() )
      scriptWidget_->currentScript->setText(script);

    // Set lastfilename to the opened file
    lastFile_ = _filename;

    slotExecuteScript(script);

  } else
Dirk Wilden's avatar
Dirk Wilden committed
308
    emit log(LOGERR,tr("Unable to open script file!"));
Jan Möbius's avatar
 
Jan Möbius committed
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
}

void ScriptingPlugin::slotExecuteScriptButton() {
  slotExecuteScript( scriptWidget_->currentScript->toPlainText() );
}

QString ScriptingPlugin::mangleScript(QString _input ) {

  // Update list of available functions
  QStringList functions;
  emit getAvailableFunctions( functions  );

  std::cerr << "Todo : mangle script " << std::endl;
  return _input;

}

void ScriptingPlugin::sleep( int _seconds ) {

  if ( OpenFlipper::Options::nogui() )
    return;

  QTimer timer;

  timer.setSingleShot(true);
  timer.start( _seconds * 1000 );

  while (timer.isActive() )
    QApplication::processEvents();

}

void ScriptingPlugin::sleepmsecs( int _mseconds ) {

  if ( OpenFlipper::Options::nogui() )
    return;

  QTimer timer;

  timer.setSingleShot(true);
  timer.start( _mseconds );

  while (timer.isActive() )
    QApplication::processEvents();

}

void ScriptingPlugin::frameStart( ) {
  frameTime_.restart();
}

void ScriptingPlugin::waitFrameEnd( int _mseconds ) {
  int elapsed = frameTime_.elapsed();

  // Wait remaining time
  if ( elapsed < _mseconds ) {
    sleepmsecs( _mseconds - elapsed );
  }

  // restart timer
  frameTime_.restart();

}


void ScriptingPlugin::waitContinue( ) {
  if ( OpenFlipper::Options::nogui() )
    return;

  QMessageBox box;

Dirk Wilden's avatar
Dirk Wilden committed
380
381
  box.addButton(tr("Continue"),QMessageBox::AcceptRole);
  box.setText(tr("Script execution has been interrupted"));
Jan Möbius's avatar
 
Jan Möbius committed
382
383
  box.setIcon(QMessageBox::Information);
  box.setWindowModality(Qt::NonModal);
Dirk Wilden's avatar
Dirk Wilden committed
384
  box.setWindowTitle(tr("Continue?"));
Jan Möbius's avatar
 
Jan Möbius committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
  box.setWindowFlags( box.windowFlags() | Qt::WindowStaysOnTopHint);
  box.show();

  while ( box.isVisible() )
    QApplication::processEvents();

}

void ScriptingPlugin::waitContinue( QString _msg, int _x, int _y ) {
  if ( OpenFlipper::Options::nogui() )
    return;

  QMessageBox box;


Dirk Wilden's avatar
Dirk Wilden committed
400
  box.addButton(tr("Continue"),QMessageBox::AcceptRole);
Jan Möbius's avatar
 
Jan Möbius committed
401
402
403
  box.setText(_msg);
  box.setIcon(QMessageBox::Information);
  box.setWindowModality(Qt::NonModal);
Dirk Wilden's avatar
Dirk Wilden committed
404
  box.setWindowTitle(tr("Continue?"));
Jan Möbius's avatar
 
Jan Möbius committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  box.setWindowFlags( box.windowFlags() | Qt::WindowStaysOnTopHint);
  if(_x!=-1 && _y!=-1)
    box.move(_x,_y);
  box.show();

  while ( box.isVisible() )
    QApplication::processEvents();

}


void ScriptingPlugin::slotLoadScript(){
  QString filename = QFileDialog::getOpenFileName(0,
     tr("Load Script"),OpenFlipper::Options::currentScriptDirStr(), tr("Script Files (*.ofs)"));

  if (filename == "")
    return;
422
423
424
  
  slotLoadScript(filename);
}
Jan Möbius's avatar
 
Jan Möbius committed
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
void ScriptingPlugin::slotLoadScript( QString _filename ) {
  
  if (_filename == "")
      return;
    
  // Check if we are in gui mode. Otherwise just ignore this call
  if ( OpenFlipper::Options::gui() ) {
    scriptWidget_->currentScript->clear();
  
    QFile data(_filename);
    
    if (data.open(QFile::ReadOnly)) {
      QTextStream input(&data);
      do {
        scriptWidget_->currentScript->append(input.readLine());
      } while (!input.atEnd());
      
      lastFile_ = _filename;
      OpenFlipper::Options::currentScriptDir( QFileInfo(_filename).absolutePath() );
      
      scriptWidget_->actionSave_Script->setEnabled( false );
      
      scriptWidget_->show();
    }
  }
  
Jan Möbius's avatar
 
Jan Möbius committed
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
}

void ScriptingPlugin::slotSaveScript(){

  QFile file(lastFile_);

  if ( !file.exists())
    slotSaveScriptAs();
  else{
    //write script to file
    if (file.open(QFile::WriteOnly)) {
      QTextStream output(&file);
      output << scriptWidget_->currentScript->toPlainText();
    }
    scriptWidget_->actionSave_Script->setEnabled( false );
  }
}

void ScriptingPlugin::slotSaveScriptAs(){
  QString filename = QFileDialog::getSaveFileName(scriptWidget_,
     tr("Save Script"),OpenFlipper::Options::currentScriptDirStr(), tr("Script Files (*.ofs)"));

  if (filename == "") return;

  QFile data(filename);

  //perhaps add an extension
  if (!data.exists()){
    QFileInfo fi(filename);
    if (fi.completeSuffix() == ""){
      filename = filename + ".ofs";
      data.setFileName(filename);
    }
  }

  //write script to file
  if (data.open(QFile::WriteOnly)) {
    QTextStream output(&data);
    output << scriptWidget_->currentScript->toPlainText();
 }

 lastFile_ = filename;

  OpenFlipper::Options::currentScriptDir( QFileInfo(filename).absolutePath() );
  scriptWidget_->actionSave_Script->setEnabled( false );
}

void ScriptingPlugin::slotFunctionClicked(QListWidgetItem * _item)
{

  QString slotDescription;
  QStringList params;
  QStringList descriptions;

  emit getDescription(_item->text(), slotDescription, params, descriptions);

  if ( !slotDescription.isEmpty() ){

    if (descriptionLabels_.count() > 0){
      //first remove old stuff
      for (int i = 0; i < descriptionLabels_.count(); i++){
        descrLayout_->removeWidget( descriptionLabels_[i] );
        delete descriptionLabels_[i];
      }
      descriptionLabels_.clear();
    }else
      descrLayout_ = new QVBoxLayout();

    QLabel* lSlotName = new QLabel("<B>" + _item->text() + "</B>");
    QLabel* lDescription = new QLabel(slotDescription);
    lDescription->setWordWrap(true);

    descrLayout_->addWidget(lSlotName);
    descrLayout_->addWidget(lDescription);

    descriptionLabels_.append(lSlotName);
    descriptionLabels_.append(lDescription);

    if ( params.count() == descriptions.count() ){

      //get parameter-types from function-name
      QString typeStr = _item->text().section("(",1,1).section(")",0,0);
      QStringList types = typeStr.split(",");

      if (types.count() == params.count()){

        for(int p=0; p < params.count(); p++ ){
          QLabel* param = new QLabel("<B>" + types[p] + " " + params[p] + ":</B>" );
          QLabel* descr = new QLabel(descriptions[p]);
          descr->setWordWrap(true);
          descrLayout_->addWidget(param);
          descrLayout_->addWidget(descr);

          descriptionLabels_.append(param);
          descriptionLabels_.append(descr);
        }

      }

    }


    scriptWidget_->description->setLayout( descrLayout_ );
  }

  scriptWidget_->description->setVisible( !slotDescription.isEmpty() );
}

void ScriptingPlugin::slotFunctionDoubleClicked(QListWidgetItem * _item)
{
  scriptWidget_->currentScript->insertPlainText( _item->text() );
}

565
566
567
568
569
570
571
572
573
574
void ScriptingPlugin::showScriptInEditor(QString _code)
{
  if ( OpenFlipper::Options::nogui() )
    return;

  showScriptWidget ();

  scriptWidget_->currentScript->setText (_code);
}

575
576
577
578
void ScriptingPlugin::clearEditor() {
  scriptWidget_->currentScript->clear();
}

Jan Möbius's avatar
 
Jan Möbius committed
579
580
Q_EXPORT_PLUGIN2( skriptingplugin , ScriptingPlugin );