Skip to content
This repository
branch: topic/supernov…
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 529 lines (442 sloc) 14.002 kb
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
/************************************************************************
*
* Copyright 2010-2011 Jakob Leben (jakob.leben@gmail.com)
*
* This file is part of SuperCollider Qt GUI.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
************************************************************************/

#include "QObjectProxy.h"
#include "QcApplication.h"
#include "Common.h"
#include "Slot.h"
#include "QcSignalSpy.h"

#include <QApplication>
#include <QWidget>
#include <QVarLengthArray>
#include <QThread>

#include <PyrKernel.h>
#include <VMGlobals.h>

using namespace QtCollider;

void interpretMouseEvent( QEvent *e, QList<QVariant> &args );
void interpretKeyEvent( QEvent *e, QList<QVariant> &args );

QObjectProxy::QObjectProxy( QObject *qObject_, PyrObject *scObject_ )
: qObject( qObject_ ),
  _scObject( scObject_ ),
  _scClassName( slotRawSymbol( &scObject_->classptr->name )->name )
{
  ProxyToken *token = new ProxyToken( this, qObject );
  // WARNING: make sure the signal is already in normalized signature,
  // to avoid triggering very expensive normalization!
  connect( qObject, SIGNAL(destroyed(QObject*)), this, SLOT(invalidate()) );
  qObject->installEventFilter( this );
  _eventHandlers.reserve(10);
}

QObjectProxy::~QObjectProxy()
{
  qcProxyDebugMsg( 1, QString("Proxy is being deleted.") );
}

bool QObjectProxy::compareThread() {
  return gMainVMGlobals->canCallOS;
}

void QObjectProxy::invalidate() {
  qcProxyDebugMsg( 1, QString("Object has been deleted. Invalidating proxy.") );
  mutex.lock(); qObject = 0; mutex.unlock();
  QApplication::postEvent( this, new QEvent((QEvent::Type) QtCollider::Event_Proxy_Release) );
}

bool QObjectProxy::invokeMethod( const char *method, PyrSlot *retSlot, PyrSlot *argSlot,
                                 Qt::ConnectionType ctype )
{
  mutex.lock();
  if( !qObject ) {
    mutex.unlock();
    return true;
  }

  // the signature char array
  QVarLengthArray<char, 512> sig;

  // serialize method name
  int len = qstrlen( method );
  if( len <= 0 ) {
    mutex.unlock();
    return false;
  }
  sig.append( method, len );
  sig.append( '(' );

  // get data from argument slots
  QtCollider::Variant argSlots[10];

  if( isKindOfSlot( argSlot, class_array ) ) {
    PyrSlot *slots = slotRawObject( argSlot )->slots;
    int size = slotRawObject( argSlot )->size;
    int i;
    for( i = 0; i<size && i<10; ++i ) {
      argSlots[i].setData( slots );
      ++slots;
    }
  }
  else argSlots[0].setData( argSlot );

  // serialize argument types
  int i;
  for( i = 0; i < 10; ++i ) {
    int type = argSlots[i].type();
    if( type == QMetaType::Void ) break;
    const char *typeName = QMetaType::typeName( type );
    int len = qstrlen( typeName );
    if( len <= 0 ) break;
    sig.append( typeName, len );
    sig.append( ',' );
  }

  // finalize the signature
  if( i==0 ) sig.append( ')' );
  else sig[sig.size() - 1] = ')';

  sig.append('\0');

  // get the meta method
  const QMetaObject *mo = qObject->metaObject();

  int mi = mo->indexOfMethod( sig.constData() );
  if( mi < 0 ) {
    QByteArray mnorm = QMetaObject::normalizedSignature( sig.constData() );
    mi = mo->indexOfMethod( mnorm.constData() );
  }

  if( mi < 0 || mi >= mo->methodCount() ) {
    qcProxyDebugMsg( 1, QString("WARNING: No such method: %1::%2").arg( mo->className() )
                        .arg( sig.constData() ) );
    mutex.unlock();
    return false;
  }

  QMetaMethod mm = mo->method( mi );

  // construct the return data object
  QGenericReturnArgument retGArg;
  const char *retTypeName = mm.typeName();
  int retType = QMetaType::type( retTypeName );
  void *retPtr = 0;
  if( retSlot ) {
    retPtr = QMetaType::construct( retType );
    retGArg = QGenericReturnArgument( retTypeName, retPtr );
  }

  //do it!
  bool success =
    mm.invoke( qObject, ctype, retGArg,
                argSlots[0].asGenericArgument(),
                argSlots[1].asGenericArgument(),
                argSlots[2].asGenericArgument(),
                argSlots[3].asGenericArgument(),
                argSlots[4].asGenericArgument(),
                argSlots[5].asGenericArgument(),
                argSlots[6].asGenericArgument(),
                argSlots[7].asGenericArgument(),
                argSlots[8].asGenericArgument(),
                argSlots[9].asGenericArgument());

  // store the return data into the return slot
  if( success && retPtr ) {
    QVariant retVar( retType, retPtr );
    Slot::setVariant( retSlot, retVar );
  };

  if( retPtr )
    QMetaType::destroy( retType, retPtr );

  mutex.unlock();
  return success;
}

void QObjectProxy::invokeScMethod
( PyrSymbol *method, const QList<QVariant> & args, PyrSlot *result,
  bool locked )
{
  qcProxyDebugMsg(1, QString("SC METHOD CALL [+++]: ") + QString(method->name) );

  if( !locked ) {
    QtCollider::lockLang();
  }

  if( _scObject ) {
    QtCollider::runLang( _scObject, method, args, result );
  }
  else {
    if(result) SetNil( result );
    qcDebugMsg(1, "WARNING: no SC object");
  }

  if( !locked ) QtCollider::unlockLang();

  qcProxyDebugMsg(1, QString("SC METHOD CALL [---]: ") + QString(method->name) );
}

void QObjectProxy::customEvent( QEvent *event )
{
  switch ( event->type() ) {
    case (QEvent::Type) QtCollider::Event_ScMethodCall:
      scMethodCallEvent( static_cast<ScMethodCallEvent*>(event) );
      return;
    case (QEvent::Type) QtCollider::Event_Proxy_SetProperty:
      setPropertyEvent( static_cast<SetPropertyEvent*>(event) );
      return;
    case (QEvent::Type) QtCollider::Event_Proxy_Destroy:
      destroyEvent( static_cast<DestroyEvent*>(event) );
      return;
    case (QEvent::Type) QtCollider::Event_Proxy_Release:
      invokeScMethod(SC_SYM(prRelease));
      return;
    default: ;
  }
}

bool QObjectProxy::setParent( QObjectProxy *parentProxy ) {
  if( qObject && parentProxy->object() )
    qObject->setParent( parentProxy->object() );

  return true;
}

bool QObjectProxy::setProperty( const char *property, const QVariant & val )
{
  if( !qObject ) return true;
  if( !qObject->setProperty( property, val ) ) {
    qcProxyDebugMsg(1, QString("WARNING: Property '%1' not found. Setting dynamic property.")
                        .arg( property ) );
  }
  return false;
}

bool QObjectProxy::setPropertyEvent( SetPropertyEvent *e )
{
  return setProperty( e->property->name, e->value );
}

QVariant QObjectProxy::property( const char *property )
{
  return qObject ? qObject->property( property ) : QVariant();
}

bool QObjectProxy::setEventHandler( int type, PyrSymbol *method,
                                    QtCollider::Synchronicity sync, bool enable )
{
  EventHandlerData data;
  data.type = type;
  data.method = method;
  data.sync = sync;
  data.enabled = enable;

  EventHandlerData *d = _eventHandlers.data();
  int n = _eventHandlers.size();
  while(n--)
  {
      if(d->type == type)
      {
          *d = data;
          break;
      }
      ++d;
  }
  if(n < 0)
      _eventHandlers.append(data);

  return true;
}

bool QObjectProxy::setEventHandlerEnabled( int type, bool enabled )
{
  EventHandlerData *d = _eventHandlers.data();
  int n = _eventHandlers.size();
  while(n--)
  {
      if(d->type == type)
      {
          d->enabled = enabled;
          break;
      }
      ++d;
  }

  return n >= 0;
}

bool QObjectProxy::connectObject( const char *signal, PyrObject *object,
                                    Qt::ConnectionType ctype )
{
  if( !qObject ) return true;

  QcFunctionSignalHandler *handler =
    new QcFunctionSignalHandler( this, signal, object, ctype );

  if( !handler->isValid() ) { delete handler; return false; }

  funcSigHandlers.append( handler );

  return true;
}

bool QObjectProxy::connectMethod( const char *signal, PyrSymbol *method,
                                  Qt::ConnectionType ctype )
{
  if( !qObject ) return true;

  QcMethodSignalHandler *handler =
    new QcMethodSignalHandler( this, signal, method, ctype );

  if( handler->isValid() ) {
    methodSigHandlers.append( handler );
    return true;
  }
  else {
    delete handler;
    return false;
  }
}

bool QObjectProxy::disconnectObject( const char *sig, PyrObject *object )
{
  if( !qObject ) return true;

  const QMetaObject *mo = qObject->metaObject();
  QByteArray signal = QMetaObject::normalizedSignature( sig );
  int sigId = mo->indexOfSignal( signal );
  if( sigId < 0 ) {
    qcDebugMsg( 1, QString("WARNING: No such signal: '%1'").arg(signal.constData()) );
    return false;
  }

  for( int i = 0; i < funcSigHandlers.size(); ++i ) {
    QcFunctionSignalHandler *h = funcSigHandlers[i];
    if( h->indexOfSignal() == sigId && h->function() == object ) {
      funcSigHandlers.removeAt(i);
      delete h;
      return true;
    }
  }

  return false;
}

bool QObjectProxy::disconnectMethod( const char *sig, PyrSymbol *method)
{
  if( !qObject ) return true;

  const QMetaObject *mo = qObject->metaObject();
  QByteArray signal = QMetaObject::normalizedSignature( sig );
  int sigId = mo->indexOfSignal( signal );
  if( sigId < 0 ) {
    qcDebugMsg( 1, QString("WARNING: No such signal: '%1'").arg(signal.constData()) );
    return false;
  }

  for( int i = 0; i < methodSigHandlers.size(); ++i ) {
    QcMethodSignalHandler *h = methodSigHandlers[i];
    if( h->indexOfSignal() == sigId && h->method() == method ) {
      methodSigHandlers.removeAt(i);
      delete h;
      return true;
    }
  }

  return false;
}

void QObjectProxy::destroy( DestroyAction action )
{
  switch( action ) {
    case DestroyObject:
      delete qObject;
      return;
    case DestroyProxy:
      delete this;
      return;
    case DestroyProxyAndObject:
      delete qObject;
      delete this;
      return;
  }
}

bool QObjectProxy::destroyEvent( DestroyEvent *e )
{
  destroy( e->action() );
  return true;
}

QList<PyrObject*> QObjectProxy::children( PyrSymbol *className )
{
  QList<PyrObject*> scChildren;

  if( !qObject ) return scChildren;

  const QObjectList &children = qObject->children();

  Q_FOREACH( QObject *child, children ) {

    QObjectProxy *proxy = QObjectProxy::fromObject( child );
    if( !proxy ) continue;

    PyrObject * obj = proxy->_scObject;

    if( obj ) {
        if( className && !isKindOf( obj, className->u.classobj ) )
            continue;
        scChildren.append( obj );
    }
  }

  return scChildren;
}

PyrObject *QObjectProxy::parent( PyrSymbol *className )
{
  if( !qObject ) return 0;

  QObject *parent = qObject->parent();

  while( parent ) {
      // see if this parent has a corresponding proxy
      QObjectProxy *proxy = QObjectProxy::fromObject( parent );
      if( proxy ) {
          // if parent does not have a corresponding SC object (it is just
          // being deleted) return no parent;
          PyrObject *scobj = proxy->_scObject;
          if( !scobj ) return 0;

          // if parent SC object is of desired class (or no class specified)
          // return it, else continue
          if( !className || isKindOf( scobj, className->u.classobj ) ) {
              return scobj;
          }
      }

      // if this parent was not appropriate continue to consider the parent's parent
      parent = parent->parent();
  }

  return 0;
}

bool QObjectProxy::eventFilter( QObject * watched, QEvent * event )
{
  int type = event->type();

  EventHandlerData *d = _eventHandlers.data();
  int n = _eventHandlers.size();
  while(n--)
  {
      if(d->type == type)
          break;
      ++d;
  }
  if(n < 0)
  {
      qcProxyDebugMsg(3,QString("No handler for event (%1), forwarding to the widget")
        .arg(type));
      return false;
  }

  QList<QVariant> args;

  if( !filterEvent( watched, event, *d, args ) ) {
    qcProxyDebugMsg(3,QString("Event (%1, %2) not handled, forwarding to the widget")
      .arg(type)
      .arg(event->spontaneous() ? "spontaneous" : "inspontaneous") );
    return false;
  }

  qcProxyDebugMsg(1,QString("Will handle event (%1, %2) -> (%3, %4)")
    .arg(type)
    .arg(event->spontaneous() ? "spontaneous" : "inspontaneous")
    .arg(d->method->name)
    .arg(d->sync == Synchronous ? "sync" : "async") );

  return invokeEventHandler( event, *d, args );
}

bool QObjectProxy::invokeEventHandler( QEvent *event, EventHandlerData &eh, QList<QVariant> & args )
{
  PyrSymbol *method = eh.method;

  if( eh.sync == Synchronous ) {
    PyrSlot result;
    invokeScMethod( method, args, &result );
    if( IsTrue( &result ) ) {
      qcProxyDebugMsg(2,"Event accepted");
      event->accept();
      return true;
    }
    else if( IsFalse( &result ) ) {
      qcProxyDebugMsg(2,"Event ignored");
      event->ignore();
      return true;
    }
  }
  else {
    ScMethodCallEvent *e = new ScMethodCallEvent( method, args );
    QApplication::postEvent( this, e );
  }

  qcProxyDebugMsg(2,"Forwarding event to the system");
  return false;
}

bool QObjectProxy::filterEvent( QObject *, QEvent *e, EventHandlerData & eh, QList<QVariant> & args )
{
  return eh.enabled;
}

inline void QObjectProxy::scMethodCallEvent( ScMethodCallEvent *e )
{
  invokeScMethod( e->method, e->args, 0, e->locked );
}

QObjectProxy * QObjectProxy::fromObject( QObject *object )
{
  const QObjectList &children = object->children();
  Q_FOREACH( QObject *child, children ) {
    ProxyToken *token = qobject_cast<QtCollider::ProxyToken*>( child );
    if( token ) return token->proxy;
  }
  return 0;
}
Something went wrong with that request. Please try again.