static gboolean pluginCore (piArgs *argp) { GimpDrawable *drw, *ndrw = NULL; GimpPixelRgn srcPr, dstPr; gboolean success = TRUE; gint nl = 0; gint y, i; gint Y, I, Q; guint width, height, bpp; gint sel_x1, sel_x2, sel_y1, sel_y2; gint prog_interval; guchar *src, *s, *dst, *d; guchar r, prev_r=0, new_r=0; guchar g, prev_g=0, new_g=0; guchar b, prev_b=0, new_b=0; gdouble fy, fc, t, scale; gdouble pr, pg, pb; gdouble py; drw = gimp_drawable_get (argp->drawable); width = drw->width; height = drw->height; bpp = drw->bpp; if (argp->new_layerp) { gchar name[40]; const gchar *mode_names[] = { "ntsc", "pal", }; const gchar *action_names[] = { "lum redux", "sat redux", "flag", }; g_snprintf (name, sizeof (name), "hot mask (%s, %s)", mode_names[argp->mode], action_names[argp->action]); nl = gimp_layer_new (argp->image, name, width, height, GIMP_RGBA_IMAGE, (gdouble)100, GIMP_NORMAL_MODE); ndrw = gimp_drawable_get (nl); gimp_drawable_fill (nl, GIMP_TRANSPARENT_FILL); gimp_image_insert_layer (argp->image, nl, -1, 0); } gimp_drawable_mask_bounds (drw->drawable_id, &sel_x1, &sel_y1, &sel_x2, &sel_y2); width = sel_x2 - sel_x1; height = sel_y2 - sel_y1; src = g_new (guchar, width * height * bpp); dst = g_new (guchar, width * height * 4); gimp_pixel_rgn_init (&srcPr, drw, sel_x1, sel_y1, width, height, FALSE, FALSE); if (argp->new_layerp) { gimp_pixel_rgn_init (&dstPr, ndrw, sel_x1, sel_y1, width, height, FALSE, FALSE); } else { gimp_pixel_rgn_init (&dstPr, drw, sel_x1, sel_y1, width, height, TRUE, TRUE); } gimp_pixel_rgn_get_rect (&srcPr, src, sel_x1, sel_y1, width, height); s = src; d = dst; build_tab (argp->mode); gimp_progress_init (_("Hot")); prog_interval = height / 10; for (y = sel_y1; y < sel_y2; y++) { gint x; if (y % prog_interval == 0) gimp_progress_update ((double) y / (double) (sel_y2 - sel_y1)); for (x = sel_x1; x < sel_x2; x++) { if (hotp (r = *(s + 0), g = *(s + 1), b = *(s + 2))) { if (argp->action == ACT_FLAG) { for (i = 0; i < 3; i++) *d++ = 0; s += 3; if (bpp == 4) *d++ = *s++; else if (argp->new_layerp) *d++ = 255; } else { /* * Optimization: cache the last-computed hot pixel. */ if (r == prev_r && g == prev_g && b == prev_b) { *d++ = new_r; *d++ = new_g; *d++ = new_b; s += 3; if (bpp == 4) *d++ = *s++; else if (argp->new_layerp) *d++ = 255; } else { Y = tab[0][0][r] + tab[0][1][g] + tab[0][2][b]; I = tab[1][0][r] + tab[1][1][g] + tab[1][2][b]; Q = tab[2][0][r] + tab[2][1][g] + tab[2][2][b]; prev_r = r; prev_g = g; prev_b = b; /* * Get Y and chroma amplitudes in floating point. * * If your C library doesn't have hypot(), just use * hypot(a,b) = sqrt(a*a, b*b); * * Then extract linear (un-gamma-corrected) * floating-point pixel RGB values. */ fy = (double)Y / (double)SCALE; fc = hypot ((double) I / (double) SCALE, (double) Q / (double) SCALE); pr = (double) pix_decode (r); pg = (double) pix_decode (g); pb = (double) pix_decode (b); /* * Reducing overall pixel intensity by scaling R, * G, and B reduces Y, I, and Q by the same factor. * This changes luminance but not saturation, since * saturation is determined by the chroma/luminance * ratio. * * On the other hand, by linearly interpolating * between the original pixel value and a grey * pixel with the same luminance (R=G=B=Y), we * change saturation without affecting luminance. */ if (argp->action == ACT_LREDUX) { /* * Calculate a scale factor that will bring the pixel * within both chroma and composite limits, if we scale * luminance and chroma simultaneously. * * The calculated chrominance reduction applies * to the gamma-corrected RGB values that are * the input to the RGB-to-YIQ operation. * Multiplying the original un-gamma-corrected * pixel values by the scaling factor raised to * the "gamma" power is equivalent, and avoids * calling gc() and inv_gc() three times each. */ scale = chroma_lim / fc; t = compos_lim / (fy + fc); if (t < scale) scale = t; scale = pow (scale, mode[argp->mode].gamma); r = (guint8) pix_encode (scale * pr); g = (guint8) pix_encode (scale * pg); b = (guint8) pix_encode (scale * pb); } else { /* ACT_SREDUX hopefully */ /* * Calculate a scale factor that will bring the * pixel within both chroma and composite * limits, if we scale chroma while leaving * luminance unchanged. * * We have to interpolate gamma-corrected RGB * values, so we must convert from linear to * gamma-corrected before interpolation and then * back to linear afterwards. */ scale = chroma_lim / fc; t = (compos_lim - fy) / fc; if (t < scale) scale = t; pr = gc (pr, argp->mode); pg = gc (pg, argp->mode); pb = gc (pb, argp->mode); py = pr * mode[argp->mode].code[0][0] + pg * mode[argp->mode].code[0][1] + pb * mode[argp->mode].code[0][2]; r = pix_encode (inv_gc (py + scale * (pr - py), argp->mode)); g = pix_encode (inv_gc (py + scale * (pg - py), argp->mode)); b = pix_encode (inv_gc (py + scale * (pb - py), argp->mode)); } *d++ = new_r = r; *d++ = new_g = g; *d++ = new_b = b; s += 3; if (bpp == 4) *d++ = *s++; else if (argp->new_layerp) *d++ = 255; } } } else { if (!argp->new_layerp) { for (i = 0; i < bpp; i++) *d++ = *s++; } else { s += bpp; d += 4; } } } } gimp_progress_update (1.0); gimp_pixel_rgn_set_rect (&dstPr, dst, sel_x1, sel_y1, width, height); g_free (src); g_free (dst); if (argp->new_layerp) { gimp_drawable_flush (ndrw); gimp_drawable_update (nl, sel_x1, sel_y1, width, height); } else { gimp_drawable_flush (drw); gimp_drawable_merge_shadow (drw->drawable_id, TRUE); gimp_drawable_update (drw->drawable_id, sel_x1, sel_y1, width, height); } gimp_displays_flush (); return success; }
runtime·mallocgc ( uintptr size , uint32 flag , int32 dogc , int32 zeroed ) { int32 sizeclass , rate; MCache *c; uintptr npages; MSpan *s; void *v; #line 2080 "C:\Go\src\pkg\runtime\malloc.goc" if ( runtime·gcwaiting && g != m->g0 && m->locks == 0 ) runtime·gosched ( ) ; if ( m->mallocing ) runtime·throw ( "malloc/free - deadlock" ) ; m->mallocing = 1; if ( size == 0 ) size = 1; #line 2088 "C:\Go\src\pkg\runtime\malloc.goc" c = m->mcache; c->local_nmalloc++; if ( size <= MaxSmallSize ) { #line 2092 "C:\Go\src\pkg\runtime\malloc.goc" sizeclass = runtime·SizeToClass ( size ) ; size = runtime·class_to_size[sizeclass]; v = runtime·MCache_Alloc ( c , sizeclass , size , zeroed ) ; if ( v == nil ) runtime·throw ( "out of memory" ) ; c->local_alloc += size; c->local_total_alloc += size; c->local_by_size[sizeclass].nmalloc++; } else { #line 2104 "C:\Go\src\pkg\runtime\malloc.goc" npages = size >> PageShift; if ( ( size & PageMask ) != 0 ) npages++; s = runtime·MHeap_Alloc ( &runtime·mheap , npages , 0 , 1 ) ; if ( s == nil ) runtime·throw ( "out of memory" ) ; size = npages<<PageShift; c->local_alloc += size; c->local_total_alloc += size; v = ( void* ) ( s->start << PageShift ) ; #line 2116 "C:\Go\src\pkg\runtime\malloc.goc" runtime·markspan ( v , 0 , 0 , true ) ; } if ( ! ( flag & FlagNoGC ) ) runtime·markallocated ( v , size , ( flag&FlagNoPointers ) != 0 ) ; #line 2121 "C:\Go\src\pkg\runtime\malloc.goc" m->mallocing = 0; #line 2123 "C:\Go\src\pkg\runtime\malloc.goc" if ( ! ( flag & FlagNoProfiling ) && ( rate = runtime·MemProfileRate ) > 0 ) { if ( size >= rate ) goto profile; if ( m->mcache->next_sample > size ) m->mcache->next_sample -= size; else { #line 2131 "C:\Go\src\pkg\runtime\malloc.goc" if ( rate > 0x3fffffff ) rate = 0x3fffffff; m->mcache->next_sample = runtime·fastrand1 ( ) % ( 2*rate ) ; profile: runtime·setblockspecial ( v , true ) ; runtime·MProf_Malloc ( v , size ) ; } } #line 2140 "C:\Go\src\pkg\runtime\malloc.goc" if ( dogc && mstats.heap_alloc >= mstats.next_gc ) runtime·gc ( 0 ) ; return v; }
virtual void on_expose() { /* draw the label */ rectangle rect = get_rect(); graphics_context gc ( m_display, id() ); gc.set_font(helvetica); color black ( m_display, 0, 0, 0 ); color white ( m_display, 255, 255, 255 ); color gray ( m_display, 131, 129, 131 ); color ltgray (m_display, 197, 194, 197 ); gc.set_foreground ( &black ); /* draw the text */ int x, y; rectangle text_rect = gc.get_text_rect ( m_text ); y = rect.height()/2 + text_rect.height()/2; switch ( text_alignment ) { case JUSTIFY_CENTER: x = rect.width()/2 - text_rect.width()/2; break; case JUSTIFY_RIGHT: x = rect.width() - text_rect.width(); break; case JUSTIFY_LEFT: default: x = 0; } x = x + text_xoffset; y = y + text_yoffset; gc.draw_text ( point(x, y), m_text ); if (draw_border) { gc.set_foreground ( <gray ); /* draw the borders */ gc.draw_line ( line ( point(0, rect.height()-1), point(rect.width()-1, rect.height()-1) ) ); // right gc.draw_line ( line ( point ( rect.width()-1, 0 ), point ( rect.width()-1, rect.height()-1 ) ) ); gc.set_foreground ( &black ); //was white // top gc.draw_line ( line ( point ( 0,0 ), point ( rect.width()-2, 0 ) ) ); // left gc.draw_line ( line ( point ( 0,0 ), point ( 0, rect.height()-2 ) ) ); gc.set_foreground ( &gray ); // bottom gc.draw_line ( line ( point ( 1, rect.height()-2 ), point(rect.width()-2,rect.height()-2) ) ); // right gc.draw_line ( line ( point ( rect.width()-2, 1 ), point(rect.width()-2,rect.height()-2) ) ); } }
void XBPyThread::Process() { CLog::Log(LOGDEBUG,"Python thread: start processing"); int m_Py_file_input = Py_file_input; // get the global lock PyEval_AcquireLock(); PyThreadState* state = Py_NewInterpreter(); if (!state) { PyEval_ReleaseLock(); CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!"); return; } // swap in my thread state PyThreadState_Swap(state); XBMCAddon::AddonClass::Ref<XBMCAddon::Python::LanguageHook> languageHook(new XBMCAddon::Python::LanguageHook(state->interp)); languageHook->RegisterMe(); m_pExecuter->InitializeInterpreter(addon); CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source); // get path from script file name and add python path's // this is used for python so it will search modules from script path first CStdString scriptDir; URIUtils::GetDirectory(CSpecialProtocol::TranslatePath(m_source), scriptDir); URIUtils::RemoveSlashAtEnd(scriptDir); CStdString path = scriptDir; // add on any addon modules the user has installed ADDON::VECADDONS addons; ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons); for (unsigned int i = 0; i < addons.size(); ++i) #ifdef TARGET_WINDOWS { CStdString strTmp(CSpecialProtocol::TranslatePath(addons[i]->LibPath())); g_charsetConverter.utf8ToSystem(strTmp); path += PY_PATH_SEP + strTmp; } #else path += PY_PATH_SEP + CSpecialProtocol::TranslatePath(addons[i]->LibPath()); #endif // and add on whatever our default path is path += PY_PATH_SEP; // we want to use sys.path so it includes site-packages // if this fails, default to using Py_GetPath PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete if( pathObj && PyList_Check(pathObj) ) { for( int i = 0; i < PyList_Size(pathObj); i++ ) { PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete if( e && PyString_Check(e) ) { path += PyString_AsString(e); // returns internal data, don't delete or modify path += PY_PATH_SEP; } } } else { path += Py_GetPath(); } Py_DECREF(sysMod); // release ref to sysMod // set current directory and python's path. if (m_argv != NULL) PySys_SetArgv(m_argc, m_argv); CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str()); PySys_SetPath((char *)path.c_str()); CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str()); PyObject* module = PyImport_AddModule((char*)"__main__"); PyObject* moduleDict = PyModule_GetDict(module); // when we are done initing we store thread state so we can be aborted PyThreadState_Swap(NULL); PyEval_ReleaseLock(); // we need to check if we was asked to abort before we had inited bool stopping = false; { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = state; stopping = m_stopping; } PyEval_AcquireLock(); PyThreadState_Swap(state); if (!stopping) { try { if (m_type == 'F') { // run script from file // We need to have python open the file because on Windows the DLL that python // is linked against may not be the DLL that xbmc is linked against so // passing a FILE* to python from an fopen has the potential to crash. PyObject* file = PyFile_FromString((char *) CSpecialProtocol::TranslatePath(m_source).c_str(), (char*)"r"); FILE *fp = PyFile_AsFile(file); if (fp) { PyObject *f = PyString_FromString(CSpecialProtocol::TranslatePath(m_source).c_str()); PyDict_SetItemString(moduleDict, "__file__", f); if (addon.get() != NULL) { PyObject *pyaddonid = PyString_FromString(addon->ID().c_str()); PyDict_SetItemString(moduleDict, "__xbmcaddonid__", pyaddonid); CStdString version = ADDON::GetXbmcApiVersionDependency(addon); PyObject *pyxbmcapiversion = PyString_FromString(version.c_str()); PyDict_SetItemString(moduleDict, "__xbmcapiversion__", pyxbmcapiversion); CLog::Log(LOGDEBUG,"Instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",addon->ID().c_str(),version.c_str()); } Py_DECREF(f); XBMCAddon::Python::PyContext pycontext; // this is a guard class that marks this callstack as being in a python context PyRun_FileExFlags(fp, CSpecialProtocol::TranslatePath(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL); } else CLog::Log(LOGERROR, "%s not found!", m_source); } else { //run script PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict); } } catch (const XbmcCommons::Exception& e) { e.LogThrowMessage(); } catch (...) { CLog::Log(LOGERROR, "failure in %s", m_source); } } if (!PyErr_Occurred()) CLog::Log(LOGINFO, "Scriptresult: Success"); else if (PyErr_ExceptionMatches(PyExc_SystemExit)) CLog::Log(LOGINFO, "Scriptresult: Aborted"); else { PythonBindings::PythonToCppException e; e.LogThrowMessage(); { CPyThreadState releaseGil; CSingleLock gc(g_graphicsContext); CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST); if (pDlgToast) { CStdString desc; CStdString path; CStdString script; URIUtils::Split(m_source, path, script); if (script.Equals("default.py")) { CStdString path2; URIUtils::RemoveSlashAtEnd(path); URIUtils::Split(path, path2, script); } desc.Format(g_localizeStrings.Get(2100), script); pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc); } } } PyObject *m = PyImport_AddModule((char*)"xbmc"); if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1))) CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested"); // make sure all sub threads have finished for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;) { if(s == state) { s = s->next; continue; } if(old != s) { CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id); old = s; } CPyThreadState pyState; Sleep(100); pyState.Restore(); s = state->interp->tstate_head; } // pending calls must be cleared out XBMCAddon::RetardedAsynchCallbackHandler::clearPendingCalls(state); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); //set stopped event - this allows ::stop to run and kill remaining threads //this event has to be fired without holding m_pExecuter->m_critSection //before //Also the GIL (PyEval_AcquireLock) must not be held //if not obeyed there is still no deadlock because ::stop waits with timeout (smart one!) stoppedEvent.Set(); { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = NULL; } PyEval_AcquireLock(); PyThreadState_Swap(state); m_pExecuter->DeInitializeInterpreter(); // run the gc before finishing if (!m_stopping && languageHook->HasRegisteredAddonClasses() && PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running prior to shutting down the Interpreter %s",m_source); Py_EndInterpreter(state); // This is a total hack. Python doesn't necessarily release // all of the objects associated with the interpreter when // you end the interpreter. As a result there are objects // managed by the windowing system that still receive events // until python decides to clean them up. Python will eventually // clean them up on the creation or ending of a subsequent // interpreter. So we are going to keep creating and ending // interpreters until we have no more python objects hanging // around. if (languageHook->HasRegisteredAddonClasses()) { CLog::Log(LOGDEBUG, "The python script \"%s\" has left several " "classes in memory that we will be attempting to clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); int countLimit; for (countLimit = 0; languageHook->HasRegisteredAddonClasses() && countLimit < 100; countLimit++) { PyThreadState* tmpstate = Py_NewInterpreter(); PyThreadState* oldstate = PyThreadState_Swap(tmpstate); if (PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running %s",m_source); PyThreadState_Swap(oldstate); Py_EndInterpreter(tmpstate); } // If necessary and successfull, debug log the results. if (countLimit > 0 && !languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGDEBUG,"It took %d Py_NewInterpreter/Py_EndInterpreter calls" " to clean up the classes leftover from running \"%s.\"", countLimit,m_source); // If not successful, produce an error message detailing what's been left behind if (languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGERROR, "The python script \"%s\" has left several " "classes in memory that we couldn't clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); } // unregister the language hook languageHook->UnregisterMe(); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); }
void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected) { wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, false); wxString value = grid.GetTable()->GetValue(row, col); wxString label; auto it = glyphs.find(value); if (it == glyphs.end()) return; const SvgGlyph &glyph = it->second; if (!glyph.IsOk()) return; if (showGlyphNames) label = glyph.glyphName; else label.Printf("%04x", glyph.unicode[0]); std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc))); wxRect newRect = rect; // replace with gc->GetRenderer()->GetName() == L"cairo" after wx 3.1 bool isCairo = false; #if wxUSE_CAIRO isCairo = true; #endif // Oh, crap if (isCairo) { newRect.x += dc.GetDeviceOrigin().x; newRect.y += dc.GetDeviceOrigin().y; } std::map<wxString, wxBitmap>::iterator findIt = glyphCache.find(glyph.unicode); if (findIt == glyphCache.end()) { bool result; std::tie(findIt, result) = glyphCache.emplace(glyph.unicode, GetBitmapForGlyph(glyph, fontSize, glyphColor, attr.GetBackgroundColour(), false)); if (!result) return; } if (hlCellCoords.GetCol() == col && hlCellCoords.GetRow() == row) { gc->SetPen(wxPen(hlColor, 1)); gc->DrawRoundedRectangle(newRect.x + 1, newRect.y + 1, newRect.width - 2, newRect.height - 2, 5); } newRect.height -= labelFont.GetPixelSize().GetHeight() + 2 * padding; const wxBitmap &glyphBitmap = findIt->second; if (glyphBitmap.IsOk()) { gc->DrawBitmap(glyphBitmap, newRect.x + (newRect.width - glyphBitmap.GetWidth()) / 2, newRect.y + (newRect.height - glyphBitmap.GetHeight()) / 2, glyphBitmap.GetWidth(), glyphBitmap.GetHeight()); } double maxTextWidth = std::max(0, newRect.width - 2); double width, height, descent, externalLeading; gc->SetFont(labelFont, labelColor); gc->GetTextExtent(label, &width, &height, &descent, &externalLeading); wxString origLabel = label; size_t cutCntr = 1; while (width > maxTextWidth && !label.IsEmpty()) { label = origLabel.Left(origLabel.Length() - cutCntr++) + L"\u2026"; gc->GetTextExtent(label, &width, &height, &descent, &externalLeading); } gc->DrawText(label, newRect.x + (newRect.width - width) / 2, newRect.y + newRect.height + padding); }
HRESULT CLR_RT_StackFrame::MakeCall( CLR_RT_MethodDef_Instance md, CLR_RT_HeapBlock* obj, CLR_RT_HeapBlock* args, int nArgs ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); const CLR_RECORD_METHODDEF* mdR = md.m_target; bool fStatic =(mdR->flags & CLR_RECORD_METHODDEF::MD_Static) != 0; int numArgs = mdR->numArgs; int argsOffset = 0; CLR_RT_StackFrame* stackSub; CLR_RT_HeapBlock tmp; tmp.SetObjectReference( NULL ); CLR_RT_ProtectFromGC gc(tmp); if(mdR->flags & CLR_RECORD_METHODDEF::MD_Constructor) { CLR_RT_TypeDef_Instance owner; owner.InitializeFromMethod( md ); _ASSERTE(obj == NULL); _SIDE_ASSERTE(owner.InitializeFromMethod( md )); TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObject( tmp, owner )); obj = &tmp; // // Make a copy of the object pointer. // PushValueAndAssign( tmp ); } if(!fStatic) { FAULT_ON_NULL(obj); numArgs--; argsOffset = 1; } if(numArgs != nArgs) TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); // // In case the invoked method is abstract or virtual, resolve it to the correct method implementation. // if(mdR->flags & (CLR_RECORD_METHODDEF::MD_Abstract | CLR_RECORD_METHODDEF::MD_Virtual)) { CLR_RT_TypeDef_Index cls; CLR_RT_MethodDef_Index mdReal; _ASSERTE(obj); _ASSERTE(!fStatic); TINYCLR_CHECK_HRESULT(CLR_RT_TypeDescriptor::ExtractTypeIndexFromObject( *obj, cls )); if(g_CLR_RT_EventCache.FindVirtualMethod( cls, md, mdReal ) == false) { TINYCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE); } md.InitializeFromIndex( mdReal ); mdR = md.m_target; } #if defined(TINYCLR_APPDOMAINS) if(!fStatic && obj->IsTransparentProxy()) { TINYCLR_CHECK_HRESULT(CLR_RT_StackFrame::PushAppDomainTransition( m_owningThread, md, obj, args )); stackSub = m_owningThread->CurrentFrame(); stackSub->m_flags |= CLR_RT_StackFrame::c_AppDomainMethodInvoke; } else #endif { TINYCLR_CHECK_HRESULT(CLR_RT_StackFrame::Push( m_owningThread, md, md.m_target->numArgs )); stackSub = m_owningThread->CurrentFrame(); if(!fStatic) { stackSub->m_arguments[ 0 ].Assign( *obj ); } if(numArgs) { memcpy( &stackSub->m_arguments[ argsOffset ], args, sizeof(CLR_RT_HeapBlock) * numArgs ); } } TINYCLR_CHECK_HRESULT(stackSub->FixCall()); TINYCLR_SET_AND_LEAVE(CLR_E_RESTART_EXECUTION); TINYCLR_NOCLEANUP(); }
static int nat2seq(int n, int bits) { // go from natural ordering to sequency ordering: // first take gray code encoding, then reverse those bits return bitrev(gc(n), bits); }
inline int fast(){int n=0;char ch=gc();while(ch<48)ch=gc(); while(ch>47){n=(n<<1)+(n<<3)+ch-48;ch=gc();}return n;}
void Extruder::on_gcode_received(void *argument) { Gcode *gcode = static_cast<Gcode *>(argument); // M codes most execute immediately, most only execute if enabled if (gcode->has_m) { if (gcode->m == 114 && this->enabled) { char buf[16]; int n = snprintf(buf, sizeof(buf), " E:%1.3f ", this->current_position); gcode->txt_after_ok.append(buf, n); gcode->mark_as_taken(); } else if (gcode->m == 92 && ( (this->enabled && !gcode->has_letter('P')) || (gcode->has_letter('P') && gcode->get_value('P') == this->identifier) ) ) { float spm = this->steps_per_millimeter; if (gcode->has_letter('E')) { spm = gcode->get_value('E'); this->steps_per_millimeter = spm; } gcode->stream->printf("E:%g ", spm); gcode->add_nl = true; gcode->mark_as_taken(); } else if (gcode->m == 200 && ( (this->enabled && !gcode->has_letter('P')) || (gcode->has_letter('P') && gcode->get_value('P') == this->identifier)) ) { if (gcode->has_letter('D')) { THEKERNEL->conveyor->wait_for_empty_queue(); // only apply after the queue has emptied this->filament_diameter = gcode->get_value('D'); if(filament_diameter > 0.01) { this->volumetric_multiplier = 1.0F / (powf(this->filament_diameter / 2, 2) * PI); } else { this->volumetric_multiplier = 1.0F; } } gcode->mark_as_taken(); } else if (gcode->m == 204 && gcode->has_letter('E') && ( (this->enabled && !gcode->has_letter('P')) || (gcode->has_letter('P') && gcode->get_value('P') == this->identifier)) ) { // extruder acceleration M204 Ennn mm/sec^2 (Pnnn sets the specific extruder for M500) this->acceleration= gcode->get_value('E'); gcode->mark_as_taken(); } else if (gcode->m == 207 && ( (this->enabled && !gcode->has_letter('P')) || (gcode->has_letter('P') && gcode->get_value('P') == this->identifier)) ) { // M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop] Q[zlift feedrate mm/min] if(gcode->has_letter('S')) retract_length = gcode->get_value('S'); if(gcode->has_letter('F')) retract_feedrate = gcode->get_value('F')/60.0F; // specified in mm/min converted to mm/sec if(gcode->has_letter('Z')) retract_zlift_length = gcode->get_value('Z'); if(gcode->has_letter('Q')) retract_zlift_feedrate = gcode->get_value('Q'); gcode->mark_as_taken(); } else if (gcode->m == 208 && ( (this->enabled && !gcode->has_letter('P')) || (gcode->has_letter('P') && gcode->get_value('P') == this->identifier)) ) { // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min] if(gcode->has_letter('S')) retract_recover_length = gcode->get_value('S'); if(gcode->has_letter('F')) retract_recover_feedrate = gcode->get_value('F')/60.0F; // specified in mm/min converted to mm/sec gcode->mark_as_taken(); } else if (gcode->m == 221 && this->enabled) { // M221 S100 change flow rate by percentage if(gcode->has_letter('S')) this->extruder_multiplier= gcode->get_value('S')/100.0F; gcode->mark_as_taken(); } else if (gcode->m == 500 || gcode->m == 503) { // M500 saves some volatile settings to config override file, M503 just prints the settings if( this->single_config ) { gcode->stream->printf(";E Steps per mm:\nM92 E%1.4f\n", this->steps_per_millimeter); gcode->stream->printf(";E Filament diameter:\nM200 D%1.4f\n", this->filament_diameter); gcode->stream->printf(";E retract length, feedrate, zlift length, feedrate:\nM207 S%1.4f F%1.4f Z%1.4f Q%1.4f\n", this->retract_length, this->retract_feedrate*60.0F, this->retract_zlift_length, this->retract_zlift_feedrate); gcode->stream->printf(";E retract recover length, feedrate:\nM208 S%1.4f F%1.4f\n", this->retract_recover_length, this->retract_recover_feedrate*60.0F); gcode->stream->printf(";E acceleration mm/sec^2:\nM204 E%1.4f\n", this->acceleration); } else { gcode->stream->printf(";E Steps per mm:\nM92 E%1.4f P%d\n", this->steps_per_millimeter, this->identifier); gcode->stream->printf(";E Filament diameter:\nM200 D%1.4f P%d\n", this->filament_diameter, this->identifier); gcode->stream->printf(";E retract length, feedrate:\nM207 S%1.4f F%1.4f Z%1.4f Q%1.4f P%d\n", this->retract_length, this->retract_feedrate*60.0F, this->retract_zlift_length, this->retract_zlift_feedrate, this->identifier); gcode->stream->printf(";E retract recover length, feedrate:\nM208 S%1.4f F%1.4f P%d\n", this->retract_recover_length, this->retract_recover_feedrate*60.0F, this->identifier); gcode->stream->printf(";E acceleration mm/sec^2:\nM204 E%1.4f P%d\n", this->acceleration, this->identifier); } gcode->mark_as_taken(); } else if( gcode->m == 17 || gcode->m == 18 || gcode->m == 82 || gcode->m == 83 || gcode->m == 84 ) { // Mcodes to pass along to on_gcode_execute THEKERNEL->conveyor->append_gcode(gcode); gcode->mark_as_taken(); } } else if(gcode->has_g) { // G codes, NOTE some are ignored if not enabled if( (gcode->g == 92 && gcode->has_letter('E')) || (gcode->g == 90 || gcode->g == 91) ) { // Gcodes to pass along to on_gcode_execute THEKERNEL->conveyor->append_gcode(gcode); gcode->mark_as_taken(); } else if( this->enabled && gcode->g < 4 && gcode->has_letter('E') && !gcode->has_letter('X') && !gcode->has_letter('Y') && !gcode->has_letter('Z') ) { // This is a solo move, we add an empty block to the queue to prevent subsequent gcodes being executed at the same time THEKERNEL->conveyor->append_gcode(gcode); THEKERNEL->conveyor->queue_head_block(); gcode->mark_as_taken(); } else if( this->enabled && (gcode->g == 10 || gcode->g == 11) ) { // firmware retract command gcode->mark_as_taken(); // check we are in the correct state of retract or unretract if(gcode->g == 10 && !retracted) { this->retracted= true; this->cancel_zlift_restore= false; } else if(gcode->g == 11 && retracted) { this->retracted= false; } else return; // ignore duplicates // now we do a special hack to add zlift if needed, this should go in Robot but if it did the zlift would be executed before retract which is bad // this way zlift will happen after retract, (or before for unretract) NOTE we call the robot->on_gcode_receive directly to avoid recursion if(retract_zlift_length > 0 && gcode->g == 11 && !this->cancel_zlift_restore) { // reverse zlift happens before unretract // NOTE we do not do this if cancel_zlift_restore is set to true, which happens if there is an absolute Z move inbetween G10 and G11 char buf[32]; int n= snprintf(buf, sizeof(buf), "G0 Z%1.4f F%1.4f", -retract_zlift_length, retract_zlift_feedrate); string cmd(buf, n); Gcode gc(cmd, &(StreamOutput::NullStream)); bool oldmode= THEKERNEL->robot->absolute_mode; THEKERNEL->robot->absolute_mode= false; // needs to be relative mode THEKERNEL->robot->on_gcode_received(&gc); // send to robot directly THEKERNEL->robot->absolute_mode= oldmode; // restore mode } // This is a solo move, we add an empty block to the queue to prevent subsequent gcodes being executed at the same time THEKERNEL->conveyor->append_gcode(gcode); THEKERNEL->conveyor->queue_head_block(); if(retract_zlift_length > 0 && gcode->g == 10) { char buf[32]; int n= snprintf(buf, sizeof(buf), "G0 Z%1.4f F%1.4f", retract_zlift_length, retract_zlift_feedrate); string cmd(buf, n); Gcode gc(cmd, &(StreamOutput::NullStream)); bool oldmode= THEKERNEL->robot->absolute_mode; THEKERNEL->robot->absolute_mode= false; // needs to be relative mode THEKERNEL->robot->on_gcode_received(&gc); // send to robot directly THEKERNEL->robot->absolute_mode= oldmode; // restore mode } } else if( this->enabled && this->retracted && (gcode->g == 0 || gcode->g == 1) && gcode->has_letter('Z')) { // NOTE we cancel the zlift restore for the following G11 as we have moved to an absolute Z which we need to stay at this->cancel_zlift_restore= true; } } }
/* Walk through the table and remove all entries which lifetime ended. We have a problem here. To actually remove the entries we must get the write-lock. But since we want to keep the time we have the lock as short as possible we cannot simply acquire the lock when we start looking for timedout entries. Therefore we do it in two stages: first we look for entries which must be invalidated and remember them. Then we get the lock and actually remove them. This is complicated by the way we have to free the data structures since some hash table entries share the same data. */ time_t prune_cache (struct database_dyn *table, time_t now, int fd) { size_t cnt = table->head->module; /* If this table is not actually used don't do anything. */ if (cnt == 0) { if (fd != -1) { /* Reply to the INVALIDATE initiator. */ int32_t resp = 0; writeall (fd, &resp, sizeof (resp)); } /* No need to do this again anytime soon. */ return 24 * 60 * 60; } /* If we check for the modification of the underlying file we invalidate the entries also in this case. */ if (table->check_file && now != LONG_MAX) { struct traced_file *runp = table->traced_files; while (runp != NULL) { #ifdef HAVE_INOTIFY if (runp->inotify_descr == -1) #endif { struct stat64 st; if (stat64 (runp->fname, &st) < 0) { char buf[128]; /* We cannot stat() the file, disable file checking if the file does not exist. */ dbg_log (_("cannot stat() file `%s': %s"), runp->fname, strerror_r (errno, buf, sizeof (buf))); if (errno == ENOENT) table->check_file = 0; } else { if (st.st_mtime != table->file_mtime) { /* The file changed. Invalidate all entries. */ now = LONG_MAX; table->file_mtime = st.st_mtime; } } } runp = runp->next; } } /* We run through the table and find values which are not valid anymore. Note that for the initial step, finding the entries to be removed, we don't need to get any lock. It is at all timed assured that the linked lists are set up correctly and that no second thread prunes the cache. */ bool *mark; size_t memory_needed = cnt * sizeof (bool); bool mark_use_alloca; if (__glibc_likely (memory_needed <= MAX_STACK_USE)) { mark = alloca (cnt * sizeof (bool)); memset (mark, '\0', memory_needed); mark_use_alloca = true; } else { mark = xcalloc (1, memory_needed); mark_use_alloca = false; } size_t first = cnt + 1; size_t last = 0; char *const data = table->data; bool any = false; if (__glibc_unlikely (debug_level > 2)) dbg_log (_("pruning %s cache; time %ld"), dbnames[table - dbs], (long int) now); #define NO_TIMEOUT LONG_MAX time_t next_timeout = NO_TIMEOUT; do { ref_t run = table->head->array[--cnt]; while (run != ENDREF) { struct hashentry *runp = (struct hashentry *) (data + run); struct datahead *dh = (struct datahead *) (data + runp->packet); /* Some debug support. */ if (__glibc_unlikely (debug_level > 2)) { char buf[INET6_ADDRSTRLEN]; const char *str; if (runp->type == GETHOSTBYADDR || runp->type == GETHOSTBYADDRv6) { inet_ntop (runp->type == GETHOSTBYADDR ? AF_INET : AF_INET6, data + runp->key, buf, sizeof (buf)); str = buf; } else str = data + runp->key; dbg_log (_("considering %s entry \"%s\", timeout %" PRIu64), serv2str[runp->type], str, dh->timeout); } /* Check whether the entry timed out. */ if (dh->timeout < now) { /* This hash bucket could contain entries which need to be looked at. */ mark[cnt] = true; first = MIN (first, cnt); last = MAX (last, cnt); /* We only have to look at the data of the first entries since the count information is kept in the data part which is shared. */ if (runp->first) { /* At this point there are two choices: we reload the value or we discard it. Do not change NRELOADS if we never not reload the record. */ if ((reload_count != UINT_MAX && __builtin_expect (dh->nreloads >= reload_count, 0)) /* We always remove negative entries. */ || dh->notfound /* Discard everything if the user explicitly requests it. */ || now == LONG_MAX) { /* Remove the value. */ dh->usable = false; /* We definitely have some garbage entries now. */ any = true; } else { /* Reload the value. We do this only for the initially used key, not the additionally added derived value. */ assert (runp->type < LASTREQ && readdfcts[runp->type] != NULL); time_t timeout = readdfcts[runp->type] (table, runp, dh); next_timeout = MIN (next_timeout, timeout); /* If the entry has been replaced, we might need cleanup. */ any |= !dh->usable; } } } else { assert (dh->usable); next_timeout = MIN (next_timeout, dh->timeout); } run = runp->next; } } while (cnt > 0); if (__glibc_unlikely (fd != -1)) { /* Reply to the INVALIDATE initiator that the cache has been invalidated. */ int32_t resp = 0; writeall (fd, &resp, sizeof (resp)); } if (first <= last) { struct hashentry *head = NULL; /* Now we have to get the write lock since we are about to modify the table. */ if (__glibc_unlikely (pthread_rwlock_trywrlock (&table->lock) != 0)) { ++table->head->wrlockdelayed; pthread_rwlock_wrlock (&table->lock); } while (first <= last) { if (mark[first]) { ref_t *old = &table->head->array[first]; ref_t run = table->head->array[first]; assert (run != ENDREF); do { struct hashentry *runp = (struct hashentry *) (data + run); struct datahead *dh = (struct datahead *) (data + runp->packet); if (! dh->usable) { /* We need the list only for debugging but it is more costly to avoid creating the list than doing it. */ runp->dellist = head; head = runp; /* No need for an atomic operation, we have the write lock. */ --table->head->nentries; run = *old = runp->next; } else { old = &runp->next; run = runp->next; } } while (run != ENDREF); } ++first; } /* It's all done. */ pthread_rwlock_unlock (&table->lock); /* Make sure the data is saved to disk. */ if (table->persistent) msync (table->head, data + table->head->first_free - (char *) table->head, MS_ASYNC); /* One extra pass if we do debugging. */ if (__glibc_unlikely (debug_level > 0)) { struct hashentry *runp = head; while (runp != NULL) { char buf[INET6_ADDRSTRLEN]; const char *str; if (runp->type == GETHOSTBYADDR || runp->type == GETHOSTBYADDRv6) { inet_ntop (runp->type == GETHOSTBYADDR ? AF_INET : AF_INET6, data + runp->key, buf, sizeof (buf)); str = buf; } else str = data + runp->key; dbg_log ("remove %s entry \"%s\"", serv2str[runp->type], str); runp = runp->dellist; } } } if (__glibc_unlikely (! mark_use_alloca)) free (mark); /* Run garbage collection if any entry has been removed or replaced. */ if (any) gc (table); /* If there is no entry in the database and we therefore have no new timeout value, tell the caller to wake up in 24 hours. */ return next_timeout == NO_TIMEOUT ? 24 * 60 * 60 : next_timeout - now; }
bool module_init(int argc, char ** argv, love::Core * core) { //std::cout << "argv[0] = " << argv[0] << std::endl; std::cout << "INIT love.system [" << "Generic" << "]" << std::endl; // Get used modules. filesystem = core->getFilesystem(); graphics = core->getGraphics(); // Verify all. if(!filesystem->verify()) { std::cerr << "Required module filesystem not loaded." << std::endl; return false; } if(!graphics->verify()) { std::cerr << "Required module graphics not loaded." << std::endl; return false; } // Set function pointers and load module. { love::System * s = core->getSystem(); s->getGame = love_system::getGame; s->error = love_system::syserr; s->loaded = true; } bool compatible = true; // Check command line arguments. std::string arg_game = love::get_arg_game(argc, argv); bool nogame = arg_game.empty(); // Get leaf. std::string arg0 = std::string(argv[0]); std::string leaf = love::get_leaf(arg0); // True if embedded mode. #ifdef WIN32 bool embedded = (leaf.compare("lov8.exe") != 0); #else bool embedded = (leaf.compare("lov8") != 0); #endif std::string base; bool absolute; std::string game_source; if(embedded) { // Create the game source. base = std::string(filesystem->getBaseDirectory()); absolute = love::is_arg_absolute(arg0); game_source = absolute ? arg0 : (base + "/" + leaf); printf("%s\n", game_source.c_str()); } else if(nogame) // Arguments might be empty. { std::cout << "Usage: love [FILE]" << std::endl; std::cout << std::endl << "Examples:" << std::endl << " love demo01.love"; std::cout << std::endl << " love /home/nyan/mygame" << std::endl << std::endl; // If no arguments, just load the no-game. main_game.reset<love::Game>(new LuaGame(love::nogame_lua, core)); if(!main_game->load()) { std::cout << "Could not load the no-game." << std::endl; return false; } current_game = main_game; return true; } else // Normal { // Create the game source. base = std::string(filesystem->getBaseDirectory()); absolute = love::is_arg_absolute(arg_game); game_source = absolute ? (arg_game) : (base + "/" + arg_game); } // Setup the save directory. if(!filesystem->setSaveDirectory(game_source)) { std::cerr << "Could not set save directory!" << std::endl; return false; } // Add the game source to the search path. if(!filesystem->addDirectory(game_source)) { std::cerr << "Game (" << game_source << ") does not exist." << std::endl; return false; } // Create configuration. love::pFile * conf = filesystem->getFile(GAME_CONF, love::FILE_READ); love::Configuration gc(*conf); delete conf; // Get entry point and create game. bool useV8 = filesystem->exists(GAME_MAIN_JS); love::pFile * main = useV8 ? filesystem->getFile(GAME_MAIN_JS, love::FILE_READ) : filesystem->getFile(GAME_MAIN, love::FILE_READ); if (useV8) main_game.reset<love::Game>(new V8Game(*main, core)); else main_game.reset<love::Game>(new LuaGame(*main, core)); delete main; // Also create error game, but load nothing yet. if(filesystem->exists(std::string(GAME_ERROR))) { love::pFile * error_main = filesystem->getFile(GAME_ERROR, love::FILE_READ); error_game.reset<love::Game>(new LuaGame(*error_main, core)); delete error_main; } else error_game.reset<love::Game>(new LuaGame(love::error_lua, core)); // The main game is the current game for now. current_game = main_game; // Create default values for the game configuration. gc.add("title", "Untitled Game"); gc.add("author", "Unknown Author"); gc.add("width", 800); gc.add("height", 600); gc.add("vsync", true); gc.add("fsaa", 0); gc.add("fullscreen", false); gc.add("love_version", std::string(LOVE_VERSION_STR)); gc.add("display_auto", true); // Now load the config file, causing default values // to be overwritten. if(filesystem->exists(GAME_CONF) && !gc.load()) { std::cerr << "Could not load configuration." << std::endl; return false; } // Set the window title. graphics->setCaption(gc.getString("title").c_str()); // Check if this game is made for a compatible // version of LOVE. std::string love_version = gc.getString("love_version"); compatible = love::is_compatible(love_version.c_str()); // Set the display mode, unless the user wants to do // that in Lua. // Note! In case the game isn't compatible, we must use // config settings. (Main game isn't loaded) if(gc.getBool("display_auto") || !compatible) { // Try config. if(!graphics->setMode(gc.getInt("width"), gc.getInt("height"), gc.getBool("fullscreen"), gc.getBool("vsync"), gc.getInt("fsaa"))) { // Try failsafe. if(!graphics->setMode(800, 600, false, true, 0)) { std::cerr << "Could not set display mode." << std::endl; return false; } } } // If the game isn't compatible, change to error game. if(!compatible) { std::stringstream err; err << "This game is made for another version of LOVE! The current " << "version is " << LOVE_VERSION_STR << " (game was made for " << love_version << ")."; suspend(); message(err.str().c_str(), love::TAG_INCOMPATIBLE); } // Current game should be set at this point. if(!current_game->isLoaded()) { if(compatible && current_game != 0 && !current_game->load()) { std::cerr << "Game could not be loaded." << std::endl; return false; } } return true; }
Lex Scanner::get_lex() { int d = 0, j, n = 1; double r = 0; CS = H; do { switch (CS) { case H: if (c == ' ' || c == '\n' || c == '\r' || c == '\t') gc(); else if (isalpha(c)) { clear(); add(); gc(); CS = IDENT; //cout << "H IDENT" << endl; } else if (isdigit(c)) { d = c - '0'; gc(); CS = NUM; //cout << "H NUM" << endl; } else if (c == '{') { gc(); CS = COM; //cout << "H COM" << endl; } else if (c == ':' || c == '<' || c == '>') { clear(); add(); gc(); CS = ALE; //cout << "H ALE" << endl; } else if (c == '@') { //cout << "H return" << endl; return Lex(LEX_FIN); } else if (c == '!') { clear(); add(); gc(); CS = NEQ; //cout << "H NEQ" << endl; } else if (c == '&') { clear(); add(); gc(); CS = UNMINUS; //cout << "H NEQ" << endl; } else { CS = DELIM; //cout << "H DELIM" << endl; } break; case IDENT: if (isalpha(c) || isdigit(c)) { //cout << "IDENT here1" << endl; add(); gc(); } else if (j = look(buf, TW)) { //cout << "IDENT here2" << endl; cout << "buf " << buf << endl; return Lex(words[j], j); } else { //cout << "IDENT here3" << endl; //cout << "buf " << buf << endl; j = TID.put(buf); return Lex(LEX_ID, j); } break; case NUM: if (isdigit(c)) { d = d * 10 + (c - '0'); gc(); } else if (c == '.') { gc(); CS = REAL; } else return Lex(LEX_NUM, d); break; case REAL: if (isdigit(c)) { r = r * 10 + (c - '0'); n *= 10; gc(); } else return Lex(LEX_NUM, d + r / n); break; case COM: if (c == '}') { gc(); CS = H; } else if (c == '@' || c == '{') throw c; else { gc(); } break; case ALE: if (c == '=') { add(); gc(); j = look(buf, TD); cout << "buf " << buf << endl; return Lex(dlms[j], j); } else { j = look(buf, TD); return Lex(dlms[j], j); } break; case NEQ: if (c == '=') { add(); gc(); j = look(buf, TD); return Lex(LEX_NEQ, j); } else throw '!'; break; case UNMINUS: j = look(buf, TD); return Lex(LEX_UN_MINUS, j); break; case DELIM: clear(); add(); if (j = look(buf, TD)) { gc(); return Lex(dlms[j], j); } else throw c; break; } // end switch } while (true); }
void KisQPainterCanvas::paintEvent(QPaintEvent * ev) { KisImageWSP image = canvas()->image(); if (image == 0) return; setAutoFillBackground(false); if (m_buffer.size() != size()) { m_buffer = QImage(size(), QImage::Format_ARGB32_Premultiplied); } QPainter gc(&m_buffer); // we double buffer, so we paint on an image first, then from the image onto the canvas, // so copy the clip region since otherwise we're filling the whole buffer every time with // the background color _and_ the transparent squares. gc.setClipRegion(ev->region()); KisCoordinatesConverter *converter = coordinatesConverter(); QTransform imageTransform = converter->viewportToWidgetTransform(); gc.save(); gc.setCompositionMode(QPainter::CompositionMode_Source); gc.fillRect(QRect(QPoint(0, 0), size()), borderColor()); QTransform checkersTransform; QPointF brushOrigin; QPolygonF polygon; converter->getQPainterCheckersInfo(&checkersTransform, &brushOrigin, &polygon); gc.setPen(Qt::NoPen); gc.setBrush(m_d->checkBrush); gc.setBrushOrigin(brushOrigin); gc.setTransform(checkersTransform); gc.drawPolygon(polygon); gc.setTransform(imageTransform); gc.setRenderHint(QPainter::SmoothPixmapTransform, true); QRectF viewportRect = converter->widgetToViewport(ev->rect()); gc.setCompositionMode(QPainter::CompositionMode_SourceOver); gc.drawImage(viewportRect, m_d->prescaledProjection->prescaledQImage(), viewportRect); gc.restore(); #ifdef DEBUG_REPAINT QColor color = QColor(random() % 255, random() % 255, random() % 255, 150); gc.fillRect(ev->rect(), color); #endif drawDecorations(gc, ev->rect()); gc.end(); QPainter painter(this); painter.drawImage(ev->rect(), m_buffer, ev->rect()); }
template<class T> inline void fr(T&r) { char c=gc(); for(;c<'0'||'9'<c;c=gc()); for(r=0;'0'<=c&&c<='9';c=getchar()) r=r*10+c-'0'; }
void wmem_gc(wmem_allocator_t *allocator) { allocator->gc(allocator->private_data); }
void replica::on_check_timer() { init_checkpoint(); gc(); }
HRESULT Library_spot_net_native_Microsoft_SPOT_Net_SocketNative::getaddrinfo___STATIC__VOID__STRING__BYREF_STRING__BYREF_SZARRAY_SZARRAY_U1( CLR_RT_StackFrame& stack ) { NATIVE_PROFILE_CLR_NETWORK(); TINYCLR_HEADER(); LPCSTR szName = stack.Arg0().RecoverString(); struct SOCK_addrinfo hints; struct SOCK_addrinfo* addr = NULL; struct SOCK_addrinfo* addrT; CLR_UINT32 cAddresses = 0; CLR_RT_HeapBlock* pAddress; CLR_INT32 timeout_ms = 30000; CLR_RT_HeapBlock hbTimeout; CLR_INT32 ret; bool fRes = true; CLR_INT64* timeout; hbTimeout.SetInteger( timeout_ms ); TINYCLR_CHECK_HRESULT(stack.SetupTimeout( hbTimeout, timeout )); do { memset( &hints, 0, sizeof(hints) ); ret = SOCK_getaddrinfo( szName, NULL, &hints, &addr ); if(ret == SOCK_SOCKET_ERROR) { if(SOCK_getlasterror() == SOCK_EWOULDBLOCK) { // non-blocking - allow other threads to run while we wait for handle activity TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.WaitEvents( stack.m_owningThread, *timeout, CLR_RT_ExecutionEngine::c_Event_Socket, fRes )); } else { break; } } else { break; } } while(fRes); // timeout expired if(!fRes) { ret = SOCK_SOCKET_ERROR; ThrowError( stack, SOCK_ETIMEDOUT ); TINYCLR_SET_AND_LEAVE( CLR_E_PROCESS_EXCEPTION ); } // getaddrinfo returns a winsock error code rather than SOCK_SOCKET_ERROR, so pass this on to the exception handling if(ret != 0) { ThrowError( stack, ret ); TINYCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } { CLR_RT_HeapBlock hbCanonicalName; CLR_RT_HeapBlock hbAddresses; hbCanonicalName.SetObjectReference( NULL ); CLR_RT_ProtectFromGC gc( hbCanonicalName ); hbAddresses.SetObjectReference( NULL ); CLR_RT_ProtectFromGC gc2( hbAddresses ); for(int pass = 0; pass < 2; pass++) { cAddresses = 0; for(addrT = addr; addrT != NULL; addrT = addrT->ai_next) { if(pass == 1) { if(addrT->ai_canonname && addrT->ai_canonname[ 0 ]) { //allocate return string TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_String::CreateInstance( hbCanonicalName, addrT->ai_canonname )); TINYCLR_CHECK_HRESULT(hbCanonicalName.StoreToReference( stack.Arg1(), 0 )); } //allocate address and store into array pAddress = (CLR_RT_HeapBlock*)hbAddresses.DereferenceArray()->GetElement( cAddresses ); TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( *pAddress, (CLR_UINT32)addrT->ai_addrlen, g_CLR_RT_WellKnownTypes.m_UInt8 )); //copy address. memcpy( pAddress->DereferenceArray()->GetFirstElement(), addrT->ai_addr, addrT->ai_addrlen ); } cAddresses++; } if(pass == 0) { //allocate array of byte arrays CLR_RT_ReflectionDef_Index idx; idx.m_kind = REFLECTION_TYPE; idx.m_levels = 2; idx.m_data.m_type.m_data = g_CLR_RT_WellKnownTypes.m_UInt8.m_data; TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( hbAddresses, cAddresses, idx )); TINYCLR_CHECK_HRESULT(hbAddresses.StoreToReference( stack.Arg2(), 0 )); } } } stack.PopValue(); // Timeout TINYCLR_CLEANUP(); if( addr ) SOCK_freeaddrinfo( addr ); TINYCLR_CLEANUP_END(); }
void MissingClassStaticMethod( char *className, char *methodName, char *methodDescr ) { union { int64_t lval; double dval; int32_t ival[2]; uint32_t uval[2]; } pair; if (strcmp(className,"java/lang/System") == 0) { if (strcmp(methodName,"gc") == 0) { if (strcmp(methodDescr,"()V") == 0) { gc(); return; } } else { fprintf(stderr, "Static method %s.%s with signature %s is unsupported\n", className, methodName, methodDescr); exit(1); } } if (strcmp(className,"java/lang/Integer") == 0) { if (strcmp(methodName,"parseInt") == 0) { if (strcmp(methodDescr,"(Ljava/lang/String;)I") == 0) { int ival = 0; HeapPointer hp = JVM_Pop(); if (hp == NULL_HEAP_REFERENCE) throwExceptionExternal("NullPointerException", methodName, className); StringInstance *arg = REAL_HEAP_POINTER(hp); if (sscanf(arg->sval, "%d", &ival) < 1) throwExceptionExternal( "NumberFormatException", methodName, className ); JVM_Push( (uint32_t)ival ); return; } } } if (strcmp(className,"java/lang/Double") == 0) { if (strcmp(methodName,"parseDouble") == 0) { if (strcmp(methodDescr,"(Ljava/lang/String;)D") == 0) { HeapPointer hp = JVM_Pop(); if (hp == NULL_HEAP_REFERENCE) throwExceptionExternal("NullPointerException", methodName, className); StringInstance *arg = REAL_HEAP_POINTER(hp); if (sscanf(arg->sval, "%lg", &pair.dval) < 1) throwExceptionExternal( "NumberFormatException", methodName, className ); JVM_Push(pair.uval[0]); JVM_Push(pair.uval[1]); return; } } } if (strcmp(className,"java/lang/Float") == 0) { if (strcmp(methodName,"parseFloat") == 0) { if (strcmp(methodDescr,"(Ljava/lang/String;)F") == 0) { float fval = 0.0; HeapPointer hp = JVM_Pop(); if (hp == NULL_HEAP_REFERENCE) throwExceptionExternal("NullPointerException", methodName, className); StringInstance *arg = REAL_HEAP_POINTER(hp); if (sscanf(arg->sval, "%f", &fval) < 1) throwExceptionExternal( "NumberFormatException", methodName, className ); JVM_PushFloat(fval); return; } } } fprintf(stderr, "Static method %s.%s with signature %s is missing or unsupported\n", className, methodName, methodDescr); exit(1); }
HRESULT CLR_RT_HeapBlock_Delegate_List::Change( CLR_RT_HeapBlock& reference, CLR_RT_HeapBlock& delegateSrc, CLR_RT_HeapBlock& delegateTarget, bool fCombine, bool fWeak ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); CLR_RT_HeapBlock_Delegate_List* dlgListSrc; CLR_RT_HeapBlock_Delegate_List* dlgListDst; CLR_RT_HeapBlock_Delegate* dlg; CLR_RT_HeapBlock* newDlgs; CLR_RT_HeapBlock* oldDlgs; CLR_UINT32 oldNum; CLR_UINT32 newNum; CLR_UINT32 num = 0; reference.SetObjectReference( NULL ); if(delegateSrc .DataType() != DATATYPE_OBJECT || delegateTarget.DataType() != DATATYPE_OBJECT ) { TINYCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE); } dlg = delegateTarget.DereferenceDelegate(); if(dlg == NULL) { reference.SetObjectReference( delegateSrc.DereferenceDelegate() ); TINYCLR_SET_AND_LEAVE(S_OK); } if(dlg->DataType() == DATATYPE_DELEGATELIST_HEAD) { CLR_RT_HeapBlock intermediate; intermediate.Assign( delegateSrc ); CLR_RT_ProtectFromGC gc( intermediate ); dlgListDst = (CLR_RT_HeapBlock_Delegate_List*)dlg; newDlgs = dlgListDst->GetDelegates(); for(num=0; num<dlgListDst->m_length; num++, newDlgs++) { if(newDlgs->DataType() == DATATYPE_OBJECT && newDlgs->DereferenceDelegate() != NULL) // The delegate could have been GC'ed. { TINYCLR_CHECK_HRESULT(Change( reference, intermediate, *newDlgs, fCombine, fWeak )); intermediate.Assign( reference ); } } } else { dlgListSrc = delegateSrc.DereferenceDelegateList(); if(dlgListSrc == NULL) { oldDlgs = NULL; oldNum = 0; } else { switch(dlgListSrc->DataType()) { case DATATYPE_DELEGATE_HEAD: oldDlgs = &delegateSrc; oldNum = 1; break; case DATATYPE_DELEGATELIST_HEAD: oldDlgs = dlgListSrc->GetDelegates(); oldNum = dlgListSrc->m_length; break; default: TINYCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE); } } if(fCombine) { if(oldNum == 0 && fWeak == false) { // // Empty input list, copy the delegate. // reference.Assign( delegateTarget ); TINYCLR_SET_AND_LEAVE(S_OK); } //--// newNum = oldNum + 1; } else { for(num=0, newDlgs=oldDlgs; num<oldNum; num++, newDlgs++) { CLR_RT_HeapBlock_Delegate* ptr = newDlgs->DereferenceDelegate(); if(ptr) { if( ptr->DelegateFtn().m_data == dlg->DelegateFtn().m_data && ptr->m_object.Dereference() == dlg->m_object.Dereference() ) { break; } } } if(num == oldNum) { reference.Assign( delegateSrc ); // Nothing to remove. TINYCLR_SET_AND_LEAVE(S_OK); } if(oldNum == 2 && (dlgListSrc->m_flags & CLR_RT_HeapBlock_Delegate_List::c_Weak) == 0) { reference.Assign( oldDlgs[ 1-num ] ); // Convert from a list to delegate. TINYCLR_SET_AND_LEAVE(S_OK); } if(oldNum == 1) { reference.SetObjectReference( NULL ); // Oops, empty delegate... TINYCLR_SET_AND_LEAVE(S_OK); } //--// newNum = oldNum - 1; } TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Delegate_List::CreateInstance( dlgListDst, newNum )); dlgListDst->m_cls = dlg->m_cls; newDlgs = dlgListDst->GetDelegates(); if(fCombine) { newDlgs = dlgListDst->CopyAndCompress( oldDlgs, newDlgs, oldNum ); newDlgs->Assign( delegateTarget ); } else { newDlgs = dlgListDst->CopyAndCompress( oldDlgs , newDlgs, num++ ); newDlgs = dlgListDst->CopyAndCompress( oldDlgs + num, newDlgs, oldNum - num ); } dlgListDst->m_flags = (dlgListSrc && oldNum > 1) ? dlgListSrc->m_flags : 0; if(fWeak) dlgListDst->m_flags |= CLR_RT_HeapBlock_Delegate_List::c_Weak; reference.SetObjectReference( dlgListDst ); } TINYCLR_NOCLEANUP(); }
void test(bool mirrorX, bool mirrorY, qreal rotation, bool mirrorDabX, bool mirrorDabY, qreal dabRotation) { KisSurrogateUndoStore *undoStore = new KisSurrogateUndoStore(); KisImageSP image = createTrivialImage(undoStore); image->initialRefreshGraph(); KisNodeSP paint1 = findNode(image->root(), "paint1"); QVERIFY(paint1->extent().isEmpty()); KisPainter gc(paint1->paintDevice()); QScopedPointer<KoCanvasResourceManager> manager( utils::createResourceManager(image, 0, m_presetFileName)); KisPaintOpPresetSP preset = manager->resource(KisCanvasResourceProvider::CurrentPaintOpPreset).value<KisPaintOpPresetSP>(); preset->settings()->setCanvasRotation(rotation); preset->settings()->setCanvasMirroring(mirrorY, mirrorX); if (mirrorDabX || mirrorDabY) { KisPaintOpSettingsSP settings = preset->settings()->clone(); KisPressureMirrorOption mirrorOption; mirrorOption.readOptionSetting(settings); mirrorOption.setChecked(true); mirrorOption.setCurveUsed(false); mirrorOption.enableHorizontalMirror(mirrorDabX); mirrorOption.enableVerticalMirror(mirrorDabY); mirrorOption.writeOptionSetting(settings.data()); preset->setSettings(settings); } if (dabRotation != 0.0) { KisPaintOpSettingsSP settings = preset->settings()->clone(); KisPressureRotationOption rotationOption; rotationOption.readOptionSetting(settings); rotationOption.setChecked(true); rotationOption.setCurveUsed(false); rotationOption.setValue(dabRotation / 360.0); rotationOption.writeOptionSetting(settings.data()); preset->setSettings(settings); } QString testName = QString("%7_cmY_%1_cmX_%2_cR_%3_dmX_%4_dmY_%5_dR_%6") .arg(mirrorY) .arg(mirrorX) .arg(rotation) .arg(mirrorDabX) .arg(mirrorDabY) .arg(std::fmod(360.0 - dabRotation, 360.0)) .arg(m_prefix); KisResourcesSnapshotSP resources = new KisResourcesSnapshot(image, paint1, manager.data()); resources->setupPainter(&gc); doPaint(gc); checkOneLayer(image, paint1, testName); }
HRESULT CLR_RT_HeapBlock_Array::Copy( CLR_RT_HeapBlock_Array* arraySrc, int indexSrc, CLR_RT_HeapBlock_Array* arrayDst, int indexDst, int length ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); if(length) { int numElemSrc = arraySrc->m_numOfElements; int numElemDst = arrayDst->m_numOfElements; if(length < 0 || indexSrc < 0 || indexDst < 0 || length + indexSrc > numElemSrc || length + indexDst > numElemDst ) { TINYCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); } // // Copy of an array on itself. // if(arraySrc == arrayDst && indexSrc == indexDst) TINYCLR_SET_AND_LEAVE(S_OK); if(arraySrc->SameHeader( *arrayDst )) { CLR_UINT8* dataSrc = arraySrc->GetFirstElement(); CLR_UINT8* dataDst = arrayDst->GetFirstElement(); CLR_UINT8 sizeElem = arraySrc->m_sizeOfElement; dataSrc += indexSrc * sizeElem; dataDst += indexDst * sizeElem; if(!arraySrc->m_fReference) { memmove( dataDst, dataSrc, length * sizeElem ); } else { CLR_RT_HeapBlock* ptrSrc = (CLR_RT_HeapBlock*)dataSrc; CLR_RT_HeapBlock* ptrDst = (CLR_RT_HeapBlock*)dataDst; int incr; if(arraySrc == arrayDst && ptrSrc < ptrDst) { incr = -1; ptrSrc += length-1; ptrDst += length-1; } else { incr = 1; } for(int i=0; i<length; i++, ptrSrc += incr, ptrDst += incr) { TINYCLR_CHECK_HRESULT(ptrDst->Reassign( *ptrSrc )); } } } else if(arraySrc->m_fReference && arrayDst->m_fReference) { CLR_RT_TypeDescriptor descSrc; CLR_RT_TypeDescriptor descDst; CLR_RT_HeapBlock* ptrSrc = (CLR_RT_HeapBlock*)arraySrc->GetElement( indexSrc ); CLR_RT_HeapBlock* ptrDst = (CLR_RT_HeapBlock*)arrayDst->GetElement( indexDst ); TINYCLR_CHECK_HRESULT(descDst.InitializeFromObject( *arrayDst )); descDst.GetElementType( descDst ); for(int i=0; i<length; i++, ptrSrc++, ptrDst++) { if(ptrSrc->DataType() == DATATYPE_OBJECT && ptrSrc->Dereference() == NULL) { ; } else { TINYCLR_CHECK_HRESULT(descSrc.InitializeFromObject( *ptrSrc )); if(CLR_RT_ExecutionEngine::IsInstanceOf( descSrc, descDst ) == false) { TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_CAST); } } TINYCLR_CHECK_HRESULT(ptrDst->Reassign( *ptrSrc )); } } else { CLR_RT_TypeDescriptor descSrc; CLR_RT_TypeDescriptor descDst; CLR_RT_HeapBlock ref; CLR_RT_HeapBlock elem; elem.SetObjectReference( NULL ); CLR_RT_ProtectFromGC gc( elem ); TINYCLR_CHECK_HRESULT(descDst.InitializeFromObject( *arrayDst )); descDst.GetElementType( descDst ); for(int i=0; i<length; i++) { ref.InitializeArrayReferenceDirect( *arraySrc, indexSrc++ ); TINYCLR_CHECK_HRESULT(elem.LoadFromReference( ref )); if(elem.DataType() == DATATYPE_OBJECT && elem.Dereference() == NULL) { ; } else { TINYCLR_CHECK_HRESULT(descSrc.InitializeFromObject( elem )); if(CLR_RT_ExecutionEngine::IsInstanceOf( descSrc, descDst ) == false) { TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_CAST); } } ref.InitializeArrayReferenceDirect( *arrayDst, indexDst++ ); TINYCLR_CHECK_HRESULT(elem.StoreToReference( ref, 0 )); } } } TINYCLR_NOCLEANUP(); }
// display model using colors stored in each node // used when preview is running void ModelClass::DisplayModelOnWindow(wxWindow* window) { size_t NodeCount=Nodes.size(); wxCoord sx,sy; wxPen pen; wxColour color; wxDouble w, h; ModelGraphics gc(window); /* // this isn't an ideal scaling algorithm - room for improvement here double windowDiagonal=sqrt(w*w+h*h); double modelDiagonal=sqrt(RenderWi*RenderWi+RenderHt*RenderHt); double scale=windowDiagonal / modelDiagonal * PreviewScale; */ gc.GetSize(&w, &h); double scale=RenderHt > RenderWi ? double(h) / RenderHt * PreviewScale : double(w) / RenderWi * PreviewScale; gc.Translate(int(offsetXpct*w)+w/2, -(int(offsetYpct*h)+h- std::max((int(h)-int(double(RenderHt-1)*scale))/2,1))); // avoid performing StrobeRate test in inner loop for performance reasons if (StrobeRate==0) { // no strobing for(size_t n=0; n<NodeCount; n++) { Nodes[n]->GetColor(color); size_t CoordCount=GetCoordCount(n); for(size_t c=0; c < CoordCount; c++) { // draw node on screen sx=Nodes[n]->Coords[c].screenX; sy=Nodes[n]->Coords[c].screenY; gc.AddSquare(color,sx*scale,sy*scale,0.0); } } } else { // flash individual nodes according to StrobeRate for(size_t n=0; n<NodeCount; n++) { Nodes[n]->GetColor(color); bool CanFlash = color.GetRGB() == 0x00ffffff; size_t CoordCount=GetCoordCount(n); for(size_t c=0; c < CoordCount; c++) { wxColor c2 = *wxBLACK; // draw node on screen if (CanFlash && rand() % StrobeRate == 0) { c2 = color; } sx=Nodes[n]->Coords[c].screenX; sy=Nodes[n]->Coords[c].screenY; gc.AddSquare(c2,sx*scale,sy*scale,0.0); } } } }
void vm_gc(){ gc(global_vm); }
clSelectDriveDlgMenu::clSelectDriveDlgMenu( Win* parent, clMenuData* data ) : Win( Win::WT_CHILD, Win::WH_TABFOCUS | Win::WH_CLICKFOCUS, parent ) , _data( data ) , _current( 0 ) , _itemH( 16 ) , _width( 50 ) , _nameW( 10 ) , _comment1W( 0 ) , _comment2W( 0 ) , _splitterH( 5 ) , _splitterW( 1 ) { wal::GC gc( this ); gc.Set( GetFont() ); int w = 0; int height = 0; static unicode_t A[] = {'A', 'B', 'C'}; cpoint p = gc.GetTextExtents( A, 3 ); _itemH = p.y; if ( _itemH < 16 ) { _itemH = 16; } _splitterH = _itemH / 4; if ( _splitterH < 3 ) { _splitterH = 3; } for ( int i = 0 ; i < _data->Count(); i++ ) { unicode_t* name = _data->list[i].name.data(); if ( _data->list[i].cmd != 0 ) { if ( name ) { cpoint p = gc.GetTextExtents( name ); if ( _nameW < p.x ) { _nameW = p.x; } } unicode_t* comment1 = _data->list[i].comment1.data(); unicode_t* comment2 = _data->list[i].comment2.data(); if ( comment1 ) { cpoint p = gc.GetTextExtents( comment1 ); if ( _comment1W < p.x ) { _comment1W = p.x; } } if ( comment2 ) { cpoint p = gc.GetTextExtents( comment2 ); if ( _comment2W < p.x ) { _comment2W = p.x; } } height += _itemH; } else { height += _splitterH; } } w = 16 + 5 + _nameW + 5 + _comment1W + 30 + _comment2W; if ( _width < w ) { _width = w; } SetLSize( LSize( cpoint( _width, height ) ) ); }
void GlobalsCollector::collect(MacroDef & macrodef) { GlobalsCollector gc(macrodef); gc.collect(); //gc.print_info(); }
void gi(T&x){ for(c=gc();c<'0'||c>'9';c=gc()); x=c&15; for(c=gc();c>='0'&&c<='9';c=gc())x=x*10+(c&15); }
// issue home command void SCARAcal::home() { Gcode gc("G28", &(StreamOutput::NullStream)); THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc); }
/* * v_match -- % * Search to matching character. * * PUBLIC: int v_match(SCR *, VICMD *); */ int v_match(SCR *sp, VICMD *vp) { VCS cs; MARK *mp; size_t cno, len, off; int cnt, isempty, matchc, startc, (*gc)(SCR *, VCS *); CHAR_T *p; CHAR_T *cp; const CHAR_T *match_chars; /* * Historically vi would match (), {} and [] however * an update included <>. This is ok for editing HTML * but a pain in the butt for C source. * Making it an option lets the user decide what is 'right'. */ match_chars = VIP(sp)->mcs; /* * !!! * Historic practice; ignore the count. * * !!! * Historical practice was to search for the initial character in the * forward direction only. */ if (db_eget(sp, vp->m_start.lno, &p, &len, &isempty)) { if (isempty) goto nomatch; return (1); } for (off = vp->m_start.cno;; ++off) { if (off >= len) { nomatch: msgq(sp, M_BERR, "184|No match character on this line"); return (1); } startc = p[off]; cp = STRCHR(match_chars, startc); if (cp != NULL) { cnt = cp - match_chars; matchc = match_chars[cnt ^ 1]; gc = cnt & 1 ? cs_prev : cs_next; break; } } cs.cs_lno = vp->m_start.lno; cs.cs_cno = off; if (cs_init(sp, &cs)) return (1); for (cnt = 1;;) { if (gc(sp, &cs)) return (1); if (cs.cs_flags != 0) { if (cs.cs_flags == CS_EOF || cs.cs_flags == CS_SOF) break; continue; } if (cs.cs_ch == startc) ++cnt; else if (cs.cs_ch == matchc && --cnt == 0) break; } if (cnt) { msgq(sp, M_BERR, "185|Matching character not found"); return (1); } vp->m_stop.lno = cs.cs_lno; vp->m_stop.cno = cs.cs_cno; /* * If moving right, non-motion commands move to the end of the range. * Delete and yank stay at the start. * * If moving left, all commands move to the end of the range. * * !!! * Don't correct for leftward movement -- historic vi deleted the * starting cursor position when deleting to a match. */ if (vp->m_start.lno < vp->m_stop.lno || (vp->m_start.lno == vp->m_stop.lno && vp->m_start.cno < vp->m_stop.cno)) vp->m_final = ISMOTION(vp) ? vp->m_start : vp->m_stop; else vp->m_final = vp->m_stop; /* * !!! * If the motion is across lines, and the earliest cursor position * is at or before any non-blank characters in the line, i.e. the * movement is cutting all of the line's text, and the later cursor * position has nothing other than whitespace characters between it * and the end of its line, the buffer is in line mode. */ if (!ISMOTION(vp) || vp->m_start.lno == vp->m_stop.lno) return (0); mp = vp->m_start.lno < vp->m_stop.lno ? &vp->m_start : &vp->m_stop; if (mp->cno != 0) { cno = 0; if (nonblank(sp, mp->lno, &cno)) return (1); if (cno < mp->cno) return (0); } mp = vp->m_start.lno < vp->m_stop.lno ? &vp->m_stop : &vp->m_start; if (db_get(sp, mp->lno, DBG_FATAL, &p, &len)) return (1); for (p += mp->cno + 1, len -= mp->cno; --len; ++p) if (!isblank(*p)) return (0); F_SET(vp, VM_LMODE); return (0); }
inline char gchar(char r=gc()) { for(;r==' '||r=='\n'||r=='\r'; r=gc());return r;}
VPoint3 GetFGravityCenter(VPoint3& p1,VPoint3& p2,VPoint3& p3){ //求三个点组成的三角形的重心 VPoint3 gc(0.0,0.0,0.0); gc += p1 + p2 + p3; gc /= 3.0f; return gc; }