예제 #1
0
void RivenOptionsDialog::handleCommand(GUI::CommandSender *sender, uint32 cmd, uint32 data) {
	switch (cmd) {
	case GUI::kOKCmd:
		_vm->_vars["azip"] = _zipModeCheckbox->getState() ? 1 : 0;
		_vm->_vars["waterenabled"] = _waterEffectCheckbox->getState() ? 1 : 0;
		_vm->_vars["transitionmode"] = _transitionModePopUp->getSelectedTag();
		setResult(1);
		close();
		break;
	case kQuitCmd: {
		Common::Event eventQ;
		eventQ.type = Common::EVENT_QUIT;
		g_system->getEventManager()->pushEvent(eventQ);
		close();
		break;
	}
	default:
		MohawkOptionsDialog::handleCommand(sender, cmd, data);
	}
}
예제 #2
0
LoginDialog::LoginDialog()
        : LoginDlgBase(NULL, "logindlg", true)
{
    setIcon(Pict("licq"));
    bLogin = false;
    edtUIN->setValidator(new QIntValidator(100000, 0x7FFFFFFF, this));
    connect(edtUIN, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&)));
    edtPasswd->setEchoMode(QLineEdit::Password);
    connect(edtPasswd, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&)));
    connect(chkOldUser, SIGNAL(toggled(bool)), this, SLOT(setOldUser(bool)));
    connect(btnClose, SIGNAL(clicked()), this, SLOT(close()));
    connect(btnLogin, SIGNAL(clicked()), this, SLOT(login()));
    connect(btnProxy, SIGNAL(clicked()), this, SLOT(proxySetup()));
    setOldUser(false);
    textChanged("");
    QSize s = sizeHint();
    QWidget *desktop = QApplication::desktop();
    move((desktop->width() - s.width()) / 2, (desktop->height() - s.height()) / 2);
    setResult(0);
};
예제 #3
0
void MxfWriter::run()
{
    int i = 0;

    opendcpMxf->mxf.frame_done.callback = MxfWriter::frameDoneCb;
    opendcpMxf->mxf.frame_done.argument = this;

    filelist_t *fileList = filelist_alloc(mxfFileList.size());

    while (!mxfFileList.isEmpty()) {
        sprintf(fileList->files[i++],"%s",mxfFileList.takeFirst().absoluteFilePath().toUtf8().data());
    }

    rc = write_mxf(opendcpMxf, fileList, mxfOutputFile.toUtf8().data());

    filelist_free(fileList);

    emit setResult(rc);
    emit finished();
}
예제 #4
0
파일: latencytask.cpp 프로젝트: dotse/bbk
bool LatencyTask::requestComplete(HttpClientConnection *conn) {
    auto p = current_request.find(conn->contents());
    if (p == current_request.end()) {
        log() << "unexpected response: " << conn->contents();
    } else {
        double latency = secondsSince(p->second);
        log() << "got " << conn->contents() << " after " << latency << " sec";
        samples.push_back(latency);
    }

    if (samples.size() < 12)
        return true;

    if (!terminated()) {
        log() << "Samples: " << json11::Json(samples).dump();
        setResult(calculateLatency(samples));
    }

    return false;
}
예제 #5
0
파일: dialog.cpp 프로젝트: 86400/scummvm
void Dialog::handleKeyDown(Common::KeyState state) {
	if (_focusedWidget) {
		if (_focusedWidget->handleKeyDown(state))
			return;
	}

	// Hotkey handling
	if (state.ascii != 0) {
		Widget *w = _firstWidget;
		state.ascii = toupper(state.ascii);
		while (w) {
			if (w->_type == kButtonWidget && state.ascii == toupper(((ButtonWidget *)w)->_hotkey)) {
				// The hotkey for widget w was pressed. We fake a mouse click into the
				// button by invoking the appropriate methods.
				w->handleMouseDown(0, 0, 1, 1);
				w->handleMouseUp(0, 0, 1, 1);
				return;
			}
			w = w->_next;
		}
	}

	// ESC closes all dialogs by default
	if (state.keycode == Common::KEYCODE_ESCAPE) {
		setResult(-1);
		close();
	}

	if (state.keycode == Common::KEYCODE_TAB) {
		// TODO: Maybe add Tab behaviours for all widgets too.
		// searches through widgets on screen for tab widget
		Widget *w = _firstWidget;
		while (w) {
			if (w->_type == kTabWidget)
				if (w->handleKeyDown(state))
					return;

			w = w->_next;
		}
	}
}
예제 #6
0
int GtkFileDialog::exec() {
    d->setModality(windowModality());

    bool deleteOnClose = testAttribute(Qt::WA_DeleteOnClose);
    setAttribute(Qt::WA_DeleteOnClose, false);

    bool wasShowModal = testAttribute(Qt::WA_ShowModal);
    setAttribute(Qt::WA_ShowModal, true);
    setResult(0);

    show();

    QPointer<QDialog> guard = this;
    d->exec();
    if (guard.isNull())
        return QDialog::Rejected;

    setAttribute(Qt::WA_ShowModal, wasShowModal);

    return result();
}
예제 #7
0
//---------------------------------------------------------------------------------------------------------------------
void ConfigDialog::Apply()
{
    switch (contentsWidget->currentRow())
    {
        case (0):
            configurationPage->Apply();
            break;
        case (1):
            patternPage->Apply();
            break;
        case (2):
            communityPage->Apply();
            break;
        case (3):
            pathPage->Apply();
            break;
        default:
            break;
    }
    setResult(QDialog::Accepted);
}
예제 #8
0
MStatus tm_polySlot::undoIt()
//
//	Description:
//		implements undo for the MEL tm_polySlot command.  
//
//		This method is called to undo a previous command of this type.  The 
//		system should be returned to the exact state that it was it previous 
//		to this command being executed.  That includes the selection state.
//
//	Return Value:
//		MS::kSuccess - command succeeded
//		MS::kFailure - redoIt failed.  this is a serious problem that will
//                     likely cause the undo queue to be purged
//
{
	MStatus status;
	status = undoModifyPoly();
	if( !status) setResult( "tm_polySlot undo failed!" );
	MGlobal::setActiveSelectionList( oldSelList);
 	return status;
}
예제 #9
0
void c_GenMapWaitHandle::onUnblocked() {
  for (;
       m_deps->iter_valid(m_iterPos);
       m_iterPos = m_deps->iter_next(m_iterPos)) {

    Cell* current = tvAssertCell(m_deps->iter_value(m_iterPos));
    assert(current->m_type == KindOfObject);
    assert(current->m_data.pobj->instanceof(c_WaitHandle::classof()));
    auto child = static_cast<c_WaitHandle*>(current->m_data.pobj);

    if (child->isSucceeded()) {
      cellSet(child->getResult(), *current);
    } else if (child->isFailed()) {
      putException(m_exception, child->getException());
    } else {
      assert(child->instanceof(c_WaitHandle::classof()));
      auto child_wh = static_cast<c_WaitableWaitHandle*>(child);

      try {
        if (isInContext()) {
          child_wh->enterContext(getContextIdx());
        }
        detectCycle(child_wh);
        blockOn(child_wh);
        return;
      } catch (const Object& cycle_exception) {
        putException(m_exception, cycle_exception.get());
      }
    }
  }

  if (m_exception.isNull()) {
    setResult(make_tv<KindOfObject>(m_deps.get()));
    m_deps = nullptr;
  } else {
    setException(m_exception.get());
    m_exception = nullptr;
    m_deps = nullptr;
  }
}
예제 #10
0
MStatus tm_polyExtract::doIt( const MArgList& args )
{
	MStatus stat = MS::kSuccess;
	clearResult();

	MArgDatabase argData( syntax(), args);

//	if(argData.isFlagSet( extractFaces_Flag))
	{
		MSelectionList selectionList;
		argData.getObjects( selectionList);
		MStringArray node_names;
		bool result = extractFaces_Func( selectionList, node_names);
		if(!result)
		{
			MGlobal::displayError("tm_polyExtract: extractFaces function call failed.");
			return MStatus::kFailure;
		}
		setResult( node_names);
		return stat;
	}
}
예제 #11
0
void IDBOpenDBRequest::onUpgradeNeeded(const IDBResultData& resultData)
{
    ASSERT(currentThread() == originThreadID());

    Ref<IDBDatabase> database = IDBDatabase::create(*scriptExecutionContext(), connectionProxy(), resultData);
    Ref<IDBTransaction> transaction = database->startVersionChangeTransaction(resultData.transactionInfo(), *this);

    ASSERT(transaction->info().mode() == IndexedDB::TransactionMode::VersionChange);
    ASSERT(transaction->originalDatabaseInfo());

    uint64_t oldVersion = transaction->originalDatabaseInfo()->version();
    uint64_t newVersion = transaction->info().newVersion();

    LOG(IndexedDB, "IDBOpenDBRequest::onUpgradeNeeded() - current version is %" PRIu64 ", new is %" PRIu64, oldVersion, newVersion);

    setResult(WTFMove(database));
    m_isDone = true;
    m_transaction = WTFMove(transaction);
    m_transaction->addRequest(*this);

    enqueueEvent(IDBVersionChangeEvent::create(oldVersion, newVersion, eventNames().upgradeneededEvent));
}
예제 #12
0
bool YouTubeEnclosureRequest::getEnclosure(const QString &url, const QVariantMap &settings) {
    if (status() == Active) {
        return false;
    }

    const QString videoId = url.section(QRegExp("v=|list=|/"), -1).section(QRegExp("&|\\?"), 0, 0);
    
    
    if (videoId.isEmpty()) {
        setErrorString(tr("Cannot extract video ID from URL"));
        setResult(Enclosure());
        setStatus(Error);
        emit finished(this);
        return false;
    }

    m_settings = settings;
    m_settings["videoId"] = videoId;
    setStatus(Active);
    getStreams();
    return true;
}
예제 #13
0
// --------------------------------------------------------------------------
QList<QVariantMap> qMidasAPI::synchronousQuery(
  bool &ok,
  const QString& midasUrl,const QString& method,
  const ParametersType& parameters,
  int maxWaitingTimeInMSecs)
{
  qMidasAPI midasAPI;
  midasAPI.setMidasUrl(midasUrl);
  midasAPI.setTimeOut(maxWaitingTimeInMSecs);
  midasAPI.query(method, parameters);
  qMidasAPIResult queryResult;
  QObject::connect(&midasAPI, SIGNAL(resultReceived(QUuid,QList<QVariantMap>)),
                   &queryResult, SLOT(setResult(QUuid,QList<QVariantMap>)));
  QObject::connect(&midasAPI, SIGNAL(errorReceived(QString)),
                   &queryResult, SLOT(setError(QString)));
  QEventLoop eventLoop;
  QObject::connect(&midasAPI, SIGNAL(resultReceived(QUuid,QList<QVariantMap>)),
                   &eventLoop, SLOT(quit()));
  // Time out will fire an error which will quit the event loop.
  QObject::connect(&midasAPI, SIGNAL(errorReceived(QString)),
                   &eventLoop, SLOT(quit()));
  eventLoop.exec();
  ok = queryResult.Error.isNull();
  if (!ok)
    {
    QVariantMap map;
    map["queryError"] = queryResult.Error;
    queryResult.Result.push_front(map);
    }
  if (queryResult.Result.count() == 0)
    {
    // \tbd
    Q_ASSERT(queryResult.Result.count());
    QVariantMap map;
    map["queryError"] = tr("Unknown error");
    queryResult.Result.push_front(map);
    }
  return queryResult.Result;
}
예제 #14
0
void SearchController::statusAction()
{
    const int id = params()["id"].toInt();

    const auto searchHandlers = sessionManager()->session()->getData<SearchHandlerDict>(SEARCH_HANDLERS);
    if ((id != 0) && !searchHandlers.contains(id))
        throw APIError(APIErrorType::NotFound);

    QJsonArray statusArray;
    const QList<int> searchIds {(id == 0) ? searchHandlers.keys() : QList<int> {id}};

    for (const int searchId : searchIds) {
        const SearchHandlerPtr searchHandler = searchHandlers[searchId];
        statusArray << QJsonObject {
            {"id", searchId},
            {"status", searchHandler->isActive() ? "Running" : "Stopped"},
            {"total", searchHandler->results().size()}
        };
    }

    setResult(statusArray);
}
MStatus CMayaGetFolder::doIt( const MArgList &args )
{
	BROWSEINFO browseInfo = 
	{
		NULL,
		NULL,
		NULL,
		"Select folder",
		NULL,
		NULL,
		NULL
	};
	LPITEMIDLIST itemList = SHBrowseForFolder(&browseInfo);	
	if(itemList)
	{
		char folder[MAX_PATH];
		SHGetPathFromIDList(itemList, folder);
		setResult(folder);
	}

	return MStatus::kSuccess;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
MStatus CVstSelectCoincidentFacesCmd::redoIt()
{
	MStatus mStatus;

	if ( !mStatus )
	{
		setResult( MString( "Cannot parse command line" ) + mStatus.errorString() );
		return MS::kFailure;
	}

	const MArgDatabase &mArgDatabase( m_undo.ArgDatabase() );

	m_undo.SaveCurrentSelection();

	if ( mArgDatabase.isFlagSet( kOptHelp ) )
	{
		GetSyntaxHelp()->PrintHelp( GetName(), GetDesc() );
		return MS::kSuccess;
	}

	return DoSelect();
}
예제 #17
0
int K3bInteractionDialog::exec( bool returnOnHide )
{
  m_exitLoopOnHide = returnOnHide;

  // the following code is mainly taken from QDialog::exec

  if( m_inLoop ) {
    kdError() << "(K3bInteractionDialog::exec) Recursive call detected." << endl;
    return -1;
  }

  bool destructiveClose = testWFlags( WDestructiveClose );
  clearWFlags( WDestructiveClose );

  bool wasShowModal = testWFlags( WShowModal );
  setWFlags( WShowModal );
  setResult( 0 );

  loadStartupSettings();
  show();
  if( m_delayedInit )
    QTimer::singleShot( 0, this, SLOT(slotDelayedInit()) );
  else
    init();

  m_inLoop = true;
  QApplication::eventLoop()->enterLoop();

  if( !wasShowModal )
    clearWFlags( WShowModal );

  int res = result();

  if( destructiveClose )
    delete this;

  return res;
}
HxUniformScalarField3* HxMovingLeastSquaresWarp::createOutputDataSet() {
    HxUniformScalarField3* fromImage =
        dynamic_cast<HxUniformScalarField3*>(portFromImage.getSource());
    HxUniformScalarField3* toImage =
        dynamic_cast<HxUniformScalarField3*>(portToImage.getSource());
    HxUniformScalarField3* warpedImage =
        dynamic_cast<HxUniformScalarField3*>(getResult(0));

    if (!fromImage)
        return (0);

    McDim3l dims;
    McBox3f bbox;

    if (toImage) {
        dims = toImage->lattice().getDims();
        bbox = toImage->getBoundingBox();
    }
    if (!warpedImage || warpedImage->lattice().getDims()[0] != dims[0] ||
        warpedImage->lattice().getDims()[1] != dims[1] ||
        warpedImage->lattice().getDims()[2] != dims[2])
        warpedImage = 0;

    if (!warpedImage) {
        if (toImage->isOfType(HxUniformLabelField3::getClassTypeId())) {
            warpedImage = new HxUniformLabelField3(dims);
            ((HxUniformLabelField3*)warpedImage)->parameters =
                ((HxUniformLabelField3*)fromImage)->parameters;
        } else
            warpedImage =
                new HxUniformScalarField3(dims, fromImage->primType());
    }

    warpedImage->setBoundingBox(bbox);
    warpedImage->composeLabel(fromImage->getLabel(), "Warped");
    setResult(0, warpedImage);
    return (warpedImage);
}
예제 #19
0
void YouTubeEnclosureRequest::checkStreams() {
    if (m_streamsRequest->status() == QYouTube::StreamsRequest::Ready) {
        const QVariantList items = m_streamsRequest->result().toList();
        const int start = qMax(0, VIDEO_FORMATS.indexOf(m_settings.value("videoFormat", "22").toString()));
        
        for (int i = start; i < VIDEO_FORMATS.size(); i++) {
            foreach (const QVariant &item, items) {
                const QVariantMap stream = item.toMap();

                if (stream.value("id") == VIDEO_FORMATS.at(i)) {
                    m_result.request = QNetworkRequest(stream.value("url").toString());
                    getVideo();
                    return;
                }
            }
        }

        setErrorString(tr("No video streams found"));
        setResult(Enclosure());
        setStatus(Error);
        emit finished(this);
    }
    else if (m_streamsRequest->status() == QYouTube::StreamsRequest::Failed) {
예제 #20
0
void CalDialog::waitButton(int axis, bool press, int &lastVal)
{
  JoyDevice::EventType type;
  int number, value;
  bool button = false;
  lastVal = 0;

  setResult(-1);
  // loop until the user presses a button on the device or on the dialog
  do
  {
    qApp->processEvents(QEventLoop::AllEvents, 100);

    if ( joydev->getEvent(type, number, value) )
    {
      button = ( (type == JoyDevice::BUTTON) && (press ? (value == 1) : (value == 0)) );

      if ( (type == JoyDevice::AXIS) && (number == axis) )
        valueLbl->setText(i18n("Value Axis %1: %2", axis+1, lastVal = value));
    }
  }
  while ( !button && (result() == -1) );
}
예제 #21
0
 void _q_onDownloadRedirect() {
     if (!reply) {
         return;
     }
     
     if (reply->error() == QNetworkReply::NoError) {
         QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
         
         if (redirect.isEmpty()) {
             redirect = reply->header(QNetworkRequest::LocationHeader).toString();
         }
         
         if (!redirect.isEmpty()) {
             redirect.setScheme("http");
             QString ext = track.value("original_format").toString();
             formats << Format("original", QString("%1 (%2)").arg(StreamsRequest::tr("Original format")).arg(ext.toUpper()),
                               ext, redirect);
         }
     }
     
     reply->deleteLater();
     reply = 0;
         
     if (track.value("streamable").toBool()) {
         getRedirect(track.value("stream_url").toString(), SLOT(_q_onStreamRedirect()));
     }
     else {
         Q_Q(StreamsRequest);
         
         setResult(formats);
         setStatus(Request::Ready);
         setError(Request::NoError);
         setErrorString(QString());
         
         emit q->finished();
     }
 }
예제 #22
0
void ImportTextDialog::convertTextFile() {
    int import_file_fd;
    char *tmpname;
    int err;

    capfile_name_.clear();
    /* Choose a random name for the temporary import buffer */
    import_file_fd = create_tempfile(&tmpname, "import");
    capfile_name_.append(tmpname);

    import_info_.wdh = wtap_dump_fdopen(import_file_fd, WTAP_FILE_TYPE_SUBTYPE_PCAP, import_info_.encapsulation, import_info_.max_frame_length, FALSE, &err);
    qDebug() << capfile_name_ << ":" << import_info_.wdh << import_info_.encapsulation << import_info_.max_frame_length;
    if (import_info_.wdh == NULL) {
        open_failure_alert_box(capfile_name_.toUtf8().constData(), err, TRUE);
        fclose(import_info_.import_text_file);
        setResult(QDialog::Rejected);
        return;
    }

    text_import_setup(&import_info_);

    text_importin = import_info_.import_text_file;

    text_importlex();

    text_import_cleanup();

    if (fclose(import_info_.import_text_file))
    {
        read_failure_alert_box(import_info_.import_text_filename, errno);
    }

    if (!wtap_dump_close(import_info_.wdh, &err))
    {
        write_failure_alert_box(capfile_name_.toUtf8().constData(), err);
    }
}
void c_ExternalThreadEventWaitHandle::process() {
  assert(getState() == STATE_WAITING);

  if (isInContext()) {
    getContext()->unregisterExternalThreadEvent(m_index);
  }

  try {
    TypedValue result;
    m_event->unserialize(&result);
    assert(tvIsPlausible(&result));
    setResult(&result);
    tvRefcountedDecRefCell(&result);
  } catch (const Object& exception) {
    setException(exception.get());
  }

  // event is processed, destroy it, unregister sweepable and decref ownership
  m_event->release();
  m_event = nullptr;
  m_privData = nullptr;
  unregister();
  decRefObj(this);
}
예제 #24
0
void SelfUpdater::DownloadFinished()
{
    if(currentDownload)
    {
        FileManager::Instance()->ClearTempDirectory();

        const QString & archiveFilePath = FileManager::Instance()->GetTempDownloadFilepath();
        const QString & tempDir = FileManager::Instance()->GetTempDirectory();
        const QString & appDir = FileManager::Instance()->GetLauncherDirectory();
        const QString & selfUpdateDir = FileManager::Instance()->GetSelfUpdateTempDirectory();

        QFile archiveFile(archiveFilePath);
        archiveFile.open(QFile::WriteOnly);
        archiveFile.write(currentDownload->readAll());
        archiveFile.close();

        currentDownload->deleteLater();
        currentDownload = 0;

        unpacker->UnZipFile(archiveFilePath, selfUpdateDir);

        FileManager::Instance()->MoveFilesOnlyToDirectory(appDir, tempDir);
        FileManager::Instance()->MoveFilesOnlyToDirectory(selfUpdateDir, appDir);
        FileManager::Instance()->DeleteDirectory(selfUpdateDir);

        ErrorMessanger::Instance()->ShowNotificationDlg("Launcher was updated. Please, relaunch application.");

        qApp->exit();
    }
    else if(lastErrorCode != QNetworkReply::OperationCanceledError)
    {
        setResult(QDialog::Rejected);
        ErrorMessanger::Instance()->ShowErrorMessage(ErrorMessanger::ERROR_NETWORK, lastErrorCode, lastErrorDesrc);
        close();
    }
}
MStatus liqIPRNodeMessage::doIt( const MArgList& args)
//
// Takes the  nodes that are on the active selection list and adds an
// attriubte changed callback to each one.
//
{	
	MStatus 		stat;

	for( unsigned i( 0 ); i < args.length(); i++ ) 
	{
		MString arg = args.asString( i, &stat );
		IfMErrorWarn(stat);

		if( (arg == kRegisterFlag) || (arg == kRegisterFlagLong) ){
			isRunningIPR = 1;
			liqRibTranslator::getInstancePtr()->IPRRenderBegin();
			IfMErrorWarn(registerCallback());
			//liqRibTranslator::getInstancePtr()->IPRDoIt();
		}
		else if( (arg == kUnregisterFlag) || (arg == kUnregisterFlagLong) ){
			IfMErrorWarn(unregisterCallback());

			liqRibTranslator::getInstancePtr()->IPRRenderEnd();
			isRunningIPR = 0;
		}
		else if( (arg == kIsRunningIPR) || (arg == kIsRunningIPRLong) ){
			setResult(isRunningIPR);
		}
		else{
			liquidMessage2(messageError,"Parameter [%s] is undefined in liqIPRNodeMessage.", arg.asChar());
			return MS::kUnknownParameter;
		}
	}

	return MS::kSuccess;
}
예제 #26
0
void DeleteMessageBox::on_btt_No_clicked()
{
    setResult(0);
    hide();
}
예제 #27
0
void DeleteMessageBox::on_btt_yes_clicked()
{
    setResult(1);
    hide();
}
예제 #28
0
    void _q_onReplyFinished() {
        if (!reply) {
            return;
        }
    
        Q_Q(StreamsRequest);
        
        if (redirects < MAX_REDIRECTS) {
            QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
    
            if (redirect.isEmpty()) {
                redirect = reply->header(QNetworkRequest::LocationHeader).toString();
            }
    
            if (!redirect.isEmpty()) {
                reply->deleteLater();
                reply = 0;
                followRedirect(redirect);
                return;
            }
        }
        
        QString response = QString::fromUtf8(reply->readAll());
        QNetworkReply::NetworkError e = reply->error();
        QString es = reply->errorString();
        reply->deleteLater();
        reply = 0;
        
        switch (e) {
        case QNetworkReply::NoError:
            break;
        case QNetworkReply::OperationCanceledError:
            setStatus(Request::Canceled);
            setError(Request::NoError);
            setErrorString(QString());
            emit q->finished();
            return;
        case QNetworkReply::AuthenticationRequiredError:
            if (refreshToken.isEmpty()) {
                setStatus(Request::Failed);
                setError(Request::Error(e));
                setErrorString(es);
                emit q->finished();
            }
            else {
                refreshAccessToken();
            }
        
            return;
        default:
            setStatus(Request::Failed);
            setError(Request::Error(e));
            setErrorString(es);
            emit q->finished();
            return;
        }
        
        bool ok = true;
        track = QtJson::Json::parse(response, ok).toMap();
        formats.clear();
        
        if (ok) {
            if (track.value("downloadable").toBool()) {
                getRedirect(track.value("download_url").toString(), SLOT(_q_onDownloadRedirect()));
                return;
            }
            
            if (track.value("streamable").toBool()) {
                getRedirect(track.value("stream_url").toString(), SLOT(_q_onStreamRedirect()));
                return;
            }
            
            setResult(formats);
            setStatus(Request::Ready);
            setError(Request::NoError);
            setErrorString(QString());
        }
        else {
            setStatus(Request::Failed);
            setError(Request::ParseError);
            setErrorString(Request::tr("Unable to parse response"));
        }

        emit q->finished();
    }
예제 #29
0
TomahawkTrayIcon::TomahawkTrayIcon( QObject* parent )
    : QSystemTrayIcon( parent )
    , m_currentAnimationFrame( 0 )
    , m_showWindowAction( 0 )
    , m_stopContinueAfterTrackAction( 0 )
    , m_loveTrackAction( 0 )
{
#ifdef Q_OS_MAC
    QIcon icon( RESPATH "icons/tomahawk-grayscale-icon-128x128.png" );
#else
    QIcon icon( RESPATH "icons/tomahawk-icon-128x128.png" );
#endif

    setIcon( icon );

    refreshToolTip();

    m_contextMenu = new QMenu();
    m_contextMenu->setFont( TomahawkUtils::systemFont() );
    setContextMenu( m_contextMenu );

    m_loveTrackAction = new QAction( this );
    m_stopContinueAfterTrackAction = new QAction( this );

    ActionCollection *ac = ActionCollection::instance();
    m_contextMenu->addAction( ac->getAction( "playPause" ) );
    m_contextMenu->addAction( ac->getAction( "stop" ) );
    m_contextMenu->addSeparator();
    m_contextMenu->addAction( m_loveTrackAction );
    m_contextMenu->addAction( m_stopContinueAfterTrackAction );
    m_contextMenu->addSeparator();
    m_contextMenu->addAction( ac->getAction( "previousTrack" ) );
    m_contextMenu->addAction( ac->getAction( "nextTrack" ) );
    m_contextMenu->addSeparator();
    m_contextMenu->addAction( ActionCollection::instance()->getAction( "togglePrivacy" ) );

#ifdef Q_OS_MAC
    // On mac you can close the windows while leaving the app open. We then need a way to show the main window again
    m_contextMenu->addSeparator();
    m_showWindowAction = m_contextMenu->addAction( tr( "Hide Tomahawk Window" ) );
    m_showWindowAction->setData( true );
    connect( m_showWindowAction, SIGNAL( triggered() ), this, SLOT( showWindow() ) );

    connect( m_contextMenu, SIGNAL( aboutToShow() ), this, SLOT( menuAboutToShow() ) );
#endif

    m_contextMenu->addSeparator();
    m_contextMenu->addAction( ac->getAction( "quit" ) );

    connect( m_loveTrackAction, SIGNAL( triggered() ), SLOT( loveTrackTriggered() ) );
    connect( m_stopContinueAfterTrackAction, SIGNAL( triggered() ), SLOT( stopContinueAfterTrackActionTriggered() ) );

    connect( AudioEngine::instance(), SIGNAL( loading( Tomahawk::result_ptr ) ), SLOT( setResult( Tomahawk::result_ptr ) ) );
    connect( AudioEngine::instance(), SIGNAL( started( Tomahawk::result_ptr ) ), SLOT( onPlay() ) );
    connect( AudioEngine::instance(), SIGNAL( resumed() ), SLOT( onResume() ) );
    connect( AudioEngine::instance(), SIGNAL( stopped() ), SLOT( onStop() ) );
    connect( AudioEngine::instance(), SIGNAL( paused() ),  SLOT( onPause() ) );
    connect( AudioEngine::instance(), SIGNAL( stopAfterTrackChanged() ), SLOT( onStopContinueAfterTrackChanged() ) );

    connect( &m_animationTimer, SIGNAL( timeout() ), SLOT( onAnimationTimer() ) );
    connect( this, SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ), SLOT( onActivated( QSystemTrayIcon::ActivationReason ) ) );

    onStop();
    show();
}
예제 #30
0
// process a single acquisition
int RtCurrentActivation::process(ACE_Message_Block *mb) {
  ACE_TRACE(("RtCurrentActivation::process"));

  timer tim;
  if(printTiming) {
    tim.start();
  }

  // get pointer to message
  RtStreamMessage *msg = (RtStreamMessage*) mb->rd_ptr();

  // get the current image to operate on
  RtMRIImage *dat = (RtMRIImage*) msg->getCurrentData();

  // check for validity of data
  if (dat == NULL) {
    cerr << "RtCurrentActivation::process: data passed is NULL" << endl;

    if(logOutput) {
      stringstream logs("");
      logs << "RtCurrentActivation::process: data passed is NULL" << endl;
      log(logs);
    }

    return 0;
  }

  // get mask from msg
  RtMaskImage *mask = getMaskFromMessage(*msg);

  // check validity of mask
  if (mask == NULL) {
    cerr << "RtCurrentActivation::process: mask is NULL" << endl;

    if(logOutput) {
      stringstream logs("");
      logs << "RtCurrentActivation::process: mask is NULL at tr "
           << dat->getDataID().getTimePoint() << endl;
      log(logs);
    }

    return 0;
  }

  // initialize the computation if necessary
  if (needsInit) {
    initEstimation(*dat, mask);
  }

  // get design
  // TODO this may not work if there are more than one design matrix
  RtDataID tempDataID;
  tempDataID.setDataName(NAME_DESIGN);

  // debug
  // getDataStore().getAvailableData();

  RtDesignMatrix *design = static_cast<RtDesignMatrix*>(
      getDataStore().getData(tempDataID));

  if(design == NULL) {
    cerr << "error: could not find design matrix in datastore!" << endl;
    cerr << "searched for design matrix id: " << tempDataID << endl;
    return 0;
  }

  // allocate a new data image for the stats
  RtActivation *currentActivation = new RtActivation(*dat);

  // setup the data id
  currentActivation->getDataID().setFromInputData(*dat, *this);
  currentActivation->getDataID().setDataName(NAME_ACTIVATION);
  currentActivation->getDataID().setRoiID(modelFitRoiID);

  currentActivation->initToNans();

  // get the residual and the beta images for discounting nuissance
  // signals

  // find the betas
  RtActivation **betas = new RtActivation*[design->getNumColumns()];
  for(unsigned int j = 0; j < design->getNumColumns(); j++) {
    betas[j] = (RtActivation*) msg->getData(modelFitModuleID,
                                            string(NAME_BETA)
                                            + "_" +
                                            design->getColumnName(j),
                                            modelFitRoiID);
    // check for found
    if (betas[j] == NULL) {
      cerr << "RtCurrentActivation:process: beta " << j << " is null" << endl;

      if(logOutput) {
        stringstream logs("");
        logs << "RtCurrentActivation::process: beta " << j
             << " is NULL at tr "
             << dat->getDataID().getTimePoint() << endl;
        log(logs);
      }

      return 0;
    }
  }

  // get residual from message if timepoint is less than
  // numDataPointsForErrEst otherwise use the steady state
  // residual value
  RtActivation *residual;
  if (dat->getDataID().getTimePoint() < numDataPointsForErrEst) {
    // get residual off of msg
    residual = (RtActivation *) msg->getData(modelFitModuleID,
                                             NAME_RESIDUAL_MSE,
                                             modelFitRoiID);
    // save off residual
    steadyStateResidual = residual;
  }
  else {
    // post-numDataPointsForErrEst, use saved residual
    residual = steadyStateResidual;
  }

  // check that residual is not null
  if (residual == NULL) {
    cerr << "RtCurrentActivation:process: residual is null" << endl;

    if(logOutput) {
      stringstream logs("");
      logs << "RtCurrentActivation::process: residual is NULL at tr "
           << dat->getDataID().getTimePoint() << endl;
      log(logs);
    }

    return 0;
  }

  // get this design matrix row
  vnl_vector<double> Xrow = design->getRow(dat->getDataID().getTimePoint()-1);

  // include this timepoint for each voxel
  RtElementAccess datAc(dat, mask);
  RtElementAccess resAc(residual, mask);
  vector<unsigned int> inds = datAc.getElementIndices();
  for(vector<unsigned int>::iterator it = inds.begin();
      it != inds.end(); it++) {
    // get voxel intensity
    double y = datAc.getDoubleElement(*it);

    double *betavals = new double[Xrow.size()];

    // compute error
    double err = y;
    for (unsigned int j = 0; j < Xrow.size(); j++) {
      if (!design->isColumnOfInterest(j)) {
        double beta = betas[j]->getPixel(*it);
        err -= beta * Xrow[j];
        betavals[j] = beta;
      }
      else { // for debug output
        betavals[j] = betas[j]->getPixel(*it);
      }
    }

    // compute the dev and current activation (magic happens here)
    double dev = sqrt(resAc.getDoubleElement(*it)
                      / (residual->getDataID().getTimePoint()));
    currentActivation->setPixel(*it, err / dev);

    if (dumpAlgoVars && dat->getDataID().getTimePoint() > 2) {
      dumpFile
          << dat->getDataID().getTimePoint() << " "
          << *it << " "
          << y << " "
          << err << " "
          << Xrow[0] << " "
          << residual->getPixel(*it) << " "
          << dev << " "
          << currentActivation->getPixel(*it) << " ";
      for (unsigned int b = 0; b < design->getNumColumns(); b++) {
        dumpFile << betavals[b] << " ";
      }
      dumpFile << endl;
    }

    delete [] betavals;

  }
  setResult(msg, currentActivation);
  setResult(msg, residual);

  delete [] betas;


  if(printTiming) {
    tim.stop();
    cout << "RtCurrentActivation process at tr "
         << dat->getDataID().getTimePoint()
         << " elapsed time: " << tim.elapsed_time()*1000 << "ms"  << endl;
  }

  if(print) {
    cout << "RtCurrentActivation: done at tr "
         << dat->getDataID().getTimePoint() << endl;
  }

  if(logOutput) {
    stringstream logs("");
    logs << "RtCurrentActivation: done at tr "
         << dat->getDataID().getTimePoint() << endl;
    log(logs);
  }

  if(saveResult) {
    string fn = getExperimentConfig().getVolFilename(
        dat->getDataID().getSeriesNum(),
        dat->getDataID().getTimePoint());
    string stem = getExperimentConfig().get("study:volumeFileStem").str();
    currentActivation->setFilename(fn.replace(fn.rfind(stem), stem.size(),
                                              "curact"));
    currentActivation->save();
  }

  return 0;
}