void data_address(TTPtr self, t_symbol *address) { WrappedModularInstancePtr x = (WrappedModularInstancePtr)self; // Avoid succession of address changes if (!EXTRA->changingAddress) { EXTRA->changingAddress = YES; // filter repetitions if (!(x->arrayAddress == TTAddress(address->s_name))) { if (!x->iterateInternals) { // unregister internals wrappedModularClass_unregister(x); x->arraySize = 0; // rebuild internals defer(self,(method)data_new_address, address, 0, NULL); // for array mode : output the array once afterward if (x->arrayAttrFormat == gensym("array")) { TTValue array; t_symbol *msg; long argc = 0; t_atom *argv = NULL; TTBoolean shifted = NO; data_edit_array(self, array); jamoma_ttvalue_to_typed_Atom(array, &msg, &argc, &argv, shifted); // avoid blank before data if (msg == _sym_nothing) outlet_atoms(x->outlets[data_out], argc, argv); else outlet_anything(x->outlets[data_out], msg, argc, argv); if (shifted) argv--; sysmem_freeptr(argv); } } } EXTRA->changingAddress = NO; return; } object_error((t_object*)x, "can't change to %s address. Please defer low", address->s_name); }
void DesktopConnector::jsConnectorReadySlot() { // at this point it's safe to start using setState as the javascript // connector has registered to listen for the signal qDebug() << "JS Connector is ready!!!!"; // time to call the initialize callback defer( std::bind( m_initializeCallback, true)); // m_initializeCallback(true); }
void Waiter::wait() { if (proceeder.unique()) { JLOG("everything done, nothing to do"); return; } defer([this] { auto toDestroy = std::move(proceeder); }); init0(); }
void irphase_process (t_irphase *x, t_symbol *target, t_symbol *source, double phase, double time_mul, t_phase_type mode) { t_atom args[5]; atom_setsym(args + 0, target); atom_setsym(args + 1, source); atom_setfloat(args + 2, phase); atom_setfloat(args + 3, time_mul); atom_setlong(args + 4, mode); defer(x, (method) irphase_process_internal, 0, 5, args); }
TCResult ast::EnumDefn::typecheck(sst::TypecheckState* fs, fir::Type* infer, const TypeParamMap_t& gmaps) { fs->pushLoc(this); defer(fs->popLoc()); auto tcr = this->generateDeclaration(fs, infer, gmaps); if(tcr.isParametric()) return tcr; else if(tcr.isError()) error(this, "failed to generate declaration for enum '%s'", this->name); auto defn = dcast(sst::EnumDefn, tcr.defn()); iceAssert(defn); auto oldscope = fs->getCurrentScope(); fs->teleportToScope(defn->id.scope); fs->pushTree(defn->id.name); if(this->memberType) defn->memberType = fs->convertParserTypeToFIR(this->memberType); else defn->memberType = fir::Type::getInt64(); auto ety = fir::EnumType::get(defn->id, defn->memberType); size_t index = 0; for(auto cs : this->cases) { sst::Expr* val = 0; if(cs.value) { iceAssert(defn->memberType); val = cs.value->typecheck(fs, defn->memberType).expr(); if(val->type != defn->memberType) error(cs.value, "mismatched type in enum case value; expected type '%s', but found type '%s'", defn->memberType, val->type); } auto ecd = util::pool<sst::EnumCaseDefn>(cs.loc); ecd->id = Identifier(cs.name, IdKind::Name); ecd->id.scope = fs->getCurrentScope(); ecd->type = ety; ecd->parentEnum = defn; ecd->val = val; ecd->index = index++; defn->cases[cs.name] = ecd; fs->stree->addDefinition(cs.name, ecd); } defn->type = ety; fs->popTree(); fs->teleportToScope(oldscope); return TCResult(defn); }
void LCD_linesegment(Lcd *x, long fromx, long fromy, long tox, long toy, long color) { Atom a[5]; EnterCallback(); SETLONG(a,fromx); SETLONG(a+1,fromy); SETLONG(a+2,tox); SETLONG(a+3,toy); SETLONG(a+4,color); defer(x,(method)LCD_dolinesegment,0L,5,a); ExitCallback(); }
/*------------------------------------ cmd_Mute ---*/ Pvoid cmd_Mute(QtPtr xx, long muting) { EnterCallback(); #if defined(TRACE_MESSAGES) LOG_POST_1("Mute") #endif /* TRACE_MESSAGES */ if (xx) defer(xx, reinterpret_cast<method>(deferred_Mute), reinterpret_cast<PSymbol>(muting), 0, NULL_PTR); ExitMaxMessageHandler() } /* cmd_Mute */
MirrorWidget::MirrorWidget(Aqpm::Configuration::MirrorType type, QWidget *parent) : QWidget(parent) , m_ui(new Ui::MirrorWidget) , m_type(type) { m_ui->setupUi(this); reloadMirrors(); connect(m_ui->deferButton, SIGNAL(clicked()), this, SIGNAL(defer())); connect(m_ui->preferButton, SIGNAL(clicked()), this, SIGNAL(prefer())); connect(m_ui->removeButton, SIGNAL(clicked()), this, SIGNAL(remove())); }
void LCD_frameRect(Lcd *x, long left, long top, long right, long bottom, long color) { Atom a[5]; EnterCallback(); SETLONG(a,left); SETLONG(a+1,top); SETLONG(a+2,right); SETLONG(a+3,bottom); SETLONG(a+4,color); defer(x,(method)LCD_doframeRect,0L,5,a); ExitCallback(); }
Future<Nothing> acquire() { if (!promises.empty()) { // Need to wait for others to get permits first. Promise<Nothing>* promise = new Promise<Nothing>(); promises.push_back(promise); return promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); } if (timeout.remaining() > Seconds(0)) { // Need to wait a bit longer, but first one in the queue. Promise<Nothing>* promise = new Promise<Nothing>(); promises.push_back(promise); delay(timeout.remaining(), self(), &Self::_acquire); return promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); } // No need to wait! timeout = Seconds(1) / permitsPerSecond; return Nothing(); }
Future<Option<MasterInfo>> detect( const Option<MasterInfo>& previous = None()) { if (leader != previous) { return leader; } Promise<Option<MasterInfo>>* promise = new Promise<Option<MasterInfo>>(); promise->future() .onDiscard(defer(self(), &Self::discard, promise->future())); promises.insert(promise); return promise->future(); }
Future<Future<Nothing>> LeaderContenderProcess::contend() { if (contending.isSome()) { return Failure("Cannot contend more than once"); } LOG(INFO) << "Joining the ZK group"; candidacy = group->join(data, label); candidacy .onAny(defer(self(), &Self::joined)); // Okay, we wait and see what unfolds. contending = new Promise<Future<Nothing>>(); return contending.get()->future(); }
void LeaderContenderProcess::cancel() { if (!candidacy.isReady()) { // Nothing to cancel. if (withdrawing.isSome()) { withdrawing.get()->set(false); } return; } LOG(INFO) << "Now cancelling the membership: " << candidacy->id(); group->cancel(candidacy.get()) .onAny(defer(self(), &Self::cancelled, lambda::_1)); }
bool ShaderProgram::attachShaderFromMemory(ShaderType type, const std::string& source) { if (!handle) handle = glCreateProgram(); const char* shaderSource{source.c_str()}; u32 shader{0}; if (type == ShaderType::Vertex) shader = glCreateShader(GL_VERTEX_SHADER); else if (type == ShaderType::Fragment) shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(shader, 1, &shaderSource, nullptr); glCompileShader(shader); s32 status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == false) { std::string msg; if (type == ShaderType::Vertex) msg = "Compile failure in vertex shader: \n"; else if (type == ShaderType::Fragment) msg = "Compile failure in fragment shader: \n"; s32 infoLogLength; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); char* strInfoLog{new char[infoLogLength + 1]}; defer(delete[] strInfoLog); glGetShaderInfoLog(shader, infoLogLength, nullptr, strInfoLog); msg.append(strInfoLog); msg.append("\n"); errorLog.append(msg); glDeleteShader(shader); return false; } glAttachShader(handle, shader); return true; }
void DesktopConnector::jsUpdateViewSlot(const QString & viewName, int width, int height) { ViewInfo * viewInfo = findViewInfo( viewName); if( ! viewInfo) { qWarning() << "Received update for unknown view " << viewName; return; } IView * view = viewInfo-> view; viewInfo-> clientSize = QSize( width, height); defer([this,view,viewInfo](){ view-> handleResizeRequest( viewInfo-> clientSize); refreshView( view); }); }
Image load_image( const char* filename ) { i32 width; i32 height; i32 format; // Using NULL because stbi_load takes an integer and nullptr // has type nullptr_t. u8* pixels = stbi_load( filename, &width, &height, &format, 0 ); defer( stbi_image_free( pixels ) ); if ( !pixels ) throw std::runtime_error( stbi_failure_reason() ); return load_image( width, height, (ImageFormat)format, pixels ); }
int main() { session_t sess; datum id; time_t create_time, last_seen; bool do_allow; char *reason; openlog("dorian/query", LOG_PID, LOG_MAIL); for (;;) { do_allow = false; if ((sess = sess_req(stdin)) == NULL) break; /* white listing */ for_each(i, whitelist_prefix) if (!strncasecmp(whitelist_prefix[i], sess->attr[Krecipient], strlen(whitelist_prefix[i]))) { do_allow = true; reason = "whitelist address"; break; } if (!do_allow) { sess_derive_key(sess, &id); { if (seen(id, &create_time, &last_seen)) { if (create_time < expired()) { bump(id, create_time); do_allow = true; reason = "in database"; } } else add(id); } free(id.dptr); } sess_free(&sess); if (do_allow) allow(reason); else defer(); } closelog(); return 0; }
/*------------------------------------ cmd_Rate ---*/ Pvoid cmd_Rate(QtPtr xx, long numerator, long denominator) { Atom avRate[2]; EnterCallback(); #if defined(TRACE_MESSAGES) LOG_POST_1("Rate") #endif /* TRACE_MESSAGES */ SETLONG(avRate, numerator); SETLONG(avRate + 1, denominator); if (xx) defer(xx, reinterpret_cast<method>(deferred_Rate), NULL_PTR, 2, avRate); ExitMaxMessageHandler() } /* cmd_Rate */
/** Removes a client from the list. */ bool Clients::remove(int remid){ iterator it = find(remid); if (it != end()){ Client* cl = readyiter->second; cl->clearPlayers(); mute || cout << ticks() << ": client #" << cl->id << " left" << endl; if (cl->game != 0){ cl->game->removeClient(cl->id); cl->game = 0; } defer(cl->id); return true; } return false; }
INTERNAL String shaderSourceFromFile(const String& filename) { String filePath = BaseDirectory::Shaders + filename; std::ifstream file; file.open(cString(filePath), std::ios::in | std::ios::binary); if (!file.is_open()) { panic("Failed to open shader file: " + filePath); return {}; } defer(file.close()); String output; String line; while (file.good()) { getline(file, line); line = Strings::trimSpace(line); if (Strings::hasPrefix(line, "#include")) { String includeFilename = substring(line, 8, len(line)); includeFilename = Strings::trimSpace(includeFilename); includeFilename = Strings::trim(includeFilename, "\""); if (len(includeFilename) > 0) { // Recursively append source of header file and append header // extension const String& withExt = cString(includeFilename + ".head.glsl"); append(output, shaderSourceFromFile(withExt)); } } else { append(output, line); } append(output, '\n'); // Append a *nix newline } return output; }
void flip_image_v( Image& img ) { usize pitch = img.width * (u32)img.format; u32 half_rows = img.height / 2; u8* temp = new u8[ pitch ]; defer( delete[] temp ); for ( u32 i = 0; i < half_rows; ++i ) { u8* row = img.pixels + ( i * img.width ) * (u32)img.format; u8* opp = img.pixels + ( ( img.height - i - 1 ) * img.width ) * (u32)img.format; memcpy( temp, row , pitch ); memcpy( row , opp , pitch ); memcpy( opp , temp, pitch ); } }
void DesktopConnector::jsSendCommandSlot(const QString &cmd, const QString & parameter) { // call all registered callbacks and collect results, but asynchronously defer( [cmd, parameter, this ]() { auto & allCallbacks = m_commandCallbackMap[ cmd]; QStringList results; for( auto & cb : allCallbacks) { results += cb( cmd, parameter, "1"); // session id fixed to "1" } // pass results back to javascript emit jsCommandResultsSignal( results.join("|")); if( allCallbacks.size() == 0) { qWarning() << "JS command has no server listener:" << cmd << parameter; } }); }
TCResult ast::DecompVarDefn::typecheck(sst::TypecheckState* fs, fir::Type* infer) { fs->pushLoc(this); defer(fs->popLoc()); auto ret = util::pool<sst::DecompDefn>(this->loc); ret->immutable = this->immut; if(auto splat = dcast(ast::SplatOp, this->initialiser)) { if(this->bindings.array) { SpanError::make(SimpleError::make(this->loc, "value splats can only be assigned to tuple decompositions")) ->add(util::ESpan(this->initialiser->loc, "")) ->postAndQuit(); } bool isnest = false; for(const auto& b : this->bindings.inner) { if(b.name.empty()) { isnest = true; break; } } if(isnest) { SpanError::make(SimpleError::make(this->loc, "cannot assign value splats to nested tuple decomposition")) ->add(util::ESpan(this->initialiser->loc, "")) ->postAndQuit(); } // ok, at this point we should be fine. this->initialiser = util::pool<ast::LitTuple>(splat->loc, std::vector<ast::Expr*>(this->bindings.inner.size(), splat->expr)); } ret->init = this->initialiser->typecheck(fs).expr(); ret->bindings = fs->typecheckDecompositions(this->bindings, ret->init->type, this->immut, false); return TCResult(ret); }
CheckedBoolean MapData::ensureSpaceForAppend(CallFrame* callFrame) { if (m_capacity > m_size) return true; size_t requiredSize = std::max(m_capacity + (m_capacity / 2) + 1, minimumMapSize); void* newStorage = 0; if (!callFrame->heap()->tryAllocateStorage(this, requiredSize * sizeof(Entry), &newStorage)) { throwOutOfMemoryError(callFrame); return false; } DeferGC defer(*callFrame->heap()); Entry* newEntries = static_cast<Entry*>(newStorage); if (shouldPack()) replaceAndPackBackingStore(newEntries, requiredSize); else replaceBackingStore(newEntries, requiredSize); return true; }
void ServerConnector::initialize(const InitializeCallback & cb) { try { // start with unintialized state Q_ASSERT_X( ! m_initialized, "ServerConnector::initialize()", "Calling initialize twice?"); // Initialize PureWeb libraries CSI::Library::Initialize(); // this thread is the UI thread CSI::Threading::UiDispatcher::InitMessageThread(); // Create PureWeb object instances m_server = new CSI::PureWeb::Server::StateManagerServer(); m_stateManager = new CSI::PureWeb::Server::StateManager("pingpong"); m_stateManager-> Initialized() += OnPWStateInitialized; m_stateManager->PluginManager().RegisterPlugin( "QtMessageTickler", new QtMessageTickler()); m_server->Start(m_stateManager.get()); m_server->ShutdownRequested() += OnPureWebShutdown; // extract URL encoded arguments for( auto kv : m_server-> StartupParameters()) { QString key = kv.first.ToAscii().begin(); QString val = kv.second.ToAscii().begin(); m_urlParams[ key ] = val; //qDebug() << key << "=" << val; } // register generic command listener CSI::PureWeb::Server::StateManager::Instance()->CommandManager().AddUiHandler( "generic", CSI::Bind( this, &ServerConnector::genericCommandListener)); m_initialized = true; } catch ( ... ) { qCritical() << "Could not initialize PureWeb"; } // schedule the callback immediately, as we already know if we succeeded or not defer( std::bind( cb, m_initialized)); } // initialize
b32 ShaderProgram::link() { if (!handle) handle = glCreateProgram(); if (!isLinked) { glLinkProgram(handle); s32 status; glGetProgramiv(handle, GL_LINK_STATUS, &status); if (!status) { String msg{"ShaderProgram linking failure: \n"}; s32 infoLogLength; glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &infoLogLength); Allocator& a = defaultAllocator(); char* strInfoLog = (char*)a.allocate((infoLogLength + 1) * sizeof(char)); defer(a.deallocate(strInfoLog)); glGetProgramInfoLog(handle, infoLogLength, nullptr, strInfoLog); append(msg, strInfoLog); append(msg, "\n"); append(errorLog, msg); glDeleteProgram(handle); handle = 0; isLinked = false; return isLinked; } isLinked = true; } return isLinked; }
CGResult sst::TupleAssignOp::_codegen(cgn::CodegenState* cs, fir::Type* infer) { cs->pushLoc(this); defer(cs->popLoc()); auto tuple = this->right->codegen(cs).value; if(!tuple->getType()->isTupleType()) error(this->right, "Expected tuple type in assignment to tuple on left-hand-side; found type '%s' instead", tuple->getType()); auto tty = tuple->getType()->toTupleType(); std::vector<CGResult> results; size_t idx = 0; for(auto v : this->lefts) { auto res = v->codegen(cs, tty->getElementN(idx)); if(res->islvalue()) error(v, "Cannot assign to non-lvalue expression in tuple assignment"); results.push_back(res); idx++; } for(size_t i = 0; i < idx; i++) { auto lr = results[i]; auto val = cs->irb.ExtractValue(tuple, { i }); auto rr = cs->oneWayAutocast(val, lr.value->getType()); if(!rr || rr->getType() != lr.value->getType()) { error(this->right, "Mismatched types in assignment to tuple element %d; assigning type '%s' to '%s'", val->getType(), lr.value->getType()); } cs->autoAssignRefCountedValue(lr.value, rr, /* isInitial: */ false, /* performStore: */ true); } return CGResult(0); }
void flip_image_h( Image& img ) { std::cerr << "Warning: Image::FlipH(): Not yet implemented!" << std::endl; return; size_t pitch = img.width * (u32)img.format / 2; u32 half_width = img.width / 2; u8* temp = new u8[ pitch ]; defer( delete[] temp ); for ( u32 i = 0; i < img.height; ++i ) { u8* row = img.pixels + ( i * half_width ) * (u32)img.format; u8* opp = img.pixels + ( i * half_width + half_width ) * (u32)img.format; memcpy( temp, row , pitch ); memcpy( row , opp , pitch ); memcpy( opp , temp, pitch ); } }
bool ShaderProgram::link() { if (!handle) handle = glCreateProgram(); if (!isLinked) { glLinkProgram(handle); s32 status; glGetProgramiv(handle, GL_LINK_STATUS, &status); if (!status) { std::string msg{"ShaderProgram linking failure: \n"}; s32 infoLogLength; glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &infoLogLength); char* strInfoLog{new char[infoLogLength + 1]}; defer(delete[] strInfoLog); glGetProgramInfoLog(handle, infoLogLength, nullptr, strInfoLog); msg.append(strInfoLog); msg.append("\n"); errorLog.append(msg); glDeleteProgram(handle); handle = 0; isLinked = false; return isLinked; } isLinked = true; } return isLinked; }
bool loadCommonTextureExt(char const* fname, GLuint textureId, bool flip) { int width, height, n; unsigned char *textureData = stbi_load(fname, &width, &height, &n, 3); if(textureData == nullptr) { std::cout << "ERROR: loadCommonTextureExt failed, fname = " << fname << ", stbi_load returned nullptr" << std::endl; return false; } defer(stbi_image_free(textureData)); if(flip) flipTexture(textureData, width, height, n); glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // glBindTexture(GL_TEXTURE_2D, 0); // unbind return true; }