text
stringlengths
5
1.04M
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 1996. // // File: seltrig.hxx // // Contents: Task wizard trigger selection property page. // // Classes: CSelectTriggerPage // // History: 4-30-1997 DavidMun Created // //--------------------------------------------------------------------------- #ifndef __SELTRIG_HXX_ #define __SELTRIG_HXX_ //+-------------------------------------------------------------------------- // // Class: CSelectTriggerPage // // Purpose: Implement the task wizard trigger selection dialog // // History: 4-28-1997 DavidMun Created // //--------------------------------------------------------------------------- class CSelectTriggerPage: public CWizPage { public: CSelectTriggerPage::CSelectTriggerPage( CTaskWizard *pParent, LPTSTR ptszFolderPath, HPROPSHEETPAGE *phPSP); CSelectTriggerPage::~CSelectTriggerPage(); // // CPropPage overrides // virtual LRESULT _OnCommand( INT id, HWND hwndCtl, UINT codeNotify); // // CWizPage overrides // virtual LRESULT _OnInitDialog( LPARAM lParam); virtual LRESULT _OnPSNSetActive( LPARAM lParam); virtual LRESULT _OnWizBack(); virtual LRESULT _OnWizNext(); // // New methods // ULONG GetSelectedTriggerPageID(); ULONG GetSelectedTriggerType(); CTriggerPage * GetSelectedTriggerPage(); LPCTSTR GetTaskName(); LPCTSTR GetJobObjectFullPath(); private: CTaskWizard *_pParent; ULONG _idSelectedTrigger; TCHAR _tszDisplayName[MAX_PATH + 1]; TCHAR _tszJobObjectFullPath[MAX_PATH + 1]; }; //+-------------------------------------------------------------------------- // // Member: CSelectTriggerPage::GetSelectedTriggerPageID // // Synopsis: Return the resource id of the trigger page the user selected // // Returns: IDD_* // // History: 5-06-1997 DavidMun Created // //--------------------------------------------------------------------------- inline ULONG CSelectTriggerPage::GetSelectedTriggerPageID() { if (_idSelectedTrigger == seltrig_startup_rb || _idSelectedTrigger == seltrig_logon_rb) { return IDD_SELECT_TRIGGER; } return IDD_DAILY + (_idSelectedTrigger - seltrig_first_rb); } //+-------------------------------------------------------------------------- // // Member: CSelectTriggerPage::GetSelectedTriggerType // // Synopsis: Return the resource id of the selected trigger radio button // // History: 5-20-1997 DavidMun Created // //--------------------------------------------------------------------------- inline ULONG CSelectTriggerPage::GetSelectedTriggerType() { return _idSelectedTrigger; } //+-------------------------------------------------------------------------- // // Member: CSelectTriggerPage::GetSelectedTriggerPage // // Synopsis: Return a pointer to the wizard page corresponding to the // selected trigger radio button, or NULL if there is no such // page or a radio button hasn't been selected yet. // // History: 5-20-1997 DavidMun Created // //--------------------------------------------------------------------------- inline CTriggerPage * CSelectTriggerPage::GetSelectedTriggerPage() { if (!_idSelectedTrigger || _idSelectedTrigger == seltrig_startup_rb || _idSelectedTrigger == seltrig_logon_rb) { return NULL; } TASK_WIZARD_PAGE twp; twp = (TASK_WIZARD_PAGE) ((ULONG)TWP_DAILY + (_idSelectedTrigger - seltrig_first_rb)); return (CTriggerPage *)_pParent->GetPage(twp); } //+-------------------------------------------------------------------------- // // Member: CSelectTriggerPage::GetTaskName // // Synopsis: Return the task display name, which is used as the filename // of the .job object path returned by GetJobObjectFullPath. // // History: 5-06-1997 DavidMun Created // //--------------------------------------------------------------------------- inline LPCTSTR CSelectTriggerPage::GetTaskName() { return _tszDisplayName; } //+-------------------------------------------------------------------------- // // Member: CSelectTriggerPage::GetJobObjectFullPath // // Synopsis: Return the full path to the .job object // // History: 5-19-1997 DavidMun Created // //--------------------------------------------------------------------------- inline LPCTSTR CSelectTriggerPage::GetJobObjectFullPath() { return _tszJobObjectFullPath; } #endif // __SELTRIG_HXX_
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #include "config.h" #include "main.h" #include "promptline.h" #include "errorlog.h" #include "pcell_params.h" #include "dsp_inlines.h" #include "dsp_tkif.h" #include "oa_if.h" #include "python_if.h" #include "tcltk_if.h" #include "si_parsenode.h" #include "si_args.h" #include "si_handle.h" #include "si_parser.h" #include "tech.h" #include "reltag.h" #ifdef HAVE_SECURE #include "secure.h" #endif #include "miscutil/filestat.h" #ifdef HAVE_MOZY #include "help/help_defs.h" #endif #ifdef HAVE_OA #include <dlfcn.h> //#include <pwd.h> #endif //----------------------------------------------------------------------------- // Interface to OpenAccess database. // namespace { #ifdef HAVE_OA // Dynamically open our helper lib, and return a pointer to the // OA interface if successful. // cOA_base *find_oa(char **lname) { bool verbose = (getenv("XIC_PLUGIN_DBG") != 0); #ifdef HAVE_SECURE // Use requires a license. int code = XM()->Auth()->validate(OA_CODE, CDvdb()->getVariable(VA_LibPath)); if (code != OA_CODE) { if (verbose) printf("The OpenAccess plug-in is not licensed, " "contact\nWhiteley Research for product and licensing " "information.\n"); return (0); } #endif sLstr lstr; const char *oaso_path = getenv("XIC_OASO_PATH"); if (oaso_path) { // User told us where to look. lstr.add(oaso_path); } else { // Look in the plugins directory. lstr.add(XM()->ProgramRoot()); lstr.add("/plugins/"); lstr.add("oa."); #ifdef __APPLE__ lstr.add("dylib"); #else lstr.add("so"); #endif } if (verbose) { const char *lp = getenv("LD_LIBRARY_PATH"); if (lp && *lp) printf("lib path: %s\n", lp); else printf("lib path: %s\n", "null"); } void *handle = dlopen(lstr.string(), RTLD_LAZY | RTLD_GLOBAL); if (!handle) { if (verbose) { printf("dlopen failed: %s\n", dlerror()); printf("plugin: %s\n", lstr.string()); } return (0); } cOA_base*(*oaptr)() = (cOA_base*(*)())dlsym(handle, "oaptr"); if (!oaptr) { if (verbose) { printf("dlsym failed: %s\n", dlerror()); printf("plugin: %s\n", lstr.string()); } return (0); } char idstr[64]; sprintf(idstr, "%s %s", XM()->OSname(), XIC_RELEASE_TAG); cOA_base *oa = (*oaptr)(); if (oa && (!oa->id_string() || strcmp(idstr, oa->id_string()))) { if (verbose) { printf ("OpenAccess plug-in version mismatch:\n" "Xic is \"%s\", plug-in is \"%s\"\n", idstr, oa->id_string() ? oa->id_string() : ""); printf("plugin: %s\n", lstr.string()); } return (0); } if (!oa) { if (verbose) printf ("oa interface returned null pointer\n"); return (0); } if (lname) *lname = lstring::copy(lstring::strip_path(lstr.string())); return (oa); } #endif // Phony class when OA is not available. class cOA_stubs : public cOA_base { const char *id_string() { return (""); } bool initialize() { return (false); } const char *version() { return (0); } const char *set_debug_flags(const char*, const char*) { return ("unavailable"); } bool is_library(const char*, bool*) { return (false); } bool list_libraries(stringlist**) { return (0); } bool list_lib_cells(const char*, stringlist**) { return (0); } bool list_cell_views(const char*, const char*, stringlist**) { return (0); } bool set_lib_open(const char*, bool) { return (false); } bool is_lib_open(const char*, bool*) { return (false); } bool is_oa_cell(const char*, bool, bool*) { return (false); } bool is_cell_in_lib(const char*, const char*, bool*) { return (false); } bool is_oa_cellview(const char*, const char*, bool, bool*) { return (false); } bool is_cellview_in_lib(const char*, const char*, const char*, bool*) { return (false); } bool create_lib(const char*, const char*) { return (false); } bool brand_lib(const char*, bool) { return (false); } bool is_lib_branded(const char*, bool*) { return (false); } bool destroy(const char*, const char*, const char*) { return (false); } bool load_library(const char*) { return (false); } bool load_cell(const char*, const char*, const char*, int, bool, const char** = 0, PCellParam** = 0) { return (false); } OItype open_lib_cell(const char*, CDcbin*) { return (OIerror); } void clear_name_table() { } bool save(const CDcbin*, const char*, bool = false, const char * = 0) { return (false); } bool attach_tech(const char*, const char*) { return (false); } bool destroy_tech(const char*, bool) { return (false); } bool has_attached_tech(const char*, char**) { return (false); } bool has_local_tech(const char*, bool*) { return (false); } bool create_local_tech(const char*) { return (false); } bool save_tech() { return (false); } bool print_tech(FILE*, const char*, const char*, const char*) { return (false); } }; #ifdef HAVE_OA void setup_bang_cmds(); void setup_vars(); void setup_funcs(); #endif } cOAif *cOAif::instancePtr = 0; cOAif::cOAif() { if (instancePtr) { fprintf(stderr, "Singleton class cOAif already instantiated.\n"); exit(1); } instancePtr = this; #ifdef HAVE_OA char *lname = 0; oaPtr = find_oa(&lname); if (oaPtr) { has_oa = true; setup_bang_cmds(); setup_vars(); setup_funcs(); #ifdef HAVE_MOZY // Define "OpenAccess" in the help database, makes visible // related text and topics. HLP()->define("OpenAccess"); #endif printf("Using OpenAccess (%s).\n", lname); delete [] lname; return; } #endif has_oa = false; oaPtr = new cOA_stubs; } // Private static error exit. // void cOAif::on_null_ptr() { fprintf(stderr, "Singleton class cOAif used before instantiated.\n"); exit(1); } // // ! (Bang) Commands // #ifdef HAVE_OA namespace { namespace oa_bangcmds { void oaversion(const char*); void oadebug(const char*); void oanewlib(const char*); void oabrand(const char*); void oatech(const char*); void oasave(const char*); void oaload(const char*); void oareset(const char*); void oadelete(const char*); } } void oa_bangcmds::oaversion(const char*) { PL()->ShowPromptV("Using OpenAccess %s.", OAif()->version()); } void oa_bangcmds::oanewlib(const char *s) { const char *usage = "Usage: oanewlib libname [oldlibname]"; char *libname = lstring::gettok(&s); if (!libname) { PL()->ShowPrompt(usage); return; } GCarray<char*> gc_libname(libname); char *oldlibname = lstring::gettok(&s); GCarray<char*> gc_oldlibname(oldlibname); if (!OAif()->create_lib(libname, oldlibname)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ErasePrompt(); return; } PL()->ShowPromptV( "OpenAccess library %s has been created if it didn't exist.", libname); } void oa_bangcmds::oabrand(const char *s) { const char *usage = "Usage: oabrand [libname] [y|n]"; char *libname = lstring::gettok(&s); if (!libname) { s = CDvdb()->getVariable(VA_OaDefLibrary); libname = lstring::gettok(&s); } if (!libname) { PL()->ShowPromptV("No library given and no default. %s", usage); return; } GCarray<char*> gc_libname(libname); char *yn = lstring::gettok(&s); if (!yn) { bool islib; if (!OAif()->is_library(libname, &islib)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ErasePrompt(); return; } if (!islib) { PL()->ShowPromptV("Unknown OpenAccess library %s.", libname); return; } bool isb; if (!OAif()->is_lib_branded(libname, &isb)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ErasePrompt(); return; } PL()->ShowPromptV( "OpenAccess library %s %s branded (can save only to " "branded libraries).", libname, isb ? "is" : "is NOT"); return; } lstring::strtolower(yn); bool yes = (*yn == 'y' || *yn == '1' || *yn == 't'); if (!yes) { bool no = (*yn == 'n' || *yn == '1' || *yn == 'f'); if (!no) { PL()->ShowPrompt(usage); return; } } bool islib; if (!OAif()->is_library(libname, &islib)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ErasePrompt(); return; } if (!islib) { if (!yes) { PL()->ShowPromptV("Unknown OpenAccess library %s.", libname); return; } const char *in = PL()->EditPrompt( "Library does not exist, create it? ", "n"); in = lstring::strip_space(in); if (in == 0) { PL()->ErasePrompt(); return; } if (*in == 'y' || *in == '1' || *in == 't') { if (!OAif()->create_lib(libname, 0)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ErasePrompt(); return; } // The create_lib call brands the new library, so the // brand_lib call below is redundant but harmless. } else { PL()->ErasePrompt(); return; } } if (!OAif()->brand_lib(libname, yes)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); return; } if (yes) PL()->ShowPromptV( "OpenAccess library %s is branded, can save to this library.", libname); else PL()->ShowPromptV( "OpenAccess library %s is NOT branded, can NOT save to this " "library.", libname); } void oa_bangcmds::oatech(const char *s) { char *tok = lstring::gettok(&s); if (!tok) return; char sel[4]; strncpy(sel, tok, 4); sel[3] = 0; delete [] tok; char *libname = lstring::gettok(&s); if (!libname) { PL()->ShowPrompt("No library name given."); return; } GCarray<char*> gc_libname(libname); if (lstring::ciprefix("a", sel) || lstring::ciprefix("-a", sel)) { // attach: libname fromlib char *fromlib = lstring::gettok(&s); if (!fromlib) { PL()->ShowPrompt("No source library name given."); return; } if (!OAif()->attach_tech(libname, fromlib)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ShowPrompt("Attachment failed."); } else PL()->ShowPrompt("Attachment succeeded."); delete [] fromlib; } else if (lstring::ciprefix("d", sel) || lstring::ciprefix("-d", sel)) { // destroy: libname bool has_attch = false; char *alib; if (OAif()->has_attached_tech(libname, &alib)) { has_attch = (alib != 0); delete [] alib; } if (!OAif()->destroy_tech(libname, false)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ShowPromptV("Tech %s failed.", has_attch ? "unattach" : "delete"); } else PL()->ShowPromptV("Tech %s succeeded.", has_attch ? "unattach" : "delete"); } else if (lstring::ciprefix("h", sel) || lstring::ciprefix("-h", sel)) { // has attached: libname char *alib; if (OAif()->has_attached_tech(libname, &alib)) { PL()->ShowPromptV( "Technology from library %s is attached to library %s.", alib, libname); delete [] alib; } else PL()->ShowPromptV( "Library %s has no attached technology database.", libname); } else if (lstring::ciprefix("p", sel) || lstring::ciprefix("-p", sel)) { // print: libname [-o filename] [which [prname]] char *fname = 0; char *which = 0; char *prname = 0; while ((tok = lstring::gettok(&s)) != 0) { if (!strcmp(tok, "-o")) { delete [] tok; delete [] fname; fname = lstring::gettok(&s); continue; } if (!which) { which = tok; continue; } if (!prname) { prname = tok; continue; } delete [] tok; } GCarray<char*> gc_fname(fname); GCarray<char*> gc_which(which); GCarray<char*> gc_prname(prname); FILE *fp; if (fname) { fp = filestat::open_file(fname, "w"); if (!fp) { Log()->ErrorLog(mh::Initialization, filestat::error_msg()); PL()->ShowPrompt("Can't open file."); return; } } else fp = stdout; bool ok = OAif()->print_tech(fp, libname, which, prname); if (!ok) Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); if (fp != stdout) { fclose(fp); if (ok) { char tbuf[256]; snprintf(tbuf, 256, "OA tech listing saved in file %s, view file? ", fname); char *in = PL()->EditPrompt(tbuf, "n"); in = lstring::strip_space(in); if (in && (*in == 'y' || *in == 'Y')) DSPmainWbag(PopUpFileBrowser(fname)) } } PL()->ErasePrompt(); } else if (lstring::ciprefix("s", sel) || lstring::ciprefix("-s", sel)) { // save: libname } else if (lstring::ciprefix("u", sel) || lstring::ciprefix("-u", sel)) { // unattach: libname bool has_attch = false; char *alib; if (OAif()->has_attached_tech(libname, &alib)) { has_attch = (alib != 0); delete [] alib; } if (!has_attch) { PL()->ShowPromptV("No attached technology database in %s.", libname); return; } if (!OAif()->destroy_tech(libname, true)) { Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); PL()->ShowPromptV("Tech unattach failed."); } else PL()->ShowPromptV("Tech unattach succeeded."); } else { PL()->ShowPromptV("Unrecognized command sub-type."); } } void oa_bangcmds::oasave(const char *s) { bool all = false; char *libname = 0; char *tok; while ((tok = lstring::gettok(&s)) != 0) { if (*tok == '-') { if (tok[1] == 'a' || tok[1] == 'A') all = true; delete [] tok; continue; } if (!libname) { libname = tok; continue; } delete tok; } if (!libname) { s = CDvdb()->getVariable(VA_OaDefLibrary); libname = lstring::gettok(&s); } if (!libname) { PL()->ShowPrompt("No library given and no default."); return; } GCarray<char*> gc_libname(libname); CDcbin cbin(CurCell(Physical)); if (OAif()->save(&cbin, libname, all)) { if (all) { PL()->ShowPromptV( "Hierarchy under %s saved to library %s.", Tstring(DSP()->CurCellName()), libname); } else { PL()->ShowPromptV( "Cell %s saved to library %s.", Tstring(DSP()->CurCellName()), libname); } return; } PL()->ShowPrompt("Operation FAILED."); if (Errs()->has_error()) Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); } void oa_bangcmds::oaload(const char *s) { char *libname = lstring::getqtok(&s); char *cellname = lstring::getqtok(&s); if (!libname) { s = CDvdb()->getVariable(VA_OaDefLibrary); libname = lstring::gettok(&s); } if (!libname) { PL()->ShowPrompt("No library given and no default."); return; } GCarray<char*> gc_libname(libname); if (cellname) { if (OAif()->load_cell(libname, cellname, 0, CDMAXCALLDEPTH, true)) PL()->ShowPromptV("Cell %s from library %s loaded.", cellname, libname); else { PL()->ShowPrompt("Operation FAILED."); if (Errs()->has_error()) Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); } } else { if (OAif()->load_library(libname)) PL()->ShowPromptV("All cells from library %s loaded.", libname); else { PL()->ShowPrompt("Operation FAILED."); if (Errs()->has_error()) Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); } } delete [] cellname; delete [] libname; } void oa_bangcmds::oareset(const char*) { OAif()->clear_name_table(); PL()->ShowPrompt("OpenAccess cells-loaded table has been cleared."); } void oa_bangcmds::oadelete(const char *s) { char *libname = lstring::gettok(&s); char *cellname = lstring::gettok(&s); char *tok3 = lstring::gettok(&s); // tok3 can be a view name, or "electrical" or "physical" PCellDesc::LCVcleanup lcv(libname, cellname, tok3); bool ok = OAif()->destroy(libname, cellname, tok3); if (!ok) Log()->ErrorLog(mh::OpenAccess, Errs()->get_error()); } void oa_bangcmds::oadebug(const char *s) { const char *usage = "usage: !oadebug [+|-] [l[oad]] [p[cell]] [n[et]]"; bool plus = true; char onchars[64], offchars[64]; int oncnt = 0, offcnt = 0; char *tok; while ((tok = lstring::gettok(&s)) != 0) { char *t = tok; if (*t == '+') { plus = true; t++; } else if (*t == '-') { plus = false; t++; } if (*t == 'l' || *t == 'L') { if (plus) onchars[oncnt++] = 'l'; else offchars[offcnt++] = 'l'; } else if (*t == 'p' || *t == 'P') { if (plus) onchars[oncnt++] = 'p'; else offchars[offcnt++] = 'p'; } else if (*t == 'n' || *t == 'N') { if (plus) onchars[oncnt++] = 'n'; else offchars[offcnt++] = 'n'; } else { PL()->ShowPrompt(usage); delete [] tok; return; } delete [] tok; } onchars[oncnt] = 0; offchars[offcnt] = 0; s = OAif()->set_debug_flags(onchars, offchars); PL()->ShowPromptV("OA debug flags %s.", s); } namespace { void setup_bang_cmds() { XM()->RegisterBangCmd("oaversion", &oa_bangcmds::oaversion); XM()->RegisterBangCmd("oadebug", &oa_bangcmds::oadebug); XM()->RegisterBangCmd("oanewlib", &oa_bangcmds::oanewlib); XM()->RegisterBangCmd("oabrand", &oa_bangcmds::oabrand); XM()->RegisterBangCmd("oatech", &oa_bangcmds::oatech); XM()->RegisterBangCmd("oasave", &oa_bangcmds::oasave); XM()->RegisterBangCmd("oaload", &oa_bangcmds::oaload); XM()->RegisterBangCmd("oareset", &oa_bangcmds::oareset); XM()->RegisterBangCmd("oadelete", &oa_bangcmds::oadelete); } } #endif // End of bang commands #ifdef HAVE_OA // // Variables // namespace { void postOaLibs(const char*) { OAif()->PopUpOAlibraries(0, MODE_UPD); } void postOaDefs(const char*) { OAif()->PopUpOAdefs(0, MODE_UPD, 0, 0); } bool evOaDefs(const char*, bool) { CDvdb()->registerPostFunc(postOaDefs); return (true); } bool evOaLibs(const char*, bool) { CDvdb()->registerPostFunc(postOaLibs); return (true); } #define B 'b' #define S 's' void vsetup(const char *vname, char c, bool(*fn)(const char*, bool)) { CDvdb()->registerInternal(vname, fn); if (c == B) Tech()->RegisterBooleanAttribute(vname); else if (c == S) Tech()->RegisterStringAttribute(vname); } void setup_vars() { vsetup(VA_OaLibraryPath, S, evOaDefs); vsetup(VA_OaDefLibrary, S, evOaDefs); vsetup(VA_OaDefTechLibrary, S, evOaDefs); vsetup(VA_OaDefLayoutView, S, evOaDefs); vsetup(VA_OaDefSchematicView, S, evOaDefs); vsetup(VA_OaDefSymbolView, S, evOaDefs); vsetup(VA_OaDefDevPropView, S, evOaDefs); vsetup(VA_OaDmSystem, S, evOaDefs); vsetup(VA_OaDumpCdfFiles, B, evOaDefs); vsetup(VA_OaUseOnly, S, evOaLibs); } } // End of variables // // Script interface functions // namespace { namespace oa_funcs { // OpenAccess bool IFoaVersion(Variable*, Variable*, void*); bool IFoaIsLibrary(Variable*, Variable*, void*); bool IFoaListLibraries(Variable*, Variable*, void*); bool IFoaListLibCells(Variable*, Variable*, void*); bool IFoaListCellViews(Variable*, Variable*, void*); bool IFoaIsLibOpen(Variable*, Variable*, void*); bool IFoaOpenLibrary(Variable*, Variable*, void*); bool IFoaCloseLibrary(Variable*, Variable*, void*); bool IFoaIsOaCell(Variable*, Variable*, void*); bool IFoaIsCellInLib(Variable*, Variable*, void*); bool IFoaIsCellView(Variable*, Variable*, void*); bool IFoaIsCellViewInLib(Variable*, Variable*, void*); bool IFoaCreateLibrary(Variable*, Variable*, void*); bool IFoaBrandLibrary(Variable*, Variable*, void*); bool IFoaIsLibBranded(Variable*, Variable*, void*); bool IFoaDestroy(Variable*, Variable*, void*); bool IFoaLoad(Variable*, Variable*, void*); bool IFoaReset(Variable*, Variable*, void*); bool IFoaSave(Variable*, Variable*, void*); bool IFoaAttachTech(Variable*, Variable*, void*); bool IFoaGetAttachedTech(Variable*, Variable*, void*); bool IFoaHasLocalTech(Variable*, Variable*, void*); bool IFoaCreateLocalTech(Variable*, Variable*, void*); bool IFoaDestroyTech(Variable*, Variable*, void*); } using namespace oa_funcs; #ifdef HAVE_PYTHON // Python wrappers. PY_FUNC(OaVersion, 0, IFoaVersion); PY_FUNC(OaIsLibrary, 1, IFoaIsLibrary); PY_FUNC(OaListLibraries, 0, IFoaListLibraries); PY_FUNC(OaListLibCells, 1, IFoaListLibCells); PY_FUNC(OaListCellViews, 2, IFoaListCellViews); PY_FUNC(OaIsLibOpen, 1, IFoaIsLibOpen); PY_FUNC(OaOpenLibrary, 1, IFoaOpenLibrary); PY_FUNC(OaCloseLibrary, 1, IFoaCloseLibrary); PY_FUNC(OaIsOaCell, 2, IFoaIsOaCell); PY_FUNC(OaIsCellInLib, 2, IFoaIsCellInLib); PY_FUNC(OaIsCellView, 3, IFoaIsCellView); PY_FUNC(OaIsCellViewInLib, 3, IFoaIsCellViewInLib); PY_FUNC(OaCreateLibrary, 2, IFoaCreateLibrary); PY_FUNC(OaBrandLibrary, 2, IFoaBrandLibrary); PY_FUNC(OaIsLibBranded, 1, IFoaIsLibBranded); PY_FUNC(OaDestroy, 3, IFoaDestroy); PY_FUNC(OaLoad, 2, IFoaLoad); PY_FUNC(OaReset, 0, IFoaReset); PY_FUNC(OaSave, 3, IFoaSave); PY_FUNC(OaAttachTech, 2, IFoaAttachTech); PY_FUNC(OaGetAttachedTech, 1, IFoaGetAttachedTech); PY_FUNC(OaHasLocalTech, 1, IFoaHasLocalTech); PY_FUNC(OaCreateLocalTech, 1, IFoaCreateLocalTech); PY_FUNC(OaDestroyTech, 2, IFoaDestroyTech); void py_register_oa() { cPyIf::register_func("OaVersion", pyOaVersion); cPyIf::register_func("OaIsLibrary", pyOaIsLibrary); cPyIf::register_func("OaListLibraries", pyOaListLibraries); cPyIf::register_func("OaListLibCells", pyOaListLibCells); cPyIf::register_func("OaListCellViews", pyOaListCellViews); cPyIf::register_func("OaIsLibOpen", pyOaIsLibOpen); cPyIf::register_func("OaOpenLibrary", pyOaOpenLibrary); cPyIf::register_func("OaCloseLibrary", pyOaCloseLibrary); cPyIf::register_func("OaIsOaCell", pyOaIsOaCell); cPyIf::register_func("OaIsCellInLib", pyOaIsCellInLib); cPyIf::register_func("OaIsCellView", pyOaIsCellView); cPyIf::register_func("OaIsCellViewInLib", pyOaIsCellViewInLib); cPyIf::register_func("OaCreateLibrary", pyOaCreateLibrary); cPyIf::register_func("OaBrandLibrary", pyOaBrandLibrary); cPyIf::register_func("OaIsLibBranded", pyOaIsLibBranded); cPyIf::register_func("OaDestroy", pyOaDestroy); cPyIf::register_func("OaLoad", pyOaLoad); cPyIf::register_func("OaReset", pyOaReset); cPyIf::register_func("OaSave", pyOaSave); cPyIf::register_func("OaAttachTech", pyOaAttachTech); cPyIf::register_func("OaGetAttachedTech", pyOaGetAttachedTech); cPyIf::register_func("OaHasLocalTech", pyOaHasLocalTech); cPyIf::register_func("OaCreateLocalTech", pyOaCreateLocalTech); cPyIf::register_func("OaDestroyTech", pyOaDestroyTech); } #endif // HAVE_PYTHON #ifdef HAVE_TCL // TclTk wrappers. TCL_FUNC(OaVersion, 0, IFoaVersion); TCL_FUNC(OaIsLibrary, 1, IFoaIsLibrary); TCL_FUNC(OaListLibraries, 0, IFoaListLibraries); TCL_FUNC(OaListLibCells, 1, IFoaListLibCells); TCL_FUNC(OaListCellViews, 2, IFoaListCellViews); TCL_FUNC(OaIsLibOpen, 1, IFoaIsLibOpen); TCL_FUNC(OaOpenLibrary, 1, IFoaOpenLibrary); TCL_FUNC(OaCloseLibrary, 1, IFoaCloseLibrary); TCL_FUNC(OaIsOaCell, 2, IFoaIsOaCell); TCL_FUNC(OaIsCellInLib, 2, IFoaIsCellInLib); TCL_FUNC(OaIsCellView, 3, IFoaIsCellView); TCL_FUNC(OaIsCellViewInLib, 3, IFoaIsCellViewInLib); TCL_FUNC(OaCreateLibrary, 2, IFoaCreateLibrary); TCL_FUNC(OaBrandLibrary, 2, IFoaBrandLibrary); TCL_FUNC(OaIsLibBranded, 1, IFoaIsLibBranded); TCL_FUNC(OaDestroy, 3, IFoaDestroy); TCL_FUNC(OaLoad, 2, IFoaLoad); TCL_FUNC(OaReset, 0, IFoaReset); TCL_FUNC(OaSave, 3, IFoaSave); TCL_FUNC(OaAttachTech, 2, IFoaAttachTech); TCL_FUNC(OaGetAttachedTech, 1, IFoaGetAttachedTech); TCL_FUNC(OaHasLocalTech, 1, IFoaHasLocalTech); TCL_FUNC(OaCreateLocalTech, 1, IFoaCreateLocalTech); TCL_FUNC(OaDestroyTech, 2, IFoaDestroyTech); void tcl_register_oa() { cTclIf::register_func("OaVersion", tclOaVersion); cTclIf::register_func("OaIsLibrary", tclOaIsLibrary); cTclIf::register_func("OaListLibraries", tclOaListLibraries); cTclIf::register_func("OaListLibCells", tclOaListLibCells); cTclIf::register_func("OaListCellViews", tclOaListCellViews); cTclIf::register_func("OaIsLibOpen", tclOaIsLibOpen); cTclIf::register_func("OaOpenLibrary", tclOaOpenLibrary); cTclIf::register_func("OaCloseLibrary", tclOaCloseLibrary); cTclIf::register_func("OaIsOaCell", tclOaIsOaCell); cTclIf::register_func("OaIsCellInLib", tclOaIsCellInLib); cTclIf::register_func("OaIsCellView", tclOaIsCellView); cTclIf::register_func("OaIsCellViewInLib", tclOaIsCellViewInLib); cTclIf::register_func("OaCreateLibrary", tclOaCreateLibrary); cTclIf::register_func("OaBrandLibrary", tclOaBrandLibrary); cTclIf::register_func("OaIsLibBranded", tclOaIsLibBranded); cTclIf::register_func("OaDestroy", tclOaDestroy); cTclIf::register_func("OaLoad", tclOaLoad); cTclIf::register_func("OaReset", tclOaReset); cTclIf::register_func("OaSave", tclOaSave); cTclIf::register_func("OaAttachTech", tclOaAttachTech); cTclIf::register_func("OaGetAttachedTech", tclOaGetAttachedTech); cTclIf::register_func("OaHasLocalTech", tclOaHasLocalTech); cTclIf::register_func("OaCreateLocalTech", tclOaCreateLocalTech); cTclIf::register_func("OaDestroyTech", tclOaDestroyTech); } #endif // HAVE_TCL void setup_funcs() { using namespace oa_funcs; // OpenAccess SIparse()->registerFunc("OaVersion", 0, IFoaVersion); SIparse()->registerFunc("OaIsLibrary", 1, IFoaIsLibrary); SIparse()->registerFunc("OaListLibraries", 0, IFoaListLibraries); SIparse()->registerFunc("OaListLibCells", 1, IFoaListLibCells); SIparse()->registerFunc("OaListCellViews", 2, IFoaListCellViews); SIparse()->registerFunc("OaIsLibOpen", 1, IFoaIsLibOpen); SIparse()->registerFunc("OaOpenLibrary", 1, IFoaOpenLibrary); SIparse()->registerFunc("OaCloseLibrary", 1, IFoaCloseLibrary); SIparse()->registerFunc("OaIsOaCell", 2, IFoaIsOaCell); SIparse()->registerFunc("OaIsCellInLib", 2, IFoaIsCellInLib); SIparse()->registerFunc("OaIsCellView", 3, IFoaIsCellView); SIparse()->registerFunc("OaIsCellViewInLib", 3, IFoaIsCellViewInLib); SIparse()->registerFunc("OaCreateLibrary", 2, IFoaCreateLibrary); SIparse()->registerFunc("OaBrandLibrary", 2, IFoaBrandLibrary); SIparse()->registerFunc("OaIsLibBranded", 1, IFoaIsLibBranded); SIparse()->registerFunc("OaDestroy", 3, IFoaDestroy); SIparse()->registerFunc("OaLoad", 2, IFoaLoad); SIparse()->registerFunc("OaReset", 0, IFoaReset); SIparse()->registerFunc("OaSave", 3, IFoaSave); SIparse()->registerFunc("OaAttachTech", 2, IFoaAttachTech); SIparse()->registerFunc("OaGetAttachedTech", 1, IFoaGetAttachedTech); SIparse()->registerFunc("OaHasLocalTech", 1, IFoaHasLocalTech); SIparse()->registerFunc("OaCreateLocalTech", 1, IFoaCreateLocalTech); SIparse()->registerFunc("OaCDestroyTech", 2, IFoaDestroyTech); #ifdef HAVE_PYTHON py_register_oa(); #endif #ifdef HAVE_TCL tcl_register_oa(); #endif } } // // OpenAccess script functions. // An OpenAccess exception will trigger a fatal error. // // (string) OaVersion() // // Return the version string of the connected OpenAccess database. In // none, a null string is returned. // bool oa_funcs::IFoaVersion(Variable *res, Variable*, void*) { const char *vrs = OAif()->version(); res->type = TYP_STRING; res->content.string = lstring::copy(vrs); res->flags |= VF_ORIGINAL; return (OK); } // (int) OaIsLibrary(libname) // // Return 1 if the library named in the string argument is known to // OpenAccess, 0 if not. // bool oa_funcs::IFoaIsLibrary(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool retval; if (!OAif()->is_library(libname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (stringlist_handle) OaListLibraries() // // Return a handle to a list of library names known to OpenAccess. // bool oa_funcs::IFoaListLibraries(Variable *res, Variable*, void*) { stringlist *s0; if (!OAif()->list_libraries(&s0)) return (BAD); sHdl *hdl = new sHdlString(s0); res->type = TYP_HANDLE; res->content.value = hdl->id; return (OK); } // (stringlist.handle) OaListLibCells(libname) // // Return a list of the names of cells contained in the OpenAccess // library named in the argument. // bool oa_funcs::IFoaListLibCells(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) stringlist *s0; if (!OAif()->list_lib_cells(libname, &s0)) return (BAD); sHdl *hdl = new sHdlString(s0); res->type = TYP_HANDLE; res->content.value = hdl->id; return (OK); } // (stringlist_handle) OaListCellViews(libname, cellname) // // Return a handle to a list of view names found for the given cell in // the given OpenAccess library. // bool oa_funcs::IFoaListCellViews(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *cellname; ARG_CHK(arg_string(args, 1, &cellname)) stringlist *s0; if (!OAif()->list_cell_views(libname, cellname, &s0)) return (BAD); sHdl *hdl = new sHdlString(s0); res->type = TYP_HANDLE; res->content.value = hdl->id; return (OK); } // (int) IsLibOpen(libname) // // Return 1 if the OpenAccess library named in the argument is open, 0 // otherwise. // bool oa_funcs::IFoaIsLibOpen(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool retval; if (!OAif()->is_lib_open(libname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaOpenLibrary(libname) // // Open the OpenAccess library of the given name, where the name // should match a library defined in the lib.defs or cds.lib file. A // library being open means that it is available for resolving // undefined references when reading cell data in Xic. The return is // 1 on success, 0 if error. // bool oa_funcs::IFoaOpenLibrary(Variable *res, Variable *args, void*) { const char *name; ARG_CHK(arg_string(args, 0, &name)) res->type = TYP_SCALAR; res->content.value = OAif()->set_lib_open(name, true); return (OK); } // (int) OaCloseLibrary(libname) // // Close the OpenAccess library of the given name, where the name // should match a library defined in the lib.defs or cds.lib file. A // library being open means that it is available for resolving // undefined references when reading cell data in Xic. The return is // 1 on success, 0 if error. // bool oa_funcs::IFoaCloseLibrary(Variable *res, Variable *args, void*) { const char *name; ARG_CHK(arg_string(args, 0, &name)) res->type = TYP_SCALAR; res->content.value = OAif()->set_lib_open(name, false); return (OK); } // (int) OaIsOaCell(cellname, open_only) // // Return 1 if a cell with the given name can be resolved in an // OpenAccess library, 0 otherwise. If the boolean value open_only is // true, only open libraries are considered, otherwise all libraries // are considered. // bool oa_funcs::IFoaIsOaCell(Variable *res, Variable *args, void*) { const char *cellname; ARG_CHK(arg_string(args, 0, &cellname)) bool open_only; ARG_CHK(arg_boolean(args, 1, &open_only)) bool retval; if (!OAif()->is_oa_cell(cellname, open_only, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaIsCellInLib(libname, cellname) // // Return 1 if the given cell can be found in the OpenAccess library // given as the first argument, 0 otherwise. // bool oa_funcs::IFoaIsCellInLib(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *cellname; ARG_CHK(arg_string(args, 1, &cellname)) bool retval; if (!OAif()->is_cell_in_lib(libname, cellname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaIsCellView(cellname, viewname, open_only) // // Return 1 if the cellname and viewname resolve as a cellview in an // OpenAccess library, 0 otherwise. If the boolean open_only is true, // only open libraries are considered, otherwise all libraries are // considered. // bool oa_funcs::IFoaIsCellView(Variable *res, Variable *args, void*) { const char *cellname; ARG_CHK(arg_string(args, 0, &cellname)) const char *viewname; ARG_CHK(arg_string(args, 1, &viewname)) bool open_only; ARG_CHK(arg_boolean(args, 2, &open_only)) bool retval; if (!OAif()->is_oa_cellview(cellname, viewname, open_only, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaIsCellViewInLib(libname, cellname, viewname) // // Return 1 is the cellname and viewname resolve as a cellview in the // given OpenAccess library, 0 otherwise. // bool oa_funcs::IFoaIsCellViewInLib(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *cellname; ARG_CHK(arg_string(args, 1, &cellname)) const char *viewname; ARG_CHK(arg_string(args, 2, &viewname)) bool retval; if (!OAif()->is_cellview_in_lib(libname, cellname, viewname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaCreateLibrary(libname, techlibname) // // This will create the library in the OpenAccess database if libname // currently does not exist. This will also set up the technology for // the new library if techlibname is given (not null or empty). The // new library will attach to the same library as techlibname, or will // attach to techlibname if it has a local tech database. If // techlibname is given then it must exist. // bool oa_funcs::IFoaCreateLibrary(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *techlibname; ARG_CHK(arg_string(args, 1, &techlibname)) if (!OAif()->create_lib(libname, techlibname)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaBrandLibrary(libname, branded) // // Set or remove the Xic "brand" of the given library. Xic can only // write to a branded library. If the boolean branded is true, the // library will have its flag set, otherwise the branded status is // unset. // bool oa_funcs::IFoaBrandLibrary(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool branded; ARG_CHK(arg_boolean(args, 1, &branded)) if (!OAif()->brand_lib(libname, branded)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaIsLibBranded(libname) // // Return 1 if the named library is "branded" (writable by Xic), 0 // otherwise. // bool oa_funcs::IFoaIsLibBranded(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool retval; if (!OAif()->is_lib_branded(libname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaDestroy(libname, cellname, viewname) // // Destroy the named view from the given cell in the given OpenAccess // library. If the viewname is null or empty, destroy all views from // the named cell, i.e., the cell itself. If the cellname is null or // empty, undefine the library in the library definition (lib.defs or // cds.lib) file, and change the directory name to have a ".defunct" // extension. We don't blow away the data, the user can revert by // hand, or delete the directory. // bool oa_funcs::IFoaDestroy(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *cellname; ARG_CHK(arg_string(args, 1, &cellname)) const char *viewname; ARG_CHK(arg_string(args, 2, &viewname)) if (!OAif()->destroy(libname, cellname, viewname)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaLoad(libname, cellname) // // If cellname is null or empty, load all cells in the OpenAccess // library named in libname into Xic. The current cell is not // changed. Otherwise, load the cell and its hierarchy and make it // the current cell. The function always returns 1, a fatal error is // thrown if the load fails. // bool oa_funcs::IFoaLoad(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *cellname; ARG_CHK(arg_string(args, 1, &cellname)) if (!libname || !*libname) { Errs()->add_error("OaLoad: null or empty library name."); return (BAD); } if (cellname && *cellname) { if (!OAif()->load_cell(libname, cellname, 0, CDMAXCALLDEPTH, true)) return (BAD); } else { if (!OAif()->load_library(libname)) return (BAD); } res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaReset() // // There is a table in Xic that records the cells that have been // loaded from OpenAccess. This avoids the "merge control" pop-up // which appears if a common subcell was previously read and is // already in memory, the in-memory cell will not be overwritten. // This function clears the table, and should be called if this // protection should be ended, for example if the Xic database has // been cleared. // bool oa_funcs::IFoaReset(Variable *res, Variable*, void*) { OAif()->clear_name_table(); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaSave(libname, allhier) // // Write the current cell to the OpenAccess library whose name is // given in the first argument. This must exist, and be writable from // Xic. Whether the physical or electrical views are written, or // both, is determined by the value of the OaUseOnly variable. If the // value is "1" or starts with 'p' or 'P', only the physical (layout) // views are written. If the value is "2" or starts with 'e' or 'E', // only the electrical (schematic and symbol) views are written. If // anything else or not set, both physical and electrical views are // written. The second argument is a boolean that if true (nonzero) // indicates that the entire cell hierarchy under the current cell // should be saved. Otherwise, only the current cell is saved. // // The actual view names used are given in the OaDefLayoutView, // OaDefSchematicView, and OaDefSymbolView variables, or default to // "layout", "schematic", and "symbol". // bool oa_funcs::IFoaSave(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool all; ARG_CHK(arg_boolean(args, 2, &all)) if (!libname || !*libname) { Errs()->add_error("OaSave: null or empty library name."); return (BAD); } CDcbin cbin(CurCell(Physical)); if (!OAif()->save(&cbin, libname, all)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaAttachTech(libname, techlibname) // // If techlibname has an attached tech library, then that library will // be attached to libname. If techlibname has a local tech database, // then techlibname itself will be attached to libname. This will // fail if libname has a local tech database. The local database // should be destroyed first. // bool oa_funcs::IFoaAttachTech(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) const char *techlibname; ARG_CHK(arg_string(args, 1, &techlibname)) if (!OAif()->attach_tech(libname, techlibname)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (string) OaGetAttachedTech(libname) // // Return the name of the OpenAccess library providing the attached // technology, or a null string if no attachment. // bool oa_funcs::IFoaGetAttachedTech(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) char *atchname; if (!OAif()->has_attached_tech(libname, &atchname)) return (BAD); res->type = TYP_STRING; res->content.string = atchname; if (atchname) res->flags |= VF_ORIGINAL; return (OK); } // (int) OaHasLocalTech(libname) // // Return 1 if the OpenAccess library has a local technology database, // 0 if not. // bool oa_funcs::IFoaHasLocalTech(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool retval; if (!OAif()->has_local_tech(libname, &retval)) return (BAD); res->type = TYP_SCALAR; res->content.value = retval; return (OK); } // (int) OaCreateLocalTech(libname) // // If the library does not have an attached or local technology // database, create a new local database. // bool oa_funcs::IFoaCreateLocalTech(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) if (!OAif()->create_local_tech(libname)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } // (int) OaDestroyTech(libname, unattach_only) // // If libname has an attached technology library, unattach it. If the // boolean second argument is false, and the library has a local // database, destroy the database. // bool oa_funcs::IFoaDestroyTech(Variable *res, Variable *args, void*) { const char *libname; ARG_CHK(arg_string(args, 0, &libname)) bool unattach_only; ARG_CHK(arg_boolean(args, 1, &unattach_only)) if (!OAif()->destroy_tech(libname, unattach_only)) return (BAD); res->type = TYP_SCALAR; res->content.value = 1; return (OK); } #endif
/** * @file AzureBlobStorageClient.cpp * AzureBlobStorageClient class implementation * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AzureBlobStorageClient.h" #include "azure/identity.hpp" namespace org::apache::nifi::minifi::azure::storage { void AzureBlobStorageClient::resetClientIfNeeded(const AzureStorageCredentials &credentials, const std::string &container_name) { if (container_client_ && credentials == credentials_ && container_name == container_name_) { logger_->log_debug("Azure Blob Storage client credentials have not changed, no need to reset client"); return; } if (credentials.getUseManagedIdentityCredentials()) { auto storage_client = Azure::Storage::Blobs::BlobServiceClient( "https://" + credentials.getStorageAccountName() + ".blob." + credentials.getEndpointSuffix(), std::make_shared<Azure::Identity::ManagedIdentityCredential>()); container_client_ = std::make_unique<Azure::Storage::Blobs::BlobContainerClient>(storage_client.GetBlobContainerClient(container_name)); logger_->log_debug("Azure Blob Storage client has been reset with new managed identity credentials."); } else { container_client_ = std::make_unique<Azure::Storage::Blobs::BlobContainerClient>( Azure::Storage::Blobs::BlobContainerClient::CreateFromConnectionString(credentials.buildConnectionString(), container_name)); logger_->log_debug("Azure Blob Storage client has been reset with new connection string credentials."); } credentials_ = credentials; container_name_ = container_name; } bool AzureBlobStorageClient::createContainerIfNotExists(const PutAzureBlobStorageParameters& params) { resetClientIfNeeded(params.credentials, params.container_name); return container_client_->CreateIfNotExists().Value.Created; } Azure::Storage::Blobs::Models::UploadBlockBlobResult AzureBlobStorageClient::uploadBlob(const PutAzureBlobStorageParameters& params, gsl::span<const uint8_t> buffer) { resetClientIfNeeded(params.credentials, params.container_name); auto blob_client = container_client_->GetBlockBlobClient(params.blob_name); return blob_client.UploadFrom(buffer.data(), buffer.size()).Value; } std::string AzureBlobStorageClient::getUrl(const PutAzureBlobStorageParameters& params) { resetClientIfNeeded(params.credentials, params.container_name); return container_client_->GetUrl(); } } // namespace org::apache::nifi::minifi::azure::storage
// Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "multisigdialog.h" #include "forms/ui_multisigdialog.h" #include "askpassphrasedialog.h" #include "primitives/transaction.h" #include "addressbookpage.h" #include "utilstrencodings.h" #include "core_io.h" #include "script/script.h" #include "base58.h" #include "coins.h" #include "keystore.h" #include "init.h" #include "wallet/wallet.h" #include "script/sign.h" #include "script/interpreter.h" #include "utilmoneystr.h" #include "guiutil.h" #include "qvalidatedlineedit.h" #include "bitcoinamountfield.h" #include <QVariant> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QToolButton> #include <QSpinBox> #include <QClipboard> #include <QDebug> #include <QArgument> #include <QtGlobal> #include <QString> MultisigDialog::MultisigDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::MultisigDialog), model(0) { ui->setupUi(this); multisigTx = CMutableTransaction(); //flag to show keyScrollArea on first priv key added isFirstPrivKey = true; isFirstRawTx = true; ui->keyScrollArea->hide(); ui->txInputsScrollArea->hide(); connect(ui->commitButton, SIGNAL(clicked()), this, SLOT(commitMultisigTx())); //populate lists with initial objects on_addAddressButton_clicked(); on_addAddressButton_clicked(); on_addDestinationButton_clicked(); this->setStyleSheet(GUIUtil::loadStyleSheet()); } MultisigDialog::~MultisigDialog() { delete ui; } void MultisigDialog::setModel(WalletModel *model) { this->model = model; } void MultisigDialog::showTab(int index) { ui->multisigTabWidget->setCurrentIndex(index); this->show(); } void MultisigDialog::updateCoinControl(CAmount nAmount, unsigned int nQuantity) { ui->labelAmount_int->setText(QString::fromStdString(FormatMoney(nAmount))); ui->labelQuantity_int->setText(QString::number(nQuantity)); } /** * Private Slots */ //slot for pasting addresses void MultisigDialog::pasteText() { QWidget* pasteButton = qobject_cast<QWidget*>(sender()); if(!pasteButton)return; QFrame* addressFrame = qobject_cast<QFrame*>(pasteButton->parentWidget()); if(!addressFrame)return; QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address"); if(!vle)return; vle->setText(QApplication::clipboard()->text()); } //slot for deleting QFrames with the delete buttons void MultisigDialog::deleteFrame() { QWidget *buttonWidget = qobject_cast<QWidget*>(sender()); if(!buttonWidget)return; //if deleting last raw input/priv key, hide scroll area if(buttonWidget->objectName() == "inputDeleteButton" && ui->inputsList->count() == 1){ isFirstRawTx = true; ui->txInputsScrollArea->hide(); }else if(buttonWidget->objectName() == "keyDeleteButton" && ui->keyList->count() == 1){ isFirstPrivKey = true; ui->keyScrollArea->hide(); } QFrame* frame = qobject_cast<QFrame*>(buttonWidget->parentWidget()); if(!frame)return; //figure out which frame was updated so we can update the correct list bool destinationFrame = false, addressFrame = false, keyFrame = false, txInputFrame = false; if (frame->objectName() == QString::fromStdString("destinationFrame")) destinationFrame = true; else if (frame->objectName() == QString::fromStdString("addressFrame")) addressFrame = true; else if (frame->objectName() == QString::fromStdString("keyFrame")) keyFrame = true; else if (frame->objectName() == QString::fromStdString("txInputFrame")) txInputFrame = true; delete frame; //update the correct list inputs //using else-if instead of else to stop accidental Seg faults //if method is called on a frame that isn't a destinationFrame, addressFrame, keyFrame, txInputFrame if (addressFrame) { for (int i = 0; i < ui->addressList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->addressList->itemAt(i)->widget()); QLabel *addressLabel = input->findChild<QLabel *>("addressLabel"); addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", i + 1).c_str(), 0)); } } else if (destinationFrame) { for (int i = 0; i < ui->destinationsList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->destinationsList->itemAt(i)->widget()); QLabel *destinationAddressLabel = input->findChild<QLabel *>("destinationAddressLabel"); destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", i + 1).c_str(), 0)); } } else if (keyFrame) { for (int i = 0; i < ui->keyList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->keyList->itemAt(i)->widget()); QLabel *keyListLabel = input->findChild<QLabel *>("keyLabel"); keyListLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", i + 1).c_str(), 0)); } } else if (txInputFrame) { for (int i = 0; i < ui->inputsList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->inputsList->itemAt(i)->widget()); QLabel *txInputIdLabel = input->findChild<QLabel *>("txInputIdLabel"); txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", i + 1).c_str(), 0)); } } } //slot to open address book dialog void MultisigDialog::addressBookButtonReceiving() { QWidget* addressButton = qobject_cast<QWidget*>(sender()); if(!addressButton)return; QFrame* addressFrame = qobject_cast<QFrame*>(addressButton->parentWidget()); if(!addressFrame)return; QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address"); if(!vle)return; if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { vle->setText(dlg.getReturnValue()); } } } //create address void MultisigDialog::on_addMultisigButton_clicked() { if(!model) return; int m = ui->enterMSpinbox->value(); std::vector<std::string> keys; for (int i = 0; i < ui->addressList->count(); i++) { QWidget* address = qobject_cast<QWidget*>(ui->addressList->itemAt(i)->widget()); QValidatedLineEdit* vle = address->findChild<QValidatedLineEdit*>("address"); if(!vle->text().isEmpty()){ keys.push_back(vle->text().toStdString()); } } addMultisig(m, keys); } void MultisigDialog::on_importAddressButton_clicked(){ if(!model) return; std::string sRedeem = ui->importRedeem->text().toStdString(); if(sRedeem.empty()){ ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText("Import box empty!"); return; } std::vector<std::string> vRedeem; size_t pos = 0; //search redeem input delimited by space while ((pos = sRedeem.find(" ")) != std::string::npos) { vRedeem.push_back(sRedeem.substr(0, pos)); sRedeem.erase(0, pos + 1); } std::vector<std::string> keys(vRedeem.begin()+1, vRedeem.end()-1); addMultisig(stoi(vRedeem[0]), keys); // rescan to find txs associated with imported address pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } bool MultisigDialog::addMultisig(int m, std::vector<std::string> keys){ try{ std::string error; CScript redeem; if(!createRedeemScript(m, keys, redeem, error)){ throw std::runtime_error(error.data()); } if (::IsMine(*pwalletMain, redeem) == ISMINE_SPENDABLE){ throw std::runtime_error("The wallet already contains this script"); } if(!pwalletMain->AddCScript(redeem)){ throw std::runtime_error("Failure: address invalid or already exists"); } CScriptID innerID(redeem); std::string label = ui->multisigAddressLabel->text().toStdString(); pwalletMain->SetAddressBook(innerID, label, "receive"); if (!pwalletMain->AddMultiSig(redeem)){ throw std::runtime_error("Failure: unable to add address as watch only"); } ui->addMultisigStatus->setStyleSheet("QLabel { color: black; }"); ui->addMultisigStatus->setText("Multisignature address " + QString::fromStdString(CBitcoinAddress(innerID).ToString()) + " has been added to the wallet.\nSend the redeem below for other owners to import:\n" + QString::fromStdString(redeem.ToString())); }catch(const std::runtime_error& e) { ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText(tr(e.what())); return false; } return true; } //spend void MultisigDialog::on_createButton_clicked() { if(!model) return; std::vector<CTxIn> vUserIn; std::vector<CTxOut> vUserOut; try{ //Add inputs from Coin Control if any are selected if (CoinControlDialog::coinControl->HasSelected()) { std::vector<COutPoint> vSelected; CoinControlDialog::coinControl->ListSelected(vSelected); for (auto outpoint : vSelected) vUserIn.emplace_back(CTxIn(outpoint)); }else{//check for raw inputs for(int i = 0; i < ui->inputsList->count(); i++){ QWidget* input = qobject_cast<QWidget*>(ui->inputsList->itemAt(i)->widget()); QLineEdit* txIdLine = input->findChild<QLineEdit*>("txInputId"); if(txIdLine->text().isEmpty()){ ui->createButtonStatus->setStyleSheet("QLabel { color: red; }"); ui->createButtonStatus->setText(tr("Invalid Tx Hash.")); return; } QSpinBox* txVoutLine = input->findChild<QSpinBox*>("txInputVout"); int nOutput = txVoutLine->value(); if(nOutput < 0){ ui->createButtonStatus->setStyleSheet("QLabel { color: red; }"); ui->createButtonStatus->setText(tr("Vout position must be positive.")); return; } uint256 txid = uint256S(txIdLine->text().toStdString()); CTxIn in(COutPoint(txid, nOutput)); vUserIn.emplace_back(in); } } //validate destinations bool validInput = true; for(int i = 0; i < ui->destinationsList->count(); i++){ QWidget* dest = qobject_cast<QWidget*>(ui->destinationsList->itemAt(i)->widget()); QValidatedLineEdit* addr = dest->findChild<QValidatedLineEdit*>("destinationAddress"); BitcoinAmountField* amt = dest->findChild<BitcoinAmountField*>("destinationAmount"); CBitcoinAddress address; bool validDest = true; if(!model->validateAddress(addr->text())){ addr->setValid(false); validDest = false; }else{ address = CBitcoinAddress(addr->text().toStdString()); } if(!amt->validate()){ amt->setValid(false); validDest = false; } if(!validDest){ validInput = false; continue; } CScript scriptPubKey = GetScriptForDestination(address.Get()); CTxOut out(amt->value(), scriptPubKey); vUserOut.push_back(out); } //if all user data valid create a multisig tx if(validInput){ //clear member variable multisigTx = CMutableTransaction(); std::string error; std::string fee; if(!createMultisigTransaction(vUserIn, vUserOut, fee, error)){ throw std::runtime_error(error); } //display status string ui->createButtonStatus->setStyleSheet("QTextEdit{ color: black }"); QString status(strprintf("Transaction has successfully created with a fee of %s.\n" "The transaction has been automatically imported to the sign tab.\n" "Please continue on to sign the tx from this wallet, to access the hex to send to other owners.", fee).c_str()); ui->createButtonStatus->setText(status); ui->transactionHex->setText(QString::fromStdString(EncodeHexTx(multisigTx))); } }catch(const std::runtime_error& e){ ui->createButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->createButtonStatus->setText(tr(e.what())); } } bool MultisigDialog::createMultisigTransaction(std::vector<CTxIn> vUserIn, std::vector<CTxOut> vUserOut, std::string& feeStringRet, std::string& errorRet) { try{ //attempt to access the given inputs CCoinsViewCache view = getInputsCoinsViewCache(vUserIn); //retrieve total input val and change dest CAmount totalIn = 0; std::vector<CAmount> vInputVals; CScript changePubKey; bool fFirst = true; for(CTxIn in : vUserIn){ const CCoins* coins = view.AccessCoins(in.prevout.hash); if(!coins->IsAvailable(in.prevout.n) || coins == NULL){ continue; } CTxOut prevout = coins->vout[in.prevout.n]; CScript privKey = prevout.scriptPubKey; vInputVals.push_back(prevout.nValue); totalIn += prevout.nValue; if(!fFirst){ if(privKey != changePubKey){ throw std::runtime_error("Address mismatch! Inputs must originate from the same multisignature address."); } }else{ fFirst = false; changePubKey = privKey; } } CAmount totalOut = 0; //retrieve total output val for(CTxOut out : vUserOut){ totalOut += out.nValue; } if(totalIn < totalOut){ throw std::runtime_error("Not enough XXX provided as input to complete transaction (including fee)."); } //calculate change amount CAmount changeAmount = totalIn - totalOut; CTxOut change(changeAmount, changePubKey); //generate random position for change unsigned int changeIndex = rand() % (vUserOut.size() + 1); //insert change into random position if(changeIndex < vUserOut.size()){ vUserOut.insert(vUserOut.begin() + changeIndex, change); }else{ vUserOut.emplace_back(change); } //populate tx CMutableTransaction tx; tx.vin = vUserIn; tx.vout = vUserOut; const CCoins* coins = view.AccessCoins(tx.vin[0].prevout.hash); if(coins == NULL || !coins->IsAvailable(tx.vin[0].prevout.n)){ throw std::runtime_error("Coins unavailable (unconfirmed/spent)"); } CScript prevPubKey = coins->vout[tx.vin[0].prevout.n].scriptPubKey; //get payment destination CTxDestination address; if(!ExtractDestination(prevPubKey, address)){ throw std::runtime_error("Could not find address for destination."); } CScriptID hash = boost::get<CScriptID>(address); CScript redeemScript; if (!pwalletMain->GetCScript(hash, redeemScript)){ throw std::runtime_error("could not redeem"); } txnouttype type; std::vector<CTxDestination> addresses; int nReq; if(!ExtractDestinations(redeemScript, type, addresses, nReq)){ throw std::runtime_error("Could not extract destinations from redeem script."); } for(CTxIn& in : tx.vin){ in.scriptSig.clear(); //scale estimate to account for multisig scriptSig for(unsigned int i = 0; i < 50*(nReq+addresses.size()); i++){ in.scriptSig << INT64_MAX; } } //calculate fee unsigned int nBytes = tx.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); CAmount fee = ::minRelayTxFee.GetFee(nBytes); if(tx.vout.at(changeIndex).nValue > fee){ tx.vout.at(changeIndex).nValue -= fee; feeStringRet = strprintf("%d",((double)fee)/COIN).c_str(); }else{ throw std::runtime_error("Not enough XXX provided to cover fee"); } //clear junk from script sigs for(CTxIn& in : tx.vin){ in.scriptSig.clear(); } multisigTx = tx; }catch(const std::runtime_error& e){ errorRet = e.what(); return false; } return true; } //sign void MultisigDialog::on_signButton_clicked() { if(!model) return; try{ //parse tx hex CTransaction txRead; if(!DecodeHexTx(txRead, ui->transactionHex->text().toStdString())){ throw std::runtime_error("Failed to decode transaction hex!"); } CMutableTransaction tx(txRead); //check if transaction is already fully verified if(isFullyVerified(tx)){ this->multisigTx = tx; ui->commitButton->setEnabled(true); ui->signButtonStatus->setText("This transaction is ready to commit. \nThe commit button in now enabled."); return; } std::string errorOut = std::string(); bool fComplete = signMultisigTx(tx, errorOut, ui->keyList); if(!errorOut.empty()){ throw std::runtime_error(errorOut.data()); }else{ this->multisigTx = tx; } ui->signButtonStatus->setStyleSheet("QTextEdit{ color: black }"); ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); }catch(const std::runtime_error& e){ ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->signButtonStatus->setText(tr(e.what())); } } /*** *private helper functions */ QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx) { std::string sTxHex = EncodeHexTx(tx); if(fComplete){ ui->commitButton->setEnabled(true); std::string sTxId = tx.GetHash().GetHex(); std::string sTxComplete = "Complete: true!\n" "The commit button has now been enabled for you to finalize the transaction.\n" "Once the commit button is clicked, the transaction will be published and coins transferred " "to their destinations.\nWARNING: THE ACTIONS OF THE COMMIT BUTTON ARE FINAL AND CANNOT BE REVERSED."; return QString(strprintf("%s\nTx Id:\n%s\nTx Hex:\n%s",sTxComplete, sTxId, sTxHex).c_str()); } else { std::string sTxIncomplete = "Complete: false.\n" "You may now send the hex below to another owner to sign.\n" "Keep in mind the transaction must be passed from one owner to the next for signing.\n" "Ensure all owners have imported the redeem before trying to sign. (besides creator)"; return QString(strprintf("%s\nTx Hex: %s", sTxIncomplete, sTxHex).c_str()); } } CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const std::vector<CTxIn>& vin) { CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache& viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view for(const CTxIn& txin : vin) { const uint256& prevHash = txin.prevout.hash; view.AccessCoins(prevHash); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } return view; } bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, std::string& errorOut, QVBoxLayout* keyList) { //will be set false if all inputs are not fully signed(valid) bool fComplete = true; //if keyslist is not default value AND has items in list then true bool fGivenKeys = (keyList != nullptr) && (keyList->count() > 0); try{ //copy of vin for reference before vin is mutated std::vector<CTxIn> oldVin(tx.vin); CBasicKeyStore privKeystore; //if keys were given, attempt to collect redeem and scriptpubkey if(fGivenKeys){ for(int i = 0; i < keyList->count(); i++){ QWidget* keyFrame = qobject_cast<QWidget*>(keyList->itemAt(i)->widget()); QLineEdit* key = keyFrame->findChild<QLineEdit*>("key"); CBitcoinSecret vchSecret; if (!vchSecret.SetString(key->text().toStdString())) throw std::runtime_error("Invalid private key"); CKey cKey = vchSecret.GetKey(); if (!cKey.IsValid()) throw std::runtime_error("Private key outside allowed range"); privKeystore.AddKey(cKey); } for(CTxIn& txin : tx.vin){ //get inputs CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) throw std::runtime_error("txin could not be found"); if (hashBlock == 0) throw std::runtime_error("txin is unconfirmed"); //get pubkey from input CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; //get payment destination CTxDestination address; if(!ExtractDestination(prevPubKey, address)){ throw std::runtime_error("Could not find address for destination."); } //get redeem script related to destination CScriptID hash = boost::get<CScriptID>(address); CScript redeemScript; if (!pwalletMain->GetCScript(hash, redeemScript)){ errorOut = "could not redeem"; } privKeystore.AddCScript(redeemScript); } }else{ if (model->getEncryptionStatus() == model->Locked) { if (!model->requestUnlock(AskPassphraseDialog::Context::Multi_Sig, true).isValid()) { // Unlock wallet was cancelled throw std::runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first."); } } } //choose between local wallet and provided const CKeyStore& keystore = fGivenKeys ? privKeystore : *pwalletMain; //attempt to sign each input from local wallet int nIn = 0; for(CTxIn& txin : tx.vin){ //get inputs CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) throw std::runtime_error("txin could not be found"); if (hashBlock == 0) throw std::runtime_error("txin is unconfirmed"); txin.scriptSig.clear(); CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; //sign what we can SignSignature(keystore, prevPubKey, tx, nIn); //merge in any previous signatures txin.scriptSig = CombineSignatures(prevPubKey, tx, nIn, txin.scriptSig, oldVin[nIn].scriptSig); if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){ fComplete = false; } nIn++; } ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); }catch(const std::runtime_error& e){ errorOut = std::string(e.what()); fComplete = false; } return fComplete; } // quick check for an already fully signed tx bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){ try{ int nIn = 0; for(CTxIn& txin : tx.vin){ CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)){ throw std::runtime_error("txin could not be found"); } if (hashBlock == 0){ throw std::runtime_error("txin is unconfirmed"); } //get pubkey from this input as output in last tx CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){ return false; } nIn++; } }catch(const std::runtime_error& e){ return false; } return true; } void MultisigDialog::commitMultisigTx() { CMutableTransaction tx(multisigTx); try{ #ifdef ENABLE_WALLET CWalletTx wtx(pwalletMain, tx); CReserveKey keyChange(pwalletMain); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw std::runtime_error(std::string("Transaction rejected - Failed to commit")); #else uint256 hashTx = tx.GetHash(); CCoinsViewCache& view = *pcoinsTip; const CCoins* existingCoins = view.AccessCoins(hashTx); bool fOverrideFees = false; bool fHaveMempool = mempool.exists(hashTx); bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000; if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets CValidationState state; if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) { if (state.IsInvalid()) throw std::runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason())); else throw std::runtime_error(std::string("Transaction rejected - ") + state.GetRejectReason()); } } else if (fHaveChain) { throw std::runtime_error("transaction already in block chain"); } RelayTransaction(tx); #endif //disable commit if successfully committed ui->commitButton->setEnabled(false); ui->signButtonStatus->setText(strprintf("Transaction has been successfully published with transaction ID:\n %s", tx.GetHash().GetHex()).c_str()); }catch(const std::runtime_error& e){ ui->signButtonStatus->setText(e.what()); } } bool MultisigDialog::createRedeemScript(int m, std::vector<std::string> vKeys, CScript& redeemRet, std::string& errorRet) { try{ int n = vKeys.size(); //gather pub keys if (n < 1) throw std::runtime_error("a Multisignature address must require at least one key to redeem"); if (n < m) throw std::runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", m, n)); if (n > 15) throw std::runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number"); std::vector<CPubKey> pubkeys; pubkeys.resize(n); int i = 0; for(std::vector<std::string>::iterator it = vKeys.begin(); it != vKeys.end(); ++it) { std::string keyString = *it; #ifdef ENABLE_WALLET // Case 1: XXX address and we have full public key: CBitcoinAddress address(keyString); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) { throw std::runtime_error( strprintf("%s does not refer to a key", keyString)); } CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw std::runtime_error( strprintf("no full public key for address %s", keyString)); if (!vchPubKey.IsFullyValid()){ std::string sKey = keyString.empty()?"(empty)":keyString; throw std::runtime_error(" Invalid public key: " + sKey ); } pubkeys[i++] = vchPubKey; } //case 2: hex pub key else #endif if (IsHex(keyString)) { CPubKey vchPubKey(ParseHex(keyString)); if (!vchPubKey.IsFullyValid()){ throw std::runtime_error(" Invalid public key: " + keyString); } pubkeys[i++] = vchPubKey; } else { throw std::runtime_error(" Invalid public key: " + keyString); } } //populate redeem script //OP_N for required signatures redeemRet << redeemRet.EncodeOP_N(m); //public keys for(CPubKey& key : pubkeys){ std::vector<unsigned char> vKey= ToByteVector(key); redeemRet << vKey; } //OP_N for total pubkeys redeemRet << redeemRet.EncodeOP_N(pubkeys.size()); redeemRet << OP_CHECKMULTISIG; return true; }catch(const std::runtime_error& e){ errorRet = std::string(e.what()); return false; } } /*** * Begin QFrame object creation methods */ //creates an address object on the create tab void MultisigDialog::on_addAddressButton_clicked() { //max addresses 15 if(ui->addressList->count() >= 15){ ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText(tr("Maximum possible addresses reached. (15)")); return; } QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); QFrame* addressFrame = new QFrame(); sizePolicy.setHeightForWidth(addressFrame->sizePolicy().hasHeightForWidth()); addressFrame->setSizePolicy(sizePolicy); addressFrame->setFrameShape(QFrame::StyledPanel); addressFrame->setFrameShadow(QFrame::Raised); addressFrame->setObjectName(QStringLiteral("addressFrame")); QVBoxLayout* frameLayout = new QVBoxLayout(addressFrame); frameLayout->setSpacing(1); frameLayout->setObjectName(QStringLiteral("frameLayout")); frameLayout->setContentsMargins(6, 6, 6, 6); QHBoxLayout* addressLayout = new QHBoxLayout(); addressLayout->setSpacing(2); addressLayout->setObjectName(QStringLiteral("addressLayout")); QLabel* addressLabel = new QLabel(addressFrame); addressLabel->setObjectName(QStringLiteral("addressLabel")); addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", ui->addressList->count()+1).c_str() , 0)); addressLayout->addWidget(addressLabel); QValidatedLineEdit* address = new QValidatedLineEdit(addressFrame); address->setObjectName(QStringLiteral("address")); addressLayout->addWidget(address); QToolButton* addressBookButton = new QToolButton(addressFrame); addressBookButton->setObjectName(QStringLiteral("addressBookButton")); QIcon icon3; icon3.addFile(QStringLiteral(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off); addressBookButton->setIcon(icon3); connect(addressBookButton, SIGNAL(clicked()), this, SLOT(addressBookButtonReceiving())); addressLayout->addWidget(addressBookButton); QToolButton* addressPasteButton = new QToolButton(addressFrame); addressPasteButton->setObjectName(QStringLiteral("addressPasteButton")); QIcon icon4; icon4.addFile(QStringLiteral(":/icons/editpaste"), QSize(), QIcon::Normal, QIcon::Off); addressPasteButton->setIcon(icon4); connect(addressPasteButton, SIGNAL(clicked()), this, SLOT(pasteText())); addressLayout->addWidget(addressPasteButton); QToolButton* addressDeleteButton = new QToolButton(addressFrame); addressDeleteButton->setObjectName(QStringLiteral("addressDeleteButton")); QIcon icon5; icon5.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); addressDeleteButton->setIcon(icon5); connect(addressDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); addressLayout->addWidget(addressDeleteButton); frameLayout->addLayout(addressLayout); ui->addressList->addWidget(addressFrame); } void MultisigDialog::on_pushButtonCoinControl_clicked() { CoinControlDialog coinControlDialog(this, true); coinControlDialog.setModel(model); coinControlDialog.exec(); } void MultisigDialog::on_addInputButton_clicked() { if(isFirstRawTx){ isFirstRawTx = false; ui->txInputsScrollArea->show(); } QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); QFrame* txInputFrame = new QFrame(ui->txInputsWidget); sizePolicy.setHeightForWidth(txInputFrame->sizePolicy().hasHeightForWidth()); txInputFrame->setFrameShape(QFrame::StyledPanel); txInputFrame->setFrameShadow(QFrame::Raised); txInputFrame->setObjectName(QStringLiteral("txInputFrame")); QVBoxLayout* frameLayout = new QVBoxLayout(txInputFrame); frameLayout->setSpacing(1); frameLayout->setObjectName(QStringLiteral("txInputFrameLayout")); frameLayout->setContentsMargins(6, 6, 6, 6); QHBoxLayout* txInputLayout = new QHBoxLayout(); txInputLayout->setSpacing(2); txInputLayout->setObjectName(QStringLiteral("txInputLayout")); QLabel* txInputIdLabel = new QLabel(txInputFrame); txInputIdLabel->setObjectName(QStringLiteral("txInputIdLabel")); txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", ui->inputsList->count()+1).c_str(), 0)); txInputLayout->addWidget(txInputIdLabel); QLineEdit* txInputId = new QLineEdit(txInputFrame); txInputId->setObjectName(QStringLiteral("txInputId")); txInputLayout->addWidget(txInputId); QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); txInputLayout->addItem(horizontalSpacer); QLabel* txInputVoutLabel = new QLabel(txInputFrame); txInputVoutLabel->setObjectName(QStringLiteral("txInputVoutLabel")); txInputVoutLabel->setText(QApplication::translate("MultisigDialog", "Vout Position: ", 0)); txInputLayout->addWidget(txInputVoutLabel); QSpinBox* txInputVout = new QSpinBox(txInputFrame); txInputVout->setObjectName("txInputVout"); sizePolicy.setHeightForWidth(txInputVout->sizePolicy().hasHeightForWidth()); txInputVout->setSizePolicy(sizePolicy); txInputLayout->addWidget(txInputVout); QToolButton* inputDeleteButton = new QToolButton(txInputFrame); inputDeleteButton->setObjectName(QStringLiteral("inputDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); inputDeleteButton->setIcon(icon); connect(inputDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); txInputLayout->addWidget(inputDeleteButton); frameLayout->addLayout(txInputLayout); ui->inputsList->addWidget(txInputFrame); } void MultisigDialog::on_addDestinationButton_clicked() { QFrame* destinationFrame = new QFrame(ui->destinationsScrollAreaContents); destinationFrame->setObjectName(QStringLiteral("destinationFrame")); destinationFrame->setFrameShape(QFrame::StyledPanel); destinationFrame->setFrameShadow(QFrame::Raised); QVBoxLayout* frameLayout = new QVBoxLayout(destinationFrame); frameLayout->setObjectName(QStringLiteral("destinationFrameLayout")); QHBoxLayout* destinationLayout = new QHBoxLayout(); destinationLayout->setSpacing(0); destinationLayout->setObjectName(QStringLiteral("destinationLayout")); QLabel* destinationAddressLabel = new QLabel(destinationFrame); destinationAddressLabel->setObjectName(QStringLiteral("destinationAddressLabel")); destinationLayout->addWidget(destinationAddressLabel); QValidatedLineEdit* destinationAddress = new QValidatedLineEdit(destinationFrame); destinationAddress->setObjectName(QStringLiteral("destinationAddress")); destinationLayout->addWidget(destinationAddress); QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); destinationLayout->addItem(horizontalSpacer); QLabel* destinationAmountLabel = new QLabel(destinationFrame); destinationAmountLabel->setObjectName(QStringLiteral("destinationAmountLabel")); destinationLayout->addWidget(destinationAmountLabel); BitcoinAmountField* destinationAmount = new BitcoinAmountField(destinationFrame); destinationAmount->setObjectName(QStringLiteral("destinationAmount")); destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", ui->destinationsList->count()+1).c_str(), 0)); destinationAmountLabel->setText(QApplication::translate("MultisigDialog", "Amount: ", 0)); destinationLayout->addWidget(destinationAmount); QToolButton* destinationDeleteButton = new QToolButton(destinationFrame); destinationDeleteButton->setObjectName(QStringLiteral("destinationDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); destinationDeleteButton->setIcon(icon); connect(destinationDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); destinationLayout->addWidget(destinationDeleteButton); frameLayout->addLayout(destinationLayout); ui->destinationsList->addWidget(destinationFrame); } void MultisigDialog::on_addPrivKeyButton_clicked() { if(isFirstPrivKey){//on first click the scroll area must show isFirstPrivKey = false; ui->keyScrollArea->show(); } if(ui->keyList->count() >= 15){ ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->signButtonStatus->setText(tr("Maximum (15)")); return; } QFrame* keyFrame = new QFrame(ui->keyScrollAreaContents); keyFrame->setObjectName(QStringLiteral("keyFrame")); keyFrame->setFrameShape(QFrame::StyledPanel); keyFrame->setFrameShadow(QFrame::Raised); QHBoxLayout* keyLayout = new QHBoxLayout(keyFrame); keyLayout->setObjectName(QStringLiteral("keyLayout")); QLabel* keyLabel = new QLabel(keyFrame); keyLabel->setObjectName(QStringLiteral("keyLabel")); keyLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", (ui->keyList->count()+1)).c_str(), 0)); keyLayout->addWidget(keyLabel); QLineEdit* key = new QLineEdit(keyFrame); key->setObjectName(QStringLiteral("key")); key->setEchoMode(QLineEdit::Password); keyLayout->addWidget(key); QToolButton* keyDeleteButton = new QToolButton(keyFrame); keyDeleteButton->setObjectName(QStringLiteral("keyDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); keyDeleteButton->setIcon(icon); connect(keyDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); keyLayout->addWidget(keyDeleteButton); ui->keyList->addWidget(keyFrame); }
#include<bits/stdc++.h> using namespace std; void __print(int x){cout<<x;}void __print(long long x){cout<<x;} void __print(double x){cout<<x;}void __print(long double x){cout<<x;} void __print(char x){cout<<'\''<<x<<'\'';}void __print(const char *x){cout<<'\"'<<x<<'\"';} void __print(const string &x){cout<<'\"'<<x<<'\"';}void __print(bool x){cout<<(x?"True":"False");} template<typename T,typename V> void __print(const pair<T,V>&x){cout<<'{';__print(x.first);cout<<',';__print(x.second);cout<<'}';} template<typename T> void __print(const T &x){int f=0;cout<<'{';for(auto &i:x)cout<<(f++?",":""),__print(i);cout<<"}";} void _print(){cout<<"]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); /* 'if' begin */ if (sizeof...(v)) /* 'if' inside */ cout << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cout << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif #define gcd(a,b) __gcd(a,b) #define all(a) a.begin(), a.end() #define pb push_back #define sz(a) (ll)a.size() #define ll long long int #define ld long double #define pii pair<int, int> #define pll pair<long long int, long long int> #define Int vector<int> #define Ll vector<ll> #define String vector<string> #define Char vector<char> #define Bool vector<bool> constexpr long long N = 1e5; constexpr long long inf = 1e18; constexpr long long mod = 1e9 + 7; constexpr long long MOD = 998244353; constexpr long double PI = 3.141592653589793238462; int modpow(int a, int b, int m = mod) { a = a & m; int ans = 1; while (b) { /* 'if' begin */ if (b & 1) /* 'if' inside */ { ans = (ans * a) % m; } b = b >> 1; a = (a * a) % m; } return ans; } int modinv(int a, int m = mod) { return modpow(a, m - 2); } int modadd(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } int modsub(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } int modmul(int a, int b, int m = mod) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } int moddiv(int a, int b, int m = mod) { a = a % m; b = b % m; return (modmul(a, modinv(b, m), m) + m) % m; } int gcd(int a, int b) { /* 'if' begin */ if (b == 0) /* 'if' inside */ { return a; } return gcd(b, a % b); } int lcm(int a, int b) { return (a / gcd(a, b)) * b; } bool cmp(const pii &a, const pii &b){ return (a.second < b.second); } void solve() { int n; cin>>n; Ll arr(n); for(int i = 0; i<n; i++)/* 'for' inside */ { cin>>arr[i]; } Ll cnt(31, 0); for(int i = 0; i < n; i++)/* 'for' inside */ { ll x = arr[i]; ll indx = 0; while(x){ /* 'if' begin */ if(x&1)/* 'if' inside */ { cnt[indx]++; } x = x>>1; indx++; } } for(int i = 1; i<=n; i++)/* 'for' inside */ { bool flag = true; for(int j=0; j<31; j++)/* 'for' inside */ { /* 'if' begin */ if(cnt[j]%i)/* 'if' inside */ { flag = false; break; } } /* 'if' begin */ if(flag)/* 'if' inside */ { cout<<i<<" "; } } cout<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cout<<fixed; cout<<setprecision(10); int t; cin>>t; while(t--){ solve(); } return 0; }
/* auth.cpp Subroutines having to do with authentication. */ /* * Copyright (c) 2002-2006 Nominum, Inc. * All rights reserved. * * Copyright (c) 1998-2001 Internet Software Consortium. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Nominum, Internet Software Consortium nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY NOMINUM, THE INTERNET SOFTWARE * CONSORTIUM AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL NOMINUM, THE INTERNET SOFTWARE CONSORTIUM OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef lint static char copyright[] __attribute__((unused)) = "$Id: auth.cpp,v 1.2 2006/05/12 21:51:35 mellon Exp $ Copyright 1998-2000 The Internet Software Consortium."; #endif #include "dhcpd.h" auth_hash_t *auth_key_hash; HASH_FUNCTIONS (auth_key, const char *, auth_key_t, auth_hash_t) isc_result_t auth_key_enter (auth_key_t *a) { auth_key_t *tk; tk = (auth_key_t *)0; if (auth_key_hash) { auth_key_hash_lookup (&tk, auth_key_hash, a->name, 0); if (tk == a) { return ISC_R_SUCCESS; } if (tk) { auth_key_hash_delete (auth_key_hash, tk->name, 0); } } else { if (!auth_key_new_hash (&auth_key_hash, 1)) return ISC_R_NOMEMORY; } auth_key_hash_add (auth_key_hash, a->name, 0, a); return ISC_R_SUCCESS; } isc_result_t auth_key_lookup_name (auth_key_t **a, const char *name) { if (!auth_key_hash) return ISC_R_NOTFOUND; if (!auth_key_hash_lookup (a, auth_key_hash, name, 0)) return ISC_R_NOTFOUND; return ISC_R_SUCCESS; }
// // Created by xiaofeng on 2019/11/29. // //The 0.4.0 version of solidity language will automatically supplement //fallback function for contracts. The fallback functions provided by //contract writers may bring security risks. //source file /* author=__xiaofeng__ */ #include <iostream> #include "RedFallback.h" bool RedFallback::IsVersion(const string & _str) { string temp = ""; for (char c : _str) { if (!isblank(c)) temp.push_back(c); } if (temp.find(RF_PRAGMA) < temp.size()) return true; return false; } int RedFallback::GetVersion(const string & _str) { vector<string> vec; split(_str, vec); istringstream iss(vec[1].c_str()); int result; iss >> result; return result; } void RedFallback::split(const string & _str, vector<string>& vec, const char flag) { vec.clear(); istringstream iss(_str); string temp = ""; while (getline(iss, temp, flag)) vec.push_back(temp); temp.clear(); } bool RedFallback::IsFallback(const string & _str) { string temp = ""; for (char c : _str) { if (!isblank(c)) temp.push_back(c); } if (temp.find(RF_FALLBACK) < temp.size()) return true; return false; } RedFallback::RedFallback(const string _report_name, const vector<string> _content) { report_name = _report_name; content = _content; RFName = "Redundant refusal of payment"; OtherOperation = "The 0.4.0 version of Solidity language will automatically \n" "supplement fallback function for contracts. The fallback functions\n" "provided by contract writers may bring security risks.\nBug level: warning"; VersionNum = 5; } RedFallback::~RedFallback() { report_name.clear(); content.clear(); RFName.clear(); OtherOperation.clear(); row_number.clear(); } string RedFallback::MakeReport(const vector<int>& _row_number) { if (_row_number.empty()) { return "No redundant refusal of payment.\n\n"; } string _report = ""; _report += "[Bug 12]\n"; _report += "bug name: "; _report += RFName; _report += '\n'; _report += "number of bugs: "; _report += to_string(_row_number.size()); _report += '\n'; _report += "row number: "; for (auto i = _row_number.begin(); i != _row_number.end(); i++) { _report += to_string((*i)); _report += " "; } _report += '\n'; if (OtherOperation.size() != 0) { _report += "additional description: "; _report += OtherOperation; _report += '\n'; } return _report; } int RedFallback::GetNumber() { return row_number.size(); } vector<int> RedFallback::GetRowNumber() { return row_number; } void RedFallback::Detection() { for (auto i = content.begin(); i != content.end(); i++) { if (IsVersion(*i)) { VersionNum = GetVersion(*i); break; } } if (VersionNum >= RF_LIMIT) { for (int i = 0; i < content.size(); i++) { if (IsFallback(content[i])) { row_number.push_back((i + 1)); } } } else return; } void RedFallback::SetVerion(const int _v) { VersionNum = _v; } int RedFallback::GetVersion() { return VersionNum; return 0; } void RedFallback::Re_Detection() { for (auto i = content.begin(); i != content.end(); i++) { if ((*i).find("pragma ")<(*i).size() && (*i).find("solidity ")<(*i).size()) { regex reg{ RF_RE_VERSION }; smatch s; if (regex_search(*i, s, reg)) { VersionNum = GetVersion(*i); break; } else continue; } else continue; } if (VersionNum >= RF_LIMIT) { for (int i = 0; i < content.size() -1 ; i++) { if (content[i].find("function")<content[i].size()) { //regex reg{ RF_RE_FALLBACK }; regex reg{"(\\b)(function)(\\s)*(\\()(\\s)*(\\))(.)*(\\s)+(payable)(\\s)*" }; regex reg1{ RF_RE_THROW }; smatch s; smatch s1; if (regex_search(content[i], s, reg) && regex_search(content[i+1], s1,reg1)) { row_number.push_back((i + 1)); } else continue; } else continue; } } else return; }
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2016 Pivotal Software, Inc. // // @filename: // var_expr_tree_generator.cc // // @doc: // Object that generator code for variable expression. // //--------------------------------------------------------------------------- #include "codegen/expr_tree_generator.h" #include "codegen/var_expr_tree_generator.h" #include "llvm/IR/Value.h" extern "C" { #include "postgres.h" // NOLINT(build/include) #include "utils/elog.h" #include "nodes/execnodes.h" } using gpcodegen::VarExprTreeGenerator; using gpcodegen::ExprTreeGenerator; using gpcodegen::CodegenUtils; bool VarExprTreeGenerator::VerifyAndCreateExprTree( ExprState* expr_state, ExprContext* econtext, std::unique_ptr<ExprTreeGenerator>* expr_tree) { assert(nullptr != expr_state && nullptr != expr_state->expr && T_Var == nodeTag(expr_state->expr) && nullptr != expr_tree); expr_tree->reset(new VarExprTreeGenerator(expr_state)); return true; } VarExprTreeGenerator::VarExprTreeGenerator(ExprState* expr_state) : ExprTreeGenerator(expr_state, ExprTreeNodeType::kVar) { } bool VarExprTreeGenerator::GenerateCode(CodegenUtils* codegen_utils, ExprContext* econtext, llvm::Function* llvm_main_func, llvm::BasicBlock* llvm_error_block, llvm::Value* llvm_isnull_arg, llvm::Value** llvm_out_value) { assert(nullptr != llvm_out_value); *llvm_out_value = nullptr; Var* var_expr = reinterpret_cast<Var*>(expr_state()->expr); int attnum = var_expr->varattno; auto irb = codegen_utils->ir_builder(); // slot = econtext->ecxt_scantuple; {{{ // At code generation time, slot is NULL. // For that reason, we keep a double pointer to slot and at execution time // we load slot. TupleTableSlot **ptr_to_slot_ptr = NULL; switch (var_expr->varno) { case INNER: /* get the tuple from the inner node */ ptr_to_slot_ptr = &econtext->ecxt_innertuple; break; case OUTER: /* get the tuple from the outer node */ ptr_to_slot_ptr = &econtext->ecxt_outertuple; break; default: /* get the tuple from the relation being scanned */ ptr_to_slot_ptr = &econtext->ecxt_scantuple; break; } llvm::Value *llvm_slot = irb->CreateLoad( codegen_utils->GetConstant(ptr_to_slot_ptr)); //}}} llvm::Value *llvm_variable_varattno = codegen_utils-> GetConstant<int32_t>(attnum); // External functions llvm::Function* llvm_slot_getattr = codegen_utils->GetOrRegisterExternalFunction(slot_getattr); // retrieve variable *llvm_out_value = irb->CreateCall( llvm_slot_getattr, { llvm_slot, llvm_variable_varattno, llvm_isnull_arg /* TODO: Fix isNull */ }); return true; }
/* This file is part of Caelum. See http://www.ogre3d.org/wiki/index.php/Caelum Copyright (c) 2006-2007 Caelum team. See Contributors.txt for details. Caelum is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Caelum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Caelum. If not, see <http://www.gnu.org/licenses/>. */ #include "CaelumPrecompiled.h" #include "CaelumExceptions.h" #include "InternalUtilities.h" #include "PrivatePtr.h" namespace Caelum { Ogre::ColourValue InternalUtilities::getInterpolatedColour ( float fx, float fy, Ogre::Image *img, bool wrapX) { // Don't -> all the time, and avoid unsigned warnings int imgWidth = static_cast<int>(img->getWidth ()); int imgHeight = static_cast<int>(img->getHeight ()); // Calculate pixel y coord. int py = Ogre::Math::IFloor(Ogre::Math::Abs (fy) * (imgHeight - 1)); // Snap to py image bounds. py = std::max(0, std::min(py, imgHeight - 1)); // Get the two closest pixels on x. // px1 and px2 are the closest integer pixels to px. float px = fx * (img->getWidth () - 1); int px1, px2; px1 = Ogre::Math::IFloor(px); px2 = Ogre::Math::ICeil(px); if (wrapX) { // Wrap x coords. The funny addition ensures that it does // "the right thing" for negative values. px1 = (px1 % imgWidth + imgWidth) % imgWidth; px2 = (px2 % imgWidth + imgWidth) % imgWidth; } else { px1 = std::max(0, std::min(px1, imgWidth - 1)); px2 = std::max(0, std::min(px2, imgWidth - 1)); } // Calculate the interpolated pixel Ogre::ColourValue c1, c2, cf; c1 = img->getColourAt (px1, py, 0); c2 = img->getColourAt (px2, py, 0); // Blend the two pixels together. // diff is the weight between pixel 1 and pixel 2. float diff = px - px1; cf = c1 * (1 - diff) + c2 * diff; return cf; } const Ogre::String InternalUtilities::pointerToString (void* pointer) { std::stringstream stream; stream.width(2 * sizeof(void *)); stream.fill('0'); stream.unsetf(std::ios::dec); stream.setf(std::ios::hex); stream.setf(std::ios::uppercase); stream << reinterpret_cast<ptrdiff_t>(pointer); return stream.str(); } Ogre::MaterialPtr InternalUtilities::checkLoadMaterialClone ( const Ogre::String& originalName, const Ogre::String& cloneName) { Ogre::MaterialPtr scriptMaterial = Ogre::MaterialManager::getSingletonPtr()->getByName(originalName); if (scriptMaterial.isNull()) { CAELUM_THROW_UNSUPPORTED_EXCEPTION ( "Can't find material \"" + originalName + "\"", "Caelum"); } // Create clone Caelum::PrivateMaterialPtr clonedMaterial (scriptMaterial->clone (cloneName)); // Test clone loads and there is at least on supported technique clonedMaterial->load (); if (clonedMaterial->getBestTechnique () == 0) { CAELUM_THROW_UNSUPPORTED_EXCEPTION ( "Can't load material \"" + originalName + "\": " + clonedMaterial->getUnsupportedTechniquesExplanation(), "Caelum"); } return clonedMaterial.release(); } Ogre::CompositorPtr InternalUtilities::checkCompositorSupported (const Ogre::String& name) { Ogre::CompositorPtr comp = Ogre::CompositorManager::getSingletonPtr()->getByName(name); if (comp.isNull()) { CAELUM_THROW_UNSUPPORTED_EXCEPTION ( "Can't find compositor \"" + name + "\"", "Caelum"); } // Check the compositor is supported after loading. comp->load (); if (comp->getNumSupportedTechniques () == 0) { CAELUM_THROW_UNSUPPORTED_EXCEPTION ( "Can't load compositor \"" + name + "\"", "Caelum"); } return comp; } void InternalUtilities::generateSphericDome (const Ogre::String &name, int segments, DomeType type) { // Return now if already exists if (Ogre::MeshManager::getSingleton ().resourceExists (name)) { return; } Ogre::LogManager::getSingleton ().logMessage ( "Caelum: Creating " + name + " sphere mesh resource..."); // Use the mesh manager to create the mesh Ogre::MeshPtr msh = Ogre::MeshManager::getSingleton ().createManual (name, RESOURCE_GROUP_NAME); // Create a submesh Ogre::SubMesh *sub = msh->createSubMesh (); // Create the shared vertex data Ogre::VertexData *vertexData = new Ogre::VertexData (); msh->sharedVertexData = vertexData; // Define the vertices' format Ogre::VertexDeclaration *vertexDecl = vertexData->vertexDeclaration; size_t currOffset = 0; // Position vertexDecl->addElement (0, currOffset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); currOffset += Ogre::VertexElement::getTypeSize (Ogre::VET_FLOAT3); // Normal vertexDecl->addElement (0, currOffset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); currOffset += Ogre::VertexElement::getTypeSize (Ogre::VET_FLOAT3); // Texture coordinates vertexDecl->addElement (0, currOffset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0); currOffset += Ogre::VertexElement::getTypeSize (Ogre::VET_FLOAT2); // Allocate the vertex buffer switch (type) { case DT_SKY_DOME: vertexData->vertexCount = segments * (segments - 1) + 2; break; case DT_IMAGE_STARFIELD: vertexData->vertexCount = (segments + 1) * (segments + 1); break; }; Ogre::HardwareVertexBufferSharedPtr vBuf = Ogre::HardwareBufferManager::getSingleton ().createVertexBuffer (vertexDecl->getVertexSize (0), vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); Ogre::VertexBufferBinding *binding = vertexData->vertexBufferBinding; binding->setBinding (0, vBuf); float *pVertex = static_cast<float *>(vBuf->lock (Ogre::HardwareBuffer::HBL_DISCARD)); // Allocate the index buffer switch (type) { case DT_SKY_DOME: sub->indexData->indexCount = 2 * segments * (segments - 1) * 3; break; case DT_IMAGE_STARFIELD: sub->indexData->indexCount = 2 * (segments - 1) * segments * 3; break; }; sub->indexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton ().createIndexBuffer (Ogre::HardwareIndexBuffer::IT_16BIT, sub->indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); Ogre::HardwareIndexBufferSharedPtr iBuf = sub->indexData->indexBuffer; unsigned short *pIndices = static_cast<unsigned short *>(iBuf->lock (Ogre::HardwareBuffer::HBL_DISCARD)); // Fill the buffers switch (type) { case DT_SKY_DOME: fillGradientsDomeBuffers (pVertex, pIndices, segments); break; case DT_IMAGE_STARFIELD: fillStarfieldDomeBuffers (pVertex, pIndices, segments); break; }; // Close the vertex buffer vBuf->unlock (); // Close the index buffer iBuf->unlock (); // Finishing it... sub->useSharedVertices = true; msh->_setBounds (Ogre::AxisAlignedBox (-1, -1, -1, 1, 1, 1), false); msh->_setBoundingSphereRadius (1); msh->load (); Ogre::LogManager::getSingleton ().logMessage ( "Caelum: generateSphericDome DONE"); } void InternalUtilities::fillGradientsDomeBuffers (float *pVertex, unsigned short *pIndices, int segments) { const float deltaLatitude = Ogre::Math::PI / (float )segments; const float deltaLongitude = Ogre::Math::PI * 2.0 / (float )segments; // Generate the rings for (int i = 1; i < segments; i++) { float r0 = Ogre::Math::Sin (Ogre::Radian (i * deltaLatitude)); float y0 = Ogre::Math::Cos (Ogre::Radian (i * deltaLatitude)); for (int j = 0; j < segments; j++) { float x0 = r0 * Ogre::Math::Sin (Ogre::Radian (j * deltaLongitude)); float z0 = r0 * Ogre::Math::Cos (Ogre::Radian (j * deltaLongitude)); *pVertex++ = x0; *pVertex++ = y0; *pVertex++ = z0; *pVertex++ = -x0; *pVertex++ = -y0; *pVertex++ = -z0; *pVertex++ = 0; *pVertex++ = 1 - y0; } } // Generate the "north pole" *pVertex++ = 0; // Position *pVertex++ = 1; *pVertex++ = 0; *pVertex++ = 0; // Normal *pVertex++ = -1; *pVertex++ = 0; *pVertex++ = 0; // UV *pVertex++ = 0; // Generate the "south pole" *pVertex++ = 0; // Position *pVertex++ = -1; *pVertex++ = 0; *pVertex++ = 0; // Normal *pVertex++ = 1; *pVertex++ = 0; *pVertex++ = 0; // UV *pVertex++ = 2; // Generate the mid segments for (int i = 0; i < segments - 2; i++) { for (int j = 0; j < segments; j++) { *pIndices++ = segments * i + j; *pIndices++ = segments * i + (j + 1) % segments; *pIndices++ = segments * (i + 1) + (j + 1) % segments; *pIndices++ = segments * i + j; *pIndices++ = segments * (i + 1) + (j + 1) % segments; *pIndices++ = segments * (i + 1) + j; } } // Generate the upper cap for (int i = 0; i < segments; i++) { *pIndices++ = segments * (segments - 1); *pIndices++ = (i + 1) % segments; *pIndices++ = i; } // Generate the lower cap for (int i = 0; i < segments; i++) { *pIndices++ = segments * (segments - 1) + 1; *pIndices++ = segments * (segments - 2) + i; *pIndices++ = segments * (segments - 2) + (i + 1) % segments; } } void InternalUtilities::fillStarfieldDomeBuffers (float *pVertex, unsigned short *pIndices, int segments) { const float deltaLatitude = Ogre::Math::PI / (float )segments; const float deltaLongitude = Ogre::Math::PI * 2.0 / (float )segments; // Generate the rings for (int i = 0; i <= segments; i++) { float r0 = Ogre::Math::Sin (Ogre::Radian (i * deltaLatitude)); float y0 = Ogre::Math::Cos (Ogre::Radian (i * deltaLatitude)); for (int j = 0; j <= segments; j++) { float x0 = r0 * Ogre::Math::Sin (Ogre::Radian (j * deltaLongitude)); float z0 = r0 * Ogre::Math::Cos (Ogre::Radian (j * deltaLongitude)); *pVertex++ = x0; *pVertex++ = y0; *pVertex++ = z0; *pVertex++ = -x0; *pVertex++ = -y0; *pVertex++ = -z0; *pVertex++ = (float )j / (float )segments; *pVertex++ = 1 - (y0 * 0.5 + 0.5); } } // Generate the mid segments int vRowSize = segments + 1; for (int i = 1; i < segments; i++) { for (int j = 0; j < segments; j++) { int baseIdx = vRowSize * i + j; *pIndices++ = baseIdx; *pIndices++ = baseIdx + 1; *pIndices++ = baseIdx + vRowSize + 1; *pIndices++ = baseIdx + 1; *pIndices++ = baseIdx; *pIndices++ = baseIdx - vRowSize; } } } }
#include "_core.h" class ::std::unique_ptr< struct ::statiskit::UnivariateDistributionEstimation, struct ::std::default_delete< struct ::statiskit::UnivariateDistributionEstimation > > (::statiskit::LazyEstimation< ::statiskit::GeometricDistribution, ::statiskit::DiscreteUnivariateDistributionEstimation >::*method_pointer_987331533ec95ef299bec4217d054eae)()const= &::statiskit::LazyEstimation< class ::statiskit::GeometricDistribution, struct ::statiskit::DiscreteUnivariateDistributionEstimation >::copy; namespace autowig { } void wrapper_3b2e19fa74a45eb49f08742886108635(pybind11::module& module) { pybind11::class_<class ::statiskit::LazyEstimation< class ::statiskit::GeometricDistribution, struct ::statiskit::DiscreteUnivariateDistributionEstimation >, autowig::HolderType< class ::statiskit::LazyEstimation< class ::statiskit::GeometricDistribution, struct ::statiskit::DiscreteUnivariateDistributionEstimation > >::Type, struct ::statiskit::DiscreteUnivariateDistributionEstimation > class_3b2e19fa74a45eb49f08742886108635(module, "_LazyEstimation_3b2e19fa74a45eb49f08742886108635", ""); class_3b2e19fa74a45eb49f08742886108635.def(pybind11::init< >()); class_3b2e19fa74a45eb49f08742886108635.def(pybind11::init< class ::statiskit::GeometricDistribution const * >()); class_3b2e19fa74a45eb49f08742886108635.def(pybind11::init< class ::statiskit::LazyEstimation< class ::statiskit::GeometricDistribution, struct ::statiskit::DiscreteUnivariateDistributionEstimation > const & >()); class_3b2e19fa74a45eb49f08742886108635.def("copy", method_pointer_987331533ec95ef299bec4217d054eae, ""); }
// ***************************************************************************** /*! \file src/RNG/MKLRNG.hpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Interface to Intel MKL VSL random number generators \details Interface to Intel MKL VSL random number generators. */ // ***************************************************************************** #ifndef MKLRNG_h #define MKLRNG_h #include <mkl_vsl.h> #include "Exception.hpp" #include "Make_unique.hpp" #include "Keywords.hpp" namespace tk { //! MKL-based random number generator used polymorphically with tk::RNG class MKLRNG { using ncomp_t = kw::ncomp::info::expect::type; public: //! Constructor //! \param[in] n Initialize RNG using this many independent streams //! \param[in] brng Index of the basic generator to initialize the stream //! \param[in] seed RNG seed //! \param[in] uniform_method MKL ID of the method to use for uniform RNGs //! \param[in] gaussian_method MKL ID of the method to use for Gaussian RNGs //! \param[in] gaussianmv_method MKL ID of the method to use for //! multi-variate Gaussian RNGs //! \param[in] beta_method MKL ID of the method to use for beta RNGs //! \param[in] gamma_method MKL ID of the method to use for gamma RNGs explicit MKLRNG( int n = 1, int brng = VSL_BRNG_MCG59, unsigned int seed = 0, int uniform_method = VSL_RNG_METHOD_UNIFORM_STD, int gaussian_method = VSL_RNG_METHOD_GAUSSIAN_BOXMULLER, int gaussianmv_method = VSL_RNG_METHOD_GAUSSIANMV_BOXMULLER2, int beta_method = VSL_RNG_METHOD_BETA_CJA, int gamma_method = VSL_RNG_METHOD_GAMMA_GNORM ) : m_brng( brng ), m_seed( seed ), m_uniform_method( uniform_method ), m_gaussian_method( gaussian_method ), m_gaussianmv_method( gaussianmv_method ), m_beta_method( beta_method ), m_gamma_method( gamma_method ), m_nthreads( n ), m_stream() { Assert( n > 0, "Need at least one thread" ); Assert( brng > 0, "Basic RNG MKL parameter must be positive" ); // Allocate array of stream-pointers for threads m_stream = tk::make_unique< VSLStreamStatePtr[] >( static_cast<std::size_t>(n) ); // Initialize thread-streams for block-splitting. These MKL VSL functions // dynamically allocate memory, so these calls being in a constructor are // a potential memory leak hazard in the presence of exceptions. However, // thankfully, the MKL functions below only emit warnings if they // encounter errors and always continue. As a result, the constructor // finishes, the MKLRNG object gets created, so the destructor will also // get called when leaving scope. if (n == 1) errchk( vslNewStream( &m_stream[0], brng, seed ) ); else for (int i=0; i<n; ++i) { auto I = static_cast< std::size_t >( i ); errchk( vslNewStream( &m_stream[I], brng, seed ) ); errchk( vslLeapfrogStream( m_stream[I], i, n ) ); } } //! Destructor ~MKLRNG() noexcept { deleteStreams(); } //! Uniform RNG: Generate uniform random numbers //! \param[in] tid Thread (or more precisely stream) ID //! \param[in] num Number of RNGs to generate //! \param[in,out] r Pointer to memory to write the random numbers to void uniform( int tid, ncomp_t num, double* r ) const { vdRngUniform( m_uniform_method, m_stream[ static_cast<std::size_t>(tid) ], static_cast< long long >( num ), r, 0.0, 1.0 ); } //! Gaussian RNG: Generate Gaussian random numbers //! \param[in] tid Thread (or more precisely stream) ID //! \param[in] num Number of RNGs to generate //! \param[in,out] r Pointer to memory to write the random numbers to void gaussian( int tid, ncomp_t num, double* r ) const { vdRngGaussian( m_gaussian_method, m_stream[ static_cast<std::size_t>(tid) ], static_cast< long long >( num ), r, 0.0, 1.0 ); } //! \brief Multi-variate Gaussian RNG: Generate multi-variate Gaussian //! random numbers //! \param[in] tid Thread (or more precisely stream) ID //! \param[in] num Number of RNGs to generate //! \param[in] d Dimension d ( d ≥ 1) of output random vectors //! \param[in] mean Mean vector of dimension d //! \param[in] cov Lower triangle of covariance matrix, stored as a vector //! of length d(d+1)/2 //! \param[in,out] r Pointer to memory to write the random numbers to void gaussianmv( int tid, ncomp_t num, ncomp_t d, const double* const mean, const double* const cov, double* r ) const { Assert( d > 0, "Dimension of multi-variate Gaussian RNGs must be positive" ); vdRngGaussianMV( m_gaussianmv_method, m_stream[ static_cast<std::size_t>(tid) ], static_cast< long long >( num ), r, static_cast< int >( d ), VSL_MATRIX_STORAGE_PACKED, mean, cov ); } //! Beta RNG: Generate beta random numbers //! \param[in] tid Thread (or more precisely stream) ID //! \param[in] num Number of RNGs to generate //! \param[in] p First beta shape parameter //! \param[in] q Second beta shape parameter //! \param[in] a Beta displacement parameter //! \param[in] b Beta scale factor //! \param[in,out] r Pointer to memory to write the random numbers to void beta( int tid, ncomp_t num, double p, double q, double a, double b, double* r ) const { vdRngBeta( m_beta_method, m_stream[ static_cast<std::size_t>(tid) ], static_cast< long long >( num ), r, p, q, a, b ); } //! Gamma RNG: Generate gamma random numbers //! \param[in] tid Thread (or more precisely stream) ID //! \param[in] num Number of RNGs to generate //! \param[in] a Gamma shape parameter //! \param[in] b Gamma scale factor //! \param[in,out] r Pointer to memory to write the random numbers to void gamma( int tid, ncomp_t num, double a, double b, double* r ) const { vdRngGamma( m_beta_method, m_stream[ static_cast<std::size_t>(tid) ], static_cast< long long >( num ), r, a, 0.0, b ); // displacement = 0.0 } //! Copy assignment MKLRNG& operator=( const MKLRNG& x ) { m_brng = x.m_brng; m_seed = x.m_seed; m_uniform_method = x.m_uniform_method; m_gaussian_method = x.m_gaussian_method; m_gaussianmv_method = x.m_gaussianmv_method; m_beta_method = x.m_beta_method; m_gamma_method = x.m_gamma_method; m_nthreads = x.m_nthreads; m_stream = tk::make_unique< VSLStreamStatePtr[] >( static_cast<std::size_t>(x.m_nthreads) ); if (m_nthreads == 1) errchk( vslNewStream( &m_stream[0], x.m_brng, x.m_seed ) ); else for (int i=0; i<x.m_nthreads; ++i) { auto I = static_cast< std::size_t >( i ); errchk( vslNewStream( &m_stream[I], x.m_brng, x.m_seed ) ); errchk( vslLeapfrogStream( m_stream[I], i, x.m_nthreads ) ); } return *this; } //! Copy constructor: in terms of copy assignment MKLRNG( const MKLRNG& x ) { operator=(x); } //! Move assignment MKLRNG& operator=( MKLRNG&& x ) { deleteStreams(); m_brng = x.m_brng; m_seed = x.m_seed; m_uniform_method = x.m_uniform_method; m_gaussian_method = x.m_gaussian_method; m_gaussianmv_method = x.m_gaussianmv_method; m_beta_method = x.m_beta_method; m_gamma_method = x.m_gamma_method; m_nthreads = x.m_nthreads; m_stream = tk::make_unique< VSLStreamStatePtr[] >( static_cast<std::size_t>(x.m_nthreads) ); for (int i=0; i<x.m_nthreads; ++i) { auto I = static_cast< std::size_t >( i ); m_stream[I] = x.m_stream[I]; x.m_stream[I] = nullptr; } x.m_brng = 0; x.m_seed = 0; x.m_uniform_method = 0; x.m_gaussian_method = 0; x.m_gaussianmv_method = 0; x.m_beta_method = 0; x.m_gamma_method = 0; x.m_nthreads = 0; x.m_stream.reset( nullptr ); return *this; } //! Move constructor: in terms of move assignment MKLRNG( MKLRNG&& x ) : m_brng( 0 ), m_seed( 0 ), m_uniform_method( 0 ), m_gaussian_method( 0 ), m_gaussianmv_method( 0 ), m_beta_method( 0 ), m_gamma_method( 0 ), m_nthreads( 0 ), m_stream( nullptr ) { *this = std::move(x); } //! Accessor to the number of threads we operate on std::size_t nthreads() const noexcept { return static_cast< std::size_t >( m_nthreads); } private: //! Delete all thread streams void deleteStreams() { for (int i=0; i<m_nthreads; ++i) { auto I = static_cast< std::size_t >( i ); if (m_stream[I]) { vslDeleteStream( &m_stream[I] ); m_stream[I] = nullptr; } } } //! MKL VSL error check //! \param[in] err MKL VSL error code as returned from MKL VSL functions //! \details This calls ErrChk(), i.e., it is not compiled away in Release //! mode as an error here can result due to user input incompatible with //! the MKL library. void errchk( int err ) { ErrChk( err == VSL_STATUS_OK, "MKL VSL Error Code: " + std::to_string(err) + ", see mkl_vsl_defines.h for more info" ); } int m_brng; //!< MKL RNG id unsigned int m_seed; //!< Seed int m_uniform_method; //!< Uniform method to use int m_gaussian_method; //!< Gaussian method to use int m_gaussianmv_method; //!< Multi-variate Gaussian method to use int m_beta_method; //!< Beta method to use int m_gamma_method; //!< Gamma method to use int m_nthreads; //!< Number of threads std::unique_ptr< VSLStreamStatePtr[] > m_stream; //!< Random number streams }; } // tk:: #endif // MKLRNG_h
#using <System.Xml.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> #using <System.dll> #using <System.Data.dll> using namespace System; using namespace System::Data; using namespace System::ComponentModel; using namespace System::Windows::Forms; public ref class Form1: public Form { protected: ErrorProvider^ errorProvider1; DataSet^ dataSet1; DataTable^ dataTable1; // <Snippet1> private: void InitializeComponent() { // Standard control setup. //.... // You set the DataSource to a data set, and the DataMember to a table. errorProvider1->DataSource = dataSet1; errorProvider1->DataMember = dataTable1->TableName; errorProvider1->ContainerControl = this; errorProvider1->BlinkRate = 200; //... // Since the ErrorProvider control does not have a visible component, // it does not need to be added to the form. } private: void buttonSave_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { // Checks for a bad post code. DataTable^ CustomersTable; CustomersTable = dataSet1->Tables[ "Customers" ]; System::Collections::IEnumerator^ myEnum = (CustomersTable->Rows)->GetEnumerator(); while ( myEnum->MoveNext() ) { DataRow^ row = safe_cast<DataRow^>(myEnum->Current); if ( Convert::ToBoolean( row[ "PostalCodeIsNull" ] ) ) { row->RowError = "The Customer details contain errors"; row->SetColumnError( "PostalCode", "Postal Code required" ); } } } // </Snippet1> };
#ifndef DOMTreeWalkerImpl_HEADER_GUARD_ #define DOMTreeWalkerImpl_HEADER_GUARD_ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMTreeWalkerImpl.hpp 568078 2007-08-21 11:43:25Z amassari $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/dom/DOMTreeWalker.hpp> XERCES_CPP_NAMESPACE_BEGIN class CDOM_EXPORT DOMTreeWalkerImpl : public DOMTreeWalker { private: // The whatToShow mask. unsigned long fWhatToShow; // The NodeFilter reference. DOMNodeFilter* fNodeFilter; // The current Node. DOMNode* fCurrentNode; // The root Node. DOMNode* fRoot; // The expandEntity reference flag. bool fExpandEntityReferences; public: // Implementation Note: No state is kept except the data above // (fWhatToShow, fNodeFilter, fCurrentNode, fRoot) such that // setters could be created for these data values and the // implementation will still work. /** Public constructor */ DOMTreeWalkerImpl ( DOMNode* root, unsigned long whatToShow, DOMNodeFilter* nodeFilter, bool expandEntityRef); DOMTreeWalkerImpl (const DOMTreeWalkerImpl& twi); DOMTreeWalkerImpl& operator= (const DOMTreeWalkerImpl& twi); // Return the root node. virtual DOMNode* getRoot (); // Return the whatToShow value. virtual unsigned long getWhatToShow (); // Return the NodeFilter. virtual DOMNodeFilter* getFilter (); // Return the current DOMNode. virtual DOMNode* getCurrentNode (); // Return the current Node. virtual void setCurrentNode (DOMNode* node); // Return the parent Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* parentNode (); // Return the first child Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* firstChild (); // Return the last child Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* lastChild (); // Return the previous sibling Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* previousSibling (); // Return the next sibling Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* nextSibling (); // Return the previous Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* previousNode (); // Return the next Node from the current node, // after applying filter, whatToshow. // If result is not null, set the current Node. virtual DOMNode* nextNode (); // Get the expandEntity reference flag. virtual bool getExpandEntityReferences(); // release the resource virtual void release(); protected: // Internal function. // Return the parent Node, from the input node // after applying filter, whatToshow. // The current node is not consulted or set. DOMNode* getParentNode (DOMNode* node); // Internal function. // Return the nextSibling Node, from the input node // after applying filter, whatToshow. // The current node is not consulted or set. DOMNode* getNextSibling (DOMNode* node); // Internal function. // Return the previous sibling Node, from the input node // after applying filter, whatToshow. // The current node is not consulted or set. DOMNode* getPreviousSibling (DOMNode* node); // Internal function. // Return the first child Node, from the input node // after applying filter, whatToshow. // The current node is not consulted or set. DOMNode* getFirstChild (DOMNode* node); // Internal function. // Return the last child Node, from the input node // after applying filter, whatToshow. // The current node is not consulted or set. DOMNode* getLastChild (DOMNode* node); // The node is accepted if it passes the whatToShow and the filter. short acceptNode (DOMNode* node); }; XERCES_CPP_NAMESPACE_END #endif
#include "token.h" #include "color.h" using namespace MiniC; Token::Token(string kind, string value) : kind(move(kind)), value(move(value)), children(), loc(nullopt) {} Token::Token(string kind) : kind(move(kind)), value(), children(), loc(nullopt) {} Token::Token(string kind, string value, location loc) : kind(move(kind)), value(move(value)), children(), loc(loc) {} Token::Token(string kind, location loc) : kind(move(kind)), value(), children(), loc(loc) {} Token::Token() = default; void Token::addChild(const Token &child) { children.push_back(child); } string Token::getKind() const { return kind; } void Token::setKind(const string &newKind) { kind = newKind; } string Token::getValue() const { return value; } vector<Token> Token::getChildren() const { return children; } Token Token::getChildren(int index) const { return children.at(index); } optional<location> Token::getLocation() const { if (loc == nullopt) { for (const auto& child : children) { auto childLoc = child.getLocation(); if (childLoc != nullopt) { return childLoc; } } return nullopt; } return loc; } string Token::toString(const string &baseIndent) const { stringstream s; s << "kind: [[" << (kind.find("ERROR") == string::npos ? BLUE : RED) << kind << RESET_COLOR << "]]"; if (!value.empty()) { s << ", value: [["; if (kind == "Type") { s << MAGENTA; } else if (kind == "Identifier") { s << CYAN; } else if (kind == "Operator") { s << BOLD_YELLOW; } else { s << BOLD_GREEN; } s << value << RESET_COLOR << "]]"; } if (!children.empty()) { string tab = " "; s << ", child: [" << endl; for (const auto &child: children) { s << tab << baseIndent << child.toString(baseIndent + tab) << endl; } s << baseIndent << "]"; } return s.str(); } bool Token::operator==(const string &str) const { return kind == str; } bool Token::operator!=(const string &str) const { return kind != str; }
//---------------------------------------------------------------------------- // // Copyright (c) Intel Corporation, 2003 - 2012 All Rights Reserved. // // File: AMT_ProvisioningCertificateHash.cpp // // Contents: A class derived from Credential that describes provisioning certificate hash entry. // // This file was automatically generated from AMT_ProvisioningCertificateHash.mof, version: 6.0.0 // //---------------------------------------------------------------------------- #include "AMT_ProvisioningCertificateHash.h" namespace Intel { namespace Manageability { namespace Cim { namespace Typed { const CimFieldAttribute AMT_ProvisioningCertificateHash::_metadata[] = { {"Description", false, false, false }, {"InstanceID", true, false, false }, {"IsDefault", false, false, false }, {"HashType", false, false, false }, {"HashData", false, false, false }, {"Enabled", false, false, false }, }; // class fields const bool AMT_ProvisioningCertificateHash::IsDefault() const { bool ret = false; TypeConverter::StringToType(GetField("IsDefault"), ret); return ret; } void AMT_ProvisioningCertificateHash::IsDefault(const bool value) { SetOrAddField("IsDefault", TypeConverter::TypeToString(value)); } bool AMT_ProvisioningCertificateHash::IsDefaultExists() const { return ContainsField("IsDefault"); } void AMT_ProvisioningCertificateHash::RemoveIsDefault() { RemoveField("IsDefault"); } const unsigned char AMT_ProvisioningCertificateHash::HashType() const { unsigned char ret = 0; TypeConverter::StringToType(GetField("HashType"), ret); return ret; } void AMT_ProvisioningCertificateHash::HashType(const unsigned char &value) { SetOrAddField("HashType", TypeConverter::TypeToString(value)); } bool AMT_ProvisioningCertificateHash::HashTypeExists() const { return ContainsField("HashType"); } void AMT_ProvisioningCertificateHash::RemoveHashType() { RemoveField("HashType"); } const Base64 AMT_ProvisioningCertificateHash::HashData() const { Base64 ret; TypeConverter::StringToType(GetField("HashData"), ret); return ret; } void AMT_ProvisioningCertificateHash::HashData(const Base64 &value) { SetOrAddField("HashData", TypeConverter::TypeToString(value)); } bool AMT_ProvisioningCertificateHash::HashDataExists() const { return ContainsField("HashData"); } void AMT_ProvisioningCertificateHash::RemoveHashData() { RemoveField("HashData"); } const bool AMT_ProvisioningCertificateHash::Enabled() const { bool ret = false; TypeConverter::StringToType(GetField("Enabled"), ret); return ret; } void AMT_ProvisioningCertificateHash::Enabled(const bool value) { SetOrAddField("Enabled", TypeConverter::TypeToString(value)); } bool AMT_ProvisioningCertificateHash::EnabledExists() const { return ContainsField("Enabled"); } void AMT_ProvisioningCertificateHash::RemoveEnabled() { RemoveField("Enabled"); } CimBase *AMT_ProvisioningCertificateHash::CreateFromCimObject(const CimObject &object) { AMT_ProvisioningCertificateHash *ret = NULL; if(object.ObjectType() != CLASS_NAME) { ret = new CimExtended<AMT_ProvisioningCertificateHash>(object); } else { ret = new AMT_ProvisioningCertificateHash(object); } return ret; } vector<shared_ptr<AMT_ProvisioningCertificateHash> > AMT_ProvisioningCertificateHash::Enumerate(ICimWsmanClient *client, const CimKeys &keys) { return CimBase::Enumerate<AMT_ProvisioningCertificateHash>(client, keys); } void AMT_ProvisioningCertificateHash::Delete(ICimWsmanClient *client, const CimKeys &keys) { CimBase::Delete(client, CLASS_URI, keys); } const vector<CimFieldAttribute> &AMT_ProvisioningCertificateHash::GetMetaData() const { return _classMetaData; } const string AMT_ProvisioningCertificateHash::CLASS_NAME = "AMT_ProvisioningCertificateHash"; const string AMT_ProvisioningCertificateHash::CLASS_URI = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_ProvisioningCertificateHash"; const string AMT_ProvisioningCertificateHash::CLASS_NS = "http://intel.com/wbem/wscim/1/amt-schema/1/AMT_ProvisioningCertificateHash"; const string AMT_ProvisioningCertificateHash::CLASS_NS_PREFIX = "APr569"; CIMFRAMEWORK_API vector <CimFieldAttribute> AMT_ProvisioningCertificateHash::_classMetaData; } } } }
/* $NoKeywords: $ */ /* // // Copyright (c) 1993-2007 Robert McNeel & Associates. All rights reserved. // Rhinoceros is a registered trademark of Robert McNeel & Assoicates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #include "opennurbs.h" bool ON_BezierCage::Read(ON_BinaryArchive& archive) { Destroy(); int major_version = 0; int minor_version = 0; bool rc = archive.BeginRead3dmChunk(TCODE_ANONYMOUS_CHUNK,&major_version,&minor_version); if ( rc ) { while(rc) { if ( major_version != 1 ) { ON_ERROR("ON_BezierCage::Read - old code unable to read new version of chunk"); rc = false; break; } int dim=0,order0=0,order1=0,order2=0; bool is_rat=false; rc = archive.ReadInt(&dim); if (!rc) break; if (dim < 1 || dim > 10000) { ON_ERROR("ON_BezierCage::Read - invalid dim"); rc=false; break; } rc = archive.ReadBool(&is_rat); if (!rc) break; rc = archive.ReadInt(&order0); if (!rc) break; if ( order0 < 2 || order0 > 10000 ) { ON_ERROR("ON_BezierCage::Read - invalid order0"); rc=false; break; } rc = archive.ReadInt(&order1); if (!rc) break; if ( order1 < 2 || order1 > 10000 ) { ON_ERROR("ON_BezierCage::Read - invalid order1"); rc=false; break; } rc = archive.ReadInt(&order2); if (!rc) break; if ( order2 < 2 || order2 > 10000 ) { ON_ERROR("ON_BezierCage::Read - invalid order2"); rc=false; break; } rc = Create(dim,is_rat,order0,order1,order2); if (!rc) break; int i,j,k; const int cv_dim = m_is_rat?(m_dim+1):m_dim; for(i = 0; i < order0 && rc; i++) { for(j = 0; j < order1 && rc; j++) { for ( k = 0; k < order2 && rc; k++) { rc = archive.ReadDouble(cv_dim,CV(i,j,k)); } } } break; } if ( !archive.EndRead3dmChunk() ) { rc = false; } } return rc; } bool ON_BezierCage::Write(ON_BinaryArchive& archive) const { bool rc = archive.BeginWrite3dmChunk(TCODE_ANONYMOUS_CHUNK,1,0); if (rc) { rc = archive.WriteInt(m_dim); if(rc) rc = archive.WriteInt(m_is_rat); if (rc) rc = archive.WriteInt(m_order[0]); if (rc) rc = archive.WriteInt(m_order[1]); if (rc) rc = archive.WriteInt(m_order[2]); int i,j,k; const int cv_dim = m_is_rat?(m_dim+1):m_dim; double* bogus_cv = (double*)alloca(cv_dim*sizeof(*bogus_cv)); for ( i = 0; i < cv_dim; i++ ) bogus_cv[i] = ON_UNSET_VALUE; for(i = 0; i < m_order[0] && rc; i++) { for(j = 0; j < m_order[1] && rc; j++) { for ( k = 0; k < m_order[2] && rc; k++) { const double* cv = CV(i,j,k); if ( !cv ) cv = bogus_cv; rc = archive.WriteDouble(cv_dim,cv); } } } if ( !archive.EndWrite3dmChunk() ) { rc = false; } } return rc; } ON_BezierCage::ON_BezierCage() : m_dim(0),m_is_rat(0),m_cv_capacity(0),m_cv(0) { m_order[0] = 0; m_order[1] = 0; m_order[2] = 0; m_cv_stride[0] = 0; m_cv_stride[1] = 0; m_cv_stride[2] = 0; } ON_BezierCage::ON_BezierCage( int dim, bool is_rat, int order0, int order1, int order2 ) : m_dim(0),m_is_rat(0),m_cv_capacity(0),m_cv(0) { m_order[0] = 0; m_order[1] = 0; m_order[2] = 0; m_cv_stride[0] = 0; m_cv_stride[1] = 0; m_cv_stride[2] = 0; Create( dim, is_rat, order0, order1, order2 ); } ON_BezierCage::ON_BezierCage( const ON_BoundingBox& bbox, int order0, int order1, int order2 ) : m_dim(0),m_is_rat(0),m_cv_capacity(0),m_cv(0) { Create(bbox,order0,order1,order2); } ON_BezierCage::ON_BezierCage( const ON_3dPoint* box_corners, int order0, int order1, int order2 ) : m_dim(0),m_is_rat(0),m_cv_capacity(0),m_cv(0) { Create(box_corners,order0,order1,order2); } ON_BezierCage::~ON_BezierCage() { Destroy(); } ON_BezierCage::ON_BezierCage(const ON_BezierCage& src) : m_dim(0),m_is_rat(0),m_cv_capacity(0),m_cv(0) { m_order[0] = 0; m_order[1] = 0; m_order[2] = 0; m_cv_stride[0] = 0; m_cv_stride[1] = 0; m_cv_stride[2] = 0; *this = src; } ON_BezierCage& ON_BezierCage::operator=(const ON_BezierCage& src) { if ( this != &src ) { if ( Create( src.m_dim, src.m_is_rat, src.m_order[0], src.m_order[1], src.m_order[3] ) ) { const int sizeof_cv = src.CVSize()*sizeof(m_cv[0]); int i, j, k; for ( i = 0; i < m_order[0]; i++ ) for ( j = 0; j < m_order[1]; j++ ) for ( k = 0; k < m_order[2]; k++ ) { memcpy( CV(i,j,k), src.CV(i,j,k), sizeof_cv ); } } else { Destroy(); } } return *this; } bool ON_BezierCage::IsValid() const { if ( m_cv == NULL ) return false; if ( m_order[0] < 2 ) return false; if ( m_order[1] < 2 ) return false; if ( m_order[2] < 2 ) return false; if ( m_dim <= 0 ) return false; if ( m_is_rat != 0 && m_is_rat != 1 ) return false; const int cvdim = m_is_rat ? (m_dim+1) : m_dim; if ( m_cv_capacity > 0 && m_cv_capacity < cvdim*m_order[0]*m_order[1]*m_order[2] ) return false; int i[3]; i[0] = (m_cv_stride[0] <= m_cv_stride[1]) ? 0 : 1; i[1] = 1-i[0]; if ( m_cv_stride[2] < m_cv_stride[i[0]] ) { i[2] = i[1]; i[1] = i[0]; i[0] = 2; } else if ( m_cv_stride[2] < m_cv_stride[i[1]] ) { i[2] = i[1]; i[1] = 2; } else { i[2] = 2; } if ( m_cv_stride[i[0]] < cvdim ) return false; if ( m_cv_stride[i[1]] < m_cv_stride[i[0]]*m_order[i[0]] ) return false; if ( m_cv_stride[i[2]] < m_cv_stride[i[1]]*m_order[i[1]] ) return false; return true; } void ON_BezierCage::Dump( ON_TextLog& dump ) const { dump.Print( "ON_BezierCage dim = %d is_rat = %d\n" " order = (%d, %d, %d) \n", m_dim, m_is_rat, m_order[0], m_order[1], m_order[2] ); dump.Print( "Control Points %d %s points\n" " index value\n", m_order[0]*m_order[1]*m_order[2], (m_is_rat) ? "rational" : "non-rational" ); if ( !m_cv ) { dump.Print(" NULL cv array\n"); } else { int i,j; char sPreamble[128]; memset(sPreamble,0,sizeof(sPreamble)); for ( i = 0; i < m_order[0]; i++ ) { for ( j = 0; j < m_order[1]; j++ ) { if ( i > 0 || j > 0) dump.Print("\n"); sPreamble[0] = 0; sprintf(sPreamble," CV[%2d][%2d]",i,j); dump.PrintPointList( m_dim, m_is_rat, m_order[2], m_cv_stride[2], CV(i,j,0), sPreamble ); } if ( i < m_order[0]-1) dump.Print("\n"); } } } int ON_BezierCage::Dimension() const { return m_dim; } bool ON_BezierCage::Create( const ON_BoundingBox& bbox, int order0, int order1, int order2 ) { /* 7______________6 |\ |\ | \ | \ | \ _____________\ | 4 | 5 | | | | | | | | 3---|----------2 | \ | \ | \ |z \ | y \ | \ | \0_____________\1 x */ ON_3dPoint box_corners[8]; box_corners[0] = bbox.Corner(0,0,0); box_corners[1] = bbox.Corner(1,0,0); box_corners[2] = bbox.Corner(1,1,0); box_corners[3] = bbox.Corner(0,1,0); box_corners[4] = bbox.Corner(0,0,1); box_corners[5] = bbox.Corner(1,0,1); box_corners[6] = bbox.Corner(1,1,1); box_corners[7] = bbox.Corner(0,1,1); return Create(box_corners,order0,order1,order2); } bool ON_BezierCage::Create( int dim, bool is_rat, int order0, int order1, int order2 ) { if ( m_cv_capacity < 1 ) m_cv = 0; m_dim = (dim>0) ? dim : 0; m_is_rat = is_rat ? 1 : 0; m_order[0] = (order0 >= 2) ? order0 : 0; m_order[1] = (order1 >= 2) ? order1 : 0; m_order[2] = (order2 >= 2) ? order2 : 0; m_cv_stride[2] = (m_dim > 0) ? m_dim+m_is_rat : 0; m_cv_stride[1] = m_cv_stride[2]*m_order[2]; m_cv_stride[0] = m_cv_stride[1]*m_order[1]; m_cv_capacity = m_cv_stride[0]*m_order[0]; m_cv = (double*)onrealloc( m_cv, m_cv_capacity*sizeof(m_cv[0]) ); return IsValid() ? true : false; } bool ON_BezierCage::Create( const ON_3dPoint* box_corners, int order0, int order1, int order2 ) { int i, j, k; double r,s,t; if ( 0 == box_corners ) return false; for( i = 0; i < 8; i++ ) { if ( !box_corners[i].IsValid() ) return false; } // create trilinear "cube" to make it easy // to calculate CV locations. ON_BezierCage cube(3,0,2,2,2); cube.SetCV(0,0,0,box_corners[0]); cube.SetCV(1,0,0,box_corners[1]); cube.SetCV(1,1,0,box_corners[2]); cube.SetCV(0,1,0,box_corners[3]); cube.SetCV(0,0,1,box_corners[4]); cube.SetCV(1,0,1,box_corners[5]); cube.SetCV(1,1,1,box_corners[6]); cube.SetCV(0,1,1,box_corners[7]); if ( 2 == order0 && 2 == order1 && 2 == order2 ) { operator=(cube); } else { if (!Create(3,0,order0,order1,order2)) return false; const int d0 = Degree(0); const int d1 = Degree(1); const int d2 = Degree(2); for (i = 0; i <= d0; i++) { r = ((double)i)/((double)d0); for (j = 0; j <= d1; j++) { s = ((double)j)/((double)d1); for (k = 0; k <= d2; k++) { t = ((double)k)/((double)d2); SetCV(i,j,k,cube.PointAt(r,s,t)); } } } } return IsValid(); } void ON_BezierCage::Destroy() { if ( m_cv && m_cv_capacity > 0 ) onfree(m_cv); m_cv_capacity = 0; m_cv_stride[0] = 0; m_cv_stride[1] = 0; m_cv_stride[2] = 0; m_cv = 0; m_dim = 0; m_is_rat = 0; m_order[0] = 0; m_order[1] = 0; m_order[2] = 0; } void ON_BezierCage::EmergencyDestroy() { m_cv_capacity = 0; m_cv_stride[0] = 0; m_cv_stride[1] = 0; m_cv_stride[2] = 0; m_cv = 0; m_dim = 0; m_is_rat = 0; m_order[0] = 0; m_order[1] = 0; m_order[2] = 0; } bool ON_BezierCage::GetBBox( // returns true if successful double* boxmin, // minimum double* boxmax, // maximum int bGrowBox // true means grow box ) const { int i, j; bool rc = (m_order[0] > 0 && m_order[1] > 0 && m_order[2] > 0) ? true : false; for ( i = 0; rc && i < m_order[0]; i++ ) for ( j = 0; rc && j < m_order[1]; j++ ) { rc = ON_GetPointListBoundingBox( m_dim, m_is_rat, m_order[2], m_cv_stride[2], CV(i,j,0), boxmin, boxmax, bGrowBox ); bGrowBox = true; } return rc; } bool ON_BezierCage::Transform( const ON_Xform& xform ) { int i,j; bool rc = (m_order[0] > 0 && m_order[1] > 0 && m_order[2]) ? true : false; if (rc) { if ( 0 == m_is_rat ) { if ( xform.m_xform[3][0] != 0.0 || xform.m_xform[3][1] != 0.0 || xform.m_xform[3][2] != 0.0 ) { MakeRational(); } } for ( i = 0; rc && i < m_order[0]; i++ ) { for ( j = 0; rc && j < m_order[1]; j++ ) { rc = ON_TransformPointList( m_dim, m_is_rat, m_order[2], m_cv_stride[2], CV(i,j,0), xform ); } } } return rc; } bool ON_BezierCage::Rotate( double sin_angle, // sin(angle) double cos_angle, // cos(angle) const ON_3dVector& axis, // axis of rotation const ON_3dPoint& center // center of rotation ) { ON_Xform rot; rot.Rotation( sin_angle, cos_angle, axis, center ); return Transform( rot ); } bool ON_BezierCage::Rotate( double angle, // angle in radians const ON_3dVector& axis, // axis of rotation const ON_3dPoint& center // center of rotation ) { return Rotate( sin(angle), cos(angle), axis, center ); } bool ON_BezierCage::Translate( const ON_3dVector& delta ) { ON_Xform tr; tr.Translation( delta ); return Transform( tr ); } bool ON_BezierCage::Scale( double x ) { ON_Xform s; s.Scale( x, x, x ); return Transform( s ); } ON_Interval ON_BezierCage::Domain( int // dir - formal parameter intentionally ignored in this virtual function ) const { return ON_Interval(0.0,1.0); } bool ON_BezierCage::Evaluate( // returns false if unable to evaluate double r, double s, double t, // evaluation parameter int der_count, // number of derivatives (>=0) int v_stride, // array stride (>=Dimension()) double* v // array of length stride*(ndir+1)*(ndir+2)/2 ) const { const int cvdim = m_is_rat?(m_dim+1):m_dim; int i,j,k,n; double Barray[64], vtmparray[10*4], Bi, Bij, Bijk, *Bj, *Bk, *vtmp; const double* CVi; const double* CVij; const double* CVijk; if ( der_count > 0 ) { // TODO - time to add support for derivative evaluation ON_ERROR("ON_BezierCage::Evaluate does not evaluate derivatives"); } i = cvdim*sizeof(*vtmp); vtmp = m_is_rat ? (i < ((int)(10*4*sizeof(vtmparray[0]))) ? vtmparray : (double*)alloca(i)) : v; memset(vtmp,0,i); // get arrays to hold values of Bernstein basis functions Bj = ((m_order[1]+m_order[2]) <= 64) ? &Barray[0] : ((double*)alloca((m_order[1]+m_order[2])*sizeof(*Bj))); Bk = Bj + m_order[1]; const int d2 = m_order[2]-1; for ( k = 0; k <= d2; k++) { Bk[k] = ON_EvaluateBernsteinBasis(d2,k,t); } const int d1 = m_order[1]-1; for ( j = 0; j <= d1; j++) { Bj[j] = ON_EvaluateBernsteinBasis(d1,j,s); } const int d0 = m_order[0]-1; for ( i = 0; i <= d0; i++ ) { CVi = m_cv + i*m_cv_stride[0]; Bi = ON_EvaluateBernsteinBasis(d0,i,r); for ( j = 0; j <= d1; j++ ) { CVij = CVi + j*m_cv_stride[1]; Bij = Bi*Bj[j]; for ( k = 0; k <= d2; k++ ) { CVijk = CVij + k*m_cv_stride[2]; Bijk = Bij*Bk[k]; n = cvdim; while(n--) { *vtmp++ += *CVijk++ * Bijk; } vtmp -= cvdim; } } } if ( m_is_rat ) { Bi = (vtmp[m_dim] != 0.0) ? (1.0/vtmp[m_dim]) : 1.0; for ( n = 0; n < m_dim; n++ ) { v[n] = vtmp[n]*Bi; } } return (0 == der_count); } ON_3dPoint ON_BezierCage::PointAt( double r, double s, double t ) const { ON_3dPoint pt; if ( m_dim <= 3 ) { pt.x = 0.0; pt.y = 0.0; pt.z = 0.0; Evaluate(r,s,t,0,3,&pt.x); } else { double* v = (double*)alloca(m_dim*sizeof(*v)); v[0] = 0.0; v[1] = 0.0; v[2] = 0.0; Evaluate(r,s,t,0,m_dim,v); pt.x = v[0]; pt.y = v[1]; pt.z = v[2]; } return pt; } ON_3dPoint ON_BezierCage::PointAt( ON_3dPoint rst ) const { ON_3dPoint pt; if ( m_dim <= 3 ) { pt.x = 0.0; pt.y = 0.0; pt.z = 0.0; Evaluate(rst.x,rst.y,rst.z,0,3,&pt.x); } else { double* v = (double*)alloca(m_dim*sizeof(*v)); v[0] = 0.0; v[1] = 0.0; v[2] = 0.0; Evaluate(rst.x,rst.y,rst.z,0,m_dim,v); pt.x = v[0]; pt.y = v[1]; pt.z = v[2]; } return pt; } bool ON_BezierCage::IsRational() const { return m_is_rat ? true : false; } int ON_BezierCage::CVSize() const { return ( m_is_rat && m_dim>0 ) ? m_dim+1 : m_dim; } int ON_BezierCage::Order( int dir ) const { return (dir>=0&&dir<=2) ? m_order[dir] : 0; } int ON_BezierCage::Degree(int dir) const { int order = Order(dir); return (order>=2) ? order-1 : 0; } double* ON_BezierCage::CV( int i, int j, int k ) const { #if defined(ON_DEBUG) if ( 0 == m_cv ) { ON_ERROR("ON_BezierCage::CV - NULL m_cv"); return 0; } if ( i < 0 || i >= m_order[0] || j< 0 || j >= m_order[1] || k < 0 || k >= m_order[2]) { ON_ERROR("ON_BezierCage::CV - (i,j,k) out of range"); return 0; } #endif return (m_cv) ? (m_cv + i*m_cv_stride[0] + j*m_cv_stride[1] + k*m_cv_stride[2]) : 0; } ON::point_style ON_BezierCage::CVStyle() const { return m_is_rat ? ON::homogeneous_rational : ON::not_rational; } double ON_BezierCage::Weight( int i, int j, int k ) const { return (m_cv && m_is_rat) ? m_cv[i*m_cv_stride[0] + j*m_cv_stride[1] + k*m_cv_stride[2] + + m_dim] : 1.0; } bool ON_BezierCage::SetWeight( int i, int j, int k, double w ) { bool rc = false; if ( m_is_rat ) { double* cv = CV(i,j,k); if (cv) { cv[m_dim] = w; rc = true; } } else if ( w == 1.0 ) { rc = true; } return rc; } bool ON_BezierCage::SetCV( int i, int j, int k, ON::point_style style, const double* Point ) { bool rc = true; int n; double w; double* cv = CV(i,j,k); if ( !cv ) return false; switch ( style ) { case ON::not_rational: // input Point is not rational memcpy( cv, Point, m_dim*sizeof(*cv) ); if ( IsRational() ) { // NURBS surface is rational - set weight to one cv[m_dim] = 1.0; } break; case ON::homogeneous_rational: // input Point is homogeneous rational if ( IsRational() ) { // NURBS surface is rational memcpy( cv, Point, (m_dim+1)*sizeof(*cv) ); } else { // NURBS surface is not rational w = (Point[m_dim] != 0.0) ? 1.0/Point[m_dim] : 1.0; for ( n = 0; n < m_dim; n++ ) { cv[n] = w*Point[n]; } } break; case ON::euclidean_rational: // input Point is euclidean rational if ( IsRational() ) { // NURBS surface is rational - convert euclean point to homogeneous form w = Point[m_dim]; for ( n = 0; n < m_dim; n++ ) cv[i] = w*Point[i]; cv[m_dim] = w; } else { // NURBS surface is not rational memcpy( cv, Point, m_dim*sizeof(*cv) ); } break; case ON::intrinsic_point_style: n = m_is_rat?m_dim+1:m_dim; memcpy(cv,Point,n*sizeof(*cv)); break; default: rc = false; break; } return rc; } bool ON_BezierCage::SetCV( int i, int j, int k, const ON_3dPoint& point ) { bool rc = false; double* cv = CV(i,j,k); if ( cv ) { cv[0] = point.x; if ( m_dim > 1 ) { cv[1] = point.y; if ( m_dim > 2 ) cv[2] = point.z; } if ( m_is_rat ) { cv[m_dim] = 1.0; } rc = true; } return rc; } bool ON_BezierCage::SetCV( int i, int j, int k, const ON_4dPoint& point ) { bool rc = false; double* cv = CV(i,j,k); if ( cv ) { if ( m_is_rat ) { cv[0] = point.x; if ( m_dim > 1 ) { cv[1] = point.y; if ( m_dim > 2 ) cv[2] = point.z; } cv[m_dim] = point.w; rc = true; } else { double w; if ( point.w != 0.0 ) { w = 1.0/point.w; rc = true; } else { w = 1.0; } cv[0] = w*point.x; if ( m_dim > 1 ) { cv[1] = w*point.y; if ( m_dim > 2 ) { cv[2] = w*point.z; } } } } return rc; } bool ON_BezierCage::GetCV( int i, int j, int k, ON::point_style style, double* Point ) const { const double* cv = CV(i,j,k); if ( !cv ) return false; int dim = Dimension(); double w = ( IsRational() ) ? cv[dim] : 1.0; switch(style) { case ON::euclidean_rational: Point[dim] = w; // no break here case ON::not_rational: if ( w == 0.0 ) return false; w = 1.0/w; while(dim--) *Point++ = *cv++ * w; break; case ON::homogeneous_rational: Point[dim] = w; memcpy( Point, cv, dim*sizeof(*Point) ); break; default: return false; } return true; } bool ON_BezierCage::GetCV( int i, int j, int k, ON_3dPoint& point ) const { bool rc = false; const double* cv = CV(i,j,k); if ( cv ) { if ( m_is_rat ) { if (cv[m_dim] != 0.0) { const double w = 1.0/cv[m_dim]; point.x = cv[0]*w; point.y = (m_dim>1)? cv[1]*w : 0.0; point.z = (m_dim>2)? cv[2]*w : 0.0; rc = true; } } else { point.x = cv[0]; point.y = (m_dim>1)? cv[1] : 0.0; point.z = (m_dim>2)? cv[2] : 0.0; rc = true; } } return rc; } bool ON_BezierCage::GetCV( int i, int j, int k, ON_4dPoint& point ) const { bool rc = false; const double* cv = CV(i,j,k); if ( cv ) { point.x = cv[0]; point.y = (m_dim>1)? cv[1] : 0.0; point.z = (m_dim>2)? cv[2] : 0.0; point.w = (m_is_rat) ? cv[m_dim] : 1.0; rc = true; } return rc; } bool ON_BezierCage::ZeroCVs() { // zeros control vertices and, if rational, sets weights to 1 bool rc = false; int i,j,k; if ( m_cv ) { if ( m_cv_capacity > 0 ) { memset( m_cv, 0, m_cv_capacity*sizeof(*m_cv) ); if ( m_is_rat ) { for ( i = 0; i < m_order[0]; i++ ) { for ( j = 0; j < m_order[1]; j++ ) { for ( k = 0; k < m_order[2]; k++ ) { SetWeight( i,j,k, 1.0 ); } } } } rc = true; } else { double* cv; int s = CVSize()*sizeof(*cv); for ( i = 0; i < m_order[0]; i++ ) { for ( j = 0; j < m_order[1]; j++ ) { for ( k = 0; k < m_order[2]; k++ ) { cv = CV(i,j,k); memset(cv,0,s); if ( m_is_rat ) cv[m_dim] = 1.0; } } } rc = (i>0) ? true : false; } } return rc; } bool ON_BezierCage::MakeRational() { if ( !IsRational() ) { ON_ERROR("TODO: fill in ON_BezierCage::MakeRational()"); /* const int dim = Dimension(); if ( m_order[0] > 0 && m_order[1] > 0 && m_order[2] > 0 && dim > 0 ) { const double* old_cv; double* new_cv; int cvi, cvj, j, cvstride; if ( m_cv_stride[0] < m_cv_stride[1] ) { cvstride = m_cv_stride[0] > dim ? m_cv_stride[0] : dim+1; ReserveCVCapacity( cvstride*m_order[0]*m_order[1] ); new_cv = m_cv + cvstride*m_order[0]*m_order[1]-1; for ( cvj = m_order[1]-1; cvj >= 0; cvj-- ) { for ( cvi = m_order[0]-1; cvi >= 0; cvi-- ) { old_cv = CV(cvi,cvj)+dim-1; *new_cv-- = 1.0; for ( j = 0; j < dim; j++ ) { *new_cv-- = *old_cv--; } } } m_cv_stride[0] = dim+1; m_cv_stride[1] = (dim+1)*m_order[0]; } else { cvstride = m_cv_stride[1] > dim ? m_cv_stride[1] : dim+1; ReserveCVCapacity( cvstride*m_order[0]*m_order[1] ); new_cv = m_cv + cvstride*m_order[0]*m_order[1]-1; for ( cvi = m_order[0]-1; cvi >= 0; cvi-- ) { for ( cvj = m_order[1]-1; cvj >= 0; cvj-- ) { old_cv = CV(cvi,cvj)+dim-1; *new_cv-- = 1.0; for ( j = 0; j < dim; j++ ) { *new_cv-- = *old_cv--; } } } m_cv_stride[1] = dim+1; m_cv_stride[0] = (dim+1)*m_order[1]; } m_is_rat = 1; } */ } return IsRational(); } bool ON_BezierCage::MakeNonRational() { if ( IsRational() ) { ON_ERROR("TODO: fill in ON_BezierCage::MakeNonRational()"); /* const int dim = Dimension(); if ( m_order[0] > 0 && m_order[1] > 0 && dim > 0 ) { double w; const double* old_cv; double* new_cv = m_cv; int cvi, cvj, j; if ( m_cv_stride[0] < m_cv_stride[1] ) { for ( cvj = 0; cvj < m_order[1]; cvj++ ) { for ( cvi = 0; cvi < m_order[0]; cvi++ ) { old_cv = CV(cvi,cvj); w = old_cv[dim]; w = ( w != 0.0 ) ? 1.0/w : 1.0; for ( j = 0; j < dim; j++ ) { *new_cv++ = w*(*old_cv++); } } } m_cv_stride[0] = dim; m_cv_stride[1] = dim*m_order[0]; } else { for ( cvi = 0; cvi < m_order[0]; cvi++ ) { for ( cvj = 0; cvj < m_order[1]; cvj++ ) { old_cv = CV(cvi,cvj); w = old_cv[dim]; w = ( w != 0.0 ) ? 1.0/w : 1.0; for ( j = 0; j < dim; j++ ) { *new_cv++ = w*(*old_cv++); } } } m_cv_stride[1] = dim; m_cv_stride[0] = dim*m_order[1]; } m_is_rat = 0; } */ } return ( !IsRational() ) ? true : false; } ///////////////////////////////////////////////////////////////// // Tools for managing CV and knot memory bool ON_BezierCage::ReserveCVCapacity( int capacity// number of doubles to reserve ) { if ( m_cv_capacity < capacity ) { if ( m_cv ) { if ( m_cv_capacity ) { m_cv = (double*)onrealloc( m_cv, capacity*sizeof(*m_cv) ); m_cv_capacity = (m_cv) ? capacity : 0; } // else user supplied m_cv[] array } else { m_cv = (double*)onmalloc( capacity*sizeof(*m_cv) ); m_cv_capacity = (m_cv) ? capacity : 0; } } return ( m_cv ) ? true : false; } bool ON_BezierCage::IsSingular( // true if surface side is collapsed to a point int side // side of parameter space to test // 0 = south, 1 = east, 2 = north, 3 = west, 4 = bottom, 5 =top ) const { ON_ERROR("TODO: fill in ON_BezierCage::IsSingular\n"); return false; /* int i,j,k=0; ON_3dPoint p[2]; double fuzz[2] = {0.0,0.0}; p[0].Zero(); p[1].Zero(); int i0 = 0; int i1 = 0; int j0 = 0; int j1 = 0; switch ( side ) { case 0: // south i0 = 0; i1 = Order(0); j0 = 0; j1 = 1; break; case 1: // east i0 = Order(0)-1; i1 = Order(0); j0 = 0; j1 = Order(1); break; case 2: // north i0 = 0; i1 = Order(0); j0 = Order(1)-1; j1 = Order(1); break; case 3: // west i0 = 0; i1 = 1; j0 = 0; j1 = Order(1); break; default: return false; break; } GetCV(i0,j0,p[k]); fuzz[k] = p[k].Fuzz(); for ( i = i0; i < i1; i++ ) for ( j = j0; j < j1; j++ ) { k = (k+1)%2; GetCV( i, j, p[k] ); fuzz[k] = p[k].Fuzz(); if ( (p[0]-p[1]).MaximumCoordinate() > fuzz[0]+fuzz[1] ) return false; } return true; */ } const ON_Xform& ON_BezierCageMorph::WorldToUnitCube() const { // maps world point into unit cube that can be morphed by // evaluation of the BezierCage() function. return m_xyz2rst; } const ON_BezierCage& ON_BezierCageMorph::BezierCage() const { // morphs a point in the unit cube into a world point. return m_rst2xyz; } bool ON_BezierCageMorph::Transform(const ON_Xform& xform) { // transforms the VolumeMorph as a piece of geometry return m_rst2xyz.Transform(xform); } bool ON_BezierCageMorph::Read(ON_BinaryArchive& archive) { int major_version = 0; int minor_version = 0; bool rc = archive.BeginRead3dmChunk(TCODE_ANONYMOUS_CHUNK,&major_version,&minor_version); if ( rc ) { if ( major_version != 1 ) rc = false; if (rc) rc = archive.ReadXform(m_xyz2rst); if(rc) rc = m_rst2xyz.Read(archive); if ( !archive.EndRead3dmChunk() ) rc = false; } return rc; } bool ON_BezierCageMorph::Write(ON_BinaryArchive& archive) const { bool rc = archive.BeginWrite3dmChunk(TCODE_ANONYMOUS_CHUNK,1,0); if (rc) { if (rc) rc = archive.WriteXform(m_xyz2rst); if(rc) rc = m_rst2xyz.Write(archive); if ( !archive.EndWrite3dmChunk() ) rc = false; } return rc; } ON_BezierCageMorph::ON_BezierCageMorph() : m_bValid(0) { } ON_BezierCageMorph::~ON_BezierCageMorph() { } ON_3dPoint ON_BezierCageMorph::MorphPoint( ON_3dPoint point ) const { ON_3dPoint Q = point; if ( m_bValid ) { ON_3dPoint rst = m_xyz2rst*point; Q = m_rst2xyz.PointAt(rst.x,rst.y,rst.z); } return Q; } bool ON_BezierCageMorph::Create( ON_3dPoint P0, ON_3dPoint P1, ON_3dPoint P2, ON_3dPoint P3, int point_countX, int point_countY, int point_countZ ) { if ( point_countX < 2 || point_countY < 2 || point_countZ < 2 || !P0.IsValid() || !P1.IsValid() || !P2.IsValid() || !P3.IsValid() ) { ON_ERROR("ON_BezierCageMorph::Create - invalid input"); } m_bValid = false; ON_3dVector X = P1-P0; ON_3dVector Y = P2-P0; ON_3dVector Z = P3-P0; ON_Xform xform(1.0); xform[0][0] = X.x; xform[1][0] = X.y; xform[2][0] = X.z; xform[0][1] = Y.x; xform[1][1] = Y.y; xform[2][1] = Y.z; xform[0][2] = Z.x; xform[1][2] = Z.y; xform[2][2] = Z.z; xform[0][3] = P0.x; xform[1][3] = P0.y; xform[2][3] = P0.z; double min_pivot = 0.0; m_bValid = xform.Invert(&min_pivot); if (m_bValid) { ON_3dPoint box_corners[8]; box_corners[0] = P0; box_corners[1] = P1; box_corners[2] = P0+X+Y; box_corners[3] = P2; box_corners[4] = P3; box_corners[5] = P3+X; box_corners[6] = P3+X+Y; box_corners[7] = P3+Y; m_bValid = m_rst2xyz.Create(box_corners,point_countX,point_countY,point_countZ); m_xyz2rst = xform; } else { ON_ERROR("ON_BezierCageMorph::Create - invalid input - P0,P1,P2,P3 are coplanar"); m_rst2xyz.Destroy(); } return m_bValid; } bool ON_BezierCageMorph::SetXform( ON_Xform world2unitcube ) { m_xyz2rst = world2unitcube; m_bValid = m_xyz2rst.IsValid() && m_rst2xyz.IsValid(); return m_bValid; } bool ON_BezierCageMorph::SetBezierCage( ON_BezierCage& unitcube2world ) { m_rst2xyz = unitcube2world; m_bValid = m_xyz2rst.IsValid() && m_rst2xyz.IsValid(); return m_bValid; }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "riegeli/bytes/limiting_backward_writer.h" #include <stddef.h> #include <string> #include <utility> #include "absl/base/optimization.h" #include "absl/strings/string_view.h" #include "riegeli/base/base.h" #include "riegeli/base/chain.h" #include "riegeli/base/object.h" #include "riegeli/bytes/backward_writer.h" namespace riegeli { LimitingBackwardWriter::LimitingBackwardWriter(BackwardWriter* dest, Position size_limit) : BackwardWriter(State::kOpen), dest_(RIEGELI_ASSERT_NOTNULL(dest)), size_limit_(size_limit) { RIEGELI_ASSERT_GE(size_limit, dest_->pos()) << "Failed precondition of " "LimitingBackwardWriter::LimitingBackwardWriter(): " "size limit smaller than current position"; SyncBuffer(); } void LimitingBackwardWriter::Done() { if (ABSL_PREDICT_TRUE(healthy())) dest_->set_cursor(cursor_); start_pos_ = pos(); BackwardWriter::Done(); } bool LimitingBackwardWriter::PushSlow() { RIEGELI_ASSERT_EQ(available(), 0u) << "Failed precondition of BackwardWriter::PushSlow(): " "space available, use Push() instead"; if (ABSL_PREDICT_FALSE(!healthy())) return false; if (ABSL_PREDICT_FALSE(pos() == size_limit_)) { cursor_ = start_; limit_ = start_; return FailOverflow(); } dest_->set_cursor(cursor_); const bool ok = dest_->Push(); SyncBuffer(); return ok; } bool LimitingBackwardWriter::WriteSlow(absl::string_view src) { RIEGELI_ASSERT_GT(src.size(), available()) << "Failed precondition of BackwardWriter::WriteSlow(string_view): " "length too small, use Write(string_view) instead"; return WriteInternal(src); } bool LimitingBackwardWriter::WriteSlow(std::string&& src) { RIEGELI_ASSERT_GT(src.size(), available()) << "Failed precondition of BackwardWriter::WriteSlow(string_view): " "length too small, use Write(string_view) instead"; return WriteInternal(std::move(src)); } bool LimitingBackwardWriter::WriteSlow(const Chain& src) { RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy())) << "Failed precondition of BackwardWriter::WriteSlow(Chain): " "length too small, use Write(Chain) instead"; return WriteInternal(src); } bool LimitingBackwardWriter::WriteSlow(Chain&& src) { RIEGELI_ASSERT_GT(src.size(), UnsignedMin(available(), kMaxBytesToCopy())) << "Failed precondition of BackwardWriter::WriteSlow(Chain&&): " "length too small, use Write(Chain&&) instead"; return WriteInternal(std::move(src)); } template <typename Src> bool LimitingBackwardWriter::WriteInternal(Src&& src) { if (ABSL_PREDICT_FALSE(!healthy())) return false; RIEGELI_ASSERT_LE(pos(), size_limit_) << "Failed invariant of LimitingBackwardWriter: " "position exceeds size limit"; if (ABSL_PREDICT_FALSE(src.size() > size_limit_ - pos())) { cursor_ = start_; limit_ = start_; return FailOverflow(); } dest_->set_cursor(cursor_); const bool ok = dest_->Write(std::forward<Src>(src)); SyncBuffer(); return ok; } bool LimitingBackwardWriter::SupportsTruncate() const { return dest_ != nullptr && dest_->SupportsTruncate(); } bool LimitingBackwardWriter::Truncate(Position new_size) { if (ABSL_PREDICT_FALSE(!healthy())) return false; dest_->set_cursor(cursor_); const bool ok = dest_->Truncate(new_size); SyncBuffer(); return ok; } inline void LimitingBackwardWriter::SyncBuffer() { start_ = dest_->start(); cursor_ = dest_->cursor(); limit_ = dest_->limit(); start_pos_ = dest_->pos() - dest_->written_to_buffer(); // dest_->start_pos_ if (ABSL_PREDICT_FALSE(limit_pos() > size_limit_)) { limit_ += IntCast<size_t>(limit_pos() - size_limit_); } if (ABSL_PREDICT_FALSE(!dest_->healthy())) Fail(*dest_); } } // namespace riegeli
// // This file contains the C++ code from Program 12.22 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C++" // by Bruno R. Preiss. // // Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved. // // http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm12_22.cpp // void PartitionAsForest::Join (Set& s, Set& t) { PartitionTree& p = dynamic_cast<PartitionTree&> (s); PartitionTree& q = dynamic_cast<PartitionTree&> (t); CheckArguments (p, q); if (p.count > q.count) { q.parent = &p; p.count += q.count; } else { p.parent = &q; q.count += p.count; } --count; }
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "low_precision_transformations/fake_quantize_precision_selection_transformation.hpp" #include "common_test_utils/test_constants.hpp" #include "lpt_ngraph_functions/fake_quantize_function.hpp" using namespace LayerTestsDefinitions; using namespace ngraph::pass::low_precision; namespace { const std::vector<ngraph::element::Type> netPrecisions = { ngraph::element::f32, ngraph::element::f16 }; const std::vector<LayerTransformation::Params> trasformationParamValues = { LayerTestsUtils::LayerTransformationParamsNGraphFactory::createParamsU8I8() }; const std::vector<FakeQuantizePrecisionSelectionTransformationTestValues> testValues = { { { ngraph::element::u8, ngraph::element::i8 }, { ngraph::element::u8 }, true, { { 256ul, { }, { 0.f }, { 25.5f }, { 0.f }, { 25.5f } }, { 255ul, { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } } }, { ngraph::element::u8, { 256ul, { }, { 0.f }, { 2.55f }, { 0.f }, { 255.f } }, { } }, }, { { ngraph::element::u8, ngraph::element::i8 }, { ngraph::element::i8 }, // INT8 is not available for limited operation (Convolution) false, { { 256ul, { }, { 0.f }, { 25.5f }, { 0.f }, { 25.5f } }, { 255ul, { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } } }, { // original precision is used ngraph::element::u8, // FakeQuantize has to select the first available: U8, not limited operation required I8 but this fact doesn't affect { 256ul, { }, { 0.f }, { 25.5f }, { 0.f }, { 255.f } }, // FakeQuantize on weights is not changed { 255ul, { 1, 1, 1, 1 }, { 0.f }, { 254.f }, { -12.7f }, { 12.7f } } }, }, }; // GPU issue INSTANTIATE_TEST_CASE_P(DISABLED_LPT, FakeQuantizePrecisionSelectionTransformation, ::testing::Combine( ::testing::ValuesIn(netPrecisions), ::testing::Values(ngraph::Shape({ 1, 32, 72, 48 })), ::testing::Values(CommonTestUtils::DEVICE_GPU), ::testing::ValuesIn(trasformationParamValues), ::testing::ValuesIn(testValues)), FakeQuantizePrecisionSelectionTransformation::getTestCaseName); } // namespace
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_dest_char_ncpy_65b.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_dest.string.label.xml Template File: sources-sink-65b.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sinks: ncpy * BadSink : Copy string to data using strncpy * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE122_Heap_Based_Buffer_Overflow__cpp_dest_char_ncpy_65 { #ifndef OMITBAD void bad_sink(char * data) { { char src[100]; memset(src, 'C', 100-1); /* fill with 'C's */ src[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if src is larger than data */ strncpy(data, src, 100); data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2B_sink(char * data) { { char src[100]; memset(src, 'C', 100-1); /* fill with 'C's */ src[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if src is larger than data */ strncpy(data, src, 100); data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ printLine(data); delete [] data; } } #endif /* OMITGOOD */ } // close namespace
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/msp/v20180319/model/ListMigrationTaskRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Msp::V20180319::Model; using namespace std; ListMigrationTaskRequest::ListMigrationTaskRequest() : m_offsetHasBeenSet(false), m_limitHasBeenSet(false), m_projectIdHasBeenSet(false) { } string ListMigrationTaskRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_offsetHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Offset"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_offset, allocator); } if (m_limitHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Limit"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_limit, allocator); } if (m_projectIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ProjectId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, m_projectId, allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } uint64_t ListMigrationTaskRequest::GetOffset() const { return m_offset; } void ListMigrationTaskRequest::SetOffset(const uint64_t& _offset) { m_offset = _offset; m_offsetHasBeenSet = true; } bool ListMigrationTaskRequest::OffsetHasBeenSet() const { return m_offsetHasBeenSet; } uint64_t ListMigrationTaskRequest::GetLimit() const { return m_limit; } void ListMigrationTaskRequest::SetLimit(const uint64_t& _limit) { m_limit = _limit; m_limitHasBeenSet = true; } bool ListMigrationTaskRequest::LimitHasBeenSet() const { return m_limitHasBeenSet; } uint64_t ListMigrationTaskRequest::GetProjectId() const { return m_projectId; } void ListMigrationTaskRequest::SetProjectId(const uint64_t& _projectId) { m_projectId = _projectId; m_projectIdHasBeenSet = true; } bool ListMigrationTaskRequest::ProjectIdHasBeenSet() const { return m_projectIdHasBeenSet; }
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Florian Zeller $ // $Authors: Lukas Mueller, Markus Mueller $ // -------------------------------------------------------------------------- // /////////////////////////////////////////////////////////////////////////// // // PEAK DETECTION OF FOURIER TRANSFORME MS INSTRUMENT DATA // // written by Markus Mueller, markus.mueller@imsb.biol.ethz.ch // ( and Lukas Mueller, Lukas.Mueller@imsb.biol.ethz.ch) // October 2005 // // Ported to OpenMS by Florian Zeller, florian.zeller@bsse.ethz.ch // December 2010 // // Group of Prof. Ruedi Aebersold, IMSB, ETH Hoenggerberg, Zurich // // #include <list> #include <map> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/SUPERHIRN/BackgroundControl.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/SUPERHIRN/CentroidPeak.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/SUPERHIRN/MSPeak.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/SUPERHIRN/BackgroundIntensityBin.h> #include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/SUPERHIRN/SuperHirnParameters.h> namespace OpenMS { using namespace std; BackgroundControl::BackgroundControl() { init(); } BackgroundControl::~BackgroundControl() { intensityBinMap.clear(); } void BackgroundControl::init() { // create a vector of intensity bin objects // first in the tr dimension: double trStart = SuperHirnParameters::instance()->getMinTR(); while (trStart <= SuperHirnParameters::instance()->getMaxTR()) { // inner loop is the mzBins: map<double, BackgroundIntensityBin> mzArray; double mzStart = SuperHirnParameters::instance()->getMinFeatureMZ(); while (mzStart <= SuperHirnParameters::instance()->getMaxFeatureMZ()) { BackgroundIntensityBin * bin = new BackgroundIntensityBin(mzStart, trStart); mzArray.insert(make_pair(mzStart, *bin)); delete bin; mzStart += SuperHirnParameters::instance()->getBackgroundIntensityBinsMZ(); } intensityBinMap.insert(make_pair(trStart, mzArray)); trStart += SuperHirnParameters::instance()->getBackgroundIntensityBinsTR(); } } void BackgroundControl::addPeakMSScan(double TR, list<CentroidPeak> * peakList) { map<double, map<double, BackgroundIntensityBin> >::iterator F = findTrKey(TR); if (F != intensityBinMap.end()) { // find the mz bins: map<double, BackgroundIntensityBin> * mzMap = &(F->second); list<CentroidPeak>::iterator mpi; for (mpi = peakList->begin(); mpi != peakList->end(); ++mpi) { map<double, BackgroundIntensityBin>::iterator F_mz = findMzKey(mpi->getMass(), mzMap); if (F_mz != mzMap->end()) { F_mz->second.addIntensity(mpi->getIntensity()); } } } } map<double, BackgroundIntensityBin>::iterator BackgroundControl::findMzKey(double mz, map<double, BackgroundIntensityBin> * mzMap) { double constraint = SuperHirnParameters::instance()->getBackgroundIntensityBinsMZ() / 2.0; map<double, map<double, BackgroundIntensityBin>::iterator> outMap; map<double, BackgroundIntensityBin>::iterator F = mzMap->lower_bound(mz); if (F != mzMap->end()) { double delta = fabs(F->first - mz); if (delta <= constraint) { outMap.insert(make_pair(delta, F)); } } if (F != mzMap->begin()) { --F; double delta = fabs(mz - F->first); if (delta <= constraint) { outMap.insert(make_pair(delta, F)); } } if (!outMap.empty()) { return outMap.begin()->second; } return mzMap->end(); } map<double, map<double, BackgroundIntensityBin> >::iterator BackgroundControl::findTrKey(double Tr) { double constraint = SuperHirnParameters::instance()->getBackgroundIntensityBinsTR() * 2; map<double, map<double, map<double, BackgroundIntensityBin> >::iterator> outMap; map<double, map<double, BackgroundIntensityBin> >::iterator F = intensityBinMap.lower_bound(Tr); if (F != intensityBinMap.end()) { double delta = fabs(Tr - F->first); if (delta <= constraint) { outMap.insert(make_pair(delta, F)); } } if (F != intensityBinMap.begin()) { --F; double delta = fabs(Tr - F->first); if (delta <= constraint) { outMap.insert(make_pair(delta, F)); } } if (!outMap.empty()) { return outMap.begin()->second; } return intensityBinMap.end(); } double BackgroundControl::getBackgroundLevel(double mz, double tr) { // find the corresponding retention time bin: map<double, map<double, BackgroundIntensityBin> >::iterator F = findTrKey(tr); if (F != intensityBinMap.end()) { map<double, BackgroundIntensityBin>::iterator F2 = findMzKey(mz, &(F->second)); if (F2 != F->second.end()) { return F2->second.getMean(); } } return -1.0; } void BackgroundControl::processIntensityMaps() { map<double, map<double, BackgroundIntensityBin> >::iterator P1 = intensityBinMap.begin(); while (P1 != intensityBinMap.end()) { map<double, BackgroundIntensityBin>::iterator P2 = P1->second.begin(); while (P2 != P1->second.end()) { P2->second.processIntensities(); ++P2; } ++P1; } } } // ns
#include <iostream> #include <vector> #include <string> #include <regex> using namespace std; // Kriptografi tugas 1 // Name : Moch. bardizba Z. // Student id : 4611416038 // Web :http://bardizba.com // Created on : 17th August 2018 // require : g++ with c++11 std, run with : g++ tugas.cpp -o tugas -std=c++11. run ./tugas on unix or tugas.exe on windows namespace Bardiz{ class playFair{ vector< vector<char> > tableKey; string key; public: string enc(string plaintext){ regex abcOnly("[^a-zA-Z]+"); vector<string> tmp; vector<string> plaintextVector; vector<string> result; string str; plaintext = regex_replace(plaintext,abcOnly,""); //cout<<plaintext; for(unsigned i=0; i<plaintext.size();i+=2){ /*if(str.size() < 2 ){ str+= plaintext[i]; }else{ tmp.push_back(str); str = plaintext[i]; }*/ if(plaintext[i] != plaintext[i+1]){ str = tolower(plaintext[i]); if(i+1 >= plaintext.size()){ str+="z"; }else{ str+=tolower(plaintext[i+1]); } }else{ str = tolower(plaintext[i]); str+="z"; i--; } if(str.size() == 1){ str+="z"; } //cout<<str<<" size = "<<str.size()<<endl; tmp.push_back(str); //str = plaintext[i] + plaintext[i+1]; } //for /*string tmpS; for(unsigned i=0;i<tmp.size();i++){ if(tmp[i][0] == tmp[i][1]){ tmpS = ""; tmpS.push_back(tmp[i][0]); tmpS.push_back('z'); plaintextVector.push_back(tmpS); plaintextVector.push_back(tmpS); //plaintextVector.push_back((tmp[i][1]+'z')); }else{ plaintextVector.push_back(tmp[i]); } //cout<<tmp[i]<<" = "<<this->_enc(tmp[i])<<endl; //cout<<tmp[i]<<endl; //this->_enc(tmp[i]); }*/ for(string &st : tmp){ result.push_back(this->_enc(st)); } return this->vec2string(result); } string dec(string plaintext){ regex abcOnly("[^a-zA-Z]+"); vector<string> tmp; vector<string> plaintextVector; string result; string str; string gb; plaintext = regex_replace(plaintext,abcOnly,""); for(unsigned i=0; i<plaintext.size();i+=2){ /*if(str.size() < 2 ){ str+= plaintext[i]; }else{ tmp.push_back(str); str = plaintext[i]; }*/ //if(plaintext[i] != plaintext[i+1]){ str = tolower(plaintext[i]); str+=tolower(plaintext[i+1]); //}else{ // str = tolower(plaintext[i]); // str+="z"; // i--; //} //cout<<str<<" size = "<<str.size()<<endl; /*if(str[0] != 'z' && str[1] == 'z'){ gb = str; str = str[0]; str+=gb[0]; } */ //str = plaintext[i] + plaintext[i+1]; tmp.push_back(str); } for(string &st : tmp){ //cout<<st<<endl; result +=this->_dec(st); } string newResult; bool pass = true; for(unsigned i = 0; i < result.size(); i++) { if(i>0){ if(result[i] == 'z'){ if(result[i-1] == result[i+1]){ pass = false; } } } if(pass){ newResult+=result[i]; } pass = true; } return newResult; } string vec2string(vector<string> vec){ string result = ""; for(string &st : vec){ result+=st; } return result; } string humanize(string raw, string temp){ int i = 0; string res = ""; for(char &c : temp){ if(c != ' ' && c!= '\n' && c!='.' && c!= ','){ res+=raw[i++]; }else{ res+=c; } } return res; } string _enc(string str){ string tmp = ""; string result=""; int ax,ay,bx,by; for(unsigned i=0;i<5;i++){ for(unsigned j=0;j<5;j++){ if(this->tableKey[i][j] == str[0]){ ay = i; ax = j; } if(this->tableKey[i][j] == str[1]){ by = i; bx = j; } } } //cout<<str[0]<<" = "<<ax<<","<<ay<<endl; //cout<<str[1]<<" = "<<bx<<","<<by<<endl; //cout<<"enc :"<<endl; //cout<<str<<"="; if(ay == by){ result+= this->tableKey[ay][(((ax+1) % 5))]; result+= this->tableKey[ay][(((bx + 1) % 5))]; }else if(ax == bx){ result+= this->tableKey[ay][(((ay+1) % 5))]; result+= this->tableKey[ay][(((by + 1) % 5))]; }else{ result+= this->tableKey[ay][bx]; result+= this->tableKey[by][ax]; } //cout<<" "; return result; } string _dec(string str){ string tmp = ""; string result=""; int ax,ay,bx,by,satu,dua,tiga,empat; for(unsigned i=0;i<5;i++){ for(unsigned j=0;j<5;j++){ if(this->tableKey[i][j] == str[0]){ ay = i; ax = j; } if(this->tableKey[i][j] == str[1]){ by = i; bx = j; } } } //cout<<str<<"="; if(ay == by){ satu = ((ax - 1)); satu = (satu < 0 ? (satu + 5) : satu); dua = ((bx - 1)); dua = (dua < 0 ? (dua + 5) : dua); //cout<<str[0]<<" = "<<<<","<<(ay)<<endl; result+= this->tableKey[ay][satu]; result+= this->tableKey[by][dua]; }else if(ax == bx){ cout<<str[0]<<" = "<<ax<<","<<ay<<endl; cout<<str[1]<<" = "<<bx<<","<<by<<endl; cout<<"enc :"<<endl; satu = ((ay - 1)); satu = (satu < 0 ? (satu + 5) : satu); dua = ((by - 1)); dua = (dua < 0 ? (dua + 5) : dua); //cout<<str[0]<<" = "<<<<","<<(ay)<<endl; result+= this->tableKey[satu][ax]; result+= this->tableKey[dua][bx]; }else{ result+= this->tableKey[ay][bx]; result+= this->tableKey[by][ax]; } //cout<<" "<<endl; return result; } string generateKey(string key,char exlude){ this->key = ""; bool found; for(char& k : key+"abcdefghijklmnopqrstuvwxyz" ) { found = false; for(char& j : this->key){ if(k == j){ found = true; } } if(!found && exlude != k){ this->key+=k; } } return this->key; } vector< vector<char> > getMatrix(){ return this->tableKey; } vector< vector<char> > generateTable(){ int index = 0; for(unsigned i = 0; i < 5; i++) { vector<char> row; for(unsigned j = 0; j < 5; j++) { row.push_back(this->key[index++]); } tableKey.push_back(row); } return tableKey; } }; }; /*int main(){ playFair pf = playFair(); string key = pf.generateKey("standerchbkfgil",'j'); string pt = "good brooms sweep clean"; vector< vector<char> > ab = pf.generateTable(); cout<<"Matrix Table : \n"; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ cout<<ab[i][j]<<" "; } cout<<"\n"; } string encr = pf.vec2string(pf.enc(pt)); //cout<<encr<<endl; string decr = pf.dec(encr); string human = pf.humanize(decr,pt); cout<<human; }*/
#include "Geometry/EcalAlgo/interface/WriteESAlignments.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "CondCore/CondDB/interface/Serialization.h" #include "Geometry/EcalAlgo/interface/EcalPreshowerGeometry.h" typedef WriteESAlignments WEA ; const unsigned int WEA::k_nA = EcalPreshowerGeometry::numberOfAlignments() ; WEA::WriteESAlignments(edm::ConsumesCollector&& cc): geometryToken_{cc.esConsumes<CaloGeometry, CaloGeometryRecord>(edm::ESInputTag{})}, alignmentToken_{cc.esConsumes<Alignments, ESAlignmentRcd>(edm::ESInputTag{})} {} void WEA::writeAlignments( const edm::EventSetup& eventSetup , const WEA::DVec& alphaVec , const WEA::DVec& betaVec , const WEA::DVec& gammaVec , const WEA::DVec& xtranslVec , const WEA::DVec& ytranslVec , const WEA::DVec& ztranslVec ) { assert( alphaVec.size() == k_nA ) ; assert( betaVec.size() == k_nA ) ; assert( gammaVec.size() == k_nA ) ; assert( xtranslVec.size() == k_nA ) ; assert( ytranslVec.size() == k_nA ) ; assert( ztranslVec.size() == k_nA ) ; AliPtr aliPtr ( new Alignments ) ;// writeOne will take ownership! AliVec& vali ( aliPtr->m_align ) ; convert( eventSetup , alphaVec , betaVec , gammaVec , xtranslVec , ytranslVec , ztranslVec , vali ) ; write( aliPtr ) ; } void WEA::write( WEA::AliPtr aliPtr ) { std::cout << "Uploading ES alignments to the database" << std::endl ; edm::Service<cond::service::PoolDBOutputService> poolDbService ; if (!poolDbService.isAvailable()) throw cms::Exception("NotAvailable") << "PoolDBOutputService not available"; poolDbService->writeOne<Alignments>(&(*aliPtr), poolDbService->currentTime(), "ESAlignmentRcd" ) ; } void WEA::convert( const edm::EventSetup& eS , const WEA::DVec& a , const WEA::DVec& b , const WEA::DVec& g , const WEA::DVec& x , const WEA::DVec& y , const WEA::DVec& z , WEA::AliVec& va ) { const auto& pG = eS.getData(geometryToken_); const CaloSubdetectorGeometry* geom(pG.getSubdetectorGeometry( DetId::Ecal, EcalPreshower) ) ; const auto& pA = eS.getData(alignmentToken_); const AliVec& vaPrev ( pA.m_align ) ; va.reserve( k_nA ) ; for( unsigned int i ( 0 ) ; i != k_nA ; ++i ) { // ordering of i is: left, right, left, right,... // starting at ES- rear, then ES- front, // then ES+ front, then ES+ rear const ESDetId id ( EcalPreshowerGeometry::detIdFromLocalAlignmentIndex( i ) ) ; double zPlanePrev ( geom->getGeometry( id )->getPosition().z() ) ; const double zAlignPrev ( vaPrev[i].translation().z() ) ; const Trl q_I ( 0, 0, zPlanePrev - zAlignPrev ) ; const Trl& s_p ( vaPrev[i].translation() ) ; const Trl t_n ( x[i], y[i], z[i] ) ; const Rot G_p ( vaPrev[i].rotation() ) ; const double gamma ( g[i] ) ; const double alpha ( a[i] ) ; const double beta ( b[i] ) ; const Rot L_n ( // New rotation in local frame! Rot( Rot( Rot().rotateZ( -gamma ) ).rotateX( -alpha ) ).rotateY( -beta ) ) ; const Rot InvL_n ( L_n.inverse() ) ; const Rot G_n ( InvL_n * G_p ) ; const Trl s_n ( t_n + s_p + q_I - InvL_n*q_I ) ; std::cout<<"For i = "<<i<<", q_I="<<q_I<<std::endl ; std::cout<<"For i = "<<i<<", s_p="<<s_p<<std::endl ; std::cout<<"For i = "<<i<<", alpha = "<<1000.*alpha<<" mr"<<std::endl; std::cout<<"For i = "<<i<<", beta = "<<1000.*beta <<" mr"<<std::endl; std::cout<<"For i = "<<i<<", gamma = "<<1000.*gamma<<" mr"<<std::endl; std::cout<<" For i = "<<i<<", L_n = "<< L_n <<" Euler angles="<<InvL_n.eulerAngles()<<"\n"<<std::endl; std::cout<<"For i = "<<i<<", t_n="<<t_n<<std::endl ; std::cout<<"For i = "<<i<<", G_p="<<G_p <<" Euler angles="<<G_p.eulerAngles()<<"\n"<<std::endl ; std::cout<<" For i = "<<i<<", InvL_n = "<< InvL_n <<" Euler angles="<<InvL_n.eulerAngles()<<"\n"<<std::endl; std::cout<<" For i ="<<i<<", G_n = "<< G_n <<" Euler angles="<<G_n.eulerAngles()<<"\n"<<std::endl; std::cout<<" For i ="<<i<<", s_n = "<< s_n<<std::endl; std::cout<<"++++++++++++++++++++++++++\n\n"<<std::endl; va.emplace_back( AlignTransform( s_n, G_n, id ) ) ; } }
#include "header.h" #include <iostream> #include "JPGImage.h" #include "templates.h" #include "BaseEngine.h" #include "Bxf03uWall.h" #include "Bxf03uHook.h" #include "Bxf03uStage.h" #include "BXf03uPlayer.h" #include "Bxf03uObstacle.h" Bxf03uStage::Bxf03uStage() { //load background to memory bg = ImageData(); bg.LoadImage("bg.png"); } Bxf03uStage::~Bxf03uStage() { } void Bxf03uStage::init(Bxf03uMain* engine) { //save a pointer to the engine this->engine = engine; //destroy old objects so we can begin engine->DestroyOldObjects(); engine->alphaStrokes.clear(); //initialise offsets Xoffset = 0; Yoffset = 0; //and score score = 0; //initialise background position bgX = -150; bgY = -1600; //create walls and store them auto wallLeft = new Bxf03uWall(engine, this, true); auto wallRight = new Bxf03uWall(engine, this, false); //all stores are made with the added auto placement (-1 push_back()) logic in BaseEngine engine->StoreObjectInArray(-1, wallLeft); engine->StoreObjectInArray(-1, wallRight); //allocate hook and store //only allocate so that the player can receive the hook //and the hook can receive the player pointer hook = (Bxf03uHook*)malloc(sizeof(Bxf03uHook)); engine->StoreObjectInArray(-1, hook); //create player and store player = new Bxf03uPlayer(engine, this, hook); engine->StoreObjectInArray(-1, player); //now we can create the hook since we have the player new (hook) Bxf03uHook(engine, this, player); //create obstacles form this location lastObstacleY = 600; //create 10 for starters for (int i = 0; i < 10; i++) { GenerateNewObstacle(); } //save an iterator for the first one //for somewhat faster looping in update() firstObstacle = engine->DisplayableObjects.begin() + 4; godMode = false; } //taking over the update loop as the DisplayableObjects queue //doesn't have the right update order void Bxf03uStage::update(int time) { //first update the player's stage location player->DoUpdate(time); //based on that update the stage offset float diff = Yoffset; Yoffset = -player->stageY + 600; Xoffset = -(player->stageX - 250)*0.7; diff -= Yoffset; //then update the player's screen location player->m_iCurrentScreenX = toActualX(player->stageX); //and the background float parallax = 0.2; bgX = toStageX(-150 / parallax) * parallax; bgY += diff*(1-parallax); //tiling the background infinitely if (0 < toActualY(bgY)) { bgY -= 1600; } else if (toActualY(bgY) < -1600) { bgY += 1600; } //if the last obstacle is about to come on-screen create a new one if (-100 < toActualY(lastObstacleY)) { GenerateNewObstacle(); } //now update the obstacles for (auto ob = firstObstacle; ob != engine->DisplayableObjects.end(); ob++) { if (*ob == NULL) break; (*ob)->DoUpdate(time); } //now that the obstacles are updated, try hooking again if needed if (player->waitForHook) { player->HookOn(player->hookCentre); } //hooking is done update the hook hook->DoUpdate(time); //everything done check if the game is over bool insideWalls = 50 + player->radius <= player->stageX && player->stageX <= 450 - player->radius; if (!insideWalls && !(player->hooked)) over(); //konami code int len = engine->alphaStrokes.size(); if (10 <= len && engine->alphaStrokes.substr(len-10, std::string::npos) == "wwssadadqe") { godMode = true; } //save the new score score = toActualY(1050); } //taking over most of the draw loop as well void Bxf03uStage::draw() { //render the parallax background bg.RenderImage(engine->GetBackground(), 0, 0, toActualX(bgX), toActualY(bgY), 800, 2400); //copied from BaseEngine engine->m_iDrawableObjectsChanged = 0; // And this re-draws the new positions if (&(engine->DisplayableObjects) != NULL) { for each (DisplayableObject* ob in engine->DisplayableObjects) { if (ob == NULL) break; ob->Draw(); if (engine->m_iDrawableObjectsChanged) return; // Abort! Something changed in the array } } if (engine->state != Bxf03uMain::running) return; //draw the score over everything char scoreString[29]; sprintf(scoreString, "%28d", score); engine->DrawScreenString(20, 10, scoreString, 0xdddddd, engine->GetFont("consola.ttf", 30)); } //stop the game void Bxf03uStage::over() { if (godMode) return; engine->state = Bxf03uMain::over; //state change, ask for a redraw engine->Redraw(true); } //takes care of generating new obstacles void Bxf03uStage::GenerateNewObstacle() { //a new obstacle every 150 pixels with some variation int locY = lastObstacleY - normalRandBetween(100, 200, 18); //make the average size of obstacles grow with the score int max = 10 + abs(Yoffset / 350); int size = normalRandBetween<int>(10, max, 10); if (size < 5) size = 5; //minimum size is 5 //place the obstacle inside the walls int locX = realRandBetween(50 + size, 450 - size); //but don't place it in front of the player for the first few seconds bool inFrontOfPlayer = 240 < locX + size && locX - size < 260; if (-1000 < locY && inFrontOfPlayer) { while (inFrontOfPlayer) { locX = realRandBetween(50 + size, 450 - size); inFrontOfPlayer = 240 < locX + size && locX - size < 260; } } //but after a while make sure the player has to do something if (engine->DisplayableObjects.size() == 14) { //the 10th obstacle will be in the way locX = 250; } //placement done, create and store the obstacle auto obstacle = new Bxf03uObstacle(engine, this, locX, locY, 2*size); engine->StoreObjectInArray(-1, obstacle); //save its y location so we can generate new ones lastObstacleY = locY; }
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2020 Daniel Chappuis * ********************************************************************************* * * * This software is provided 'as-is', without any express or implied warranty. * * In no event will the authors be held liable for any damages arising from the * * use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not claim * * that you wrote the original software. If you use this software in a * * product, an acknowledgment in the product documentation would be * * appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source distribution. * * * ********************************************************************************/ // Libraries #include <reactphysics3d/systems/CollisionDetectionSystem.h> #include <reactphysics3d/engine/PhysicsWorld.h> #include <reactphysics3d/collision/OverlapCallback.h> #include <reactphysics3d/collision/shapes/BoxShape.h> #include <reactphysics3d/collision/shapes/ConcaveShape.h> #include <reactphysics3d/collision/ContactManifoldInfo.h> #include <reactphysics3d/constraint/ContactPoint.h> #include <reactphysics3d/body/RigidBody.h> #include <reactphysics3d/configuration.h> #include <reactphysics3d/collision/CollisionCallback.h> #include <reactphysics3d/collision/OverlapCallback.h> #include <reactphysics3d/collision/narrowphase/NarrowPhaseInfoBatch.h> #include <reactphysics3d/collision/ContactManifold.h> #include <reactphysics3d/utils/Profiler.h> #include <reactphysics3d/engine/EventListener.h> #include <reactphysics3d/collision/RaycastInfo.h> #include <reactphysics3d/containers/Pair.h> #include <cassert> #include <iostream> // We want to use the ReactPhysics3D namespace using namespace reactphysics3d; using namespace std; // Constructor CollisionDetectionSystem::CollisionDetectionSystem(PhysicsWorld* world, ColliderComponents& collidersComponents, TransformComponents& transformComponents, CollisionBodyComponents& collisionBodyComponents, RigidBodyComponents& rigidBodyComponents, MemoryManager& memoryManager) : mMemoryManager(memoryManager), mCollidersComponents(collidersComponents), mCollisionDispatch(mMemoryManager.getPoolAllocator()), mWorld(world), mNoCollisionPairs(mMemoryManager.getPoolAllocator()), mOverlappingPairs(mMemoryManager.getPoolAllocator(), mMemoryManager.getSingleFrameAllocator(), mCollidersComponents, collisionBodyComponents, rigidBodyComponents, mNoCollisionPairs, mCollisionDispatch), mBroadPhaseSystem(*this, mCollidersComponents, transformComponents, rigidBodyComponents), mMapBroadPhaseIdToColliderEntity(memoryManager.getPoolAllocator()), mNarrowPhaseInput(mMemoryManager.getSingleFrameAllocator(), mOverlappingPairs), mPotentialContactPoints(mMemoryManager.getSingleFrameAllocator()), mPotentialContactManifolds(mMemoryManager.getSingleFrameAllocator()), mContactPairs1(mMemoryManager.getPoolAllocator()), mContactPairs2(mMemoryManager.getPoolAllocator()), mPreviousContactPairs(&mContactPairs1), mCurrentContactPairs(&mContactPairs2), mLostContactPairs(mMemoryManager.getSingleFrameAllocator()), mMapPairIdToContactPairIndex1(mMemoryManager.getPoolAllocator()), mMapPairIdToContactPairIndex2(mMemoryManager.getPoolAllocator()), mPreviousMapPairIdToContactPairIndex(&mMapPairIdToContactPairIndex1), mCurrentMapPairIdToContactPairIndex(&mMapPairIdToContactPairIndex2), mContactManifolds1(mMemoryManager.getPoolAllocator()), mContactManifolds2(mMemoryManager.getPoolAllocator()), mPreviousContactManifolds(&mContactManifolds1), mCurrentContactManifolds(&mContactManifolds2), mContactPoints1(mMemoryManager.getPoolAllocator()), mContactPoints2(mMemoryManager.getPoolAllocator()), mPreviousContactPoints(&mContactPoints1), mCurrentContactPoints(&mContactPoints2), mMapBodyToContactPairs(mMemoryManager.getSingleFrameAllocator()) { #ifdef IS_RP3D_PROFILING_ENABLED mProfiler = nullptr; mCollisionDispatch.setProfiler(mProfiler); mOverlappingPairs.setProfiler(mProfiler); #endif } // Compute the collision detection void CollisionDetectionSystem::computeCollisionDetection() { RP3D_PROFILE("CollisionDetectionSystem::computeCollisionDetection()", mProfiler); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(mNarrowPhaseInput, true); // Compute the narrow-phase collision detection computeNarrowPhase(); } // Compute the broad-phase collision detection void CollisionDetectionSystem::computeBroadPhase() { RP3D_PROFILE("CollisionDetectionSystem::computeBroadPhase()", mProfiler); // Ask the broad-phase to compute all the shapes overlapping with the shapes that // have moved or have been added in the last frame. This call can only add new // overlapping pairs in the collision detection. List<Pair<int32, int32>> overlappingNodes(mMemoryManager.getPoolAllocator(), 32); mBroadPhaseSystem.computeOverlappingPairs(mMemoryManager, overlappingNodes); // Create new overlapping pairs if necessary updateOverlappingPairs(overlappingNodes); // Remove non overlapping pairs removeNonOverlappingPairs(); } // Remove pairs that are not overlapping anymore void CollisionDetectionSystem::removeNonOverlappingPairs() { RP3D_PROFILE("CollisionDetectionSystem::removeNonOverlappingPairs()", mProfiler); for (uint64 i=0; i < mOverlappingPairs.getNbPairs(); i++) { // Check if we need to test overlap. If so, test if the two shapes are still overlapping. // Otherwise, we destroy the overlapping pair if (mOverlappingPairs.mNeedToTestOverlap[i]) { if(mBroadPhaseSystem.testOverlappingShapes(mOverlappingPairs.mPairBroadPhaseId1[i], mOverlappingPairs.mPairBroadPhaseId2[i])) { mOverlappingPairs.mNeedToTestOverlap[i] = false; } else { // If the two colliders of the pair were colliding in the previous frame if (mOverlappingPairs.mCollidingInPreviousFrame[i]) { // Create a new lost contact pair addLostContactPair(i); } mOverlappingPairs.removePair(mOverlappingPairs.mPairIds[i]); i--; } } } } // Add a lost contact pair (pair of colliders that are not in contact anymore) void CollisionDetectionSystem::addLostContactPair(uint64 overlappingPairIndex) { const Entity collider1Entity = mOverlappingPairs.mColliders1[overlappingPairIndex]; const Entity collider2Entity = mOverlappingPairs.mColliders2[overlappingPairIndex]; const Entity body1Entity = mCollidersComponents.getBody(collider1Entity); const Entity body2Entity = mCollidersComponents.getBody(collider2Entity); const bool isCollider1Trigger = mCollidersComponents.getIsTrigger(collider1Entity); const bool isCollider2Trigger = mCollidersComponents.getIsTrigger(collider2Entity); const bool isTrigger = isCollider1Trigger || isCollider2Trigger; // Create a lost contact pair ContactPair lostContactPair(mOverlappingPairs.mPairIds[overlappingPairIndex], body1Entity, body2Entity, collider1Entity, collider2Entity, (uint)(mLostContactPairs.size()), true, isTrigger, mMemoryManager.getHeapAllocator()); mLostContactPairs.add(lostContactPair); } // Take a list of overlapping nodes in the broad-phase and create new overlapping pairs if necessary void CollisionDetectionSystem::updateOverlappingPairs(const List<Pair<int32, int32>>& overlappingNodes) { RP3D_PROFILE("CollisionDetectionSystem::updateOverlappingPairs()", mProfiler); // For each overlapping pair of nodes for (uint i=0; i < overlappingNodes.size(); i++) { Pair<int32, int32> nodePair = overlappingNodes[i]; assert(nodePair.first != -1); assert(nodePair.second != -1); // Skip pairs with same overlapping nodes if (nodePair.first != nodePair.second) { // Get the two colliders const Entity collider1Entity = mMapBroadPhaseIdToColliderEntity[nodePair.first]; const Entity collider2Entity = mMapBroadPhaseIdToColliderEntity[nodePair.second]; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); // Get the two bodies const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; // If the two colliders are from the same body, skip it if (body1Entity != body2Entity) { // Compute the overlapping pair ID const uint64 pairId = pairNumbers(std::max(nodePair.first, nodePair.second), std::min(nodePair.first, nodePair.second)); // Check if the overlapping pair already exists auto it = mOverlappingPairs.mMapPairIdToPairIndex.find(pairId); if (it == mOverlappingPairs.mMapPairIdToPairIndex.end()) { const unsigned short shape1CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider1Index]; const unsigned short shape2CollideWithMaskBits = mCollidersComponents.mCollideWithMaskBits[collider2Index]; const unsigned short shape1CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider1Index]; const unsigned short shape2CollisionCategoryBits = mCollidersComponents.mCollisionCategoryBits[collider2Index]; // Check if the collision filtering allows collision between the two shapes if ((shape1CollideWithMaskBits & shape2CollisionCategoryBits) != 0 && (shape1CollisionCategoryBits & shape2CollideWithMaskBits) != 0) { Collider* shape1 = mCollidersComponents.mColliders[collider1Index]; Collider* shape2 = mCollidersComponents.mColliders[collider2Index]; // Check that at least one collision shape is convex if (shape1->getCollisionShape()->isConvex() || shape2->getCollisionShape()->isConvex()) { // Add the new overlapping pair mOverlappingPairs.addPair(shape1, shape2); } } } else { // We do not need to test the pair for overlap because it has just been reported that they still overlap mOverlappingPairs.mNeedToTestOverlap[it->second] = false; } } } } } // Compute the middle-phase collision detection void CollisionDetectionSystem::computeMiddlePhase(NarrowPhaseInput& narrowPhaseInput, bool needToReportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler); // Reserve memory for the narrow-phase input using cached capacity from previous frame narrowPhaseInput.reserveMemory(); // Remove the obsolete last frame collision infos and mark all the others as obsolete mOverlappingPairs.clearObsoleteLastFrameCollisionInfos(); // For each possible convex vs convex pair of bodies for (uint64 i=0; i < mOverlappingPairs.getNbConvexVsConvexPairs(); i++) { assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[i]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[i]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[i]) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[i])); // Check that at least one body is enabled (active and awake) and not static if (mOverlappingPairs.mIsActive[i]) { const Entity collider1Entity = mOverlappingPairs.mColliders1[i]; const Entity collider2Entity = mOverlappingPairs.mColliders2[i]; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index]; CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index]; NarrowPhaseAlgorithmType algorithmType = mOverlappingPairs.mNarrowPhaseAlgorithmType[i]; const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index]; const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index]; const bool reportContacts = needToReportContacts && !isCollider1Trigger && !isCollider2Trigger; // No middle-phase is necessary, simply create a narrow phase info // for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(mOverlappingPairs.mPairIds[i], i, collider1Entity, collider2Entity, collisionShape1, collisionShape2, mCollidersComponents.mLocalToWorldTransforms[collider1Index], mCollidersComponents.mLocalToWorldTransforms[collider2Index], algorithmType, reportContacts, mMemoryManager.getSingleFrameAllocator()); mOverlappingPairs.mCollidingInCurrentFrame[i] = false; } } // For each possible convex vs concave pair of bodies const uint64 convexVsConcaveStartIndex = mOverlappingPairs.getConvexVsConcavePairsStartIndex(); for (uint64 i=convexVsConcaveStartIndex; i < convexVsConcaveStartIndex + mOverlappingPairs.getNbConvexVsConcavePairs(); i++) { assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[i]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[i]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[i]) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[i])); // Check that at least one body is enabled (active and awake) and not static if (mOverlappingPairs.mIsActive[i]) { computeConvexVsConcaveMiddlePhase(i, mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, needToReportContacts); mOverlappingPairs.mCollidingInCurrentFrame[i] = false; } } } // Compute the middle-phase collision detection void CollisionDetectionSystem::computeMiddlePhaseCollisionSnapshot(List<uint64>& convexPairs, List<uint64>& concavePairs, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeMiddlePhase()", mProfiler); // Reserve memory for the narrow-phase input using cached capacity from previous frame narrowPhaseInput.reserveMemory(); // Remove the obsolete last frame collision infos and mark all the others as obsolete mOverlappingPairs.clearObsoleteLastFrameCollisionInfos(); // For each possible convex vs convex pair of bodies for (uint64 p=0; p < convexPairs.size(); p++) { const uint64 pairId = convexPairs[(uint)p]; const uint64 pairIndex = mOverlappingPairs.mMapPairIdToPairIndex[pairId]; assert(pairIndex < mOverlappingPairs.getNbPairs()); const Entity collider1Entity = mOverlappingPairs.mColliders1[pairIndex]; const Entity collider2Entity = mOverlappingPairs.mColliders2[pairIndex]; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != -1); assert(mCollidersComponents.getBroadPhaseId(collider2Entity) != -1); assert(mCollidersComponents.getBroadPhaseId(collider1Entity) != mCollidersComponents.getBroadPhaseId(collider2Entity)); CollisionShape* collisionShape1 = mCollidersComponents.mCollisionShapes[collider1Index]; CollisionShape* collisionShape2 = mCollidersComponents.mCollisionShapes[collider2Index]; NarrowPhaseAlgorithmType algorithmType = mOverlappingPairs.mNarrowPhaseAlgorithmType[pairIndex]; // No middle-phase is necessary, simply create a narrow phase info // for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(pairId, pairIndex, collider1Entity, collider2Entity, collisionShape1, collisionShape2, mCollidersComponents.mLocalToWorldTransforms[collider1Index], mCollidersComponents.mLocalToWorldTransforms[collider2Index], algorithmType, reportContacts, mMemoryManager.getSingleFrameAllocator()); } // For each possible convex vs concave pair of bodies for (uint p=0; p < concavePairs.size(); p++) { const uint64 pairId = concavePairs[p]; const uint64 pairIndex = mOverlappingPairs.mMapPairIdToPairIndex[pairId]; assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[pairIndex]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[pairIndex]) != -1); assert(mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders1[pairIndex]) != mCollidersComponents.getBroadPhaseId(mOverlappingPairs.mColliders2[pairIndex])); computeConvexVsConcaveMiddlePhase(pairIndex, mMemoryManager.getSingleFrameAllocator(), narrowPhaseInput, reportContacts); } } // Compute the concave vs convex middle-phase algorithm for a given pair of bodies void CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase(uint64 pairIndex, MemoryAllocator& allocator, NarrowPhaseInput& narrowPhaseInput, bool reportContacts) { RP3D_PROFILE("CollisionDetectionSystem::computeConvexVsConcaveMiddlePhase()", mProfiler); const Entity collider1 = mOverlappingPairs.mColliders1[pairIndex]; const Entity collider2 = mOverlappingPairs.mColliders2[pairIndex]; const uint collider1Index = mCollidersComponents.getEntityIndex(collider1); const uint collider2Index = mCollidersComponents.getEntityIndex(collider2); Transform& shape1LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider1Index]; Transform& shape2LocalToWorldTransform = mCollidersComponents.mLocalToWorldTransforms[collider2Index]; Transform convexToConcaveTransform; // Collision shape 1 is convex, collision shape 2 is concave ConvexShape* convexShape; ConcaveShape* concaveShape; const bool isShape1Convex = mOverlappingPairs.mIsShape1Convex[pairIndex]; if (isShape1Convex) { convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider1Index]); concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider2Index]); convexToConcaveTransform = shape2LocalToWorldTransform.getInverse() * shape1LocalToWorldTransform; } else { // Collision shape 2 is convex, collision shape 1 is concave convexShape = static_cast<ConvexShape*>(mCollidersComponents.mCollisionShapes[collider2Index]); concaveShape = static_cast<ConcaveShape*>(mCollidersComponents.mCollisionShapes[collider1Index]); convexToConcaveTransform = shape1LocalToWorldTransform.getInverse() * shape2LocalToWorldTransform; } assert(convexShape->isConvex()); assert(!concaveShape->isConvex()); assert(mOverlappingPairs.mNarrowPhaseAlgorithmType[pairIndex] != NarrowPhaseAlgorithmType::None); // Compute the convex shape AABB in the local-space of the convex shape AABB aabb; convexShape->computeAABB(aabb, convexToConcaveTransform); // Compute the concave shape triangles that are overlapping with the convex mesh AABB List<Vector3> triangleVertices(allocator); List<Vector3> triangleVerticesNormals(allocator); List<uint> shapeIds(allocator); concaveShape->computeOverlappingTriangles(aabb, triangleVertices, triangleVerticesNormals, shapeIds, allocator); assert(triangleVertices.size() == triangleVerticesNormals.size()); assert(shapeIds.size() == triangleVertices.size() / 3); assert(triangleVertices.size() % 3 == 0); assert(triangleVerticesNormals.size() % 3 == 0); const bool isCollider1Trigger = mCollidersComponents.mIsTrigger[collider1Index]; const bool isCollider2Trigger = mCollidersComponents.mIsTrigger[collider2Index]; reportContacts = reportContacts && !isCollider1Trigger && !isCollider2Trigger; // For each overlapping triangle for (uint i=0; i < shapeIds.size(); i++) { // Create a triangle collision shape (the allocated memory for the TriangleShape will be released in the // destructor of the corresponding NarrowPhaseInfo. TriangleShape* triangleShape = new (allocator.allocate(sizeof(TriangleShape))) TriangleShape(&(triangleVertices[i * 3]), &(triangleVerticesNormals[i * 3]), shapeIds[i], allocator); #ifdef IS_RP3D_PROFILING_ENABLED // Set the profiler to the triangle shape triangleShape->setProfiler(mProfiler); #endif // Create a narrow phase info for the narrow-phase collision detection narrowPhaseInput.addNarrowPhaseTest(mOverlappingPairs.mPairIds[pairIndex], pairIndex, collider1, collider2, isShape1Convex ? convexShape : triangleShape, isShape1Convex ? triangleShape : convexShape, shape1LocalToWorldTransform, shape2LocalToWorldTransform, mOverlappingPairs.mNarrowPhaseAlgorithmType[pairIndex], reportContacts, allocator); } } // Execute the narrow-phase collision detection algorithm on batches bool CollisionDetectionSystem::testNarrowPhaseCollision(NarrowPhaseInput& narrowPhaseInput, bool clipWithPreviousAxisIfStillColliding, MemoryAllocator& allocator) { bool contactFound = false; // Get the narrow-phase collision detection algorithms for each kind of collision shapes SphereVsSphereAlgorithm* sphereVsSphereAlgo = mCollisionDispatch.getSphereVsSphereAlgorithm(); SphereVsCapsuleAlgorithm* sphereVsCapsuleAlgo = mCollisionDispatch.getSphereVsCapsuleAlgorithm(); CapsuleVsCapsuleAlgorithm* capsuleVsCapsuleAlgo = mCollisionDispatch.getCapsuleVsCapsuleAlgorithm(); SphereVsConvexPolyhedronAlgorithm* sphereVsConvexPolyAlgo = mCollisionDispatch.getSphereVsConvexPolyhedronAlgorithm(); CapsuleVsConvexPolyhedronAlgorithm* capsuleVsConvexPolyAlgo = mCollisionDispatch.getCapsuleVsConvexPolyhedronAlgorithm(); ConvexPolyhedronVsConvexPolyhedronAlgorithm* convexPolyVsConvexPolyAlgo = mCollisionDispatch.getConvexPolyhedronVsConvexPolyhedronAlgorithm(); // get the narrow-phase batches to test for collision for contacts SphereVsSphereNarrowPhaseInfoBatch& sphereVsSphereBatchContacts = narrowPhaseInput.getSphereVsSphereBatch(); SphereVsCapsuleNarrowPhaseInfoBatch& sphereVsCapsuleBatchContacts = narrowPhaseInput.getSphereVsCapsuleBatch(); CapsuleVsCapsuleNarrowPhaseInfoBatch& capsuleVsCapsuleBatchContacts = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatchContacts = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatchContacts = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatchContacts = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Compute the narrow-phase collision detection for each kind of collision shapes (for contacts) if (sphereVsSphereBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsSphereAlgo->testCollision(sphereVsSphereBatchContacts, 0, sphereVsSphereBatchContacts.getNbObjects(), allocator); } if (sphereVsCapsuleBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsCapsuleAlgo->testCollision(sphereVsCapsuleBatchContacts, 0, sphereVsCapsuleBatchContacts.getNbObjects(), allocator); } if (capsuleVsCapsuleBatchContacts.getNbObjects() > 0) { contactFound |= capsuleVsCapsuleAlgo->testCollision(capsuleVsCapsuleBatchContacts, 0, capsuleVsCapsuleBatchContacts.getNbObjects(), allocator); } if (sphereVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= sphereVsConvexPolyAlgo->testCollision(sphereVsConvexPolyhedronBatchContacts, 0, sphereVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } if (capsuleVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= capsuleVsConvexPolyAlgo->testCollision(capsuleVsConvexPolyhedronBatchContacts, 0, capsuleVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } if (convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects() > 0) { contactFound |= convexPolyVsConvexPolyAlgo->testCollision(convexPolyhedronVsConvexPolyhedronBatchContacts, 0, convexPolyhedronVsConvexPolyhedronBatchContacts.getNbObjects(), clipWithPreviousAxisIfStillColliding, allocator); } return contactFound; } // Process the potential contacts after narrow-phase collision detection void CollisionDetectionSystem::processAllPotentialContacts(NarrowPhaseInput& narrowPhaseInput, bool updateLastFrameInfo, List<ContactPointInfo>& potentialContactPoints, Map<uint64, uint>* mapPairIdToContactPairIndex, List<ContactManifoldInfo>& potentialContactManifolds, List<ContactPair>* contactPairs, Map<Entity, List<uint>>& mapBodyToContactPairs) { assert(contactPairs->size() == 0); assert(mapPairIdToContactPairIndex->size() == 0); // get the narrow-phase batches to test for collision NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch(); NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch(); NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Process the potential contacts processPotentialContacts(sphereVsSphereBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); processPotentialContacts(sphereVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); processPotentialContacts(capsuleVsCapsuleBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); processPotentialContacts(sphereVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); processPotentialContacts(capsuleVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); processPotentialContacts(convexPolyhedronVsConvexPolyhedronBatch, updateLastFrameInfo, potentialContactPoints, mapPairIdToContactPairIndex, potentialContactManifolds, contactPairs, mapBodyToContactPairs); } // Compute the narrow-phase collision detection void CollisionDetectionSystem::computeNarrowPhase() { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhase()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getSingleFrameAllocator(); // Swap the previous and current contacts lists swapPreviousAndCurrentContacts(); // Test the narrow-phase collision detection on the batches to be tested testNarrowPhaseCollision(mNarrowPhaseInput, true, allocator); // Process all the potential contacts after narrow-phase collision processAllPotentialContacts(mNarrowPhaseInput, true, mPotentialContactPoints, mCurrentMapPairIdToContactPairIndex, mPotentialContactManifolds, mCurrentContactPairs, mMapBodyToContactPairs); // Reduce the number of contact points in the manifolds reducePotentialContactManifolds(mCurrentContactPairs, mPotentialContactManifolds, mPotentialContactPoints); assert(mCurrentContactManifolds->size() == 0); assert(mCurrentContactPoints->size() == 0); } // Compute the narrow-phase collision detection for the testOverlap() methods. /// This method returns true if contacts are found. bool CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot(NarrowPhaseInput& narrowPhaseInput, OverlapCallback* callback) { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseOverlapSnapshot()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getPoolAllocator(); // Test the narrow-phase collision detection on the batches to be tested bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator); if (collisionFound && callback != nullptr) { // Compute the overlapping colliders List<ContactPair> contactPairs(allocator); List<ContactPair> lostContactPairs(allocator); // Always empty in this case (snapshot) computeOverlapSnapshotContactPairs(narrowPhaseInput, contactPairs); // Report overlapping colliders OverlapCallback::CallbackData callbackData(contactPairs, lostContactPairs, false, *mWorld); (*callback).onOverlap(callbackData); } return collisionFound; } // Process the potential overlapping bodies for the testOverlap() methods void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInput& narrowPhaseInput, List<ContactPair>& contactPairs) const { Set<uint64> setOverlapContactPairId(mMemoryManager.getHeapAllocator()); // get the narrow-phase batches to test for collision NarrowPhaseInfoBatch& sphereVsSphereBatch = narrowPhaseInput.getSphereVsSphereBatch(); NarrowPhaseInfoBatch& sphereVsCapsuleBatch = narrowPhaseInput.getSphereVsCapsuleBatch(); NarrowPhaseInfoBatch& capsuleVsCapsuleBatch = narrowPhaseInput.getCapsuleVsCapsuleBatch(); NarrowPhaseInfoBatch& sphereVsConvexPolyhedronBatch = narrowPhaseInput.getSphereVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& capsuleVsConvexPolyhedronBatch = narrowPhaseInput.getCapsuleVsConvexPolyhedronBatch(); NarrowPhaseInfoBatch& convexPolyhedronVsConvexPolyhedronBatch = narrowPhaseInput.getConvexPolyhedronVsConvexPolyhedronBatch(); // Process the potential contacts computeOverlapSnapshotContactPairs(sphereVsSphereBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(sphereVsCapsuleBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(capsuleVsCapsuleBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(sphereVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(capsuleVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); computeOverlapSnapshotContactPairs(convexPolyhedronVsConvexPolyhedronBatch, contactPairs, setOverlapContactPairId); } // Notify that the overlapping pairs where a given collider is involved need to be tested for overlap void CollisionDetectionSystem::notifyOverlappingPairsToTestOverlap(Collider* collider) { // Get the overlapping pairs involved with this collider List<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity()); for (uint i=0; i < overlappingPairs.size(); i++) { // Notify that the overlapping pair needs to be testbed for overlap mOverlappingPairs.setNeedToTestOverlap(overlappingPairs[i], true); } } // Convert the potential overlapping bodies for the testOverlap() methods void CollisionDetectionSystem::computeOverlapSnapshotContactPairs(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, List<ContactPair>& contactPairs, Set<uint64>& setOverlapContactPairId) const { RP3D_PROFILE("CollisionDetectionSystem::computeSnapshotContactPairs()", mProfiler); // For each narrow phase info object for(uint i=0; i < narrowPhaseInfoBatch.getNbObjects(); i++) { // If there is a collision if (narrowPhaseInfoBatch.isColliding[i]) { // If the contact pair does not already exist if (!setOverlapContactPairId.contains(narrowPhaseInfoBatch.overlappingPairIds[i])) { const Entity collider1Entity = narrowPhaseInfoBatch.colliderEntities1[i]; const Entity collider2Entity = narrowPhaseInfoBatch.colliderEntities2[i]; const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index]; // Create a new contact pair ContactPair contactPair(narrowPhaseInfoBatch.overlappingPairIds[i], body1Entity, body2Entity, collider1Entity, collider2Entity, ((uint)contactPairs.size()), isTrigger, false, mMemoryManager.getHeapAllocator()); contactPairs.add(contactPair); setOverlapContactPairId.add(narrowPhaseInfoBatch.overlappingPairIds[i]); } } narrowPhaseInfoBatch.resetContactPoints(i); } } // Compute the narrow-phase collision detection for the testCollision() methods. // This method returns true if contacts are found. bool CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot(NarrowPhaseInput& narrowPhaseInput, CollisionCallback& callback) { RP3D_PROFILE("CollisionDetectionSystem::computeNarrowPhaseCollisionSnapshot()", mProfiler); MemoryAllocator& allocator = mMemoryManager.getHeapAllocator(); // Test the narrow-phase collision detection on the batches to be tested bool collisionFound = testNarrowPhaseCollision(narrowPhaseInput, false, allocator); // If collision has been found, create contacts if (collisionFound) { List<ContactPointInfo> potentialContactPoints(allocator); List<ContactManifoldInfo> potentialContactManifolds(allocator); Map<uint64, uint> mapPairIdToContactPairIndex(allocator); List<ContactPair> contactPairs(allocator); List<ContactPair> lostContactPairs(allocator); // Not used during collision snapshots List<ContactManifold> contactManifolds(allocator); List<ContactPoint> contactPoints(allocator); Map<Entity, List<uint>> mapBodyToContactPairs(allocator); // Process all the potential contacts after narrow-phase collision processAllPotentialContacts(narrowPhaseInput, true, potentialContactPoints, &mapPairIdToContactPairIndex, potentialContactManifolds, &contactPairs, mapBodyToContactPairs); // Reduce the number of contact points in the manifolds reducePotentialContactManifolds(&contactPairs, potentialContactManifolds, potentialContactPoints); // Create the actual contact manifolds and contact points createSnapshotContacts(contactPairs, contactManifolds, contactPoints, potentialContactManifolds, potentialContactPoints); // Report the contacts to the user reportContacts(callback, &contactPairs, &contactManifolds, &contactPoints, lostContactPairs); } return collisionFound; } // Swap the previous and current contacts lists void CollisionDetectionSystem::swapPreviousAndCurrentContacts() { if (mPreviousContactPairs == &mContactPairs1) { mPreviousContactPairs = &mContactPairs2; mPreviousContactManifolds = &mContactManifolds2; mPreviousContactPoints = &mContactPoints2; mPreviousMapPairIdToContactPairIndex = &mMapPairIdToContactPairIndex2; mCurrentContactPairs = &mContactPairs1; mCurrentContactManifolds = &mContactManifolds1; mCurrentContactPoints = &mContactPoints1; mCurrentMapPairIdToContactPairIndex = &mMapPairIdToContactPairIndex1; } else { mPreviousContactPairs = &mContactPairs1; mPreviousContactManifolds = &mContactManifolds1; mPreviousContactPoints = &mContactPoints1; mPreviousMapPairIdToContactPairIndex = &mMapPairIdToContactPairIndex1; mCurrentContactPairs = &mContactPairs2; mCurrentContactManifolds = &mContactManifolds2; mCurrentContactPoints = &mContactPoints2; mCurrentMapPairIdToContactPairIndex = &mMapPairIdToContactPairIndex2; } } // Create the actual contact manifolds and contacts points void CollisionDetectionSystem::createContacts() { RP3D_PROFILE("CollisionDetectionSystem::createContacts()", mProfiler); mCurrentContactManifolds->reserve(mCurrentContactPairs->size()); mCurrentContactPoints->reserve(mCurrentContactManifolds->size()); // We go through all the contact pairs and add the pairs with a least a CollisionBody at the end of the // mProcessContactPairsOrderIslands array because those pairs have not been added during the islands // creation (only the pairs with two RigidBodies are added during island creation) Set<uint32> processedContactPairsIndices(mMemoryManager.getSingleFrameAllocator(), mCurrentContactPairs->size()); for (uint32 i=0; i < mWorld->mProcessContactPairsOrderIslands.size(); i++) { processedContactPairsIndices.add(mWorld->mProcessContactPairsOrderIslands[i]); } for (uint32 i=0; i < mCurrentContactPairs->size(); i++) { if (!processedContactPairsIndices.contains(i)) { mWorld->mProcessContactPairsOrderIslands.add(i); } } assert(mWorld->mProcessContactPairsOrderIslands.size() == (*mCurrentContactPairs).size()); // Process the contact pairs in the order defined by the islands such that the contact manifolds and // contact points of a given island are packed together in the array of manifolds and contact points for (uint p=0; p < mWorld->mProcessContactPairsOrderIslands.size(); p++) { uint32 contactPairIndex = mWorld->mProcessContactPairsOrderIslands[p]; ContactPair& contactPair = (*mCurrentContactPairs)[contactPairIndex]; contactPair.contactManifoldsIndex = (uint)mCurrentContactManifolds->size(); contactPair.nbContactManifolds = (int8)contactPair.potentialContactManifoldsIndices.size(); contactPair.contactPointsIndex = (uint)mCurrentContactPoints->size(); // For each potential contact manifold of the pair for (uint m=0; m < contactPair.potentialContactManifoldsIndices.size(); m++) { ContactManifoldInfo& potentialManifold = mPotentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]]; // Start index and number of contact points for this manifold const uint contactPointsIndex = (uint)mCurrentContactPoints->size(); const int8 nbContactPoints = static_cast<int8>(potentialManifold.potentialContactPointsIndices.size()); contactPair.nbToTalContactPoints += nbContactPoints; // We create a new contact manifold ContactManifold contactManifold(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity, contactPair.collider2Entity, contactPointsIndex, nbContactPoints); // Add the contact manifold mCurrentContactManifolds->add(contactManifold); assert(potentialManifold.potentialContactPointsIndices.size() > 0); // For each contact point of the manifold for (uint c=0; c < potentialManifold.potentialContactPointsIndices.size(); c++) { ContactPointInfo& potentialContactPoint = mPotentialContactPoints[potentialManifold.potentialContactPointsIndices[c]]; // Create a new contact point ContactPoint contactPoint(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold); // Add the contact point mCurrentContactPoints->add(contactPoint); } } } // Initialize the current contacts with the contacts from the previous frame (for warmstarting) initContactsWithPreviousOnes(); // Compute the lost contacts (contact pairs that were colliding in previous frame but not in this one) computeLostContactPairs(); mPreviousContactPoints->clear(); mPreviousContactManifolds->clear(); mPreviousContactPairs->clear(); mPreviousMapPairIdToContactPairIndex->clear(); // Reset the potential contacts mPotentialContactPoints.clear(true); mPotentialContactManifolds.clear(true); mNarrowPhaseInput.clear(); } // Compute the lost contact pairs (contact pairs in contact in the previous frame but not in the current one) void CollisionDetectionSystem::computeLostContactPairs() { // For each overlapping pair for (uint i=0; i < mOverlappingPairs.getNbPairs(); i++) { // If the two colliders of the pair were colliding in the previous frame but not in the current one if (mOverlappingPairs.mCollidingInPreviousFrame[i] && !mOverlappingPairs.mCollidingInCurrentFrame[i]) { // If both bodies still exist if (mCollidersComponents.hasComponent(mOverlappingPairs.mColliders1[i]) && mCollidersComponents.hasComponent(mOverlappingPairs.mColliders2[i])) { // Create a lost contact pair addLostContactPair(i); } } } } // Create the actual contact manifolds and contacts points for testCollision() methods void CollisionDetectionSystem::createSnapshotContacts(List<ContactPair>& contactPairs, List<ContactManifold>& contactManifolds, List<ContactPoint>& contactPoints, List<ContactManifoldInfo>& potentialContactManifolds, List<ContactPointInfo>& potentialContactPoints) { RP3D_PROFILE("CollisionDetectionSystem::createSnapshotContacts()", mProfiler); contactManifolds.reserve(contactPairs.size()); contactPoints.reserve(contactManifolds.size()); // For each contact pair for (uint p=0; p < contactPairs.size(); p++) { ContactPair& contactPair = contactPairs[p]; assert(contactPair.potentialContactManifoldsIndices.size() > 0); contactPair.contactManifoldsIndex = (uint)contactManifolds.size(); contactPair.nbContactManifolds = (int8)contactPair.potentialContactManifoldsIndices.size(); contactPair.contactPointsIndex = (uint)contactPoints.size(); // For each potential contact manifold of the pair for (uint m=0; m < contactPair.potentialContactManifoldsIndices.size(); m++) { ContactManifoldInfo& potentialManifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[m]]; // Start index and number of contact points for this manifold const uint contactPointsIndex = (uint)contactPoints.size(); const int8 nbContactPoints = static_cast<int8>(potentialManifold.potentialContactPointsIndices.size()); contactPair.nbToTalContactPoints += nbContactPoints; // We create a new contact manifold ContactManifold contactManifold(contactPair.body1Entity, contactPair.body2Entity, contactPair.collider1Entity, contactPair.collider2Entity, contactPointsIndex, nbContactPoints); // Add the contact manifold contactManifolds.add(contactManifold); assert(potentialManifold.potentialContactPointsIndices.size() > 0); // For each contact point of the manifold for (uint c=0; c < potentialManifold.potentialContactPointsIndices.size(); c++) { ContactPointInfo& potentialContactPoint = potentialContactPoints[potentialManifold.potentialContactPointsIndices[c]]; // Create a new contact point ContactPoint contactPoint(potentialContactPoint, mWorld->mConfig.persistentContactDistanceThreshold); // Add the contact point contactPoints.add(contactPoint); } } } } // Initialize the current contacts with the contacts from the previous frame (for warmstarting) void CollisionDetectionSystem::initContactsWithPreviousOnes() { // For each contact pair of the current frame for (uint i=0; i < mCurrentContactPairs->size(); i++) { ContactPair& currentContactPair = (*mCurrentContactPairs)[i]; // Find the corresponding contact pair in the previous frame (if any) auto itPrevContactPair = mPreviousMapPairIdToContactPairIndex->find(currentContactPair.pairId); // If we have found a corresponding contact pair in the previous frame if (itPrevContactPair != mPreviousMapPairIdToContactPairIndex->end()) { const uint previousContactPairIndex = itPrevContactPair->second; ContactPair& previousContactPair = (*mPreviousContactPairs)[previousContactPairIndex]; // --------------------- Contact Manifolds --------------------- // const uint contactManifoldsIndex = currentContactPair.contactManifoldsIndex; const uint nbContactManifolds = currentContactPair.nbContactManifolds; // For each current contact manifold of the current contact pair for (uint m=contactManifoldsIndex; m < contactManifoldsIndex + nbContactManifolds; m++) { assert(m < mCurrentContactManifolds->size()); ContactManifold& currentContactManifold = (*mCurrentContactManifolds)[m]; assert(currentContactManifold.nbContactPoints > 0); ContactPoint& currentContactPoint = (*mCurrentContactPoints)[currentContactManifold.contactPointsIndex]; const Vector3& currentContactPointNormal = currentContactPoint.getNormal(); // Find a similar contact manifold among the contact manifolds from the previous frame (for warmstarting) const uint previousContactManifoldIndex = previousContactPair.contactManifoldsIndex; const uint previousNbContactManifolds = previousContactPair.nbContactManifolds; for (uint p=previousContactManifoldIndex; p < previousContactManifoldIndex + previousNbContactManifolds; p++) { ContactManifold& previousContactManifold = (*mPreviousContactManifolds)[p]; assert(previousContactManifold.nbContactPoints > 0); ContactPoint& previousContactPoint = (*mPreviousContactPoints)[previousContactManifold.contactPointsIndex]; // If the previous contact manifold has a similar contact normal with the current manifold if (previousContactPoint.getNormal().dot(currentContactPointNormal) >= mWorld->mConfig.cosAngleSimilarContactManifold) { // Transfer data from the previous contact manifold to the current one currentContactManifold.frictionVector1 = previousContactManifold.frictionVector1; currentContactManifold.frictionVector2 = previousContactManifold.frictionVector2; currentContactManifold.frictionImpulse1 = previousContactManifold.frictionImpulse1; currentContactManifold.frictionImpulse2 = previousContactManifold.frictionImpulse2; currentContactManifold.frictionTwistImpulse = previousContactManifold.frictionTwistImpulse; currentContactManifold.rollingResistanceImpulse = previousContactManifold.rollingResistanceImpulse; break; } } } // --------------------- Contact Points --------------------- // const uint contactPointsIndex = currentContactPair.contactPointsIndex; const uint nbTotalContactPoints = currentContactPair.nbToTalContactPoints; // For each current contact point of the current contact pair for (uint c=contactPointsIndex; c < contactPointsIndex + nbTotalContactPoints; c++) { assert(c < mCurrentContactPoints->size()); ContactPoint& currentContactPoint = (*mCurrentContactPoints)[c]; // Find a similar contact point among the contact points from the previous frame (for warmstarting) const uint previousContactPointsIndex = previousContactPair.contactPointsIndex; const uint previousNbContactPoints = previousContactPair.nbToTalContactPoints; for (uint p=previousContactPointsIndex; p < previousContactPointsIndex + previousNbContactPoints; p++) { ContactPoint& previousContactPoint = (*mPreviousContactPoints)[p]; // If the previous contact point is very close to th current one const decimal distSquare = (currentContactPoint.getLocalPointOnShape1() - previousContactPoint.getLocalPointOnShape1()).lengthSquare(); if (distSquare <= mWorld->mConfig.persistentContactDistanceThreshold * mWorld->mConfig.persistentContactDistanceThreshold) { // Transfer data from the previous contact point to the current one currentContactPoint.setPenetrationImpulse(previousContactPoint.getPenetrationImpulse()); currentContactPoint.setIsRestingContact(previousContactPoint.getIsRestingContact()); break; } } } } } } // Remove a body from the collision detection void CollisionDetectionSystem::removeCollider(Collider* collider) { const int colliderBroadPhaseId = collider->getBroadPhaseId(); assert(colliderBroadPhaseId != -1); assert(mMapBroadPhaseIdToColliderEntity.containsKey(colliderBroadPhaseId)); // Remove all the overlapping pairs involving this collider List<uint64>& overlappingPairs = mCollidersComponents.getOverlappingPairs(collider->getEntity()); while(overlappingPairs.size() > 0) { // TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds list of the two bodies involved // Remove the overlapping pair mOverlappingPairs.removePair(overlappingPairs[0]); } mMapBroadPhaseIdToColliderEntity.remove(colliderBroadPhaseId); // Remove the body from the broad-phase mBroadPhaseSystem.removeCollider(collider); } // Ray casting method void CollisionDetectionSystem::raycast(RaycastCallback* raycastCallback, const Ray& ray, unsigned short raycastWithCategoryMaskBits) const { RP3D_PROFILE("CollisionDetectionSystem::raycast()", mProfiler); RaycastTest rayCastTest(raycastCallback); // Ask the broad-phase algorithm to call the testRaycastAgainstShape() // callback method for each collider hit by the ray in the broad-phase mBroadPhaseSystem.raycast(ray, rayCastTest, raycastWithCategoryMaskBits); } // Convert the potential contact into actual contacts void CollisionDetectionSystem::processPotentialContacts(NarrowPhaseInfoBatch& narrowPhaseInfoBatch, bool updateLastFrameInfo, List<ContactPointInfo>& potentialContactPoints, Map<uint64, uint>* mapPairIdToContactPairIndex, List<ContactManifoldInfo>& potentialContactManifolds, List<ContactPair>* contactPairs, Map<Entity, List<uint>>& mapBodyToContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::processPotentialContacts()", mProfiler); // For each narrow phase info object for(uint i=0; i < narrowPhaseInfoBatch.getNbObjects(); i++) { if (updateLastFrameInfo) { narrowPhaseInfoBatch.lastFrameCollisionInfos[i]->wasColliding = narrowPhaseInfoBatch.isColliding[i]; // The previous frame collision info is now valid narrowPhaseInfoBatch.lastFrameCollisionInfos[i]->isValid = true; } const uint64 pairId = narrowPhaseInfoBatch.overlappingPairIds[i]; const uint64 pairIndex = mOverlappingPairs.mMapPairIdToPairIndex[pairId]; // If the two colliders are colliding if (narrowPhaseInfoBatch.isColliding[i]) { mOverlappingPairs.mCollidingInCurrentFrame[pairIndex] = true; // If there is not already a contact pair for this overlapping pair auto it = mapPairIdToContactPairIndex->find(pairId); ContactPair* pairContact = nullptr; if (it == mapPairIdToContactPairIndex->end()) { // Create a new ContactPair const Entity collider1Entity = narrowPhaseInfoBatch.colliderEntities1[i]; const Entity collider2Entity = narrowPhaseInfoBatch.colliderEntities2[i]; const uint32 collider1Index = mCollidersComponents.getEntityIndex(collider1Entity); const uint32 collider2Index = mCollidersComponents.getEntityIndex(collider2Entity); const Entity body1Entity = mCollidersComponents.mBodiesEntities[collider1Index]; const Entity body2Entity = mCollidersComponents.mBodiesEntities[collider2Index]; const bool isTrigger = mCollidersComponents.mIsTrigger[collider1Index] || mCollidersComponents.mIsTrigger[collider2Index]; assert(!mWorld->mCollisionBodyComponents.getIsEntityDisabled(body1Entity) || !mWorld->mCollisionBodyComponents.getIsEntityDisabled(body2Entity)); const uint newContactPairIndex = (uint)contactPairs->size(); ContactPair overlappingPairContact(pairId, body1Entity, body2Entity, collider1Entity, collider2Entity, newContactPairIndex, mOverlappingPairs.getCollidingInPreviousFrame(pairId), isTrigger, mMemoryManager.getHeapAllocator()); contactPairs->add(overlappingPairContact); pairContact = &((*contactPairs)[newContactPairIndex]); mapPairIdToContactPairIndex->add(Pair<uint64, uint>(pairId, newContactPairIndex)); auto itbodyContactPairs = mapBodyToContactPairs.find(body1Entity); if (itbodyContactPairs != mapBodyToContactPairs.end()) { itbodyContactPairs->second.add(newContactPairIndex); } else { List<uint> contactPairs(mMemoryManager.getPoolAllocator(), 1); contactPairs.add(newContactPairIndex); mapBodyToContactPairs.add(Pair<Entity, List<uint>>(body1Entity, contactPairs)); } itbodyContactPairs = mapBodyToContactPairs.find(body2Entity); if (itbodyContactPairs != mapBodyToContactPairs.end()) { itbodyContactPairs->second.add(newContactPairIndex); } else { List<uint> contactPairs(mMemoryManager.getPoolAllocator(), 1); contactPairs.add(newContactPairIndex); mapBodyToContactPairs.add(Pair<Entity, List<uint>>(body2Entity, contactPairs)); } } else { // If a ContactPair already exists for this overlapping pair, we use this one assert(it->first == pairId); const uint pairContactIndex = it->second; pairContact = &((*contactPairs)[pairContactIndex]); } assert(pairContact != nullptr); // Add the potential contacts for (uint j=0; j < narrowPhaseInfoBatch.contactPoints[i].size(); j++) { const ContactPointInfo& contactPoint = *(narrowPhaseInfoBatch.contactPoints[i][j]); // Add the contact point to the list of potential contact points const uint contactPointIndex = static_cast<uint>(potentialContactPoints.size()); potentialContactPoints.add(contactPoint); bool similarManifoldFound = false; // For each contact manifold of the overlapping pair for (uint m=0; m < pairContact->potentialContactManifoldsIndices.size(); m++) { uint contactManifoldIndex = pairContact->potentialContactManifoldsIndices[m]; // Get the first contact point of the current manifold assert(potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.size() > 0); const uint manifoldContactPointIndex = potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices[0]; const ContactPointInfo& manifoldContactPoint = potentialContactPoints[manifoldContactPointIndex]; // If we have found a corresponding manifold for the new contact point // (a manifold with a similar contact normal direction) if (manifoldContactPoint.normal.dot(contactPoint.normal) >= mWorld->mConfig.cosAngleSimilarContactManifold) { // Add the contact point to the manifold potentialContactManifolds[contactManifoldIndex].potentialContactPointsIndices.add(contactPointIndex); similarManifoldFound = true; break; } } // If we have not found a manifold with a similar contact normal for the contact point if (!similarManifoldFound) { // Create a new contact manifold for the overlapping pair ContactManifoldInfo contactManifoldInfo(pairId, mMemoryManager.getPoolAllocator()); // Add the contact point to the manifold contactManifoldInfo.potentialContactPointsIndices.add(contactPointIndex); assert(pairContact != nullptr); // Add the potential contact manifold uint contactManifoldIndex = static_cast<uint>(potentialContactManifolds.size()); potentialContactManifolds.add(contactManifoldInfo); // Add the contact manifold to the overlapping pair contact assert(pairContact->pairId == contactManifoldInfo.pairId); pairContact->potentialContactManifoldsIndices.add(contactManifoldIndex); } assert(pairContact->potentialContactManifoldsIndices.size() > 0); } narrowPhaseInfoBatch.resetContactPoints(i); } } } // Clear the obsolete manifolds and contact points and reduce the number of contacts points of the remaining manifolds void CollisionDetectionSystem::reducePotentialContactManifolds(List<ContactPair>* contactPairs, List<ContactManifoldInfo>& potentialContactManifolds, const List<ContactPointInfo>& potentialContactPoints) const { RP3D_PROFILE("CollisionDetectionSystem::reducePotentialContactManifolds()", mProfiler); // Reduce the number of potential contact manifolds in a contact pair for (uint i=0; i < contactPairs->size(); i++) { ContactPair& contactPair = (*contactPairs)[i]; // While there are too many manifolds in the contact pair while(contactPair.potentialContactManifoldsIndices.size() > mWorld->mConfig.nbMaxContactManifolds) { // Look for a manifold with the smallest contact penetration depth. decimal minDepth = DECIMAL_LARGEST; int minDepthManifoldIndex = -1; for (uint j=0; j < contactPair.potentialContactManifoldsIndices.size(); j++) { ContactManifoldInfo& manifold = potentialContactManifolds[contactPair.potentialContactManifoldsIndices[j]]; // Get the largest contact point penetration depth of the manifold const decimal depth = computePotentialManifoldLargestContactDepth(manifold, potentialContactPoints); if (depth < minDepth) { minDepth = depth; minDepthManifoldIndex = static_cast<int>(j); } } // Remove the non optimal manifold assert(minDepthManifoldIndex >= 0); contactPair.potentialContactManifoldsIndices.removeAt(minDepthManifoldIndex); } } // Reduce the number of potential contact points in the manifolds for (uint i=0; i < contactPairs->size(); i++) { const ContactPair& pairContact = (*contactPairs)[i]; // For each potential contact manifold for (uint j=0; j < pairContact.potentialContactManifoldsIndices.size(); j++) { ContactManifoldInfo& manifold = potentialContactManifolds[pairContact.potentialContactManifoldsIndices[j]]; // If there are two many contact points in the manifold if (manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD) { Entity collider1 = mOverlappingPairs.mColliders1[mOverlappingPairs.mMapPairIdToPairIndex[manifold.pairId]]; Transform shape1LocalToWorldTransoform = mCollidersComponents.getLocalToWorldTransform(collider1); // Reduce the number of contact points in the manifold reduceContactPoints(manifold, shape1LocalToWorldTransoform, potentialContactPoints); } assert(manifold.potentialContactPointsIndices.size() <= MAX_CONTACT_POINTS_IN_MANIFOLD); } } } // Return the largest depth of all the contact points of a potential manifold decimal CollisionDetectionSystem::computePotentialManifoldLargestContactDepth(const ContactManifoldInfo& manifold, const List<ContactPointInfo>& potentialContactPoints) const { decimal largestDepth = 0.0f; assert(manifold.potentialContactPointsIndices.size() > 0); for (uint i=0; i < manifold.potentialContactPointsIndices.size(); i++) { decimal depth = potentialContactPoints[manifold.potentialContactPointsIndices[i]].penetrationDepth; if (depth > largestDepth) { largestDepth = depth; } } return largestDepth; } // Reduce the number of contact points of a potential contact manifold // This is based on the technique described by Dirk Gregorius in his // "Contacts Creation" GDC presentation. This method will reduce the number of // contact points to a maximum of 4 points (but it can be less). void CollisionDetectionSystem::reduceContactPoints(ContactManifoldInfo& manifold, const Transform& shape1ToWorldTransform, const List<ContactPointInfo>& potentialContactPoints) const { assert(manifold.potentialContactPointsIndices.size() > MAX_CONTACT_POINTS_IN_MANIFOLD); // The following algorithm only works to reduce to a maximum of 4 contact points assert(MAX_CONTACT_POINTS_IN_MANIFOLD == 4); // List of the candidate contact points indices in the manifold. Every time that we have found a // point we want to keep, we will remove it from this list List<uint> candidatePointsIndices(manifold.potentialContactPointsIndices); int8 nbReducedPoints = 0; uint pointsToKeepIndices[MAX_CONTACT_POINTS_IN_MANIFOLD]; for (int8 i=0; i<MAX_CONTACT_POINTS_IN_MANIFOLD; i++) { pointsToKeepIndices[i] = 0; } // Compute the initial contact point we need to keep. // The first point we keep is always the point in a given // constant direction (in order to always have same contact points // between frames for better stability) const Transform worldToShape1Transform = shape1ToWorldTransform.getInverse(); // Compute the contact normal of the manifold (we use the first contact point) // in the local-space of the first collision shape const Vector3 contactNormalShape1Space = worldToShape1Transform.getOrientation() * potentialContactPoints[candidatePointsIndices[0]].normal; // Compute a search direction const Vector3 searchDirection(1, 1, 1); decimal maxDotProduct = DECIMAL_SMALLEST; uint elementIndexToKeep = 0; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; decimal dotProduct = searchDirection.dot(element.localPoint1); if (dotProduct > maxDotProduct) { maxDotProduct = dotProduct; elementIndexToKeep = i; nbReducedPoints = 1; } } pointsToKeepIndices[0] = candidatePointsIndices[elementIndexToKeep]; candidatePointsIndices.removeAt(elementIndexToKeep); assert(nbReducedPoints == 1); // Compute the second contact point we need to keep. // The second point we keep is the one farthest away from the first point. decimal maxDistance = decimal(0.0); elementIndexToKeep = 0; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); const decimal distance = (pointToKeep0.localPoint1 - element.localPoint1).lengthSquare(); if (distance >= maxDistance) { maxDistance = distance; elementIndexToKeep = i; nbReducedPoints = 2; } } pointsToKeepIndices[1] = candidatePointsIndices[elementIndexToKeep]; candidatePointsIndices.removeAt(elementIndexToKeep); assert(nbReducedPoints == 2); // Compute the third contact point we need to keep. // The third point is the one producing the triangle with the larger area // with first and second point. // We compute the most positive or most negative triangle area (depending on winding) uint thirdPointMaxAreaIndex = 0; uint thirdPointMinAreaIndex = 0; decimal minArea = decimal(0.0); decimal maxArea = decimal(0.0); bool isPreviousAreaPositive = true; for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; const ContactPointInfo& pointToKeep0 = potentialContactPoints[pointsToKeepIndices[0]]; const ContactPointInfo& pointToKeep1 = potentialContactPoints[pointsToKeepIndices[1]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); assert(candidatePointsIndices[i] != pointsToKeepIndices[1]); const Vector3 newToFirst = pointToKeep0.localPoint1 - element.localPoint1; const Vector3 newToSecond = pointToKeep1.localPoint1 - element.localPoint1; // Compute the triangle area decimal area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space); if (area >= maxArea) { maxArea = area; thirdPointMaxAreaIndex = i; } if (area <= minArea) { minArea = area; thirdPointMinAreaIndex = i; } } assert(minArea <= decimal(0.0)); assert(maxArea >= decimal(0.0)); if (maxArea > (-minArea)) { isPreviousAreaPositive = true; pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMaxAreaIndex]; candidatePointsIndices.removeAt(thirdPointMaxAreaIndex); } else { isPreviousAreaPositive = false; pointsToKeepIndices[2] = candidatePointsIndices[thirdPointMinAreaIndex]; candidatePointsIndices.removeAt(thirdPointMinAreaIndex); } nbReducedPoints = 3; // Compute the 4th point by choosing the triangle that adds the most // triangle area to the previous triangle and has opposite sign area (opposite winding) decimal largestArea = decimal(0.0); // Largest area (positive or negative) elementIndexToKeep = 0; nbReducedPoints = 4; decimal area; // For each remaining candidate points for (uint i=0; i < candidatePointsIndices.size(); i++) { const ContactPointInfo& element = potentialContactPoints[candidatePointsIndices[i]]; assert(candidatePointsIndices[i] != pointsToKeepIndices[0]); assert(candidatePointsIndices[i] != pointsToKeepIndices[1]); assert(candidatePointsIndices[i] != pointsToKeepIndices[2]); // For each edge of the triangle made by the first three points for (uint j=0; j<3; j++) { uint edgeVertex1Index = j; uint edgeVertex2Index = j < 2 ? j + 1 : 0; const ContactPointInfo& pointToKeepEdgeV1 = potentialContactPoints[pointsToKeepIndices[edgeVertex1Index]]; const ContactPointInfo& pointToKeepEdgeV2 = potentialContactPoints[pointsToKeepIndices[edgeVertex2Index]]; const Vector3 newToFirst = pointToKeepEdgeV1.localPoint1 - element.localPoint1; const Vector3 newToSecond = pointToKeepEdgeV2.localPoint1 - element.localPoint1; // Compute the triangle area area = newToFirst.cross(newToSecond).dot(contactNormalShape1Space); // We are looking at the triangle with maximal area (positive or negative). // If the previous area is positive, we are looking at negative area now. // If the previous area is negative, we are looking at the positive area now. if (isPreviousAreaPositive && area <= largestArea) { largestArea = area; elementIndexToKeep = i; } else if (!isPreviousAreaPositive && area >= largestArea) { largestArea = area; elementIndexToKeep = i; } } } pointsToKeepIndices[3] = candidatePointsIndices[elementIndexToKeep]; candidatePointsIndices.removeAt(elementIndexToKeep); // Only keep the four selected contact points in the manifold manifold.potentialContactPointsIndices.clear(); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[0]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[1]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[2]); manifold.potentialContactPointsIndices.add(pointsToKeepIndices[3]); } // Report contacts and triggers void CollisionDetectionSystem::reportContactsAndTriggers() { // Report contacts and triggers to the user if (mWorld->mEventListener != nullptr) { reportContacts(*(mWorld->mEventListener), mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs); reportTriggers(*(mWorld->mEventListener), mCurrentContactPairs, mLostContactPairs); } // Report contacts for debug rendering (if enabled) if (mWorld->mIsDebugRenderingEnabled) { reportDebugRenderingContacts(mCurrentContactPairs, mCurrentContactManifolds, mCurrentContactPoints, mLostContactPairs); } mOverlappingPairs.updateCollidingInPreviousFrame(); mLostContactPairs.clear(true); } // Report all contacts to the user void CollisionDetectionSystem::reportContacts(CollisionCallback& callback, List<ContactPair>* contactPairs, List<ContactManifold>* manifolds, List<ContactPoint>* contactPoints, List<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportContacts()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld); // Call the callback method to report the contacts callback.onContact(callbackData); } } // Report all triggers to the user void CollisionDetectionSystem::reportTriggers(EventListener& eventListener, List<ContactPair>* contactPairs, List<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportTriggers()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { OverlapCallback::CallbackData callbackData(*contactPairs, lostContactPairs, true, *mWorld); // Call the callback method to report the overlapping shapes eventListener.onTrigger(callbackData); } } // Report all contacts for debug rendering void CollisionDetectionSystem::reportDebugRenderingContacts(List<ContactPair>* contactPairs, List<ContactManifold>* manifolds, List<ContactPoint>* contactPoints, List<ContactPair>& lostContactPairs) { RP3D_PROFILE("CollisionDetectionSystem::reportDebugRenderingContacts()", mProfiler); // If there are contacts if (contactPairs->size() + lostContactPairs.size() > 0) { CollisionCallback::CallbackData callbackData(contactPairs, manifolds, contactPoints, lostContactPairs, *mWorld); // Call the callback method to report the contacts mWorld->mDebugRenderer.onContact(callbackData); } } // Return true if two bodies overlap (collide) bool CollisionDetectionSystem::testOverlap(CollisionBody* body1, CollisionBody* body2) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved List<uint64> convexPairs(mMemoryManager.getPoolAllocator()); List<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false); // Compute the narrow-phase collision detection return computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, nullptr); } return false; } // Report all the bodies that overlap (collide) in the world void CollisionDetectionSystem::testOverlap(OverlapCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(narrowPhaseInput, false); // Compute the narrow-phase collision detection and report overlapping shapes computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback); } // Report all the bodies that overlap (collide) with the body in parameter void CollisionDetectionSystem::testOverlap(CollisionBody* body, OverlapCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved List<uint64> convexPairs(mMemoryManager.getPoolAllocator()); List<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, false); // Compute the narrow-phase collision detection computeNarrowPhaseOverlapSnapshot(narrowPhaseInput, &callback); } } // Test collision and report contacts between two bodies. void CollisionDetectionSystem::testCollision(CollisionBody* body1, CollisionBody* body2, CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved List<uint64> convexPairs(mMemoryManager.getPoolAllocator()); List<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body1->getEntity(), body2->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } } // Test collision and report all the contacts involving the body in parameter void CollisionDetectionSystem::testCollision(CollisionBody* body, CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Filter the overlapping pairs to get only the ones with the selected body involved List<uint64> convexPairs(mMemoryManager.getPoolAllocator()); List<uint64> concavePairs(mMemoryManager.getPoolAllocator()); filterOverlappingPairs(body->getEntity(), convexPairs, concavePairs); if (convexPairs.size() > 0 || concavePairs.size() > 0) { // Compute the middle-phase collision detection computeMiddlePhaseCollisionSnapshot(convexPairs, concavePairs, narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } } // Test collision and report contacts between each colliding bodies in the world void CollisionDetectionSystem::testCollision(CollisionCallback& callback) { NarrowPhaseInput narrowPhaseInput(mMemoryManager.getPoolAllocator(), mOverlappingPairs); // Compute the broad-phase collision detection computeBroadPhase(); // Compute the middle-phase collision detection computeMiddlePhase(narrowPhaseInput, true); // Compute the narrow-phase collision detection and report contacts computeNarrowPhaseCollisionSnapshot(narrowPhaseInput, callback); } // Filter the overlapping pairs to keep only the pairs where a given body is involved void CollisionDetectionSystem::filterOverlappingPairs(Entity bodyEntity, List<uint64>& convexPairs, List<uint64>& concavePairs) const { // For each possible collision pair of bodies for (uint i=0; i < mOverlappingPairs.getNbPairs(); i++) { if (mCollidersComponents.getBody(mOverlappingPairs.mColliders1[i]) == bodyEntity || mCollidersComponents.getBody(mOverlappingPairs.mColliders2[i]) == bodyEntity) { if (i < mOverlappingPairs.getNbConvexVsConvexPairs()) { convexPairs.add(mOverlappingPairs.mPairIds[i]); } else { concavePairs.add(mOverlappingPairs.mPairIds[i]); } } } } // Filter the overlapping pairs to keep only the pairs where two given bodies are involved void CollisionDetectionSystem::filterOverlappingPairs(Entity body1Entity, Entity body2Entity, List<uint64>& convexPairs, List<uint64>& concavePairs) const { // For each possible collision pair of bodies for (uint i=0; i < mOverlappingPairs.getNbPairs(); i++) { const Entity collider1Body = mCollidersComponents.getBody(mOverlappingPairs.mColliders1[i]); const Entity collider2Body = mCollidersComponents.getBody(mOverlappingPairs.mColliders2[i]); if ((collider1Body == body1Entity && collider2Body == body2Entity) || (collider1Body == body2Entity && collider2Body == body1Entity)) { if (i < mOverlappingPairs.getNbConvexVsConvexPairs()) { convexPairs.add(mOverlappingPairs.mPairIds[i]); } else { concavePairs.add(mOverlappingPairs.mPairIds[i]); } } } } // Return the world event listener EventListener* CollisionDetectionSystem::getWorldEventListener() { return mWorld->mEventListener; } // Return the world-space AABB of a given collider const AABB CollisionDetectionSystem::getWorldAABB(const Collider* collider) const { assert(collider->getBroadPhaseId() > -1); return mBroadPhaseSystem.getFatAABB(collider->getBroadPhaseId()); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/developer/debug/debug_agent/watchpoint.h" #include <zircon/status.h> #include <gtest/gtest.h> #include "src/developer/debug/debug_agent/arch.h" #include "src/developer/debug/debug_agent/breakpoint.h" #include "src/developer/debug/debug_agent/mock_process.h" #include "src/developer/debug/debug_agent/mock_thread.h" namespace debug_agent { namespace { using AddressRange = ::debug_ipc::AddressRange; class MockProcessDelegate : public Breakpoint::ProcessDelegate { public: zx_status_t RegisterBreakpoint(Breakpoint*, zx_koid_t, uint64_t) override { return ZX_OK; } void UnregisterBreakpoint(Breakpoint* bp, zx_koid_t process_koid, uint64_t address) override {} zx_status_t RegisterWatchpoint(Breakpoint*, zx_koid_t, const debug_ipc::AddressRange&) override { return ZX_OK; } void UnregisterWatchpoint(Breakpoint*, zx_koid_t, const debug_ipc::AddressRange&) override {} }; // If |thread| is null, it means a process-wide breakpoint. debug_ipc::ProcessBreakpointSettings CreateLocation(const MockProcess& process, const MockThread* thread, const debug_ipc::AddressRange& range) { debug_ipc::ProcessBreakpointSettings location = {}; location.process_koid = process.koid(); if (thread) location.thread_koid = thread->koid(); location.address = 0; location.address_range = range; return location; } bool ContainsKoids(const Watchpoint& watchpoint, const std::vector<zx_koid_t>& koids) { auto& installed_koids = watchpoint.installed_threads(); if (installed_koids.size() != koids.size()) { ADD_FAILURE() << "Expected " << koids.size() << " koids, got " << installed_koids.size(); return false; } for (zx_koid_t koid : koids) { if (installed_koids.count(koid) == 0) { ADD_FAILURE() << "Expected koid " << koid << " to be present."; return false; } } return true; } // Tests ------------------------------------------------------------------------------------------- const AddressRange kAddressRange = {0x1000, 0x2000}; TEST(Watchpoint, SimpleInstallAndRemove) { MockProcess process(nullptr, 0x1, "process"); MockThread* thread1 = process.AddThread(0x1001); MockProcessDelegate process_delegate; debug_ipc::BreakpointSettings settings; settings.type = debug_ipc::BreakpointType::kWrite; settings.locations.push_back(CreateLocation(process, thread1, kAddressRange)); Breakpoint breakpoint1(&process_delegate); breakpoint1.SetSettings(settings); Watchpoint watchpoint(debug_ipc::BreakpointType::kWrite, &breakpoint1, &process, kAddressRange); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); // Update should install one thread ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); EXPECT_EQ(thread1->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); EXPECT_EQ(thread1->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); // Binding again to the same breakpoint should fail. ASSERT_EQ(watchpoint.RegisterBreakpoint(&breakpoint1), ZX_ERR_ALREADY_BOUND); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); // Unregistering the breakpoint should issue an uninstall. As there are no more breakpoints, // unregistering should return false. ASSERT_FALSE(watchpoint.UnregisterBreakpoint(&breakpoint1)); ASSERT_EQ(watchpoint.breakpoints().size(), 0u); ASSERT_TRUE(ContainsKoids(watchpoint, {})); EXPECT_EQ(thread1->mock_thread_handle().WatchpointUninstallCount(kAddressRange), 1u); // Registering again should add the breakpoint again. ASSERT_EQ(watchpoint.RegisterBreakpoint(&breakpoint1), ZX_OK); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); EXPECT_EQ(thread1->mock_thread_handle().WatchpointInstallCount(kAddressRange), 2u); // Create two other threads. MockThread* thread2 = process.AddThread(0x1002); MockThread* thread3 = process.AddThread(0x1003); // Create a breakpoint that targets the second thread with the correct size. // Registering the breakpoint should only add one more install. debug_ipc::BreakpointSettings settings2; settings2.type = debug_ipc::BreakpointType::kWrite; settings2.locations.push_back(CreateLocation(process, thread2, kAddressRange)); debug_ipc::AddressRange address_range2(kAddressRange.begin(), kAddressRange.end() + 8); settings2.locations.push_back(CreateLocation(process, thread3, address_range2)); Breakpoint breakpoint2(&process_delegate); breakpoint2.SetSettings(settings2); ASSERT_EQ(watchpoint.RegisterBreakpoint(&breakpoint2), ZX_OK); ASSERT_EQ(watchpoint.breakpoints().size(), 2u); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid(), thread2->koid()})); EXPECT_EQ(thread2->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); // Removing the first breakpoint should remove the first install. // Returning true means that there are more breakpoints registered. ASSERT_TRUE(watchpoint.UnregisterBreakpoint(&breakpoint1)); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); ASSERT_TRUE(ContainsKoids(watchpoint, {thread2->koid()})); EXPECT_EQ(thread1->mock_thread_handle().WatchpointUninstallCount(kAddressRange), 2u); // Add a location for another address to the already bound breakpoint. // Add a location to the already bound breakpoint. settings2.locations.push_back(CreateLocation(process, thread3, kAddressRange)); breakpoint2.SetSettings(settings2); // Updating should've only installed for the third thread. ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread2->koid(), thread3->koid()})); EXPECT_EQ(thread3->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); // Create moar threads. MockThread* thread4 = process.AddThread(0x1004); MockThread* thread5 = process.AddThread(0x1005); MockThread* thread6 = process.AddThread(0x1006); // Create a breakpoint that spans all locations. debug_ipc::BreakpointSettings settings3; settings3.type = debug_ipc::BreakpointType::kWrite; settings3.locations.push_back(CreateLocation(process, nullptr, kAddressRange)); Breakpoint breakpoint3(&process_delegate); breakpoint3.SetSettings(settings3); // Registering the breakpoint should add a breakpoint for all threads, but only updating the ones // that are not currently installed. ASSERT_EQ(watchpoint.RegisterBreakpoint(&breakpoint3), ZX_OK); ASSERT_EQ(watchpoint.breakpoints().size(), 2u); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid(), thread2->koid(), thread3->koid(), thread4->koid(), thread5->koid(), thread6->koid()})); EXPECT_EQ(thread4->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); EXPECT_EQ(thread5->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); EXPECT_EQ(thread6->mock_thread_handle().WatchpointInstallCount(kAddressRange), 1u); // Removing the other breakpoint should not remove installs. ASSERT_TRUE(watchpoint.UnregisterBreakpoint(&breakpoint2)); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid(), thread2->koid(), thread3->koid(), thread4->koid(), thread5->koid(), thread6->koid()})); EXPECT_EQ(thread1->mock_thread_handle().TotalWatchpointUninstallCalls(), 2u); EXPECT_EQ(thread3->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); EXPECT_EQ(thread4->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); EXPECT_EQ(thread5->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); EXPECT_EQ(thread6->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); // Removing the last breakpoint should remove all the installations. // Returns false because there are no more registered breakpoints. ASSERT_FALSE(watchpoint.UnregisterBreakpoint(&breakpoint3)); ASSERT_EQ(watchpoint.breakpoints().size(), 0u); ASSERT_TRUE(ContainsKoids(watchpoint, {})); EXPECT_EQ(thread1->mock_thread_handle().TotalWatchpointUninstallCalls(), 3u); EXPECT_EQ(thread2->mock_thread_handle().TotalWatchpointUninstallCalls(), 1u); EXPECT_EQ(thread3->mock_thread_handle().TotalWatchpointUninstallCalls(), 1u); EXPECT_EQ(thread4->mock_thread_handle().TotalWatchpointUninstallCalls(), 1u); EXPECT_EQ(thread5->mock_thread_handle().TotalWatchpointUninstallCalls(), 1u); EXPECT_EQ(thread6->mock_thread_handle().TotalWatchpointUninstallCalls(), 1u); } TEST(Watchpoint, InstalledRanges) { MockProcess process(nullptr, 0x1, "process"); MockThread* thread1 = process.AddThread(0x1001); MockProcessDelegate process_delegate; debug_ipc::BreakpointSettings settings; settings.type = debug_ipc::BreakpointType::kWrite; settings.locations.push_back(CreateLocation(process, thread1, kAddressRange)); Breakpoint breakpoint1(&process_delegate); breakpoint1.SetSettings(settings); Watchpoint watchpoint(debug_ipc::BreakpointType::kWrite, &breakpoint1, &process, kAddressRange); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); const debug_ipc::AddressRange kSubRange = {0x900, 0x2100}; constexpr int kSlot = 1; thread1->mock_thread_handle().set_watchpoint_range_to_return(kSubRange); thread1->mock_thread_handle().set_watchpoint_slot_to_return(kSlot); // Update should install one thread ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); // There should be an install with a different sub range. auto installs = thread1->mock_thread_handle().watchpoint_installs(); ASSERT_EQ(installs.size(), 1u); EXPECT_EQ(installs[0].address_range, kAddressRange); EXPECT_EQ(installs[0].type, debug_ipc::BreakpointType::kWrite); EXPECT_EQ(thread1->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); // The installed and actual range should be differnt. { auto& installations = watchpoint.installed_threads(); ASSERT_EQ(installations.size(), 1u); auto it = installations.find(thread1->koid()); ASSERT_NE(it, installations.end()); EXPECT_EQ(it->second.range, kSubRange); EXPECT_EQ(it->second.slot, kSlot); } } TEST(Watchpoint, MatchesException) { MockProcess process(nullptr, 0x1, "process"); MockThread* thread1 = process.AddThread(0x1001); MockThread* thread2 = process.AddThread(0x1002); MockProcessDelegate process_delegate; debug_ipc::BreakpointSettings settings; settings.type = debug_ipc::BreakpointType::kWrite; settings.locations.push_back(CreateLocation(process, thread1, kAddressRange)); Breakpoint breakpoint1(&process_delegate); breakpoint1.SetSettings(settings); Watchpoint watchpoint(debug_ipc::BreakpointType::kWrite, &breakpoint1, &process, kAddressRange); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); const debug_ipc::AddressRange kSubRange = {0x900, 0x2100}; constexpr int kSlot = 1; thread1->mock_thread_handle().set_watchpoint_range_to_return(kSubRange); thread1->mock_thread_handle().set_watchpoint_slot_to_return(kSlot); // Update should install one thread ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); // There should be an install with a different sub range. auto installs = thread1->mock_thread_handle().watchpoint_installs(); ASSERT_EQ(installs.size(), 1u); EXPECT_EQ(installs[0].address_range, kAddressRange); EXPECT_EQ(thread1->mock_thread_handle().TotalWatchpointUninstallCalls(), 0u); // The installed and actual range should be differnt. { auto& installations = watchpoint.installed_threads(); ASSERT_EQ(installations.size(), 1u); auto it = installations.find(thread1->koid()); ASSERT_NE(it, installations.end()); EXPECT_EQ(it->second.range, kSubRange); EXPECT_EQ(it->second.slot, kSlot); // Only same slot and within range should work. EXPECT_FALSE(watchpoint.MatchesException(thread1->koid(), kSubRange.begin() - 1, kSlot)); EXPECT_TRUE(watchpoint.MatchesException(thread1->koid(), kSubRange.begin(), kSlot)); EXPECT_TRUE(watchpoint.MatchesException(thread1->koid(), kSubRange.begin() + 1, kSlot)); EXPECT_TRUE(watchpoint.MatchesException(thread1->koid(), kSubRange.end() - 1, kSlot)); EXPECT_FALSE(watchpoint.MatchesException(thread1->koid(), kSubRange.end(), kSlot)); // Different slot should fail. EXPECT_FALSE(watchpoint.MatchesException(thread1->koid(), kSubRange.begin(), kSlot + 1)); // Different thread should fail. EXPECT_FALSE(watchpoint.MatchesException(thread2->koid(), kSubRange.begin(), kSlot)); } } TEST(Watchpoint, DifferentTypes) { MockProcess process(nullptr, 0x1, "process"); MockThread* thread1 = process.AddThread(0x1001); MockProcessDelegate process_delegate; debug_ipc::BreakpointSettings settings; settings.locations.push_back(CreateLocation(process, thread1, kAddressRange)); { Breakpoint breakpoint1(&process_delegate); settings.type = debug_ipc::BreakpointType::kWrite; breakpoint1.SetSettings(settings); Watchpoint watchpoint(debug_ipc::BreakpointType::kWrite, &breakpoint1, &process, kAddressRange); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); // There should be an install with a different sub range. auto installs = thread1->mock_thread_handle().watchpoint_installs(); ASSERT_EQ(installs.size(), 1u); EXPECT_EQ(installs[0].address_range, kAddressRange); EXPECT_EQ(installs[0].type, debug_ipc::BreakpointType::kWrite); } { Breakpoint breakpoint1(&process_delegate); settings.type = debug_ipc::BreakpointType::kReadWrite; breakpoint1.SetSettings(settings); Watchpoint watchpoint(debug_ipc::BreakpointType::kReadWrite, &breakpoint1, &process, kAddressRange); ASSERT_EQ(watchpoint.breakpoints().size(), 1u); ASSERT_EQ(watchpoint.Update(), ZX_OK); ASSERT_TRUE(ContainsKoids(watchpoint, {thread1->koid()})); // There should be an install with a different sub range. auto installs = thread1->mock_thread_handle().watchpoint_installs(); ASSERT_EQ(installs.size(), 2u); EXPECT_EQ(installs[1].address_range, kAddressRange); EXPECT_EQ(installs[1].type, debug_ipc::BreakpointType::kReadWrite); } } } // namespace } // namespace debug_agent
// Copyright (C) 2015 The Regents of the University of California (Regents). // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of The Regents or University of California nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #include <Eigen/Core> #include <Eigen/Geometry> #include <glog/logging.h> #include <algorithm> #include <utility> #include <vector> #include <string> #include "gtest/gtest.h" #include "theia/sfm/reconstruction.h" #include "theia/sfm/types.h" #include "theia/sfm/transformation/align_reconstructions.h" #include "theia/sfm/transformation/transform_reconstruction.h" #include "theia/util/stringprintf.h" namespace theia { Camera RandomCamera() { Camera camera; camera.SetPosition(10 * Eigen::Vector3d::Random()); camera.SetOrientationFromAngleAxis(0.2 * Eigen::Vector3d::Random()); camera.SetImageSize(1000, 1000); camera.SetFocalLength(800); camera.SetAspectRatio(1.0); camera.SetSkew(0.0); camera.SetPrincipalPoint(500.0, 500.0); return camera; } void BuildReconstructions(const int num_views, const int num_tracks, Reconstruction* reconstruction1, Reconstruction* reconstruction2) { for (int i = 0; i < num_views; i++) { const std::string name = StringPrintf("%d", i); const ViewId view_id1 = reconstruction1->AddView(name); const ViewId view_id2 = reconstruction2->AddView(name); Camera camera = RandomCamera(); *reconstruction1->MutableView(view_id1)->MutableCamera() = camera; *reconstruction2->MutableView(view_id2)->MutableCamera() = camera; reconstruction1->MutableView(view_id1)->SetEstimated(true); reconstruction2->MutableView(view_id2)->SetEstimated(true); } const std::vector<std::pair<ViewId, Feature> > track = {{0, Feature(0, 0)}, {1, Feature(0, 0)}}; for (int i = 0; i < num_tracks; i++) { const TrackId track_id1 = reconstruction1->AddTrack(track); const TrackId track_id2 = reconstruction2->AddTrack(track); const Eigen::Vector4d point = Eigen::Vector4d::Random(); *reconstruction1->MutableTrack(track_id1)->MutablePoint() = point; *reconstruction2->MutableTrack(track_id2)->MutablePoint() = point; reconstruction1->MutableTrack(track_id1)->SetEstimated(true); reconstruction2->MutableTrack(track_id2)->SetEstimated(true); } } void VerifyAlignment(const Reconstruction& reconstruction1, const Reconstruction& reconstruction2) { static const double kTolerance = 1e-8; for (const ViewId view_id : reconstruction1.ViewIds()) { const Camera& camera1 = reconstruction1.View(view_id)->Camera(); const Camera& camera2 = reconstruction2.View(view_id)->Camera(); // Verify rotation. const Eigen::Vector3d rotation1 = camera1.GetOrientationAsAngleAxis(); const Eigen::Vector3d rotation2 = camera2.GetOrientationAsAngleAxis(); EXPECT_LT((rotation1 - rotation2).norm(), kTolerance); // Verify position. const Eigen::Vector3d position1 = camera1.GetPosition(); const Eigen::Vector3d position2 = camera2.GetPosition(); EXPECT_LT((position1 - position2).norm(), kTolerance) << "Position1 = " << position1.transpose() << " position2 = " << position2.transpose(); } for (const TrackId track_id : reconstruction1.TrackIds()) { const Eigen::Vector3d point1 = reconstruction1.Track(track_id)->Point().hnormalized(); const Eigen::Vector3d point2 = reconstruction2.Track(track_id)->Point().hnormalized(); EXPECT_LT((point1 - point2).norm(), kTolerance) << "Point 1 = " << point1.transpose() << " point 2 = " << point2.transpose(); } } void TestAlignReconstructions(const int num_views, const int num_tracks, const Eigen::Matrix3d rotation, const Eigen::Vector3d translation, const double scale) { Reconstruction reconstruction1, reconstruction2; BuildReconstructions(num_views, num_tracks, &reconstruction1, &reconstruction2); TransformReconstruction(rotation, translation, scale, &reconstruction1); AlignReconstructions(reconstruction1, &reconstruction2); VerifyAlignment(reconstruction1, reconstruction2); } TEST(AlignReconstructions, Identity) { static const int kNumViews = 10; static const int kNumTracks = 20; const Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity(); const Eigen::Vector3d translation = Eigen::Vector3d::Zero(); const double scale = 1.0; TestAlignReconstructions(kNumViews, kNumTracks, rotation, translation, scale); } TEST(AlignReconstructions, Scale) { static const int kNumViews = 10; static const int kNumTracks = 20; const Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity(); const Eigen::Vector3d translation = Eigen::Vector3d::Zero(); const double scale = 5.3; TestAlignReconstructions(kNumViews, kNumTracks, rotation, translation, scale); } TEST(AlignReconstructions, Rotation) { static const int kNumViews = 10; static const int kNumTracks = 20; const Eigen::Vector3d rotation_aa = Eigen::Vector3d::Random(); const Eigen::Matrix3d rotation = Eigen::AngleAxisd(rotation_aa.norm(), rotation_aa.normalized()) .toRotationMatrix(); const Eigen::Vector3d translation = Eigen::Vector3d::Zero(); const double scale = 1.0; TestAlignReconstructions(kNumViews, kNumTracks, rotation, translation, scale); } TEST(AlignReconstructions, Translation) { static const int kNumViews = 10; static const int kNumTracks = 20; const Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity(); const Eigen::Vector3d translation = Eigen::Vector3d::Random(); const double scale = 1.0; TestAlignReconstructions(kNumViews, kNumTracks, rotation, translation, scale); } TEST(AlignReconstructions, SimilarityTransformation) { static const int kNumViews = 10; static const int kNumTracks = 20; const Eigen::Vector3d rotation_aa = Eigen::Vector3d::Random(); const Eigen::Matrix3d rotation = Eigen::AngleAxisd(rotation_aa.norm(), rotation_aa.normalized()) .toRotationMatrix(); const Eigen::Vector3d translation = Eigen::Vector3d::Random(); const double scale = 4.2; TestAlignReconstructions(kNumViews, kNumTracks, rotation, translation, scale); } } // namespace theia
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000079dbd0ea897d280a549dc6defcab1128982d75468927cdfe86e6b85883b")) ( 1, uint256("0x000001a3ddc783686b66f1911e14750c9f33e1b360327ee71f2dda7258c785cb")) ; static const CCheckpointData data = { &mapCheckpoints, 1394545186, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 1000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x332865499df77f269f1fa1c640075275abc3b452c21619bfe05f757a65a46c48")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1394545201, 0, 100 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } uint256 GetLatestHardenedCheckpoint() { const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return (checkpoints.rbegin()->second); } }
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/SimpleTypes.hpp> #include <RED4ext/Types/generated/world/Node.hpp> namespace RED4ext { namespace world { struct Effect; } namespace world { struct EffectNode : world::Node { static constexpr const char* NAME = "worldEffectNode"; static constexpr const char* ALIAS = NAME; RaRef<world::Effect> effect; // 38 float streamingDistanceOverride; // 40 uint8_t unk44[0x48 - 0x44]; // 44 }; RED4EXT_ASSERT_SIZE(EffectNode, 0x48); } // namespace world } // namespace RED4ext
/* * Copyright 2019 Codeplay Software Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "snn_fixture.h" #include "src/backend/snn_backend_provider.h" #include "sycldnn/backend/snn_backend.h" #include "sycldnn/conv2d/conv_type.h" #define BM_WITH_DIR_DTYPE(DIR, DTYPE) \ DEPTHWISE_CONVOLUTION_BENCHMARK(DIR, sycldnn::backend::SNNBackend, DTYPE, \ sycldnn::conv2d::conv_type::DIR) #define BM_WITH_DIR(DIR) BM_WITH_DIR_DTYPE(DIR, float) BM_WITH_DIR(Forward); BM_WITH_DIR(InputBackprop); BM_WITH_DIR(FilterBackprop);
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ #include <Xm/RowColumn.h> #include <Xm/Form.h> #include <Xm/LabelG.h> #include "AddBaseClassAction.h" #include "ComboBox.h" CAddBaseClassAction::CAddBaseClassAction():CImpactAction("Inherit Class"){ m_ClassesList = NULL; m_pAvailable = NULL; } CAddBaseClassAction::~CAddBaseClassAction() { m_ClassesList=NULL; if(m_pAvailable != NULL) delete m_pAvailable; } Widget CAddBaseClassAction::GetAttributesArea(Widget parent, symbolPtr* pSym){ XmString labelStr; Widget area = XtVaCreateWidget("area", xmFormWidgetClass, parent, XmNwidth, 300, XmNheight, 30, XmNnumColumns, 2, XmNpacking, XmPACK_COLUMN, XmNorientation, XmVERTICAL, NULL); labelStr = XmStringCreateLocalized("Class:"); Widget labelWidget = XtVaCreateManagedWidget("label_1",xmLabelGadgetClass, area, XmNlabelString, labelStr, XmNwidth, 100, XmNtopAttachment,XmATTACH_FORM, XmNleftAttachment,XmATTACH_FORM, XmNbottomAttachment,XmATTACH_FORM, NULL); XmStringFree(labelStr); m_ClassesList = XtVaCreateManagedWidget("classeslist", dtComboBoxWidgetClass, area, XmNtopAttachment,XmATTACH_FORM, XmNleftAttachment,XmATTACH_WIDGET, XmNleftWidget, labelWidget, XmNrightAttachment,XmATTACH_FORM, XmNbottomAttachment,XmATTACH_FORM, NULL); string result; string command; setWait(true); // now get all available class except inherited string id = prepareQuery(CEntityInfo::etag(pSym)); command = string("printformat \"%s\t%s\" name etag;source_dis closure.dis;") + string("sort name [set_subtract") + string(" [set_subtract") + string(" [set_subtract") + string(" [defines -classes /] [set_copy " + id + "]]") + string(" [query_closure 50 \"get_super_classes\" " + id + " ]]") + string(" [query_closure 50 \"get_sub_classes\" " + id + " ]]"); CEntityInfo::exec(command,result); m_pAvailable = new CQueryResult(); m_pAvailable->parse(result); if(m_pAvailable->getRecordsCount()>0) { TRecordSetIterator iter = m_pAvailable->getStartRecord(); TRecordSetIterator end = m_pAvailable->getEndRecord(); CQueryResult DeletedRecords; while(iter!=end) { TRecord* pRecord = *iter; TField* pName = (*pRecord)[1]; bool bAnon = pName->find("<anonymous")!=string::npos; bool bUnnamed = pName->find("<unnamed")!=string::npos; if(pName->length()!=0 && !bAnon && !bUnnamed) { labelStr = XmStringCreateLocalized((char*)pName->c_str()); DtComboBoxAddItem(m_ClassesList, labelStr, 0, false); XmStringFree(labelStr); } else DeletedRecords.add(pRecord); iter++; } iter = DeletedRecords.getStartRecord(); end = DeletedRecords.getEndRecord(); while(iter!=end) { TRecord* pRecord = *iter; m_pAvailable->remove(pRecord); iter++; } } setWait(false); return area; } bool CAddBaseClassAction::ActionPerformed(symbolPtr* pSym) { CImpactAction::ActionPerformed(pSym); int selectedPosition; XtVaGetValues(m_ClassesList, XmNselectedPosition, &selectedPosition, NULL); TRecord* pRecord = m_pAvailable->getRecord(selectedPosition); SetDescription(GetName()+string(" ")+*(*pRecord)[1]); string command = "Impact:AddBaseClass " + prepareQuery(CEntityInfo::etag(pSym)) + " " + prepareQuery(*(*pRecord)[2]); string results; CEntityInfo::exec(command,results); parseResult(results); return true; }
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_android.h" #include "chrome/browser/android/tab_android.h" #include "chrome/browser/ui/android/tab_model/tab_model.h" #include "chrome/browser/ui/android/tab_model/tab_model_list.h" #include "components/javascript_dialogs/android/tab_modal_dialog_view_android.h" JavaScriptTabModalDialogManagerDelegateAndroid:: JavaScriptTabModalDialogManagerDelegateAndroid( content::WebContents* web_contents) : web_contents_(web_contents) {} JavaScriptTabModalDialogManagerDelegateAndroid:: ~JavaScriptTabModalDialogManagerDelegateAndroid() = default; // Note on the two callbacks: |dialog_callback_on_button_clicked| is for the // case where user responds to the dialog. |dialog_callback_on_cancelled| is // for the case where user cancels the dialog without interacting with the // dialog (e.g. clicks the navigate back button on Android). base::WeakPtr<javascript_dialogs::TabModalDialogView> JavaScriptTabModalDialogManagerDelegateAndroid::CreateNewDialog( content::WebContents* alerting_web_contents, const base::string16& title, content::JavaScriptDialogType dialog_type, const base::string16& message_text, const base::string16& default_prompt_text, content::JavaScriptDialogManager::DialogClosedCallback callback_on_button_clicked, base::OnceClosure callback_on_cancelled) { return javascript_dialogs::TabModalDialogViewAndroid::Create( web_contents_, alerting_web_contents, title, dialog_type, message_text, default_prompt_text, std::move(callback_on_button_clicked), std::move(callback_on_cancelled)); } void JavaScriptTabModalDialogManagerDelegateAndroid::WillRunDialog() {} void JavaScriptTabModalDialogManagerDelegateAndroid::DidCloseDialog() {} void JavaScriptTabModalDialogManagerDelegateAndroid::SetTabNeedsAttention( bool attention) {} bool JavaScriptTabModalDialogManagerDelegateAndroid::IsWebContentsForemost() { TabModel* tab_model = TabModelList::GetTabModelForWebContents(web_contents_); if (tab_model) { return tab_model->IsActiveModel() && tab_model->GetActiveWebContents() == web_contents_; } else { // If tab model is not found (e.g. single tab model), fall back to check // whether the tab for this web content is interactive. TabAndroid* tab = TabAndroid::FromWebContents(web_contents_); return tab && tab->IsUserInteractable(); } } bool JavaScriptTabModalDialogManagerDelegateAndroid::IsApp() { return false; }
// Copyright (c) 2012-2016 The TMIcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include "cuckoocache.h" #include "script/sigcache.h" #include "test/test_tmicoin.h" #include "random.h" #include <thread> /** Test Suite for CuckooCache * * 1) All tests should have a deterministic result (using insecure rand * with deterministic seeds) * 2) Some test methods are templated to allow for easier testing * against new versions / comparing * 3) Results should be treated as a regression test, i.e., did the behavior * change significantly from what was expected. This can be OK, depending on * the nature of the change, but requires updating the tests to reflect the new * expected behavior. For example improving the hit rate may cause some tests * using BOOST_CHECK_CLOSE to fail. * */ FastRandomContext local_rand_ctx(true); BOOST_AUTO_TEST_SUITE(cuckoocache_tests); /** insecure_GetRandHash fills in a uint256 from local_rand_ctx */ void insecure_GetRandHash(uint256& t) { uint32_t* ptr = (uint32_t*)t.begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = local_rand_ctx.rand32(); } /* Test that no values not inserted into the cache are read out of it. * * There are no repeats in the first 200000 insecure_GetRandHash calls */ BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes) { local_rand_ctx = FastRandomContext(true); CuckooCache::cache<uint256, SignatureCacheHasher> cc{}; size_t megabytes = 4; cc.setup_bytes(megabytes << 20); uint256 v; for (int x = 0; x < 100000; ++x) { insecure_GetRandHash(v); cc.insert(v); } for (int x = 0; x < 100000; ++x) { insecure_GetRandHash(v); BOOST_CHECK(!cc.contains(v, false)); } }; /** This helper returns the hit rate when megabytes*load worth of entries are * inserted into a megabytes sized cache */ template <typename Cache> double test_cache(size_t megabytes, double load) { local_rand_ctx = FastRandomContext(true); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = local_rand_ctx.rand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; /** Do the insert */ for (uint256& h : hashes_insert_copy) set.insert(h); /** Count the hits */ uint32_t count = 0; for (uint256& h : hashes) count += set.contains(h, false); double hit_rate = ((double)count) / ((double)n_insert); return hit_rate; } /** The normalized hit rate for a given load. * * The semantics are a little confusing, so please see the below * explanation. * * Examples: * * 1) at load 0.5, we expect a perfect hit rate, so we multiply by * 1.0 * 2) at load 2.0, we expect to see half the entries, so a perfect hit rate * would be 0.5. Therefore, if we see a hit rate of 0.4, 0.4*2.0 = 0.8 is the * normalized hit rate. * * This is basically the right semantics, but has a bit of a glitch depending on * how you measure around load 1.0 as after load 1.0 your normalized hit rate * becomes effectively perfect, ignoring freshness. */ double normalize_hit_rate(double hits, double load) { return hits * std::max(load, 1.0); } /** Check the hit rate on loads ranging from 0.1 to 2.0 */ BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok) { /** Arbitrarily selected Hit Rate threshold that happens to work for this test * as a lower bound on performance. */ double HitRateThresh = 0.98; size_t megabytes = 4; for (double load = 0.1; load < 2; load *= 2) { double hits = test_cache<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes, load); BOOST_CHECK(normalize_hit_rate(hits, load) > HitRateThresh); } } /** This helper checks that erased elements are preferentially inserted onto and * that the hit rate of "fresher" keys is reasonable*/ template <typename Cache> void test_cache_erase(size_t megabytes) { double load = 1; local_rand_ctx = FastRandomContext(true); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = local_rand_ctx.rand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; /** Insert the first half */ for (uint32_t i = 0; i < (n_insert / 2); ++i) set.insert(hashes_insert_copy[i]); /** Erase the first quarter */ for (uint32_t i = 0; i < (n_insert / 4); ++i) set.contains(hashes[i], true); /** Insert the second half */ for (uint32_t i = (n_insert / 2); i < n_insert; ++i) set.insert(hashes_insert_copy[i]); /** elements that we marked erased but that are still there */ size_t count_erased_but_contained = 0; /** elements that we did not erase but are older */ size_t count_stale = 0; /** elements that were most recently inserted */ size_t count_fresh = 0; for (uint32_t i = 0; i < (n_insert / 4); ++i) count_erased_but_contained += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i) count_stale += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 2); i < n_insert; ++i) count_fresh += set.contains(hashes[i], false); double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0); double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0); double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0); // Check that our hit_rate_fresh is perfect BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0); // Check that we have a more than 2x better hit rate on stale elements than // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } BOOST_AUTO_TEST_CASE(cuckoocache_erase_ok) { size_t megabytes = 4; test_cache_erase<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes); } template <typename Cache> void test_cache_erase_parallel(size_t megabytes) { double load = 1; local_rand_ctx = FastRandomContext(true); std::vector<uint256> hashes; Cache set{}; size_t bytes = megabytes * (1 << 20); set.setup_bytes(bytes); uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); hashes.resize(n_insert); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)hashes[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = local_rand_ctx.rand32(); } /** We make a copy of the hashes because future optimizations of the * cuckoocache may overwrite the inserted element, so the test is * "future proofed". */ std::vector<uint256> hashes_insert_copy = hashes; boost::shared_mutex mtx; { /** Grab lock to make sure we release inserts */ boost::unique_lock<boost::shared_mutex> l(mtx); /** Insert the first half */ for (uint32_t i = 0; i < (n_insert / 2); ++i) set.insert(hashes_insert_copy[i]); } /** Spin up 3 threads to run contains with erase. */ std::vector<std::thread> threads; /** Erase the first quarter */ for (uint32_t x = 0; x < 3; ++x) /** Each thread is emplaced with x copy-by-value */ threads.emplace_back([&, x] { boost::shared_lock<boost::shared_mutex> l(mtx); size_t ntodo = (n_insert/4)/3; size_t start = ntodo*x; size_t end = ntodo*(x+1); for (uint32_t i = start; i < end; ++i) set.contains(hashes[i], true); }); /** Wait for all threads to finish */ for (std::thread& t : threads) t.join(); /** Grab lock to make sure we observe erases */ boost::unique_lock<boost::shared_mutex> l(mtx); /** Insert the second half */ for (uint32_t i = (n_insert / 2); i < n_insert; ++i) set.insert(hashes_insert_copy[i]); /** elements that we marked erased but that are still there */ size_t count_erased_but_contained = 0; /** elements that we did not erase but are older */ size_t count_stale = 0; /** elements that were most recently inserted */ size_t count_fresh = 0; for (uint32_t i = 0; i < (n_insert / 4); ++i) count_erased_but_contained += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i) count_stale += set.contains(hashes[i], false); for (uint32_t i = (n_insert / 2); i < n_insert; ++i) count_fresh += set.contains(hashes[i], false); double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0); double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0); double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0); // Check that our hit_rate_fresh is perfect BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0); // Check that we have a more than 2x better hit rate on stale elements than // erased elements. BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained); } BOOST_AUTO_TEST_CASE(cuckoocache_erase_parallel_ok) { size_t megabytes = 4; test_cache_erase_parallel<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes); } template <typename Cache> void test_cache_generations() { // This test checks that for a simulation of network activity, the fresh hit // rate is never below 99%, and the number of times that it is worse than // 99.9% are less than 1% of the time. double min_hit_rate = 0.99; double tight_hit_rate = 0.999; double max_rate_less_than_tight_hit_rate = 0.01; // A cache that meets this specification is therefore shown to have a hit // rate of at least tight_hit_rate * (1 - max_rate_less_than_tight_hit_rate) + // min_hit_rate*max_rate_less_than_tight_hit_rate = 0.999*99%+0.99*1% == 99.89% // hit rate with low variance. // We use deterministic values, but this test has also passed on many // iterations with non-deterministic values, so it isn't "overfit" to the // specific entropy in FastRandomContext(true) and implementation of the // cache. local_rand_ctx = FastRandomContext(true); // block_activity models a chunk of network activity. n_insert elements are // adde to the cache. The first and last n/4 are stored for removal later // and the middle n/2 are not stored. This models a network which uses half // the signatures of recently (since the last block) added transactions // immediately and never uses the other half. struct block_activity { std::vector<uint256> reads; block_activity(uint32_t n_insert, Cache& c) : reads() { std::vector<uint256> inserts; inserts.resize(n_insert); reads.reserve(n_insert / 2); for (uint32_t i = 0; i < n_insert; ++i) { uint32_t* ptr = (uint32_t*)inserts[i].begin(); for (uint8_t j = 0; j < 8; ++j) *(ptr++) = local_rand_ctx.rand32(); } for (uint32_t i = 0; i < n_insert / 4; ++i) reads.push_back(inserts[i]); for (uint32_t i = n_insert - (n_insert / 4); i < n_insert; ++i) reads.push_back(inserts[i]); for (auto h : inserts) c.insert(h); } }; const uint32_t BLOCK_SIZE = 1000; // We expect window size 60 to perform reasonably given that each epoch // stores 45% of the cache size (~472k). const uint32_t WINDOW_SIZE = 60; const uint32_t POP_AMOUNT = (BLOCK_SIZE / WINDOW_SIZE) / 2; const double load = 10; const size_t megabytes = 4; const size_t bytes = megabytes * (1 << 20); const uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256))); std::vector<block_activity> hashes; Cache set{}; set.setup_bytes(bytes); hashes.reserve(n_insert / BLOCK_SIZE); std::deque<block_activity> last_few; uint32_t out_of_tight_tolerance = 0; uint32_t total = n_insert / BLOCK_SIZE; // we use the deque last_few to model a sliding window of blocks. at each // step, each of the last WINDOW_SIZE block_activities checks the cache for // POP_AMOUNT of the hashes that they inserted, and marks these erased. for (uint32_t i = 0; i < total; ++i) { if (last_few.size() == WINDOW_SIZE) last_few.pop_front(); last_few.emplace_back(BLOCK_SIZE, set); uint32_t count = 0; for (auto& act : last_few) for (uint32_t k = 0; k < POP_AMOUNT; ++k) { count += set.contains(act.reads.back(), true); act.reads.pop_back(); } // We use last_few.size() rather than WINDOW_SIZE for the correct // behavior on the first WINDOW_SIZE iterations where the deque is not // full yet. double hit = (double(count)) / (last_few.size() * POP_AMOUNT); // Loose Check that hit rate is above min_hit_rate BOOST_CHECK(hit > min_hit_rate); // Tighter check, count number of times we are less than tight_hit_rate // (and implicitly, greater than min_hit_rate) out_of_tight_tolerance += hit < tight_hit_rate; } // Check that being out of tolerance happens less than // max_rate_less_than_tight_hit_rate of the time BOOST_CHECK(double(out_of_tight_tolerance) / double(total) < max_rate_less_than_tight_hit_rate); } BOOST_AUTO_TEST_CASE(cuckoocache_generations) { test_cache_generations<CuckooCache::cache<uint256, SignatureCacheHasher>>(); } BOOST_AUTO_TEST_SUITE_END();
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkImageModelEstimatorBase_hxx #define itkImageModelEstimatorBase_hxx #include "itkCommand.h" namespace itk { template <typename TInputImage, typename TMembershipFunction> ImageModelEstimatorBase<TInputImage, TMembershipFunction>::ImageModelEstimatorBase() = default; template <typename TInputImage, typename TMembershipFunction> void ImageModelEstimatorBase<TInputImage, TMembershipFunction>::Update() { GenerateData(); } template <typename TInputImage, typename TMembershipFunction> void ImageModelEstimatorBase<TInputImage, TMembershipFunction>::GenerateData() { this->EstimateModels(); } /** * PrintSelf */ template <typename TInputImage, typename TMembershipFunction> void ImageModelEstimatorBase<TInputImage, TMembershipFunction>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Number of models: " << m_NumberOfModels << std::endl; os << indent << " " << std::endl; os << indent << "Results of the model estimator." << std::endl; os << indent << "====================================" << std::endl; for (unsigned int classIndex = 0; classIndex < m_NumberOfModels; ++classIndex) { os << indent << "Statistics for " << classIndex << std::endl; (m_MembershipFunctions[classIndex])->Print(os); os << indent << "====================================" << std::endl; } os << indent << " " << std::endl; os << indent << "InputImage: "; os << m_InputImage.GetPointer() << std::endl; } // end PrintSelf //------------------------------------------------------------------ // Add a membership function corresponding to the class index //------------------------------------------------------------------ template <typename TInputImage, typename TMembershipFunction> unsigned int ImageModelEstimatorBase<TInputImage, TMembershipFunction>::AddMembershipFunction(MembershipFunctionPointer function) { m_MembershipFunctions.push_back(function); return static_cast<unsigned int>(m_MembershipFunctions.size()); } } // namespace itk #endif
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2011-2022 Jose Luis Blanco (joseluisblancoc@gmail.com). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #include <cstdlib> #include <ctime> #include <flann/flann.hpp> #include <fstream> #include <iostream> #include <string> using namespace std; using namespace flann; // Scan all points from file template <typename T> Matrix<T> scanPointCloud(unsigned int &N, string file) { ifstream read(file.c_str()); string temp; getline(read, temp); vector<vector<T>> cloud; vector<T> tmp; int dim = 3; T x, y, z, d; N = 0; while (read >> x >> y >> z >> d) { tmp.resize(dim); tmp[0] = x; tmp[1] = y; tmp[2] = z; cloud.push_back(tmp); N++; } Matrix<T> point(new T[N * dim], N, 3); for (unsigned int i = 0; i < N; i++) { for (unsigned int j = 0; j < dim; j++) { point[i][j] = cloud[i][j]; } } return point; } template <typename num_t> void kdtree_demo(string &path1, string &path2) { Matrix<num_t> PcloudS, PcloudT; unsigned int N; // Scan points from file PcloudS = scanPointCloud<num_t>(N, path1); PcloudT = scanPointCloud<num_t>(N, path2); // buildTime : time required to build the kd-tree index // queryTime : time required to find nearest neighbor for a single point in // the kd-tree vector<double> buildTime, queryTime; unsigned int plotCount = 10, nn = 1, dim = 3; for (unsigned int i = 1; i <= plotCount; i++) { // size of dataset currently being used unsigned int currSize = ((i * 1.0) / plotCount) * N; std::cout << currSize << " "; Matrix<num_t> cloudS(new num_t[currSize * dim], currSize, dim); Matrix<num_t> cloudT(new num_t[currSize * dim], currSize, dim); for (unsigned int j = 0; j < currSize; j++) { for (unsigned int k = 0; k < dim; k++) { cloudS[j][k] = PcloudS[j][k]; cloudT[j][k] = PcloudT[j][k]; } } clock_t begin = clock(); // construct a kd-tree index: Index<L2<num_t>> index(cloudS, flann::KDTreeIndexParams(1)); index.buildIndex(); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; buildTime.push_back(elapsed_secs); { Matrix<int> indices(new int[cloudT.rows * nn], cloudT.rows, nn); Matrix<num_t> dists(new num_t[cloudT.rows * nn], cloudT.rows, nn); clock_t begin = clock(); // do a knn search index.knnSearch(cloudT, indices, dists, nn, flann::SearchParams(-1)); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; queryTime.push_back(elapsed_secs / currSize); } } std::cout << "\n"; for (unsigned int i = 0; i < buildTime.size(); i++) std::cout << buildTime[i] << " "; std::cout << "\n"; for (unsigned int i = 0; i < queryTime.size(); i++) std::cout << queryTime[i] << " "; std::cout << "\n"; } int main(int argc, char **argv) { if (argc != 3) { cerr << "**Running Instructions:**\n./benchmark_flann_real dataFile1 " "dataFile" << endl; return 0; } string dataFile1(argv[1]); string dataFile2(argv[2]); kdtree_demo<double>(dataFile1, dataFile2); return 0; }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; int64 nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("normtxid", wtx.GetNormalizedHash().GetHex())); entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", fTestNet)); if (pwalletMain) { obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new Glancoin address for receiving payments. " "If [account] is specified (recommended), it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current Glancoin address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <glancoinaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Glancoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <glancoinaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Glancoin address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value setmininput(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "setmininput <amount>\n" "<amount> is a real and is rounded to the nearest 0.00000001"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nMinimumInputValue = nAmount; return true; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <glancoinaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Glancoin address"); // Amount int64 nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <glancoinaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <glancoinaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <glancoinaddress> [minconf=1]\n" "Returns the total amount received by <glancoinaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Glancoin address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64 nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64 nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsFinal()) continue; int64 nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64 GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number int64 nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsConfirmed()) continue; int64 allFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); int64 nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64 nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64 nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toglancoinaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.00000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Glancoin address"); int64 nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64> > vecSend; int64 totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Glancoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64 nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64 nFeeRequired = 0; string strFailReason; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // // Used by addmultisigaddress / createmultisig: // static CScript _createmultisig(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Glancoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); return result; } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a Glancoin address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n" "Creates a multi-signature address and returns a json object\n" "with keys:\n" "address : glancoin address\n" "redeemScript : hex-encoded redemption script"; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } struct tallyitem { int64 nAmount; int nConf; vector<uint256> txids; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !wtx.IsFinal()) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64 nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); Array transactions; if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64 nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included\n" " \"txids\" : list of transactions with outputs to the address\n"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.second))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (boost::int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64 nFee; string strSentAccount; list<pair<CTxDestination, int64> > listReceived; list<pair<CTxDestination, int64> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about in-wallet transaction <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; int64 nCredit = wtx.GetCredit(); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(wtx, "*", 0, false, details); entry.push_back(Pair("details", details)); return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "keypoolrefill\n" "Fills the keypool." + HelpRequiringPassphrase()); EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(); if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("bitcoin-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("bitcoin-lock-wa"); int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64 nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64* pnSleepTime = new int64(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; Glancoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <glancoinaddress>\n" "Return information about <glancoinaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value lockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock? [array-of-Objects]\n" "Updates list of temporarily unspendable outputs."); if (params.size() == 1) RPCTypeCheck(params, list_of(bool_type)); else RPCTypeCheck(params, list_of(bool_type)(array_type)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } Array outputs = params[1].get_array(); BOOST_FOREACH(Value& output, outputs) { if (output.type() != obj_type) throw JSONRPCError(-8, "Invalid parameter, expected object"); const Object& o = output.get_obj(); RPCTypeCheck(o, map_list_of("txid", str_type)("vout", int_type)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(-8, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(-8, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } Value listlockunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "Returns list of temporarily unspendable outputs."); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); Array ret; BOOST_FOREACH(COutPoint &outpt, vOutpts) { Object o; o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; }
/*************************************************************************** Copyright 2015 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #pragma once #include <stdint.h> //typedef signed and unsigned word types for the current machine #if __x86_64__ || defined(_WIN64) typedef uint64_t uword_t; typedef int64_t sword_t; static_assert(sizeof(uint64_t) == 8, "uint64_t is not 8 bytes long."); static_assert(sizeof(int64_t) == 8, "int64_t is not 8 bytes long."); #else typedef uint32_t uword_t; typedef int32_t sword_t; #endif static_assert(sizeof(uint32_t) == 4, "uint32_t is not 4 bytes long."); static_assert(sizeof(int32_t) == 4, "int32_t is not 4 bytes long."); static_assert(sizeof(uint16_t) == 2, "int16_t is not 2 bytes long."); static_assert(sizeof(int16_t) == 2, "int16_t is not 2 bytes long."); static_assert(sizeof(uint8_t) == 1, "int8_t is not 1 byte long."); static_assert(sizeof(int8_t) == 1, "int8_t is not 1 byte long.");
#define __libmd_src_file__ #ifndef libmd_h #include "../../libmd.h" #endif template<ui dim> void md<dim>::thread_index_stick(ui i) { //! //! This function copies the current position <tt>x[]</tt> of particle <tt>i</tt> to <tt>xsk[]</tt>, for use by md<dim>::test_index(). //! memcpy(particles[i].xsk,particles[i].x,dim*sizeof(ldf)); } template<ui dim> void md<dim>::index() { //! //! This function finds all the pairs of particles that are within <tt>network.ssz</tt> of each other and have an interaction. //! They are then put in each other's skinlist (<tt>network.skins[]</tt>).<br> //! It calls the algorithm specificied by <tt>indexdata.method</tt>: md<dim>::bruteforce(), md<dim>::kdtree() or md<dim>::cell(). //! for(ui i=0;i<N;i++) thread_index_stick(i); switch(indexdata.method) { case INDEX::BRUTE_FORCE: bruteforce(); break; case INDEX::KD_TREE: kdtree(); break; default: cell(); break; } avars.reindex=false; } template<ui dim> bool md<dim>::test_index() { //! //! This function determines if re-indexing is necessary, based on the position of each particle at the last time of indexing (<tt>xsk[]</tt>): //! If no particle has moved by more than \f$(ssz-rco)/2\f$, then there is no pair of particles //! that were more than <tt>network.ssz</tt> apart, but now less than <tt>network.rco</tt> apart, so re-indexing is not necessary. //! Otherwise, re-indexing might be necessary and thus should be done. //! ldf rcomax=0.0; for(auto itype:network.library) rcomax=std::max(rcomax,itype.rco); const ldf delta=std::pow(network.ssz-rcomax,2)/4.0; for(ui i=0;i<N;i++) { ldf test=0.0; for(ui d=0;d<dim;d++) test+=std::pow(dap(d,particles[i].xsk[d]-particles[i].x[d]),2); if(test>delta) return true; } return false; } /*** k-d tree ***/ // Returns the index of the median template<ui dim> ui md<dim>::kdtree_build (ui first, ui last, ui level) { //! //! This function recursively builds the k-d tree, to be used by md<dim>::kdtree().<br> //! The particles in the subtree marked by <tt>first</tt> and <tt>last</tt> at recursion depth <tt>level</tt> //! are split into two subtrees of (about) equal size. //! The particles in one subtree have a lower value of their position coordinate in a given dimension than the particles in the other subtree. //! The dimension is specified by <tt>indexdata.kdtreedata.DivideByDim[level]</tt>, which is set by md<dim>::kdtree(). //! The two subtrees are build recursively. //! if (last - first == 1) // Leaf { // Set minimum and maximum value equal to the position of this particle (Idx[first]) memcpy(indexdata.kdtreedata.Pmin[first], particles[indexdata.kdtreedata.Idx[first]].x, dim*sizeof(ldf)); memcpy(indexdata.kdtreedata.Pmax[first], particles[indexdata.kdtreedata.Idx[first]].x, dim*sizeof(ldf)); return first; } ui m = (first+last)/2; // Median ui sortedDim = indexdata.kdtreedata.DivideByDim[level]; // Put the index of particle with the median value of coordinate dim in its right place, // put all particles with lower values below, and all with higher values above std::nth_element(indexdata.kdtreedata.Idx+first, indexdata.kdtreedata.Idx+m, indexdata.kdtreedata.Idx+last, [=](ui i, ui j) -> bool { return particles[i].x[sortedDim]<particles[j].x[sortedDim];}); // Recursively build subtrees ui m1 = kdtree_build(first, m, level+1), m2 = kdtree_build(m, last, level+1), d; // Determine minimum and maximum value of each coordinate for (d = 0; d < dim; d++) { indexdata.kdtreedata.Pmin[m][d] = std::min(indexdata.kdtreedata.Pmin[m1][d], indexdata.kdtreedata.Pmin[m2][d]); indexdata.kdtreedata.Pmax[m][d] = std::max(indexdata.kdtreedata.Pmax[m1][d], indexdata.kdtreedata.Pmax[m2][d]); } return m; } template<ui dim> void md<dim>::kdtree_index (ui first1, ui last1, ui first2, ui last2) { //! //! This function recursively finds neighboring particles, one from subtree 1, the other from subtree 2 (possibly the same subtree).<br> //! First it is checked if the subtrees are too far apart; nothing is done then. //! Otherwise, the function is called for every combination of subtrees. //! When a leaf is reached, the single particle is checked against the particle<b></b>(s) in the other subtree. //! ui m1 = (first1+last1)/2, m2 = (first2+last2)/2, d; ldf sszsq = std::pow(network.ssz,2); // Base cases if (m1 == first1 || m2 == first2) // A single particle { // Note: the other subtree contains either one or two particles if (m1 != m2) skinner(indexdata.kdtreedata.Idx[m1], indexdata.kdtreedata.Idx[m2], sszsq); if (m2 != first2) skinner(indexdata.kdtreedata.Idx[m1], indexdata.kdtreedata.Idx[first2], sszsq); if (m1 != first1) skinner(indexdata.kdtreedata.Idx[first1], indexdata.kdtreedata.Idx[m2], sszsq); return; } // Compute distance (squared) between subtrees if (m1 != m2) // Note: m1 == m2 iff the subtrees are the same { ldf dissqBetweenSubtrees = 0; for (d = 0; d < dim; d++) { if (simbox.bcond[d] == BCOND::PERIODIC) { if (indexdata.kdtreedata.Pmin[m1][d] > indexdata.kdtreedata.Pmax[m2][d]) dissqBetweenSubtrees += std::pow(std::min(indexdata.kdtreedata.Pmin[m1][d] - indexdata.kdtreedata.Pmax[m2][d], simbox.L[d] + indexdata.kdtreedata.Pmin[m2][d] - indexdata.kdtreedata.Pmax[m1][d]), 2); else if (indexdata.kdtreedata.Pmin[m2][d] > indexdata.kdtreedata.Pmax[m1][d]) dissqBetweenSubtrees += std::pow(std::min(indexdata.kdtreedata.Pmin[m2][d] - indexdata.kdtreedata.Pmax[m1][d], simbox.L[d] + indexdata.kdtreedata.Pmin[m1][d] - indexdata.kdtreedata.Pmax[m2][d]), 2); } else if (indexdata.kdtreedata.Pmin[m1][d] > indexdata.kdtreedata.Pmax[m2][d]) dissqBetweenSubtrees += std::pow(indexdata.kdtreedata.Pmin[m1][d] - indexdata.kdtreedata.Pmax[m2][d], 2); else if (indexdata.kdtreedata.Pmin[m2][d] > indexdata.kdtreedata.Pmax[m1][d]) dissqBetweenSubtrees += std::pow(indexdata.kdtreedata.Pmin[m2][d] - indexdata.kdtreedata.Pmax[m1][d], 2); } if (dissqBetweenSubtrees >= sszsq) // Return if the subtrees are too far apart return; } // Recursively check subtrees kdtree_index(first1, m1, first2, m2); kdtree_index(first1, m1, m2, last2); if (m1 != m2) kdtree_index(m1, last1, first2, m2); kdtree_index(m1, last1, m2, last2); } template<ui dim> void md<dim>::kdtree() { //! //! This indexing function uses a k-d tree (a multidimensional binary tree).<br> //! It makes use of the recursive functions md<dim>::kdtree_build() and md<dim>::kdtree_index().<br> //! It does not work if there is both shear and a dimension with periodic boundary conditions. //! if (simbox.useLshear) for (ui d = 0; d < dim; d++) if (simbox.bcond[d] == BCOND::PERIODIC || simbox.bcond[d] == BCOND::BOXSHEAR) { ERROR("the kd-tree algorithm does not work with both shear and periodic boundary conditions"); return; } if (indexdata.kdtreedata.Idx == nullptr || sizeof(indexdata.kdtreedata.Idx) != N*sizeof(ui)) { delete[] indexdata.kdtreedata.Idx; delete[] indexdata.kdtreedata.Pmin; delete[] indexdata.kdtreedata.Pmax; indexdata.kdtreedata.Idx = new ui[N]; indexdata.kdtreedata.Pmin = new ldf[N][dim]; indexdata.kdtreedata.Pmax = new ldf[N][dim]; } ldf S[dim]; ui i, n, d, b; for (i = 0; i < N; i++) indexdata.kdtreedata.Idx[i] = i; // Decide on which dimensions to divide the particles by at each recursion level memcpy(S, simbox.L, sizeof(S)); for (i = 0, n = N; n > 1; i++, n = (n+1)/2) { // Look for largest dimension b = 0; for (d = 1; d < dim; d++) if (S[b] < S[d]) b = d; indexdata.kdtreedata.DivideByDim[i] = b; S[b] /= 2; // Assume that the system is nicely split into two parts } kdtree_build(0, N, 0); for (i = 0; i < N; i++) network.skins[i].clear(); kdtree_index(0, N, 0, N); } /*** Cell algorithm ***/ template<ui dim> void md<dim>::thread_cell (ui c) { //! //! This function finds the neighbors of all particles in cell <tt>c</tt>. //! It does this by considering (half of) all neighboring cells, such that no pairs of cells are processed twice. //! ui nNeighbors; // Number of neighbors of a cell int CellIndices[dim]; // Indices (0 to Q[d]) of cell ldf DissqToEdge[dim][3]; // Distance squared from particle to cell edges ui NeighboringCells[indexdata.celldata.totNeighbors]; // Cells to check (accounting for boundary conditions) ui NeighborIndex[indexdata.celldata.totNeighbors]; // Index (0 to totNeighbors) of neighboring cell ui d, i, j, k, p1, cellId; int ci; ldf dissqToCorner, sszsq = std::pow(network.ssz,2); // Determine cell indices k = c; for (d = dim-1; d < UI_MAX; d--) { DEBUG_3("indexdata.celldata.Q[" F_UI "]= " F_UI "", d, indexdata.celldata.Q[d]); CellIndices[d] = k % indexdata.celldata.Q[d]; k /= indexdata.celldata.Q[d]; } // Determine all neighbors nNeighbors = 0; for (k = 0; k < indexdata.celldata.totNeighbors; k++) { cellId = 0; for (d = 0; d < dim && (((ci = CellIndices[d]+indexdata.celldata.IndexDelta[k][d]) < (int)indexdata.celldata.Q[d] && ci >= 0) || ((simbox.bcond[d] == BCOND::PERIODIC || simbox.bcond[d] == BCOND::BOXSHEAR) && indexdata.celldata.Q[d] != 2)); d++) cellId = indexdata.celldata.Q[d] * cellId + (indexdata.celldata.Q[d] + ci) % indexdata.celldata.Q[d]; if (d == dim) { NeighboringCells[nNeighbors] = cellId; NeighborIndex[nNeighbors] = k; nNeighbors++; } } // Loop over all particles in this cell for (i = indexdata.celldata.Cells[c].size()-1; i < UI_MAX; i--) { p1 = indexdata.celldata.Cells[c][i]; // Loop over all remaining particles in the same cell for (j = i-1; j < UI_MAX; j--) skinner(p1, indexdata.celldata.Cells[c][j], sszsq); if (simbox.useLshear || indexdata.celldata.OutsideBox[i]) { // Loop over neighboring cells for (k = 0; k < nNeighbors; k++) { // Check all particles in cell for (ui p2 : indexdata.celldata.Cells[NeighboringCells[k]]) skinner(p1, p2, sszsq); } } else { for (d = 0; d < dim; d++) { DissqToEdge[d][1] = 0; if (indexdata.celldata.Q[d] == 2 && (simbox.bcond[d] == BCOND::PERIODIC || simbox.bcond[d] == BCOND::BOXSHEAR)) // Special case: two cells and pbc DissqToEdge[d][0] = DissqToEdge[d][2] = std::pow(indexdata.celldata.CellSize[d]/2 - std::abs((CellIndices[d]+.5) * indexdata.celldata.CellSize[d] - simbox.L[d]/2 - particles[p1].x[d]), 2); else { DissqToEdge[d][0] = std::pow(simbox.L[d]/2 + particles[p1].x[d] - CellIndices[d] * indexdata.celldata.CellSize[d], 2); DissqToEdge[d][2] = std::pow((CellIndices[d]+1) * indexdata.celldata.CellSize[d] - simbox.L[d]/2 - particles[p1].x[d], 2); } } // Loop over neighboring cells for (k = 0; k < nNeighbors; k++) { // Calculate distance (squared) to closest corner dissqToCorner = 0; for (d = 0; d < dim; d++) dissqToCorner += DissqToEdge[d][indexdata.celldata.IndexDelta[NeighborIndex[k]][d]+1]; // Ignore cell if it is more than sszsq away if (dissqToCorner < sszsq) // Check all particles in cell for (ui p2 : indexdata.celldata.Cells[NeighboringCells[k]]) skinner(p1, p2, sszsq); } } } } template<ui dim> void md<dim>::cell() { //! //! This indexing algorithm uses the cell method.<br> //! The system is divided into cells of equal size, which are at least <tt>network.ssz</tt> in size in each dimension. //! The particles are put in their corresponding cells. //! Two particles that are in cells that do not share at least a corner will be more than <tt>network.ssz</tt> apart, //! therefore such pairs of cells need not be checked.<br> //! DEBUG_2("exec is here"); if (network.ssz <= 0) { ERROR("skinsize is not positive (network.ssz = " F_LDF ")", network.ssz); return; } ui c, d, i, k, cellId; ldf x; std::list<ui>::iterator a, b; ldf nc = 1; if (simbox.useLshear) { ldf R; for (d = 0; d < dim; d++) { R = std::pow(dotprod<dim>(simbox.LshearInv[d], simbox.LshearInv[d]), -.5); nc *= indexdata.celldata.Q[d] = (R < network.ssz ? 1 : R/network.ssz); } } else for (d = 0; d < dim; d++) nc *= indexdata.celldata.Q[d] = (simbox.L[d] < network.ssz ? 1 : simbox.L[d]/network.ssz); // If number of cells is very large (ssz very small): reduce until number of cells is in the order of N for (; nc > N; nc /= 2) { k = 0; for (d = 1; d < dim; d++) if (indexdata.celldata.Q[k] < indexdata.celldata.Q[d]) k = d; indexdata.celldata.Q[k] = (indexdata.celldata.Q[k]+1)/2; } for (d = 0; d < dim; d++) DEBUG_3("indexdata.celldata.Q[" F_UI "] = " F_UI " (from " F_LDF " / " F_LDF " originally)", d, indexdata.celldata.Q[d], simbox.L[d], network.ssz); // Compute and check cell sizes for (d = 0; d < dim; d++) indexdata.celldata.CellSize[d] = simbox.L[d]/indexdata.celldata.Q[d]; // Compute nCells and totNeighbors indexdata.celldata.nCells = 1; indexdata.celldata.totNeighbors = 0; for (d = 0; d < dim; d++) if (indexdata.celldata.Q[d] > 1) // Ignore dimensions with only one cell { indexdata.celldata.nCells *= indexdata.celldata.Q[d]; indexdata.celldata.totNeighbors = 3*indexdata.celldata.totNeighbors+1; } // Declare dynamic arrays if (indexdata.celldata.IndexDelta == nullptr || sizeof(indexdata.celldata.Cells) != indexdata.celldata.nCells*sizeof(ui) || sizeof(indexdata.celldata.IndexDelta) != indexdata.celldata.totNeighbors*dim*sizeof(int) || sizeof(indexdata.celldata.OutsideBox) != N) { delete[] indexdata.celldata.Cells; delete[] indexdata.celldata.IndexDelta; delete[] indexdata.celldata.OutsideBox; indexdata.celldata.Cells = new std::vector<ui>[indexdata.celldata.nCells]; indexdata.celldata.IndexDelta = new int[indexdata.celldata.totNeighbors][dim]; // Relative position of neighboring cell indexdata.celldata.OutsideBox = new bool[N]; } // Determine all (potential) neighbors // Start with {0,0,...,0,+1} if (indexdata.celldata.totNeighbors > 0) { memset(indexdata.celldata.IndexDelta[0], 0, dim*sizeof(ui)); for (d = dim-1; indexdata.celldata.Q[d] == 1; d--); indexdata.celldata.IndexDelta[0][d] = 1; for (i = 1; i < indexdata.celldata.totNeighbors; i++) { memcpy(indexdata.celldata.IndexDelta[i], indexdata.celldata.IndexDelta[i-1], dim*sizeof(ui)); // Set all trailing +1's to -1 for (d = dim-1; d < dim && (indexdata.celldata.Q[d] == 1 || indexdata.celldata.IndexDelta[i][d] == 1); d--) if (indexdata.celldata.Q[d] > 1) indexdata.celldata.IndexDelta[i][d] = -1; // Increase last not-plus-one by one if (d < dim) indexdata.celldata.IndexDelta[i][d]++; } } // Put the particles in their cells for (c = 0; c < indexdata.celldata.nCells; c++) indexdata.celldata.Cells[c].clear(); for (i = 0; i < N; i++) { cellId = 0; indexdata.celldata.OutsideBox[i] = false; for (d = 0; d < dim; d++) { x = (simbox.useLshear ? dotprod<dim>(simbox.LshearInv[d], particles[i].x) : particles[i].x[d] / simbox.L[d]); if (std::abs(x) > .5+1e-9) { indexdata.celldata.OutsideBox[i] = true; cellId = indexdata.celldata.Q[d] * cellId + (x < 0 ? 0 : indexdata.celldata.Q[d]-1); } else cellId = indexdata.celldata.Q[d] * cellId + (x < -.5+3e-9 ? 0 : (ui)(indexdata.celldata.Q[d]*(x+.5-2e-9))); } indexdata.celldata.Cells[cellId].push_back(i); } for (i = 0; i < N; i++) network.skins[i].clear(); for(ui c=0;c<indexdata.celldata.nCells;c++) thread_cell(c); } template<ui dim> void md<dim>::bruteforce() { //! //! This brute force indexing algorithm simply checks every pair of particles.<br> //! This function is to be preferred over md<dim>::cell() and md<dim>::kdtree() //! if all (or most) particles are within <tt>network.ssz</tt> of each other. //! DEBUG_2("exec is here"); for(ui i=0;i<N;i++) network.skins[i].clear(); ldf sszsq=std::pow(network.ssz,2); for(ui i=0;i<N;i++) for(ui j=i+1;j<N;j++) skinner(i, j, sszsq); } template<ui dim> void md<dim>::skinner(ui i, ui j, ldf sszsq) { //! //! This function is used by the indexing algorithms. //! It checks if the squared distance between particles <tt>i</tt> and <tt>j</tt> is less than <tt>sszsq</tt> //! and if they have a (superparticle) type interaction; if so, it adds them (with the interaction) to each other's skinlist.<br> //! if (distsq(i,j) > sszsq) return; const ui K=network.spid[i]; std::pair<ui,ui> it; if(K<UI_MAX and K==network.spid[j] and network.sptypes[network.superparticles[K].sptype].splookup.count(it=network.hash(network.superparticles[K].particles[i],network.superparticles[K].particles[j]))) { interactionneighbor in(j,network.sptypes[network.superparticles[K].sptype].splookup[it]); network.skins[i].push_back(in); in.neighbor=i; network.skins[j].push_back(in); DEBUG_3("super particle skinned (i,j)=(" F_UI "," F_UI ") in " F_UI " with interaction " F_UI "",i,j,K,network.sptypes[network.superparticles[K].sptype].splookup[it]); } else { it=network.hash(particles[i].type,particles[j].type); if(network.lookup.count(it)) { interactionneighbor in(j,network.lookup[it]); network.skins[i].push_back(in); in.neighbor=i; network.skins[j].push_back(in); DEBUG_3("normally skinned (i,j)=(" F_UI "," F_UI ") with interaction " F_UI "",i,j,network.lookup[it]); } } }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blimp/engine/renderer/blimp_engine_picture_cache.h" #include "base/logging.h" #include "base/memory/ptr_util.h" namespace blimp { namespace engine { BlimpEnginePictureCache::BlimpEnginePictureCache( SkPixelSerializer* pixel_serializer) : pixel_serializer_(pixel_serializer) {} BlimpEnginePictureCache::~BlimpEnginePictureCache() = default; void BlimpEnginePictureCache::MarkUsed(const SkPicture* picture) { DCHECK(picture); reference_tracker_.IncrementRefCount(picture->uniqueID()); // Do not serialize multiple times, even though the item is referred to from // multiple places. if (pictures_.find(picture->uniqueID()) != pictures_.end()) { return; } Put(picture); } std::vector<cc::PictureData> BlimpEnginePictureCache::CalculateCacheUpdateAndFlush() { std::vector<uint32_t> added; std::vector<uint32_t> removed; reference_tracker_.CommitRefCounts(&added, &removed); // Create cache update consisting of new pictures. std::vector<cc::PictureData> update; for (const uint32_t item : added) { auto entry = pictures_.find(item); DCHECK(entry != pictures_.end()); update.push_back(entry->second); } // All new items will be sent to the client, so clear everything. pictures_.clear(); reference_tracker_.ClearRefCounts(); return update; } void BlimpEnginePictureCache::Put(const SkPicture* picture) { sk_sp<SkData> data = picture->serialize(pixel_serializer_); DCHECK_GE(data->size(), 0u); // Store the picture data until it is sent to the client. pictures_.insert( std::make_pair(picture->uniqueID(), cc::PictureData(picture->uniqueID(), std::move(data)))); } } // namespace engine } // namespace blimp
#include "Game.hpp" Game::Game(){ this->player = new Player(this->playerPos,this->playerModel,this->camera); }; Game::~Game(){ } void Game::update(){ this->player->render(); this->player->update(); }
/* * ----------------- BEGIN LICENSE BLOCK --------------------------------- * * Copyright (C) 2018-2020 Intel Corporation * * SPDX-License-Identifier: MIT * * ----------------- END LICENSE BLOCK ----------------------------------- */ /** * Generated file * @file * * Generator Version : 11.0.0-1988 */ #pragma once #include <cmath> #include <limits> #include "ad/map/lane/LaneType.hpp" #include "spdlog/fmt/ostr.h" #include "spdlog/spdlog.h" /*! * \brief check if the given LaneType is within valid input range * * \param[in] input the LaneType as an input value * \param[in] logErrors enables error logging * * \returns \c true if LaneType is considered to be within the specified input range * * \note the specified input range is defined by the valid enum literals. */ inline bool withinValidInputRange(::ad::map::lane::LaneType const &input, bool const logErrors = true) { bool inValidInputRange = (input == ::ad::map::lane::LaneType::INVALID) || (input == ::ad::map::lane::LaneType::UNKNOWN) || (input == ::ad::map::lane::LaneType::NORMAL) || (input == ::ad::map::lane::LaneType::INTERSECTION) || (input == ::ad::map::lane::LaneType::SHOULDER) || (input == ::ad::map::lane::LaneType::EMERGENCY) || (input == ::ad::map::lane::LaneType::MULTI) || (input == ::ad::map::lane::LaneType::PEDESTRIAN) || (input == ::ad::map::lane::LaneType::OVERTAKING) || (input == ::ad::map::lane::LaneType::TURN) || (input == ::ad::map::lane::LaneType::BIKE); if (!inValidInputRange && logErrors) { spdlog::error("withinValidInputRange(::ad::map::lane::LaneType)>> {}, raw value: {} ", input, static_cast<int32_t>(input)); // LCOV_EXCL_BR_LINE } return inValidInputRange; }
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/congestion_controller/congestion_controller_unittests_helper.h" #include "webrtc/base/checks.h" #include "webrtc/test/gtest.h" namespace webrtc { void ComparePacketFeedbackVectors(const std::vector<PacketFeedback>& truth, const std::vector<PacketFeedback>& input) { ASSERT_EQ(truth.size(), input.size()); size_t len = truth.size(); // truth contains the input data for the test, and input is what will be // sent to the bandwidth estimator. truth.arrival_tims_ms is used to // populate the transport feedback messages. As these times may be changed // (because of resolution limits in the packets, and because of the time // base adjustment performed by the TransportFeedbackAdapter at the first // packet, the truth[x].arrival_time and input[x].arrival_time may not be // equal. However, the difference must be the same for all x. int64_t arrival_time_delta = truth[0].arrival_time_ms - input[0].arrival_time_ms; for (size_t i = 0; i < len; ++i) { RTC_CHECK(truth[i].arrival_time_ms != PacketFeedback::kNotReceived); if (input[i].arrival_time_ms != PacketFeedback::kNotReceived) { EXPECT_EQ(truth[i].arrival_time_ms, input[i].arrival_time_ms + arrival_time_delta); } EXPECT_EQ(truth[i].send_time_ms, input[i].send_time_ms); EXPECT_EQ(truth[i].sequence_number, input[i].sequence_number); EXPECT_EQ(truth[i].payload_size, input[i].payload_size); EXPECT_EQ(truth[i].pacing_info, input[i].pacing_info); } } } // namespace webrtc
// Copyright Epic Games, Inc. All Rights Reserved. // Modified version of Recast/Detour's source file // // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #define _USE_MATH_DEFINES #include "Recast/Recast.h" #include "Recast/RecastAlloc.h" #include "Recast/RecastAssert.h" struct rcEdge { unsigned short vert[2]; unsigned short polyEdge[2]; unsigned short poly[2]; }; static bool buildMeshAdjacency(unsigned short* polys, const int npolys, const int nverts, const int vertsPerPoly) { // Based on code by Eric Lengyel from: // http://www.terathon.com/code/edges.php int maxEdgeCount = npolys*vertsPerPoly; unsigned short* firstEdge = (unsigned short*)rcAlloc(sizeof(unsigned short)*(nverts + maxEdgeCount), RC_ALLOC_TEMP); if (!firstEdge) return false; unsigned short* nextEdge = firstEdge + nverts; int edgeCount = 0; rcEdge* edges = (rcEdge*)rcAlloc(sizeof(rcEdge)*maxEdgeCount, RC_ALLOC_TEMP); if (!edges) { rcFree(firstEdge); return false; } for (int i = 0; i < nverts; i++) firstEdge[i] = RC_MESH_NULL_IDX; for (int i = 0; i < npolys; ++i) { unsigned short* t = &polys[i*vertsPerPoly*2]; for (int j = 0; j < vertsPerPoly; ++j) { if (t[j] == RC_MESH_NULL_IDX) break; unsigned short v0 = t[j]; unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1]; if (v0 < v1) { rcEdge& edge = edges[edgeCount]; edge.vert[0] = v0; edge.vert[1] = v1; edge.poly[0] = (unsigned short)i; edge.polyEdge[0] = (unsigned short)j; edge.poly[1] = (unsigned short)i; edge.polyEdge[1] = 0; // Insert edge nextEdge[edgeCount] = firstEdge[v0]; firstEdge[v0] = (unsigned short)edgeCount; edgeCount++; } } } for (int i = 0; i < npolys; ++i) { unsigned short* t = &polys[i*vertsPerPoly*2]; for (int j = 0; j < vertsPerPoly; ++j) { if (t[j] == RC_MESH_NULL_IDX) break; unsigned short v0 = t[j]; unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1]; if (v0 > v1) { for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e]) { rcEdge& edge = edges[e]; if (edge.vert[1] == v0 && edge.poly[0] == edge.poly[1]) { edge.poly[1] = (unsigned short)i; edge.polyEdge[1] = (unsigned short)j; break; } } } } } // Store adjacency for (int i = 0; i < edgeCount; ++i) { const rcEdge& e = edges[i]; if (e.poly[0] != e.poly[1]) { unsigned short* p0 = &polys[e.poly[0]*vertsPerPoly*2]; unsigned short* p1 = &polys[e.poly[1]*vertsPerPoly*2]; p0[vertsPerPoly + e.polyEdge[0]] = e.poly[1]; p1[vertsPerPoly + e.polyEdge[1]] = e.poly[0]; } } rcFree(firstEdge); rcFree(edges); return true; } static const int VERTEX_BUCKET_COUNT = (1<<12); inline int computeVertexHash(int x, int y, int z) { const unsigned int h1 = 0x8da6b343; // Large multiplicative constants; const unsigned int h2 = 0xd8163841; // here arbitrarily chosen primes const unsigned int h3 = 0xcb1ab31f; unsigned int n = h1 * x + h2 * y + h3 * z; return (int)(n & (VERTEX_BUCKET_COUNT-1)); } static unsigned short addVertex(unsigned short x, unsigned short y, unsigned short z, unsigned short* verts, int* firstVert, int* nextVert, int& nv) { int bucket = computeVertexHash(x, 0, z); int i = firstVert[bucket]; while (i != -1) { const unsigned short* v = &verts[i*3]; if (v[0] == x && (rcAbs(v[1] - y) <= 2) && v[2] == z) return (unsigned short)i; i = nextVert[i]; // next } // Could not find, create new. i = nv; nv++; unsigned short* v = &verts[i*3]; v[0] = x; v[1] = y; v[2] = z; nextVert[i] = firstVert[bucket]; firstVert[bucket] = i; return (unsigned short)i; } inline int prev(int i, int n) { return i-1 >= 0 ? i-1 : n-1; } inline int next(int i, int n) { return i+1 < n ? i+1 : 0; } inline int area2(const int* a, const int* b, const int* c) { return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]); } // Exclusive or: true iff exactly one argument is true. // The arguments are negated to ensure that they are 0/1 // values. Then the bitwise Xor operator may apply. // (This idea is due to Michael Baldwin.) inline bool xorb(bool x, bool y) { return !x ^ !y; } // Returns true iff c is strictly to the left of the directed // line through a to b. inline bool left(const int* a, const int* b, const int* c) { return area2(a, b, c) < 0; } inline bool leftOn(const int* a, const int* b, const int* c) { return area2(a, b, c) <= 0; } inline bool collinear(const int* a, const int* b, const int* c) { return area2(a, b, c) == 0; } // Returns true iff ab properly intersects cd: they share // a point interior to both segments. The properness of the // intersection is ensured by using strict leftness. static bool intersectProp(const int* a, const int* b, const int* c, const int* d) { // Eliminate improper cases. if (collinear(a,b,c) || collinear(a,b,d) || collinear(c,d,a) || collinear(c,d,b)) return false; return xorb(left(a,b,c), left(a,b,d)) && xorb(left(c,d,a), left(c,d,b)); } // Returns T iff (a,b,c) are collinear and point c lies // on the closed segement ab. static bool between(const int* a, const int* b, const int* c) { if (!collinear(a, b, c)) return false; // If ab not vertical, check betweenness on x; else on y. if (a[0] != b[0]) return ((a[0] <= c[0]) && (c[0] <= b[0])) || ((a[0] >= c[0]) && (c[0] >= b[0])); else return ((a[2] <= c[2]) && (c[2] <= b[2])) || ((a[2] >= c[2]) && (c[2] >= b[2])); } // Returns true iff segments ab and cd intersect, properly or improperly. static bool intersect(const int* a, const int* b, const int* c, const int* d) { if (intersectProp(a, b, c, d)) return true; else if (between(a, b, c) || between(a, b, d) || between(c, d, a) || between(c, d, b)) return true; else return false; } static bool vequal(const int* a, const int* b) { return a[0] == b[0] && a[2] == b[2]; } // Returns T iff (v_i, v_j) is a proper internal *or* external // diagonal of P, *ignoring edges incident to v_i and v_j*. static bool diagonalie(int i, int j, int n, const int* verts, int* indices) { const int* d0 = &verts[(indices[i] & 0x0fffffff) * 4]; const int* d1 = &verts[(indices[j] & 0x0fffffff) * 4]; // For each edge (k,k+1) of P for (int k = 0; k < n; k++) { int k1 = next(k, n); // Skip edges incident to i or j if (!((k == i) || (k1 == i) || (k == j) || (k1 == j))) { const int* p0 = &verts[(indices[k] & 0x0fffffff) * 4]; const int* p1 = &verts[(indices[k1] & 0x0fffffff) * 4]; if (vequal(d0, p0) || vequal(d1, p0) || vequal(d0, p1) || vequal(d1, p1)) continue; if (intersect(d0, d1, p0, p1)) return false; } } return true; } // Returns true iff the diagonal (i,j) is strictly internal to the // polygon P in the neighborhood of the i endpoint. static bool inCone(int i, int j, int n, const int* verts, int* indices) { const int* vi = &verts[(indices[i] & 0x0fffffff) * 4]; const int* vj = &verts[(indices[j] & 0x0fffffff) * 4]; const int* vi1 = &verts[(indices[next(i, n)] & 0x0fffffff) * 4]; const int* vin1 = &verts[(indices[prev(i, n)] & 0x0fffffff) * 4]; // If P[i] is a convex vertex [ i+1 left or on (i-1,i) ]. if (leftOn(vin1, vi, vi1)) return left(vi, vj, vin1) && left(vj, vi, vi1); // Assume (i-1,i,i+1) not collinear. // else P[i] is reflex. return !(leftOn(vi, vj, vi1) && leftOn(vj, vi, vin1)); } // Returns T iff (v_i, v_j) is a proper internal // diagonal of P. static bool diagonal(int i, int j, int n, const int* verts, int* indices) { return inCone(i, j, n, verts, indices) && diagonalie(i, j, n, verts, indices); } static int triangulate(int n, const int* verts, int* indices, int* tris) { int ntris = 0; int* dst = tris; // The last bit of the index is used to indicate if the vertex can be removed. for (int i = 0; i < n; i++) { int i1 = next(i, n); int i2 = next(i1, n); if (diagonal(i, i2, n, verts, indices)) indices[i1] |= 0x80000000; } while (n > 3) { int minLen = -1; int mini = -1; for (int i = 0; i < n; i++) { int i1 = next(i, n); if (indices[i1] & 0x80000000) { const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4]; const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4]; int dx = p2[0] - p0[0]; int dy = p2[2] - p0[2]; int len = dx*dx + dy*dy; if (minLen < 0 || len < minLen) { minLen = len; mini = i; } } } if (mini == -1) { // Should not happen. /* printf("mini == -1 ntris=%d n=%d\n", ntris, n); for (int i = 0; i < n; i++) { printf("%d ", indices[i] & 0x0fffffff); } printf("\n");*/ return -ntris; } int i = mini; int i1 = next(i, n); int i2 = next(i1, n); *dst++ = indices[i] & 0x0fffffff; *dst++ = indices[i1] & 0x0fffffff; *dst++ = indices[i2] & 0x0fffffff; ntris++; // Removes P[i1] by copying P[i+1]...P[n-1] left one index. n--; for (int k = i1; k < n; k++) indices[k] = indices[k+1]; if (i1 >= n) i1 = 0; i = prev(i1,n); // Update diagonal flags. if (diagonal(prev(i, n), i1, n, verts, indices)) indices[i] |= 0x80000000; else indices[i] &= 0x0fffffff; if (diagonal(i, next(i1, n), n, verts, indices)) indices[i1] |= 0x80000000; else indices[i1] &= 0x0fffffff; } // Append the remaining triangle. *dst++ = indices[0] & 0x0fffffff; *dst++ = indices[1] & 0x0fffffff; *dst++ = indices[2] & 0x0fffffff; ntris++; return ntris; } static int countPolyVerts(const unsigned short* p, const int nvp) { for (int i = 0; i < nvp; ++i) if (p[i] == RC_MESH_NULL_IDX) return i; return nvp; } inline bool uleft(const unsigned short* a, const unsigned short* b, const unsigned short* c) { return ((int)b[0] - (int)a[0]) * ((int)c[2] - (int)a[2]) - ((int)c[0] - (int)a[0]) * ((int)b[2] - (int)a[2]) < 0; } static int getPolyMergeValue(unsigned short* pa, unsigned short* pb, const unsigned short* verts, int& ea, int& eb, const int nvp) { const int na = countPolyVerts(pa, nvp); const int nb = countPolyVerts(pb, nvp); // If the merged polygon would be too big, do not merge. if (na+nb-2 > nvp) return -1; // Check if the polygons share an edge. ea = -1; eb = -1; for (int i = 0; i < na; ++i) { unsigned short va0 = pa[i]; unsigned short va1 = pa[(i+1) % na]; if (va0 > va1) rcSwap(va0, va1); for (int j = 0; j < nb; ++j) { unsigned short vb0 = pb[j]; unsigned short vb1 = pb[(j+1) % nb]; if (vb0 > vb1) rcSwap(vb0, vb1); if (va0 == vb0 && va1 == vb1) { ea = i; eb = j; break; } } } // No common edge, cannot merge. if (ea == -1 || eb == -1) return -1; // Check to see if the merged polygon would be convex. unsigned short va, vb, vc; va = pa[(ea+na-1) % na]; vb = pa[ea]; vc = pb[(eb+2) % nb]; if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3])) return -1; va = pb[(eb+nb-1) % nb]; vb = pb[eb]; vc = pa[(ea+2) % na]; if (!uleft(&verts[va*3], &verts[vb*3], &verts[vc*3])) return -1; va = pa[ea]; vb = pa[(ea+1)%na]; int dx = (int)verts[va*3+0] - (int)verts[vb*3+0]; int dy = (int)verts[va*3+2] - (int)verts[vb*3+2]; return dx*dx + dy*dy; } static void mergePolys(unsigned short* pa, unsigned short* pb, int ea, int eb, unsigned short* tmp, const int nvp) { const int na = countPolyVerts(pa, nvp); const int nb = countPolyVerts(pb, nvp); // Merge polygons. memset(tmp, 0xff, sizeof(unsigned short)*nvp); int n = 0; // Add pa for (int i = 0; i < na-1; ++i) tmp[n++] = pa[(ea+1+i) % na]; // Add pb for (int i = 0; i < nb-1; ++i) tmp[n++] = pb[(eb+1+i) % nb]; memcpy(pa, tmp, sizeof(unsigned short)*nvp); } static void pushFront(int v, int* arr, int& an) { an++; for (int i = an-1; i > 0; --i) arr[i] = arr[i-1]; arr[0] = v; } static void pushBack(int v, int* arr, int& an) { arr[an] = v; an++; } static bool canRemoveVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem) { const int nvp = mesh.nvp; // Count number of polygons to remove. int numRemovedVerts = 0; int numTouchedVerts = 0; int numRemainingEdges = 0; for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*nvp*2]; const int nv = countPolyVerts(p, nvp); int numRemoved = 0; int numVerts = 0; for (int j = 0; j < nv; ++j) { if (p[j] == rem) { numTouchedVerts++; numRemoved++; } numVerts++; } if (numRemoved) { numRemovedVerts += numRemoved; numRemainingEdges += numVerts-(numRemoved+1); } } // There would be too few edges remaining to create a polygon. // This can happen for example when a tip of a triangle is marked // as deletion, but there are no other polys that share the vertex. // In this case, the vertex should not be removed. if (numRemainingEdges <= 2) return false; // Find edges which share the removed vertex. const int maxEdges = numTouchedVerts*2; int nedges = 0; rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*maxEdges*3, RC_ALLOC_TEMP); if (!edges) { ctx->log(RC_LOG_WARNING, "canRemoveVertex: Out of memory 'edges' (%d).", maxEdges*3); return false; } for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*nvp*2]; const int nv = countPolyVerts(p, nvp); // Collect edges which touches the removed vertex. for (int j = 0, k = nv-1; j < nv; k = j++) { if (p[j] == rem || p[k] == rem) { // Arrange edge so that a=rem. int a = p[j], b = p[k]; if (b == rem) rcSwap(a,b); // Check if the edge exists bool exists = false; for (int m = 0; m < nedges; ++m) { int* e = &edges[m*3]; if (e[1] == b) { // Exists, increment vertex share count. e[2]++; exists = true; } } // Add new edge. if (!exists) { int* e = &edges[nedges*3]; e[0] = a; e[1] = b; e[2] = 1; nedges++; } } } } // There should be no more than 2 open edges. // This catches the case that two non-adjacent polygons // share the removed vertex. In that case, do not remove the vertex. int numOpenEdges = 0; for (int i = 0; i < nedges; ++i) { if (edges[i*3+2] < 2) numOpenEdges++; } if (numOpenEdges > 2) return false; return true; } static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short rem, const int maxTris) { const int nvp = mesh.nvp; // Count number of polygons to remove. int numRemovedVerts = 0; for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*nvp*2]; const int nv = countPolyVerts(p, nvp); for (int j = 0; j < nv; ++j) { if (p[j] == rem) numRemovedVerts++; } } int nedges = 0; rcScopedDelete<int> edges = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp*4, RC_ALLOC_TEMP); if (!edges) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'edges' (%d).", numRemovedVerts*nvp*4); return false; } int nhole = 0; rcScopedDelete<int> hole = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP); if (!hole) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hole' (%d).", numRemovedVerts*nvp); return false; } int nhreg = 0; rcScopedDelete<int> hreg = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP); if (!hreg) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'hreg' (%d).", numRemovedVerts*nvp); return false; } int nharea = 0; rcScopedDelete<int> harea = (int*)rcAlloc(sizeof(int)*numRemovedVerts*nvp, RC_ALLOC_TEMP); if (!harea) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'harea' (%d).", numRemovedVerts*nvp); return false; } for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*nvp*2]; const int nv = countPolyVerts(p, nvp); bool hasRem = false; for (int j = 0; j < nv; ++j) if (p[j] == rem) hasRem = true; if (hasRem) { // Collect edges which does not touch the removed vertex. for (int j = 0, k = nv-1; j < nv; k = j++) { if (p[j] != rem && p[k] != rem) { int* e = &edges[nedges*4]; e[0] = p[k]; e[1] = p[j]; e[2] = mesh.regs[i]; e[3] = mesh.areas[i]; nedges++; } } // Remove the polygon. unsigned short* p2 = &mesh.polys[(mesh.npolys-1)*nvp*2]; memcpy(p,p2,sizeof(unsigned short)*nvp); memset(p+nvp,0xff,sizeof(unsigned short)*nvp); mesh.regs[i] = mesh.regs[mesh.npolys-1]; mesh.areas[i] = mesh.areas[mesh.npolys-1]; mesh.npolys--; --i; } } // Remove vertex. for (int i = (int)rem; i < mesh.nverts; ++i) { mesh.verts[i*3+0] = mesh.verts[(i+1)*3+0]; mesh.verts[i*3+1] = mesh.verts[(i+1)*3+1]; mesh.verts[i*3+2] = mesh.verts[(i+1)*3+2]; } mesh.nverts--; // Adjust indices to match the removed vertex layout. for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*nvp*2]; const int nv = countPolyVerts(p, nvp); for (int j = 0; j < nv; ++j) if (p[j] > rem) p[j]--; } for (int i = 0; i < nedges; ++i) { if (edges[i*4+0] > rem) edges[i*4+0]--; if (edges[i*4+1] > rem) edges[i*4+1]--; } if (nedges == 0) return true; // Start with one vertex, keep appending connected // segments to the start and end of the hole. pushBack(edges[0], hole, nhole); pushBack(edges[2], hreg, nhreg); pushBack(edges[3], harea, nharea); while (nedges) { bool match = false; for (int i = 0; i < nedges; ++i) { const int ea = edges[i*4+0]; const int eb = edges[i*4+1]; const int r = edges[i*4+2]; const int a = edges[i*4+3]; bool add = false; if (hole[0] == eb) { // The segment matches the beginning of the hole boundary. pushFront(ea, hole, nhole); pushFront(r, hreg, nhreg); pushFront(a, harea, nharea); add = true; } else if (hole[nhole-1] == ea) { // The segment matches the end of the hole boundary. pushBack(eb, hole, nhole); pushBack(r, hreg, nhreg); pushBack(a, harea, nharea); add = true; } if (add) { // The edge segment was added, remove it. edges[i*4+0] = edges[(nedges-1)*4+0]; edges[i*4+1] = edges[(nedges-1)*4+1]; edges[i*4+2] = edges[(nedges-1)*4+2]; edges[i*4+3] = edges[(nedges-1)*4+3]; --nedges; match = true; --i; } } if (!match) break; } rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP); if (!tris) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tris' (%d).", nhole*3); return false; } rcScopedDelete<int> tverts = (int*)rcAlloc(sizeof(int)*nhole*4, RC_ALLOC_TEMP); if (!tverts) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'tverts' (%d).", nhole*4); return false; } rcScopedDelete<int> thole = (int*)rcAlloc(sizeof(int)*nhole, RC_ALLOC_TEMP); if (!tverts) { ctx->log(RC_LOG_WARNING, "removeVertex: Out of memory 'thole' (%d).", nhole); return false; } // Generate temp vertex array for triangulation. for (int i = 0; i < nhole; ++i) { const int holeVertIndex = hole[i]; tverts[i*4+0] = mesh.verts[holeVertIndex*3+0]; tverts[i*4+1] = mesh.verts[holeVertIndex*3+1]; tverts[i*4+2] = mesh.verts[holeVertIndex*3+2]; tverts[i*4+3] = 0; thole[i] = i; } // Triangulate the hole. int ntris = triangulate(nhole, &tverts[0], &thole[0], tris); if (ntris < 0) { ntris = -ntris; ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned bad results."); } // Merge the hole triangles back to polygons. rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(ntris+1)*nvp, RC_ALLOC_TEMP); if (!polys) { ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'polys' (%d).", (ntris+1)*nvp); return false; } rcScopedDelete<unsigned short> pregs = (unsigned short*)rcAlloc(sizeof(unsigned short)*ntris, RC_ALLOC_TEMP); if (!pregs) { ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pregs' (%d).", ntris); return false; } rcScopedDelete<unsigned char> pareas = (unsigned char*)rcAlloc(sizeof(unsigned char)*ntris, RC_ALLOC_TEMP); if (!pregs) { ctx->log(RC_LOG_ERROR, "removeVertex: Out of memory 'pareas' (%d).", ntris); return false; } unsigned short* tmpPoly = &polys[ntris*nvp]; // Build initial polygons. int npolys = 0; memset(polys, 0xff, ntris*nvp*sizeof(unsigned short)); for (int j = 0; j < ntris; ++j) { int* t = &tris[j*3]; if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2]) { polys[npolys*nvp+0] = (unsigned short)hole[t[0]]; polys[npolys*nvp+1] = (unsigned short)hole[t[1]]; polys[npolys*nvp+2] = (unsigned short)hole[t[2]]; pregs[npolys] = (unsigned short)hreg[t[0]]; pareas[npolys] = (unsigned char)harea[t[0]]; npolys++; } } if (!npolys) return true; // Merge polygons. if (nvp > 3) { for (;;) { // Find best polygons to merge. int bestMergeVal = 0; int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; for (int j = 0; j < npolys-1; ++j) { unsigned short* pj = &polys[j*nvp]; for (int k = j+1; k < npolys; ++k) { unsigned short* pk = &polys[k*nvp]; int ea, eb; int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp); if (v > bestMergeVal) { bestMergeVal = v; bestPa = j; bestPb = k; bestEa = ea; bestEb = eb; } } } if (bestMergeVal > 0) { // Found best, merge. unsigned short* pa = &polys[bestPa*nvp]; unsigned short* pb = &polys[bestPb*nvp]; mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp); memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp); pregs[bestPb] = pregs[npolys-1]; pareas[bestPb] = pareas[npolys-1]; npolys--; } else { // Could not merge any polygons, stop. break; } } } // Store polygons. for (int i = 0; i < npolys; ++i) { if (mesh.npolys >= maxTris) break; unsigned short* p = &mesh.polys[mesh.npolys*nvp*2]; memset(p,0xff,sizeof(unsigned short)*nvp*2); for (int j = 0; j < nvp; ++j) p[j] = polys[i*nvp+j]; mesh.regs[mesh.npolys] = pregs[i]; mesh.areas[mesh.npolys] = pareas[i]; mesh.npolys++; if (mesh.npolys > maxTris) { ctx->log(RC_LOG_ERROR, "removeVertex: Too many polygons %d (max:%d).", mesh.npolys, maxTris); return false; } } return true; } /// @par /// /// @note If the mesh data is to be used to construct a Detour navigation mesh, then the upper /// limit must be retricted to <= #DT_VERTS_PER_POLYGON. /// /// @see rcAllocPolyMesh, rcContourSet, rcPolyMesh, rcConfig bool rcBuildPolyMesh(rcContext* ctx, rcContourSet& cset, const int nvp, rcPolyMesh& mesh) { rcAssert(ctx); ctx->startTimer(RC_TIMER_BUILD_POLYMESH); rcVcopy(mesh.bmin, cset.bmin); rcVcopy(mesh.bmax, cset.bmax); mesh.cs = cset.cs; mesh.ch = cset.ch; mesh.borderSize = cset.borderSize; int maxVertices = 0; int maxTris = 0; int maxVertsPerCont = 0; for (int i = 0; i < cset.nconts; ++i) { // Skip null contours. if (cset.conts[i].nverts < 3) continue; maxVertices += cset.conts[i].nverts; maxTris += cset.conts[i].nverts - 2; maxVertsPerCont = rcMax(maxVertsPerCont, cset.conts[i].nverts); } if (maxVertices >= 0xfffe) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many vertices %d.", maxVertices); return false; } rcScopedDelete<unsigned char> vflags = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxVertices, RC_ALLOC_TEMP); if (!vflags) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'vflags' (%d).", maxVertices); return false; } memset(vflags, 0, maxVertices); mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertices*3, RC_ALLOC_PERM); if (!mesh.verts) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.verts' (%d).", maxVertices); return false; } mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris*nvp*2, RC_ALLOC_PERM); if (!mesh.polys) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.polys' (%d).", maxTris*nvp*2); return false; } mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxTris, RC_ALLOC_PERM); if (!mesh.regs) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.regs' (%d).", maxTris); return false; } mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxTris, RC_ALLOC_PERM); if (!mesh.areas) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.areas' (%d).", maxTris); return false; } mesh.nverts = 0; mesh.npolys = 0; mesh.nvp = nvp; mesh.maxpolys = maxTris; memset(mesh.verts, 0, sizeof(unsigned short)*maxVertices*3); memset(mesh.polys, 0xff, sizeof(unsigned short)*maxTris*nvp*2); memset(mesh.regs, 0, sizeof(unsigned short)*maxTris); memset(mesh.areas, 0, sizeof(unsigned char)*maxTris); rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVertices, RC_ALLOC_TEMP); if (!nextVert) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'nextVert' (%d).", maxVertices); return false; } memset(nextVert, 0, sizeof(int)*maxVertices); rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP); if (!firstVert) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT); return false; } for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) firstVert[i] = -1; rcScopedDelete<int> indices = (int*)rcAlloc(sizeof(int)*maxVertsPerCont, RC_ALLOC_TEMP); if (!indices) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'indices' (%d).", maxVertsPerCont); return false; } rcScopedDelete<int> tris = (int*)rcAlloc(sizeof(int)*maxVertsPerCont*3, RC_ALLOC_TEMP); if (!tris) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'tris' (%d).", maxVertsPerCont*3); return false; } rcScopedDelete<unsigned short> polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*(maxVertsPerCont+1)*nvp, RC_ALLOC_TEMP); if (!polys) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'polys' (%d).", maxVertsPerCont*nvp); return false; } unsigned short* tmpPoly = &polys[maxVertsPerCont*nvp]; for (int i = 0; i < cset.nconts; ++i) { rcContour& cont = cset.conts[i]; // Skip null contours. if (cont.nverts < 3) continue; // Triangulate contour for (int j = 0; j < cont.nverts; ++j) indices[j] = j; int ntris = triangulate(cont.nverts, cont.verts, &indices[0], &tris[0]); if (ntris <= 0) { // Bad triangulation, should not happen. /* printf("\tconst float bmin[3] = {%ff,%ff,%ff};\n", cset.bmin[0], cset.bmin[1], cset.bmin[2]); printf("\tconst float cs = %ff;\n", cset.cs); printf("\tconst float ch = %ff;\n", cset.ch); printf("\tconst int verts[] = {\n"); for (int k = 0; k < cont.nverts; ++k) { const int* v = &cont.verts[k*4]; printf("\t\t%d,%d,%d,%d,\n", v[0], v[1], v[2], v[3]); } printf("\t};\n\tconst int nverts = sizeof(verts)/(sizeof(int)*4);\n");*/ ctx->log(RC_LOG_WARNING, "rcBuildPolyMesh: Bad triangulation Contour %d.", i); ntris = -ntris; } // Add and merge vertices. for (int j = 0; j < cont.nverts; ++j) { const int* v = &cont.verts[j*4]; indices[j] = addVertex((unsigned short)v[0], (unsigned short)v[1], (unsigned short)v[2], mesh.verts, firstVert, nextVert, mesh.nverts); if (v[3] & RC_BORDER_VERTEX) { // This vertex should be removed. vflags[indices[j]] = 1; } } // Build initial polygons. int npolys = 0; memset(polys, 0xff, maxVertsPerCont*nvp*sizeof(unsigned short)); for (int j = 0; j < ntris; ++j) { int* t = &tris[j*3]; if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2]) { polys[npolys*nvp+0] = (unsigned short)indices[t[0]]; polys[npolys*nvp+1] = (unsigned short)indices[t[1]]; polys[npolys*nvp+2] = (unsigned short)indices[t[2]]; npolys++; } } if (!npolys) continue; // Merge polygons. if (nvp > 3) { for(;;) { // Find best polygons to merge. int bestMergeVal = 0; int bestPa = 0, bestPb = 0, bestEa = 0, bestEb = 0; for (int j = 0; j < npolys-1; ++j) { unsigned short* pj = &polys[j*nvp]; for (int k = j+1; k < npolys; ++k) { unsigned short* pk = &polys[k*nvp]; int ea, eb; int v = getPolyMergeValue(pj, pk, mesh.verts, ea, eb, nvp); if (v > bestMergeVal) { bestMergeVal = v; bestPa = j; bestPb = k; bestEa = ea; bestEb = eb; } } } if (bestMergeVal > 0) { // Found best, merge. unsigned short* pa = &polys[bestPa*nvp]; unsigned short* pb = &polys[bestPb*nvp]; mergePolys(pa, pb, bestEa, bestEb, tmpPoly, nvp); memcpy(pb, &polys[(npolys-1)*nvp], sizeof(unsigned short)*nvp); npolys--; } else { // Could not merge any polygons, stop. break; } } } // Store polygons. for (int j = 0; j < npolys; ++j) { unsigned short* p = &mesh.polys[mesh.npolys*nvp*2]; unsigned short* q = &polys[j*nvp]; for (int k = 0; k < nvp; ++k) p[k] = q[k]; mesh.regs[mesh.npolys] = cont.reg; mesh.areas[mesh.npolys] = cont.area; mesh.npolys++; if (mesh.npolys > maxTris) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Too many polygons %d (max:%d).", mesh.npolys, maxTris); return false; } } } // Remove edge vertices. for (int i = 0; i < mesh.nverts; ++i) { if (vflags[i]) { if (!canRemoveVertex(ctx, mesh, (unsigned short)i)) continue; if (!removeVertex(ctx, mesh, (unsigned short)i, maxTris)) { // Failed to remove vertex ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Failed to remove edge vertex %d.", i); return false; } // Remove vertex // Note: mesh.nverts is already decremented inside removeVertex()! // Fixup vertex flags for (int j = i; j < mesh.nverts; ++j) vflags[j] = vflags[j+1]; --i; } } // Calculate adjacency. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, nvp)) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Adjacency failed."); return false; } // Find portal edges if (mesh.borderSize > 0) { const int w = cset.width; const int h = cset.height; for (int i = 0; i < mesh.npolys; ++i) { unsigned short* p = &mesh.polys[i*2*nvp]; for (int j = 0; j < nvp; ++j) { if (p[j] == RC_MESH_NULL_IDX) break; // Skip connected edges. if (p[nvp+j] != RC_MESH_NULL_IDX) continue; int nj = j+1; if (nj >= nvp || p[nj] == RC_MESH_NULL_IDX) nj = 0; const unsigned short* va = &mesh.verts[p[j]*3]; const unsigned short* vb = &mesh.verts[p[nj]*3]; if ((int)va[0] == 0 && (int)vb[0] == 0) p[nvp+j] = 0x8000 | 0; else if ((int)va[2] == h && (int)vb[2] == h) p[nvp+j] = 0x8000 | 1; else if ((int)va[0] == w && (int)vb[0] == w) p[nvp+j] = 0x8000 | 2; else if ((int)va[2] == 0 && (int)vb[2] == 0) p[nvp+j] = 0x8000 | 3; } } } // Just allocate the mesh flags array. The user is resposible to fill it. mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*mesh.npolys, RC_ALLOC_PERM); if (!mesh.flags) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: Out of memory 'mesh.flags' (%d).", mesh.npolys); return false; } memset(mesh.flags, 0, sizeof(unsigned short) * mesh.npolys); if (mesh.nverts > 0xffff) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff); } if (mesh.npolys > 0xffff) { ctx->log(RC_LOG_ERROR, "rcBuildPolyMesh: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff); } ctx->stopTimer(RC_TIMER_BUILD_POLYMESH); return true; } /// @see rcAllocPolyMesh, rcPolyMesh bool rcMergePolyMeshes(rcContext* ctx, rcPolyMesh** meshes, const int nmeshes, rcPolyMesh& mesh) { rcAssert(ctx); if (!nmeshes || !meshes) return true; ctx->startTimer(RC_TIMER_MERGE_POLYMESH); mesh.nvp = meshes[0]->nvp; mesh.cs = meshes[0]->cs; mesh.ch = meshes[0]->ch; rcVcopy(mesh.bmin, meshes[0]->bmin); rcVcopy(mesh.bmax, meshes[0]->bmax); int maxVerts = 0; int maxPolys = 0; int maxVertsPerMesh = 0; for (int i = 0; i < nmeshes; ++i) { rcVmin(mesh.bmin, meshes[i]->bmin); rcVmax(mesh.bmax, meshes[i]->bmax); maxVertsPerMesh = rcMax(maxVertsPerMesh, meshes[i]->nverts); maxVerts += meshes[i]->nverts; maxPolys += meshes[i]->npolys; } mesh.nverts = 0; mesh.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVerts*3, RC_ALLOC_PERM); if (!mesh.verts) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.verts' (%d).", maxVerts*3); return false; } mesh.npolys = 0; mesh.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys*2*mesh.nvp, RC_ALLOC_PERM); if (!mesh.polys) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.polys' (%d).", maxPolys*2*mesh.nvp); return false; } memset(mesh.polys, 0xff, sizeof(unsigned short)*maxPolys*2*mesh.nvp); mesh.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM); if (!mesh.regs) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.regs' (%d).", maxPolys); return false; } memset(mesh.regs, 0, sizeof(unsigned short)*maxPolys); mesh.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*maxPolys, RC_ALLOC_PERM); if (!mesh.areas) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.areas' (%d).", maxPolys); return false; } memset(mesh.areas, 0, sizeof(unsigned char)*maxPolys); mesh.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxPolys, RC_ALLOC_PERM); if (!mesh.flags) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'mesh.flags' (%d).", maxPolys); return false; } memset(mesh.flags, 0, sizeof(unsigned short)*maxPolys); rcScopedDelete<int> nextVert = (int*)rcAlloc(sizeof(int)*maxVerts, RC_ALLOC_TEMP); if (!nextVert) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'nextVert' (%d).", maxVerts); return false; } memset(nextVert, 0, sizeof(int)*maxVerts); rcScopedDelete<int> firstVert = (int*)rcAlloc(sizeof(int)*VERTEX_BUCKET_COUNT, RC_ALLOC_TEMP); if (!firstVert) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'firstVert' (%d).", VERTEX_BUCKET_COUNT); return false; } for (int i = 0; i < VERTEX_BUCKET_COUNT; ++i) firstVert[i] = -1; rcScopedDelete<unsigned short> vremap = (unsigned short*)rcAlloc(sizeof(unsigned short)*maxVertsPerMesh, RC_ALLOC_PERM); if (!vremap) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Out of memory 'vremap' (%d).", maxVertsPerMesh); return false; } memset(vremap, 0, sizeof(unsigned short)*maxVertsPerMesh); for (int i = 0; i < nmeshes; ++i) { const rcPolyMesh* pmesh = meshes[i]; const unsigned short ox = (unsigned short)floorf((pmesh->bmin[0]-mesh.bmin[0])/mesh.cs+0.5f); const unsigned short oz = (unsigned short)floorf((pmesh->bmin[2]-mesh.bmin[2])/mesh.cs+0.5f); for (int j = 0; j < pmesh->nverts; ++j) { unsigned short* v = &pmesh->verts[j*3]; vremap[j] = addVertex(v[0]+ox, v[1], v[2]+oz, mesh.verts, firstVert, nextVert, mesh.nverts); } for (int j = 0; j < pmesh->npolys; ++j) { unsigned short* tgt = &mesh.polys[mesh.npolys*2*mesh.nvp]; unsigned short* src = &pmesh->polys[j*2*mesh.nvp]; mesh.regs[mesh.npolys] = pmesh->regs[j]; mesh.areas[mesh.npolys] = pmesh->areas[j]; mesh.flags[mesh.npolys] = pmesh->flags[j]; mesh.npolys++; for (int k = 0; k < mesh.nvp; ++k) { if (src[k] == RC_MESH_NULL_IDX) break; tgt[k] = vremap[src[k]]; } } } // Calculate adjacency. if (!buildMeshAdjacency(mesh.polys, mesh.npolys, mesh.nverts, mesh.nvp)) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: Adjacency failed."); return false; } if (mesh.nverts > 0xffff) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many vertices %d (max %d). Data can be corrupted.", mesh.nverts, 0xffff); } if (mesh.npolys > 0xffff) { ctx->log(RC_LOG_ERROR, "rcMergePolyMeshes: The resulting mesh has too many polygons %d (max %d). Data can be corrupted.", mesh.npolys, 0xffff); } ctx->stopTimer(RC_TIMER_MERGE_POLYMESH); return true; } bool rcCopyPolyMesh(rcContext* ctx, const rcPolyMesh& src, rcPolyMesh& dst) { rcAssert(ctx); // Destination must be empty. rcAssert(dst.verts == 0); rcAssert(dst.polys == 0); rcAssert(dst.regs == 0); rcAssert(dst.areas == 0); rcAssert(dst.flags == 0); dst.nverts = src.nverts; dst.npolys = src.npolys; dst.maxpolys = src.npolys; dst.nvp = src.nvp; rcVcopy(dst.bmin, src.bmin); rcVcopy(dst.bmax, src.bmax); dst.cs = src.cs; dst.ch = src.ch; dst.borderSize = src.borderSize; dst.verts = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.nverts*3, RC_ALLOC_PERM); if (!dst.verts) { ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.verts' (%d).", src.nverts*3); return false; } memcpy(dst.verts, src.verts, sizeof(unsigned short)*src.nverts*3); dst.polys = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys*2*src.nvp, RC_ALLOC_PERM); if (!dst.polys) { ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.polys' (%d).", src.npolys*2*src.nvp); return false; } memcpy(dst.polys, src.polys, sizeof(unsigned short)*src.npolys*2*src.nvp); dst.regs = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM); if (!dst.regs) { ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.regs' (%d).", src.npolys); return false; } memcpy(dst.regs, src.regs, sizeof(unsigned short)*src.npolys); dst.areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*src.npolys, RC_ALLOC_PERM); if (!dst.areas) { ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.areas' (%d).", src.npolys); return false; } memcpy(dst.areas, src.areas, sizeof(unsigned char)*src.npolys); dst.flags = (unsigned short*)rcAlloc(sizeof(unsigned short)*src.npolys, RC_ALLOC_PERM); if (!dst.flags) { ctx->log(RC_LOG_ERROR, "rcCopyPolyMesh: Out of memory 'dst.flags' (%d).", src.npolys); return false; } memcpy(dst.flags, src.flags, sizeof(unsigned char)*src.npolys); return true; }
// Copyright (c) 2017-2020 The Ocvcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/muhash.h> #include <crypto/chacha20.h> #include <crypto/common.h> #include <hash.h> #include <cassert> #include <cstdio> #include <limits> namespace { using limb_t = Num3072::limb_t; using double_limb_t = Num3072::double_limb_t; constexpr int LIMB_SIZE = Num3072::LIMB_SIZE; /** 2^3072 - 1103717, the largest 3072-bit safe prime number, is used as the modulus. */ constexpr limb_t MAX_PRIME_DIFF = 1103717; /** Extract the lowest limb of [c0,c1,c2] into n, and left shift the number by 1 limb. */ inline void extract3(limb_t& c0, limb_t& c1, limb_t& c2, limb_t& n) { n = c0; c0 = c1; c1 = c2; c2 = 0; } /** [c0,c1] = a * b */ inline void mul(limb_t& c0, limb_t& c1, const limb_t& a, const limb_t& b) { double_limb_t t = (double_limb_t)a * b; c1 = t >> LIMB_SIZE; c0 = t; } /* [c0,c1,c2] += n * [d0,d1,d2]. c2 is 0 initially */ inline void mulnadd3(limb_t& c0, limb_t& c1, limb_t& c2, limb_t& d0, limb_t& d1, limb_t& d2, const limb_t& n) { double_limb_t t = (double_limb_t)d0 * n + c0; c0 = t; t >>= LIMB_SIZE; t += (double_limb_t)d1 * n + c1; c1 = t; t >>= LIMB_SIZE; c2 = t + d2 * n; } /* [c0,c1] *= n */ inline void muln2(limb_t& c0, limb_t& c1, const limb_t& n) { double_limb_t t = (double_limb_t)c0 * n; c0 = t; t >>= LIMB_SIZE; t += (double_limb_t)c1 * n; c1 = t; } /** [c0,c1,c2] += a * b */ inline void muladd3(limb_t& c0, limb_t& c1, limb_t& c2, const limb_t& a, const limb_t& b) { double_limb_t t = (double_limb_t)a * b; limb_t th = t >> LIMB_SIZE; limb_t tl = t; c0 += tl; th += (c0 < tl) ? 1 : 0; c1 += th; c2 += (c1 < th) ? 1 : 0; } /** [c0,c1,c2] += 2 * a * b */ inline void muldbladd3(limb_t& c0, limb_t& c1, limb_t& c2, const limb_t& a, const limb_t& b) { double_limb_t t = (double_limb_t)a * b; limb_t th = t >> LIMB_SIZE; limb_t tl = t; c0 += tl; limb_t tt = th + ((c0 < tl) ? 1 : 0); c1 += tt; c2 += (c1 < tt) ? 1 : 0; c0 += tl; th += (c0 < tl) ? 1 : 0; c1 += th; c2 += (c1 < th) ? 1 : 0; } /** * Add limb a to [c0,c1]: [c0,c1] += a. Then extract the lowest * limb of [c0,c1] into n, and left shift the number by 1 limb. * */ inline void addnextract2(limb_t& c0, limb_t& c1, const limb_t& a, limb_t& n) { limb_t c2 = 0; // add c0 += a; if (c0 < a) { c1 += 1; // Handle case when c1 has overflown if (c1 == 0) c2 = 1; } // extract n = c0; c0 = c1; c1 = c2; } /** in_out = in_out^(2^sq) * mul */ inline void square_n_mul(Num3072& in_out, const int sq, const Num3072& mul) { for (int j = 0; j < sq; ++j) in_out.Square(); in_out.Multiply(mul); } } // namespace /** Indicates whether d is larger than the modulus. */ bool Num3072::IsOverflow() const { if (this->limbs[0] <= std::numeric_limits<limb_t>::max() - MAX_PRIME_DIFF) return false; for (int i = 1; i < LIMBS; ++i) { if (this->limbs[i] != std::numeric_limits<limb_t>::max()) return false; } return true; } void Num3072::FullReduce() { limb_t c0 = MAX_PRIME_DIFF; limb_t c1 = 0; for (int i = 0; i < LIMBS; ++i) { addnextract2(c0, c1, this->limbs[i], this->limbs[i]); } } Num3072 Num3072::GetInverse() const { // For fast exponentiation a sliding window exponentiation with repunit // precomputation is utilized. See "Fast Point Decompression for Standard // Elliptic Curves" (Brumley, Järvinen, 2008). Num3072 p[12]; // p[i] = a^(2^(2^i)-1) Num3072 out; p[0] = *this; for (int i = 0; i < 11; ++i) { p[i + 1] = p[i]; for (int j = 0; j < (1 << i); ++j) p[i + 1].Square(); p[i + 1].Multiply(p[i]); } out = p[11]; square_n_mul(out, 512, p[9]); square_n_mul(out, 256, p[8]); square_n_mul(out, 128, p[7]); square_n_mul(out, 64, p[6]); square_n_mul(out, 32, p[5]); square_n_mul(out, 8, p[3]); square_n_mul(out, 2, p[1]); square_n_mul(out, 1, p[0]); square_n_mul(out, 5, p[2]); square_n_mul(out, 3, p[0]); square_n_mul(out, 2, p[0]); square_n_mul(out, 4, p[0]); square_n_mul(out, 4, p[1]); square_n_mul(out, 3, p[0]); return out; } void Num3072::Multiply(const Num3072& a) { limb_t c0 = 0, c1 = 0, c2 = 0; Num3072 tmp; /* Compute limbs 0..N-2 of this*a into tmp, including one reduction. */ for (int j = 0; j < LIMBS - 1; ++j) { limb_t d0 = 0, d1 = 0, d2 = 0; mul(d0, d1, this->limbs[1 + j], a.limbs[LIMBS + j - (1 + j)]); for (int i = 2 + j; i < LIMBS; ++i) muladd3(d0, d1, d2, this->limbs[i], a.limbs[LIMBS + j - i]); mulnadd3(c0, c1, c2, d0, d1, d2, MAX_PRIME_DIFF); for (int i = 0; i < j + 1; ++i) muladd3(c0, c1, c2, this->limbs[i], a.limbs[j - i]); extract3(c0, c1, c2, tmp.limbs[j]); } /* Compute limb N-1 of a*b into tmp. */ assert(c2 == 0); for (int i = 0; i < LIMBS; ++i) muladd3(c0, c1, c2, this->limbs[i], a.limbs[LIMBS - 1 - i]); extract3(c0, c1, c2, tmp.limbs[LIMBS - 1]); /* Perform a second reduction. */ muln2(c0, c1, MAX_PRIME_DIFF); for (int j = 0; j < LIMBS; ++j) { addnextract2(c0, c1, tmp.limbs[j], this->limbs[j]); } assert(c1 == 0); assert(c0 == 0 || c0 == 1); /* Perform up to two more reductions if the internal state has already * overflown the MAX of Num3072 or if it is larger than the modulus or * if both are the case. * */ if (this->IsOverflow()) this->FullReduce(); if (c0) this->FullReduce(); } void Num3072::Square() { limb_t c0 = 0, c1 = 0, c2 = 0; Num3072 tmp; /* Compute limbs 0..N-2 of this*this into tmp, including one reduction. */ for (int j = 0; j < LIMBS - 1; ++j) { limb_t d0 = 0, d1 = 0, d2 = 0; for (int i = 0; i < (LIMBS - 1 - j) / 2; ++i) muldbladd3(d0, d1, d2, this->limbs[i + j + 1], this->limbs[LIMBS - 1 - i]); if ((j + 1) & 1) muladd3(d0, d1, d2, this->limbs[(LIMBS - 1 - j) / 2 + j + 1], this->limbs[LIMBS - 1 - (LIMBS - 1 - j) / 2]); mulnadd3(c0, c1, c2, d0, d1, d2, MAX_PRIME_DIFF); for (int i = 0; i < (j + 1) / 2; ++i) muldbladd3(c0, c1, c2, this->limbs[i], this->limbs[j - i]); if ((j + 1) & 1) muladd3(c0, c1, c2, this->limbs[(j + 1) / 2], this->limbs[j - (j + 1) / 2]); extract3(c0, c1, c2, tmp.limbs[j]); } assert(c2 == 0); for (int i = 0; i < LIMBS / 2; ++i) muldbladd3(c0, c1, c2, this->limbs[i], this->limbs[LIMBS - 1 - i]); extract3(c0, c1, c2, tmp.limbs[LIMBS - 1]); /* Perform a second reduction. */ muln2(c0, c1, MAX_PRIME_DIFF); for (int j = 0; j < LIMBS; ++j) { addnextract2(c0, c1, tmp.limbs[j], this->limbs[j]); } assert(c1 == 0); assert(c0 == 0 || c0 == 1); /* Perform up to two more reductions if the internal state has already * overflown the MAX of Num3072 or if it is larger than the modulus or * if both are the case. * */ if (this->IsOverflow()) this->FullReduce(); if (c0) this->FullReduce(); } void Num3072::SetToOne() { this->limbs[0] = 1; for (int i = 1; i < LIMBS; ++i) this->limbs[i] = 0; } void Num3072::Divide(const Num3072& a) { if (this->IsOverflow()) this->FullReduce(); Num3072 inv{}; if (a.IsOverflow()) { Num3072 b = a; b.FullReduce(); inv = b.GetInverse(); } else { inv = a.GetInverse(); } this->Multiply(inv); if (this->IsOverflow()) this->FullReduce(); } Num3072::Num3072(const unsigned char (&data)[BYTE_SIZE]) { for (int i = 0; i < LIMBS; ++i) { if (sizeof(limb_t) == 4) { this->limbs[i] = ReadLE32(data + 4 * i); } else if (sizeof(limb_t) == 8) { this->limbs[i] = ReadLE64(data + 8 * i); } } } void Num3072::ToBytes(unsigned char (&out)[BYTE_SIZE]) { for (int i = 0; i < LIMBS; ++i) { if (sizeof(limb_t) == 4) { WriteLE32(out + i * 4, this->limbs[i]); } else if (sizeof(limb_t) == 8) { WriteLE64(out + i * 8, this->limbs[i]); } } } Num3072 MuHash3072::ToNum3072(Span<const unsigned char> in) { unsigned char tmp[Num3072::BYTE_SIZE]; uint256 hashed_in = (CHashWriter(SER_DISK, 0) << in).GetSHA256(); ChaCha20(hashed_in.data(), hashed_in.size()).Keystream(tmp, Num3072::BYTE_SIZE); Num3072 out{tmp}; return out; } MuHash3072::MuHash3072(Span<const unsigned char> in) noexcept { m_numerator = ToNum3072(in); } void MuHash3072::Finalize(uint256& out) noexcept { m_numerator.Divide(m_denominator); m_denominator.SetToOne(); // Needed to keep the MuHash object valid unsigned char data[Num3072::BYTE_SIZE]; m_numerator.ToBytes(data); out = (CHashWriter(SER_DISK, 0) << data).GetSHA256(); } MuHash3072& MuHash3072::operator*=(const MuHash3072& mul) noexcept { m_numerator.Multiply(mul.m_numerator); m_denominator.Multiply(mul.m_denominator); return *this; } MuHash3072& MuHash3072::operator/=(const MuHash3072& div) noexcept { m_numerator.Multiply(div.m_denominator); m_denominator.Multiply(div.m_numerator); return *this; } MuHash3072& MuHash3072::Insert(Span<const unsigned char> in) noexcept { m_numerator.Multiply(ToNum3072(in)); return *this; } MuHash3072& MuHash3072::Remove(Span<const unsigned char> in) noexcept { m_denominator.Multiply(ToNum3072(in)); return *this; }
/** * \file * \date April 15, 2013 * \author Zermingore * \namespace graphics * \brief GraphicsEngine class declaration */ #ifndef GRAPHICS_GRAPHICS_ENGINE_HH_ # define GRAPHICS_GRAPHICS_ENGINE_HH_ # include <memory> # include <mutex> # include <SFML/Graphics/RenderWindow.hpp> # include <SFML/Window/Event.hpp> # include <graphics/graphic_types.hh> class Map; class Cell; class Unit; class Battle; class Interface; class TerrainsHandler; namespace graphics { /** * \class GraphicsEngine * \brief Manages the display of the scene */ class GraphicsEngine { public: /** * \brief Draws the whole scene. * - calls others drawing functions * - updates the window * \note Drawing while the window is not closed */ static void drawScene(const std::shared_ptr<Battle>& battle); /** * \brief Draw the interface of the current Player. * \note called by a State */ static void drawInterface(); /** * \brief _window setter. Disable the screenshot request, if any * (used for initialization) * \note Takes the ownership of the given unique pointer */ static void setWindow(std::unique_ptr<RenderWindow> window) { _window = std::move(window); _takeScreenshot = false; } /** * \brief Set the offset between the window border and the grid * \param map Used to get the number of columns and lines of the map */ static void setGridOffset(const std::shared_ptr<const Map>& map); /** * \brief Close the window on request; exiting the main loop * \note does not return */ [[ noreturn ]] static void exitRequest(); /** * \brief Return the next event on the window if any */ static auto pollEvent(sf::Event& event) { return _window->pollEvent(event); } /** * \brief Window size getter */ static auto windowSize() { return _window->getSize(); } /** * \brief Draws the given element * \param drawable shared pointer to an item to draw */ template <typename T> static void draw(const std::shared_ptr<T> drawable) { _window->draw(*drawable); } /** * \brief Draws the given element * \param drawable item to draw */ template <typename T> static void draw(const T drawable) { _window->draw(drawable); } /** * \brief Only performs a screenshot request * The boolean is check at each frame (instead of locking the window) */ static void screenshotRequest() { _takeScreenshot = true; } /** * \brief Resize the rendered view when the window get resized * \param width New window width * \param height New window height */ static void resizeWindow(unsigned int width, unsigned int height); private: /** * \brief Draw the map background */ static void drawBackground(); /** * \brief Draw the panel, if activated */ static void drawPanel(); /** * \brief Draws cells content (terrain, unit). * \param battle Battle content to draw. */ static void drawMap(const std::shared_ptr<Battle>& battle); /** * \brief Draws the grid, graphic cells separator. * \param map for which we draw the grid. */ static void drawGrid(const std::shared_ptr<Map>& map); /** * \brief Draws the given Unit. * \param unit Unit to draw. */ static void drawUnit(const std::shared_ptr<Unit>& unit); /** * \brief Draws the elements related to the given State */ static void drawState(); /** * \brief Save the current rendered image to a file */ static void screenshot(); static std::unique_ptr<sf::RenderWindow> _window; ///< graphics window static bool _exit; ///< true: got request to quit static bool _takeScreenshot; ///< true when a screenshot is requested static std::unique_ptr<TerrainsHandler> _terrainsHandler; ///< Terrains list }; } // namespace graphics #endif /* !GRAPHICS_GRAPHICS_ENGINE_HH_ */
// Copyright (c) 2017-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include <fstream> #include <dirent.h> #include <stdlib.h> #include <systemd/sd-daemon.h> #include <systemd/sd-event.h> #include "Systemd.h" #include "Util.h" #include "Logger.h" const std::string Systemd::SYSTEMD_CONFIG_PATH = "/lib/systemd/system/"; Systemd::Systemd() { m_state = "READY=1\n" "STATUS=initctl notifies ready event"; } Systemd::~Systemd() { } bool Systemd::notify(string name) { pid_t pid = getPid(name); if (pid <= 0) { g_logger.write("[FATAL] Negative PID"); return false; } char debug[256]; snprintf(debug, sizeof(debug), "[DEBUG] name(%s) / pid(%d)", name.c_str(), pid); g_logger.write(debug); if (sd_pid_notify(pid, 0, m_state.c_str()) <= 0) { g_logger.write("[FATAL] Failed in sd_pid_notify"); return false; } return true; } bool Systemd::startUnit(string name, bool isBlock) { std::string unitFilePath = SYSTEMD_CONFIG_PATH + name; g_logger.write("[INFO] UNIT_PATH : " + unitFilePath); std::ifstream unitStream(unitFilePath.c_str()); if (!unitStream.good()) { g_logger.write("[FATAL] Cannot find unit"); return false; } std::string command = "systemctl start "; if (!isBlock) command += "--no-block "; command += name; std::string result = Util::exec(command); return true; } pid_t Systemd::getPid(string processName) { pid_t pid = -1; // Open the /proc directory DIR* dir = opendir("/proc"); if (dir == NULL) return -1; // Enumerate all entries in directory until process found struct dirent* entry; while (pid < 0 && (entry = readdir(dir))) { // Skip non-numeric entries int id = atoi(entry->d_name); if (id <= 0) continue; // Read contents of virtual /proc/{pid}/cmdline file string cmdlinePath = string("/proc/") + entry->d_name + "/cmdline"; ifstream cmdlineStream(cmdlinePath.c_str()); string cmdline; getline(cmdlineStream, cmdline); // /proc/{pid}/cmdline is empty if (cmdline.empty()) continue; // Keep first cmdline item which contains the program path size_t pos = cmdline.find('\0'); if (pos != string::npos) cmdline = cmdline.substr(0, pos); // Keep program name only, removing the path pos = cmdline.rfind('/'); if (pos != string::npos) cmdline = cmdline.substr(pos + 1); // Compare against requested process name if (processName == cmdline) pid = id; } closedir(dir); return pid; }
#include<boost/asio.hpp> #include "server.hpp" #include <boost/array.hpp> server::server(boost::asio::io_service* io_service, unsigned short port) : acceptor(*io_service, boost::asio::local::stream_protocol::endpoint("/home/anghenfil/foobar")){ start_accept(); } using boost::asio::ip::tcp; void server::start_accept(){ boost::shared_ptr<ipc_connection> new_connection = ipc_connection::create(acceptor.get_io_service()); acceptor.async_accept(new_connection->socket(), boost::bind(&server::handle_accept, this, new_connection, _1)); } void server::handle_accept(boost::shared_ptr<ipc_connection> new_connection, const boost::system::error_code& error){ if(!error){ new_connection->start(); start_accept(); } }
#include "debug_lldb.h" #include <stdio.h> #ifdef __APPLE__ #include <stdlib.h> #endif #include <boost/filesystem.hpp> #include <iostream> #include "terminal.h" #include "filesystem.h" #include "process.hpp" #include "config.h" extern char **environ; void log(const char *msg, void *) { std::cout << "debugger log: " << msg << std::endl; } Debug::LLDB::LLDB(): state(lldb::StateType::eStateInvalid), buffer_size(131072) { if(!getenv("LLDB_DEBUGSERVER_PATH")) { #ifdef __APPLE__ std::string debug_server_path("/usr/local/opt/llvm/bin/debugserver"); if(boost::filesystem::exists(debug_server_path)) setenv("LLDB_DEBUGSERVER_PATH", debug_server_path.c_str(), 0); #else auto debug_server_path = filesystem::get_executable("lldb-server").string(); if(debug_server_path != "lldb-server") setenv("LLDB_DEBUGSERVER_PATH", debug_server_path.c_str(), 0); #endif } } std::tuple<std::vector<std::string>, std::string, std::vector<std::string> > Debug::LLDB::parse_run_arguments(const std::string &command) { std::vector<std::string> environment; std::string executable; std::vector<std::string> arguments; size_t start_pos=std::string::npos; bool quote=false; bool double_quote=false; size_t backslash_count=0; for(size_t c=0;c<=command.size();c++) { if(c==command.size() || (!quote && !double_quote && backslash_count%2==0 && command[c]==' ')) { if(c>0 && start_pos!=std::string::npos) { auto argument=command.substr(start_pos, c-start_pos); if(executable.empty()) { //Check for environment variable bool env_arg=false; for(size_t c=0;c<argument.size();++c) { if((argument[c]>='a' && argument[c]<='z') || (argument[c]>='A' && argument[c]<='Z') || (argument[c]>='0' && argument[c]<='9') || argument[c]=='_') continue; else if(argument[c]=='=' && c+1<argument.size()) { environment.emplace_back(argument.substr(0, c+1)+filesystem::unescape_argument(argument.substr(c+1))); env_arg=true; break; } else break; } if(!env_arg) { executable=filesystem::unescape_argument(argument); #ifdef _WIN32 if(remote_host.empty()) executable+=".exe"; #endif } } else arguments.emplace_back(filesystem::unescape_argument(argument)); start_pos=std::string::npos; } } else if(command[c]=='\'' && backslash_count%2==0 && !double_quote) quote=!quote; else if(command[c]=='"' && backslash_count%2==0 && !quote) double_quote=!double_quote; else if(command[c]=='\\' && !quote && !double_quote) ++backslash_count; else backslash_count=0; if(c<command.size() && start_pos==std::string::npos && command[c]!=' ') start_pos=c; } return std::make_tuple(environment, executable, arguments); } void Debug::LLDB::start(const std::string &command, const boost::filesystem::path &path, const std::vector<std::pair<boost::filesystem::path, int> > &breakpoints, const std::vector<std::string> &startup_commands, const std::string &remote_host) { if(!debugger) { lldb::SBDebugger::Initialize(); debugger=std::make_unique<lldb::SBDebugger>(lldb::SBDebugger::Create(true, log, nullptr)); listener=std::make_unique<lldb::SBListener>("juCi++ lldb listener"); } //Create executable string and argument array auto parsed_run_arguments=parse_run_arguments(command); auto &environment_from_arguments=std::get<0>(parsed_run_arguments); auto &executable=std::get<1>(parsed_run_arguments); auto &arguments=std::get<2>(parsed_run_arguments); std::vector<const char*> argv; for(size_t c=0;c<arguments.size();c++) argv.emplace_back(arguments[c].c_str()); argv.emplace_back(nullptr); auto target=debugger->CreateTarget(executable.c_str()); if(!target.IsValid()) { Terminal::get().async_print("Error (debug): Could not create debug target to: "+executable+'\n', true); for(auto &handler: on_exit) handler(-1); return; } //Set breakpoints for(auto &breakpoint: breakpoints) { if(!(target.BreakpointCreateByLocation(breakpoint.first.string().c_str(), breakpoint.second)).IsValid()) { Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+breakpoint.first.string()+":"+std::to_string(breakpoint.second)+'\n', true); for(auto &handler: on_exit) handler(-1); return; } } lldb::SBError error; if(!remote_host.empty()) { auto connect_string="connect://"+remote_host; process = std::make_unique<lldb::SBProcess>(target.ConnectRemote(*listener, connect_string.c_str(), "gdb-remote", error)); if(error.Fail()) { Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); for(auto &handler: on_exit) handler(-1); return; } lldb::SBEvent event; while(true) { if(listener->GetNextEvent(event)) { if((event.GetType() & lldb::SBProcess::eBroadcastBitStateChanged)>0) { auto state=process->GetStateFromEvent(event); this->state=state; if(state==lldb::StateType::eStateConnected) break; } } } // Create environment array std::vector<const char*> environment; for(auto &e: environment_from_arguments) environment.emplace_back(e.c_str()); environment.emplace_back(nullptr); process->RemoteLaunch(argv.data(), environment.data(), nullptr, nullptr, nullptr, nullptr, lldb::eLaunchFlagNone, false, error); if(!error.Fail()) process->Continue(); } else { // Create environment array std::vector<const char*> environment; for(auto &e: environment_from_arguments) environment.emplace_back(e.c_str()); size_t environ_size=0; while(environ[environ_size]!=nullptr) ++environ_size; for(size_t c=0;c<environ_size;++c) environment.emplace_back(environ[c]); environment.emplace_back(nullptr); process = std::make_unique<lldb::SBProcess>(target.Launch(*listener, argv.data(), environment.data(), nullptr, nullptr, nullptr, path.string().c_str(), lldb::eLaunchFlagNone, false, error)); } if(error.Fail()) { Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); for(auto &handler: on_exit) handler(-1); return; } if(debug_thread.joinable()) debug_thread.join(); for(auto &handler: on_start) handler(*process); for(auto &command: startup_commands) { lldb::SBCommandReturnObject command_return_object; debugger->GetCommandInterpreter().HandleCommand(command.c_str(), command_return_object, false); } debug_thread=std::thread([this]() { lldb::SBEvent event; while(true) { std::unique_lock<std::mutex> lock(mutex); if(listener->GetNextEvent(event)) { if((event.GetType() & lldb::SBProcess::eBroadcastBitStateChanged)>0) { auto state=process->GetStateFromEvent(event); this->state=state; if(state==lldb::StateType::eStateStopped) { for(uint32_t c=0;c<process->GetNumThreads();c++) { auto thread=process->GetThreadAtIndex(c); if(thread.GetStopReason()>=2) { process->SetSelectedThreadByIndexID(thread.GetIndexID()); break; } } } lock.unlock(); for(auto &handler: on_event) handler(event); lock.lock(); if(state==lldb::StateType::eStateExited || state==lldb::StateType::eStateCrashed) { auto exit_status=state==lldb::StateType::eStateCrashed?-1:process->GetExitStatus(); lock.unlock(); for(auto &handler: on_exit) handler(exit_status); lock.lock(); process.reset(); this->state=lldb::StateType::eStateInvalid; return; } } if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDOUT)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDOUT(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n)); } //TODO: for some reason stderr is redirected to stdout if((event.GetType() & lldb::SBProcess::eBroadcastBitSTDERR)>0) { char buffer[buffer_size]; size_t n; while((n=process->GetSTDERR(buffer, buffer_size))!=0) Terminal::get().async_print(std::string(buffer, n), true); } } lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(200)); } }); } void Debug::LLDB::continue_debug() { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) process->Continue(); } void Debug::LLDB::stop() { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateRunning) { auto error=process->Stop(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } } void Debug::LLDB::kill() { std::unique_lock<std::mutex> lock(mutex); if(process) { auto error=process->Kill(); if(error.Fail()) Terminal::get().async_print(std::string("Error (debug): ")+error.GetCString()+'\n', true); } } void Debug::LLDB::step_over() { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { process->GetSelectedThread().StepOver(); } } void Debug::LLDB::step_into() { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { process->GetSelectedThread().StepInto(); } } void Debug::LLDB::step_out() { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { process->GetSelectedThread().StepOut(); } } std::pair<std::string, std::string> Debug::LLDB::run_command(const std::string &command) { std::pair<std::string, std::string> command_return; std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped || state==lldb::StateType::eStateRunning) { lldb::SBCommandReturnObject command_return_object; debugger->GetCommandInterpreter().HandleCommand(command.c_str(), command_return_object, true); auto output=command_return_object.GetOutput(); if(output) command_return.first=output; auto error=command_return_object.GetError(); if(error) command_return.second=error; } return command_return; } std::vector<Debug::LLDB::Frame> Debug::LLDB::get_backtrace() { std::vector<Frame> backtrace; std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { auto thread=process->GetSelectedThread(); for(uint32_t c_f=0;c_f<thread.GetNumFrames();c_f++) { Frame backtrace_frame; auto frame=thread.GetFrameAtIndex(c_f); backtrace_frame.index=c_f; if(frame.GetFunctionName()!=nullptr) backtrace_frame.function_name=frame.GetFunctionName(); auto module_filename=frame.GetModule().GetFileSpec().GetFilename(); if(module_filename!=nullptr) { backtrace_frame.module_filename=module_filename; } auto line_entry=frame.GetLineEntry(); if(line_entry.IsValid()) { lldb::SBStream stream; line_entry.GetFileSpec().GetDescription(stream); auto column=line_entry.GetColumn(); if(column==0) column=1; backtrace_frame.file_path=filesystem::get_normal_path(stream.GetData()); backtrace_frame.line_nr=line_entry.GetLine(); backtrace_frame.line_index=column; } backtrace.emplace_back(backtrace_frame); } } return backtrace; } std::vector<Debug::LLDB::Variable> Debug::LLDB::get_variables() { std::vector<Debug::LLDB::Variable> variables; std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { for(uint32_t c_t=0;c_t<process->GetNumThreads();c_t++) { auto thread=process->GetThreadAtIndex(c_t); for(uint32_t c_f=0;c_f<thread.GetNumFrames();c_f++) { auto frame=thread.GetFrameAtIndex(c_f); auto values=frame.GetVariables(true, true, true, false); for(uint32_t value_index=0;value_index<values.GetSize();value_index++) { lldb::SBStream stream; auto value=values.GetValueAtIndex(value_index); Debug::LLDB::Variable variable; variable.thread_index_id=thread.GetIndexID(); variable.frame_index=c_f; if(value.GetName()!=nullptr) variable.name=value.GetName(); value.GetDescription(stream); variable.value=stream.GetData(); auto declaration=value.GetDeclaration(); if(declaration.IsValid()) { variable.declaration_found=true; variable.line_nr=declaration.GetLine(); variable.line_index=declaration.GetColumn(); if(variable.line_index==0) variable.line_index=1; auto file_spec=declaration.GetFileSpec(); variable.file_path=filesystem::get_normal_path(file_spec.GetDirectory()); variable.file_path/=file_spec.GetFilename(); } else { variable.declaration_found=false; auto line_entry=frame.GetLineEntry(); if(line_entry.IsValid()) { variable.line_nr=line_entry.GetLine(); variable.line_index=line_entry.GetColumn(); if(variable.line_index==0) variable.line_index=1; auto file_spec=line_entry.GetFileSpec(); variable.file_path=filesystem::get_normal_path(file_spec.GetDirectory()); variable.file_path/=file_spec.GetFilename(); } } variables.emplace_back(variable); } } } } return variables; } void Debug::LLDB::select_frame(uint32_t frame_index, uint32_t thread_index_id) { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { if(thread_index_id!=0) process->SetSelectedThreadByIndexID(thread_index_id); process->GetSelectedThread().SetSelectedFrame(frame_index);; } } void Debug::LLDB::cancel() { kill(); if(debug_thread.joinable()) debug_thread.join(); } std::string Debug::LLDB::get_value(const std::string &variable, const boost::filesystem::path &file_path, unsigned int line_nr, unsigned int line_index) { std::string variable_value; std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { auto frame=process->GetSelectedThread().GetSelectedFrame(); auto values=frame.GetVariables(true, true, true, false); //First try to find variable based on name, file and line number if(!file_path.empty()) { for(uint32_t value_index=0;value_index<values.GetSize();value_index++) { lldb::SBStream stream; auto value=values.GetValueAtIndex(value_index); if(value.GetName()!=nullptr && value.GetName()==variable) { auto declaration=value.GetDeclaration(); if(declaration.IsValid()) { if(declaration.GetLine()==line_nr && (declaration.GetColumn()==0 || declaration.GetColumn()==line_index)) { auto file_spec=declaration.GetFileSpec(); auto value_decl_path=filesystem::get_normal_path(file_spec.GetDirectory()); value_decl_path/=file_spec.GetFilename(); if(value_decl_path==file_path) { value.GetDescription(stream); variable_value=stream.GetData(); break; } } } } } } if(variable_value.empty()) { //In case a variable is missing file and line number, only do check on name auto value=frame.GetValueForVariablePath(variable.c_str()); if(value.IsValid()) { lldb::SBStream stream; value.GetDescription(stream); variable_value=stream.GetData(); } } } return variable_value; } std::string Debug::LLDB::get_return_value(const boost::filesystem::path &file_path, unsigned int line_nr, unsigned int line_index) { std::string return_value; std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateStopped) { auto thread=process->GetSelectedThread(); auto thread_return_value=thread.GetStopReturnValue(); if(thread_return_value.IsValid()) { auto line_entry=thread.GetSelectedFrame().GetLineEntry(); if(line_entry.IsValid()) { lldb::SBStream stream; line_entry.GetFileSpec().GetDescription(stream); if(filesystem::get_normal_path(stream.GetData())==file_path && line_entry.GetLine()==line_nr && (line_entry.GetColumn()==0 || line_entry.GetColumn()==line_index)) { lldb::SBStream stream; thread_return_value.GetDescription(stream); return_value=stream.GetData(); } } } } return return_value; } bool Debug::LLDB::is_invalid() { std::unique_lock<std::mutex> lock(mutex); return state==lldb::StateType::eStateInvalid; } bool Debug::LLDB::is_stopped() { std::unique_lock<std::mutex> lock(mutex); return state==lldb::StateType::eStateStopped; } bool Debug::LLDB::is_running() { std::unique_lock<std::mutex> lock(mutex); return state==lldb::StateType::eStateRunning; } void Debug::LLDB::add_breakpoint(const boost::filesystem::path &file_path, int line_nr) { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { if(!(process->GetTarget().BreakpointCreateByLocation(file_path.string().c_str(), line_nr)).IsValid()) Terminal::get().async_print("Error (debug): Could not create breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); } } void Debug::LLDB::remove_breakpoint(const boost::filesystem::path &file_path, int line_nr, int line_count) { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::eStateStopped || state==lldb::eStateRunning) { auto target=process->GetTarget(); for(int line_nr_try=line_nr;line_nr_try<line_count;line_nr_try++) { for(uint32_t b_index=0;b_index<target.GetNumBreakpoints();b_index++) { auto breakpoint=target.GetBreakpointAtIndex(b_index); for(uint32_t l_index=0;l_index<breakpoint.GetNumLocations();l_index++) { auto line_entry=breakpoint.GetLocationAtIndex(l_index).GetAddress().GetLineEntry(); if(line_entry.GetLine()==static_cast<uint32_t>(line_nr_try)) { auto file_spec=line_entry.GetFileSpec(); auto breakpoint_path=filesystem::get_normal_path(file_spec.GetDirectory()); breakpoint_path/=file_spec.GetFilename(); if(breakpoint_path==file_path) { if(!target.BreakpointDelete(breakpoint.GetID())) Terminal::get().async_print("Error (debug): Could not delete breakpoint at: "+file_path.string()+":"+std::to_string(line_nr)+'\n', true); return; } } } } } } } void Debug::LLDB::write(const std::string &buffer) { std::unique_lock<std::mutex> lock(mutex); if(state==lldb::StateType::eStateRunning) { process->PutSTDIN(buffer.c_str(), buffer.size()); } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/api/test/test_api.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/extensions/extension.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "net/base/net_util.h" #include "net/test/test_server.h" namespace { const char kTestServerPort[] = "testServer.port"; const char kTestDataDirectory[] = "testDataDirectory"; const char kTestWebSocketPort[] = "testWebSocketPort"; }; // namespace ExtensionApiTest::ExtensionApiTest() {} ExtensionApiTest::~ExtensionApiTest() {} ExtensionApiTest::ResultCatcher::ResultCatcher() : profile_restriction_(NULL), waiting_(false) { registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_TEST_PASSED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_TEST_FAILED, content::NotificationService::AllSources()); } ExtensionApiTest::ResultCatcher::~ResultCatcher() { } bool ExtensionApiTest::ResultCatcher::GetNextResult() { // Depending on the tests, multiple results can come in from a single call // to RunMessageLoop(), so we maintain a queue of results and just pull them // off as the test calls this, going to the run loop only when the queue is // empty. if (results_.empty()) { waiting_ = true; content::RunMessageLoop(); waiting_ = false; } if (!results_.empty()) { bool ret = results_.front(); results_.pop_front(); message_ = messages_.front(); messages_.pop_front(); return ret; } NOTREACHED(); return false; } void ExtensionApiTest::ResultCatcher::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (profile_restriction_ && content::Source<Profile>(source).ptr() != profile_restriction_) { return; } switch (type) { case chrome::NOTIFICATION_EXTENSION_TEST_PASSED: VLOG(1) << "Got EXTENSION_TEST_PASSED notification."; results_.push_back(true); messages_.push_back(""); if (waiting_) MessageLoopForUI::current()->Quit(); break; case chrome::NOTIFICATION_EXTENSION_TEST_FAILED: VLOG(1) << "Got EXTENSION_TEST_FAILED notification."; results_.push_back(false); messages_.push_back(*(content::Details<std::string>(details).ptr())); if (waiting_) MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); } } void ExtensionApiTest::SetUpInProcessBrowserTestFixture() { DCHECK(!test_config_.get()) << "Previous test did not clear config state."; test_config_.reset(new DictionaryValue()); test_config_->SetString(kTestDataDirectory, net::FilePathToFileURL(test_data_dir_).spec()); test_config_->SetInteger(kTestWebSocketPort, 0); extensions::TestGetConfigFunction::set_test_config_state( test_config_.get()); } void ExtensionApiTest::TearDownInProcessBrowserTestFixture() { extensions::TestGetConfigFunction::set_test_config_state(NULL); test_config_.reset(NULL); } bool ExtensionApiTest::RunExtensionTest(const char* extension_name) { return RunExtensionTestImpl(extension_name, "", kFlagEnableFileAccess); } bool ExtensionApiTest::RunExtensionTestIncognito(const char* extension_name) { return RunExtensionTestImpl( extension_name, "", kFlagEnableIncognito | kFlagEnableFileAccess); } bool ExtensionApiTest::RunExtensionTestIgnoreManifestWarnings( const char* extension_name) { return RunExtensionTestImpl( extension_name, "", kFlagIgnoreManifestWarnings); } bool ExtensionApiTest::RunExtensionTestAllowOldManifestVersion( const char* extension_name) { return RunExtensionTestImpl( extension_name, "", kFlagEnableFileAccess | kFlagAllowOldManifestVersions); } bool ExtensionApiTest::RunComponentExtensionTest(const char* extension_name) { return RunExtensionTestImpl( extension_name, "", kFlagEnableFileAccess | kFlagLoadAsComponent); } bool ExtensionApiTest::RunExtensionTestNoFileAccess( const char* extension_name) { return RunExtensionTestImpl(extension_name, "", kFlagNone); } bool ExtensionApiTest::RunExtensionTestIncognitoNoFileAccess( const char* extension_name) { return RunExtensionTestImpl(extension_name, "", kFlagEnableIncognito); } bool ExtensionApiTest::RunExtensionSubtest(const char* extension_name, const std::string& page_url) { return RunExtensionSubtest(extension_name, page_url, kFlagEnableFileAccess); } bool ExtensionApiTest::RunExtensionSubtest(const char* extension_name, const std::string& page_url, int flags) { DCHECK(!page_url.empty()) << "Argument page_url is required."; return RunExtensionTestImpl(extension_name, page_url, flags); } bool ExtensionApiTest::RunPageTest(const std::string& page_url) { return RunExtensionSubtest("", page_url); } bool ExtensionApiTest::RunPageTest(const std::string& page_url, int flags) { return RunExtensionSubtest("", page_url, flags); } bool ExtensionApiTest::RunPlatformAppTest(const char* extension_name) { return RunExtensionTestImpl(extension_name, "", kFlagLaunchPlatformApp); } // Load |extension_name| extension and/or |page_url| and wait for // PASSED or FAILED notification. bool ExtensionApiTest::RunExtensionTestImpl(const char* extension_name, const std::string& page_url, int flags) { bool load_as_component = (flags & kFlagLoadAsComponent) != 0; bool launch_platform_app = (flags & kFlagLaunchPlatformApp) != 0; bool use_incognito = (flags & kFlagUseIncognito) != 0; ResultCatcher catcher; DCHECK(!std::string(extension_name).empty() || !page_url.empty()) << "extension_name and page_url cannot both be empty"; const extensions::Extension* extension = NULL; if (!std::string(extension_name).empty()) { FilePath extension_path = test_data_dir_.AppendASCII(extension_name); if (load_as_component) { extension = LoadExtensionAsComponent(extension_path); } else { int browser_test_flags = ExtensionBrowserTest::kFlagNone; if (flags & kFlagEnableIncognito) browser_test_flags |= ExtensionBrowserTest::kFlagEnableIncognito; if (flags & kFlagEnableFileAccess) browser_test_flags |= ExtensionBrowserTest::kFlagEnableFileAccess; if (flags & kFlagIgnoreManifestWarnings) browser_test_flags |= ExtensionBrowserTest::kFlagIgnoreManifestWarnings; if (flags & kFlagAllowOldManifestVersions) { browser_test_flags |= ExtensionBrowserTest::kFlagAllowOldManifestVersions; } extension = LoadExtensionWithFlags(extension_path, browser_test_flags); } if (!extension) { message_ = "Failed to load extension."; return false; } } // If there is a page_url to load, navigate it. if (!page_url.empty()) { GURL url = GURL(page_url); // Note: We use is_valid() here in the expectation that the provided url // may lack a scheme & host and thus be a relative url within the loaded // extension. if (!url.is_valid()) { DCHECK(!std::string(extension_name).empty()) << "Relative page_url given with no extension_name"; url = extension->GetResourceURL(page_url); } if (use_incognito) ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url); else ui_test_utils::NavigateToURL(browser(), url); } else if (launch_platform_app) { application_launch::LaunchParams params(browser()->profile(), extension, extension_misc::LAUNCH_NONE, NEW_WINDOW); params.command_line = CommandLine::ForCurrentProcess(); application_launch::OpenApplication(params); } if (!catcher.GetNextResult()) { message_ = catcher.message(); return false; } else { return true; } } // Test that exactly one extension is loaded, and return it. const extensions::Extension* ExtensionApiTest::GetSingleLoadedExtension() { ExtensionService* service = browser()->profile()->GetExtensionService(); const extensions::Extension* extension = NULL; for (ExtensionSet::const_iterator it = service->extensions()->begin(); it != service->extensions()->end(); ++it) { // Ignore any component extensions. They are automatically loaded into all // profiles and aren't the extension we're looking for here. if ((*it)->location() == extensions::Extension::COMPONENT) continue; if (extension != NULL) { // TODO(yoz): this is misleading; it counts component extensions. message_ = base::StringPrintf( "Expected only one extension to be present. Found %u.", static_cast<unsigned>(service->extensions()->size())); return NULL; } extension = *it; } if (!extension) { message_ = "extension pointer is NULL."; return NULL; } return extension; } bool ExtensionApiTest::StartTestServer() { if (!test_server()->Start()) return false; // Build a dictionary of values that tests can use to build URLs that // access the test server and local file system. Tests can see these values // using the extension API function chrome.test.getConfig(). test_config_->SetInteger(kTestServerPort, test_server()->host_port_pair().port()); return true; } bool ExtensionApiTest::StartWebSocketServer(const FilePath& root_directory) { websocket_server_.reset(new net::TestServer( net::TestServer::TYPE_WS, net::TestServer::kLocalhost, root_directory)); if (!websocket_server_->Start()) return false; test_config_->SetInteger(kTestWebSocketPort, websocket_server_->host_port_pair().port()); return true; } void ExtensionApiTest::SetUpCommandLine(CommandLine* command_line) { ExtensionBrowserTest::SetUpCommandLine(command_line); test_data_dir_ = test_data_dir_.AppendASCII("api_test"); }
#include "my_application.h" #include <flutter_linux/flutter_linux.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen *screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar *header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "latihan_text_widget"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "latihan_text_widget"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar ***arguments, int *exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GObject::dispose. static void my_application_dispose(GObject *object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); }
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2014. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medBrowserPacsHostToolBox.h> #include <QtGui> #include <iostream> class medBrowserPacsHostToolBoxPrivate { public: QLineEdit *title; QLineEdit *port; QPushButton *apply; }; medBrowserPacsHostToolBox::medBrowserPacsHostToolBox(QWidget *parent) : medToolBox(parent), d(new medBrowserPacsHostToolBoxPrivate) { QWidget *page = new QWidget(this); QValidator* validator = new QIntValidator( 0, 65535, this ); d->title = new QLineEdit(page); d->port = new QLineEdit(page); d->port->setValidator(validator); d->apply = new QPushButton("Apply", page); QFormLayout *layout = new QFormLayout(page); layout->addRow("Title", d->title); layout->addRow("Port", d->port); layout->addRow(d->apply); this->setTitle("DICOM Server"); this->addWidget(page); connect(d->apply, SIGNAL(clicked()), this, SLOT(onSettingsApplied())); this->readSettings(); } medBrowserPacsHostToolBox::~medBrowserPacsHostToolBox(void) { this->writeSettings(); delete d; d = NULL; } void medBrowserPacsHostToolBox::readSettings(void) { QSettings settings; settings.beginGroup("medBrowserPacsHostToolBox"); QString title = settings.value("title").toString(); QString port = settings.value("port").toString(); settings.endGroup(); if (title.isEmpty()) d->title->setText("MEDINRIA"); else d->title->setText(title); if (port.isEmpty()) d->port->setText("9999"); else d->port->setText(port); } void medBrowserPacsHostToolBox::writeSettings(void) { QSettings settings; settings.beginGroup("medBrowserPacsHostToolBox"); settings.setValue("title", d->title->text()); settings.setValue("port", d->port->text()); settings.endGroup(); } QString medBrowserPacsHostToolBox::title(void) { return d->title->text(); } QString medBrowserPacsHostToolBox::port(void) { return d->port->text(); } void medBrowserPacsHostToolBox::onSettingsApplied(void) { this->writeSettings(); }
/* * Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "asr_agent.hh" #include "audio_player_agent.hh" #include "chips_agent.hh" #include "display_agent.hh" #include "extension_agent.hh" #include "mic_agent.hh" #include "nudge_agent.hh" #include "phone_call_agent.hh" #include "routine_agent.hh" #include "session_agent.hh" #include "sound_agent.hh" #include "speaker_agent.hh" #include "system_agent.hh" #include "text_agent.hh" #include "tts_agent.hh" #include "utility_agent.hh" #include "capability/capability_factory.hh" namespace NuguCapability { template <typename T, typename V> V* CapabilityFactory::makeCapability(ICapabilityListener* listener) { ICapabilityInterface* instance = new T(); if (listener) instance->setCapabilityListener(listener); return dynamic_cast<V*>(instance); } template IASRHandler* CapabilityFactory::makeCapability<ASRAgent, IASRHandler>(ICapabilityListener* listener); template ITTSHandler* CapabilityFactory::makeCapability<TTSAgent, ITTSHandler>(ICapabilityListener* listener); template IAudioPlayerHandler* CapabilityFactory::makeCapability<AudioPlayerAgent, IAudioPlayerHandler>(ICapabilityListener* listener); template ISystemHandler* CapabilityFactory::makeCapability<SystemAgent, ISystemHandler>(ICapabilityListener* listener); template ITextHandler* CapabilityFactory::makeCapability<TextAgent, ITextHandler>(ICapabilityListener* listener); template ISpeakerHandler* CapabilityFactory::makeCapability<SpeakerAgent, ISpeakerHandler>(ICapabilityListener* listener); template IMicHandler* CapabilityFactory::makeCapability<MicAgent, IMicHandler>(ICapabilityListener* listener); template ISoundHandler* CapabilityFactory::makeCapability<SoundAgent, ISoundHandler>(ICapabilityListener* listener); template ISessionHandler* CapabilityFactory::makeCapability<SessionAgent, ISessionHandler>(ICapabilityListener* listener); template IDisplayHandler* CapabilityFactory::makeCapability<DisplayAgent, IDisplayHandler>(ICapabilityListener* listener); template IUtilityHandler* CapabilityFactory::makeCapability<UtilityAgent, IUtilityHandler>(ICapabilityListener* listener); template IExtensionHandler* CapabilityFactory::makeCapability<ExtensionAgent, IExtensionHandler>(ICapabilityListener* listener); template IChipsHandler* CapabilityFactory::makeCapability<ChipsAgent, IChipsHandler>(ICapabilityListener* listener); template INudgeHandler* CapabilityFactory::makeCapability<NudgeAgent, INudgeHandler>(ICapabilityListener* listener); template IRoutineHandler* CapabilityFactory::makeCapability<RoutineAgent, IRoutineHandler>(ICapabilityListener* listener); template IPhoneCallHandler* CapabilityFactory::makeCapability<PhoneCallAgent, IPhoneCallHandler>(ICapabilityListener* listener); } // NuguCapability
// Copyright (c) 2011-2019 The F44RedCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/f44redcoin-config.h> #endif #include <qt/rpcconsole.h> #include <qt/forms/ui_debugwindow.h> #include <qt/bantablemodel.h> #include <qt/clientmodel.h> #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <chainparams.h> #include <interfaces/node.h> #include <netbase.h> #include <rpc/server.h> #include <rpc/client.h> #include <util/strencodings.h> #include <util/system.h> #include <univalue.h> #ifdef ENABLE_WALLET #include <db_cxx.h> #include <wallet/wallet.h> #endif #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QScrollBar> #include <QScreen> #include <QSettings> #include <QTime> #include <QTimer> #include <QStringList> // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const int INITIAL_TRAFFIC_GRAPH_MINS = 30; const QSize FONT_RANGE(4, 40); const char fontSizeSettingsKey[] = "consoleFontSize"; const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {nullptr, nullptr} }; namespace { // don't add private key handling cmd's to the history const QStringList historyFilter = QStringList() << "importprivkey" << "importmulti" << "sethdseed" << "signmessagewithprivkey" << "signrawtransactionwithkey" << "walletpassphrase" << "walletpassphrasechange" << "encryptwallet"; } /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public: explicit RPCExecutor(interfaces::Node& node) : m_node(node) {} public Q_SLOTS: void request(const QString &command, const WalletModel* wallet_model); Q_SIGNALS: void reply(int category, const QString &command); private: interfaces::Node& m_node; }; /** Class for handling RPC timers * (used for e.g. re-locking the wallet after a timeout) */ class QtRPCTimerBase: public QObject, public RPCTimerBase { Q_OBJECT public: QtRPCTimerBase(std::function<void()>& _func, int64_t millis): func(_func) { timer.setSingleShot(true); connect(&timer, &QTimer::timeout, [this]{ func(); }); timer.start(millis); } ~QtRPCTimerBase() {} private: QTimer timer; std::function<void()> func; }; class QtRPCTimerInterface: public RPCTimerInterface { public: ~QtRPCTimerInterface() {} const char *Name() { return "Qt"; } RPCTimerBase* NewTimer(std::function<void()>& func, int64_t millis) { return new QtRPCTimerBase(func, millis); } }; #include <qt/rpcconsole.moc> /** * Split shell command line into a list of arguments and optionally execute the command(s). * Aims to emulate \c bash and friends. * * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress()) * - Arguments are delimited with whitespace or comma * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[in] node optional node to execute command on * @param[out] strResult stringified result from the executed command(chain) * @param[in] strCommand Command line to split * @param[in] fExecute set true if you want the command to be executed * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data */ bool RPCConsole::RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut, const WalletModel* wallet_model) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); enum CmdParseState { STATE_EATING_SPACES, STATE_EATING_SPACES_IN_ARG, STATE_EATING_SPACES_IN_BRACKETS, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED, STATE_COMMAND_EXECUTED, STATE_COMMAND_EXECUTED_INNER } state = STATE_EATING_SPACES; std::string curarg; UniValue lastResult; unsigned nDepthInsideSensitive = 0; size_t filter_begin_pos = 0, chpos; std::vector<std::pair<size_t, size_t>> filter_ranges; auto add_to_current_stack = [&](const std::string& strArg) { if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) { nDepthInsideSensitive = 1; filter_begin_pos = chpos; } // Make sure stack is not empty before adding something if (stack.empty()) { stack.push_back(std::vector<std::string>()); } stack.back().push_back(strArg); }; auto close_out_params = [&]() { if (nDepthInsideSensitive) { if (!--nDepthInsideSensitive) { assert(filter_begin_pos); filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos)); filter_begin_pos = 0; } } stack.pop_back(); }; std::string strCommandTerminated = strCommand; if (strCommandTerminated.back() != '\n') strCommandTerminated += "\n"; for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos) { char ch = strCommandTerminated[chpos]; switch(state) { case STATE_COMMAND_EXECUTED_INNER: case STATE_COMMAND_EXECUTED: { bool breakParsing = true; switch(ch) { case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break; default: if (state == STATE_COMMAND_EXECUTED_INNER) { if (ch != ']') { // append char to the current argument (which is also used for the query command) curarg += ch; break; } if (curarg.size() && fExecute) { // if we have a value query, query arrays with index and objects with a string key UniValue subelement; if (lastResult.isArray()) { for(char argch: curarg) if (!IsDigit(argch)) throw std::runtime_error("Invalid result query"); subelement = lastResult[atoi(curarg.c_str())]; } else if (lastResult.isObject()) subelement = find_value(lastResult, curarg); else throw std::runtime_error("Invalid result query"); //no array or object: abort lastResult = subelement; } state = STATE_COMMAND_EXECUTED; break; } // don't break parsing when the char is required for the next argument breakParsing = false; // pop the stack and return the result to the current command arguments close_out_params(); // don't stringify the json in case of a string to avoid doublequotes if (lastResult.isStr()) curarg = lastResult.get_str(); else curarg = lastResult.write(2); // if we have a non empty result, use it as stack argument otherwise as general result if (curarg.size()) { if (stack.size()) add_to_current_stack(curarg); else strResult = curarg; } curarg.clear(); // assume eating space state state = STATE_EATING_SPACES; } if (breakParsing) break; } case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES_IN_ARG: case STATE_EATING_SPACES_IN_BRACKETS: case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case '(': case ')': case '\n': if (state == STATE_EATING_SPACES_IN_ARG) throw std::runtime_error("Invalid Syntax"); if (state == STATE_ARGUMENT) { if (ch == '(' && stack.size() && stack.back().size() > 0) { if (nDepthInsideSensitive) { ++nDepthInsideSensitive; } stack.push_back(std::vector<std::string>()); } // don't allow commands after executed commands on baselevel if (!stack.size()) throw std::runtime_error("Invalid Syntax"); add_to_current_stack(curarg); curarg.clear(); state = STATE_EATING_SPACES_IN_BRACKETS; } if ((ch == ')' || ch == '\n') && stack.size() > 0) { if (fExecute) { // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. UniValue params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); std::string method = stack.back()[0]; std::string uri; #ifdef ENABLE_WALLET if (wallet_model) { QByteArray encodedName = QUrl::toPercentEncoding(wallet_model->getWalletName()); uri = "/wallet/"+std::string(encodedName.constData(), encodedName.length()); } #endif assert(node); lastResult = node->executeRpc(method, params, uri); } state = STATE_COMMAND_EXECUTED; curarg.clear(); } break; case ' ': case ',': case '\t': if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',') throw std::runtime_error("Invalid Syntax"); else if(state == STATE_ARGUMENT) // Space ends argument { add_to_current_stack(curarg); curarg.clear(); } if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',') { state = STATE_EATING_SPACES_IN_ARG; break; } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } if (pstrFilteredOut) { if (STATE_COMMAND_EXECUTED == state) { assert(!stack.empty()); close_out_params(); } *pstrFilteredOut = strCommand; for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) { pstrFilteredOut->replace(i->first, i->second - i->first, "(…)"); } } switch(state) // final state { case STATE_COMMAND_EXECUTED: if (lastResult.isStr()) strResult = lastResult.get_str(); else strResult = lastResult.write(2); case STATE_ARGUMENT: case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command, const WalletModel* wallet_model) { try { std::string result; std::string executableCommand = command.toStdString() + "\n"; // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply. if(executableCommand == "help-console\n") { Q_EMIT reply(RPCConsole::CMD_REPLY, QString(("\n" "This console accepts RPC commands using the standard syntax.\n" " example: getblockhash 0\n\n" "This console can also accept RPC commands using the parenthesized syntax.\n" " example: getblockhash(0)\n\n" "Commands may be nested when specified with the parenthesized syntax.\n" " example: getblock(getblockhash(0) 1)\n\n" "A space or a comma can be used to delimit arguments for either syntax.\n" " example: getblockhash 0\n" " getblockhash,0\n\n" "Named results can be queried with a non-quoted key string in brackets using the parenthesized syntax.\n" " example: getblock(getblockhash(0) 1)[tx]\n\n" "Results without keys can be queried with an integer in brackets using the parenthesized syntax.\n" " example: getblock(getblockhash(0),1)[tx][0]\n\n"))); return; } if (!RPCConsole::RPCExecuteCommandLine(m_node, result, executableCommand, nullptr, wallet_model)) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result)); } catch (UniValue& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write())); } } catch (const std::exception& e) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(interfaces::Node& node, const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), m_node(node), ui(new Ui::RPCConsole), platformStyle(_platformStyle) { ui->setupUi(this); QSettings settings; if (!restoreGeometry(settings.value("RPCConsoleWindowGeometry").toByteArray())) { // Restore failed (perhaps missing setting), center the window move(QGuiApplication::primaryScreen()->availableGeometry().center() - frameGeometry().center()); } QChar nonbreaking_hyphen(8209); ui->dataDir->setToolTip(ui->dataDir->toolTip().arg(QString(nonbreaking_hyphen) + "datadir")); ui->blocksDir->setToolTip(ui->blocksDir->toolTip().arg(QString(nonbreaking_hyphen) + "blocksdir")); ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(PACKAGE_NAME)); if (platformStyle->getImagesOnButtons()) { ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger")); ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller")); // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, &QPushButton::clicked, this, &RPCConsole::clear); connect(ui->fontBiggerButton, &QPushButton::clicked, this, &RPCConsole::fontBigger); connect(ui->fontSmallerButton, &QPushButton::clicked, this, &RPCConsole::fontSmaller); connect(ui->btnClearTrafficGraph, &QPushButton::clicked, ui->trafficGraph, &TrafficGraphWidget::clear); // disable the wallet selector by default ui->WalletSelector->setVisible(false); ui->WalletSelectorLabel->setVisible(false); // set library version labels #ifdef ENABLE_WALLET ui->berkeleyDBVersion->setText(DbEnv::version(nullptr, nullptr, nullptr)); #else ui->label_berkeleyDBVersion->hide(); ui->berkeleyDBVersion->hide(); #endif // Register RPC timer interface rpcTimerInterface = new QtRPCTimerInterface(); // avoid accidentally overwriting an existing, non QTThread // based timer interface m_node.rpcSetTimerInterfaceIfUnset(rpcTimerInterface); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt(); clear(); } RPCConsole::~RPCConsole() { QSettings settings; settings.setValue("RPCConsoleWindowGeometry", saveGeometry()); m_node.rpcUnsetTimerInterface(rpcTimerInterface); delete rpcTimerInterface; delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; case Qt::Key_Return: case Qt::Key_Enter: // forward these events to lineEdit if(obj == autoCompleter->popup()) { QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); autoCompleter->popup()->hide(); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QWidget::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { clientModel = model; bool wallet_enabled{false}; #ifdef ENABLE_WALLET wallet_enabled = WalletModel::isWalletEnabled(); #endif // ENABLE_WALLET if (model && !wallet_enabled) { // Show warning, for example if this is a prerelease version connect(model, &ClientModel::alertsChanged, this, &RPCConsole::updateAlerts); updateAlerts(model->getStatusBarWarnings()); } ui->trafficGraph->setClientModel(model); if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) { // Keep up to date with client setNumConnections(model->getNumConnections()); connect(model, &ClientModel::numConnectionsChanged, this, &RPCConsole::setNumConnections); interfaces::Node& node = clientModel->node(); setNumBlocks(node.getNumBlocks(), QDateTime::fromTime_t(node.getLastBlockTime()), node.getVerificationProgress(), false); connect(model, &ClientModel::numBlocksChanged, this, &RPCConsole::setNumBlocks); updateNetworkState(); connect(model, &ClientModel::networkActiveChanged, this, &RPCConsole::setNetworkActive); updateTrafficStats(node.getTotalBytesRecv(), node.getTotalBytesSent()); connect(model, &ClientModel::bytesChanged, this, &RPCConsole::updateTrafficStats); connect(model, &ClientModel::mempoolSizeChanged, this, &RPCConsole::setMempoolSize); // set up peer table ui->peerWidget->setModel(model->getPeerTableModel()); ui->peerWidget->verticalHeader()->hide(); ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH); ui->peerWidget->horizontalHeader()->setStretchLastSection(true); // create peer table context menu actions QAction* disconnectAction = new QAction(tr("&Disconnect"), this); QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this); QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this); QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this); QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this); // create peer table context menu peersTableContextMenu = new QMenu(this); peersTableContextMenu->addAction(disconnectAction); peersTableContextMenu->addAction(banAction1h); peersTableContextMenu->addAction(banAction24h); peersTableContextMenu->addAction(banAction7d); peersTableContextMenu->addAction(banAction365d); connect(banAction1h, &QAction::triggered, [this] { banSelectedNode(60 * 60); }); connect(banAction24h, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24); }); connect(banAction7d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 7); }); connect(banAction365d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 365); }); // peer table context menu signals connect(ui->peerWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showPeersTableContextMenu); connect(disconnectAction, &QAction::triggered, this, &RPCConsole::disconnectSelectedNode); // peer table signal handling - update peer details when selecting new node connect(ui->peerWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RPCConsole::peerSelected); // peer table signal handling - update peer details when new nodes are added to the model connect(model->getPeerTableModel(), &PeerTableModel::layoutChanged, this, &RPCConsole::peerLayoutChanged); // peer table signal handling - cache selected node ids connect(model->getPeerTableModel(), &PeerTableModel::layoutAboutToBeChanged, this, &RPCConsole::peerLayoutAboutToChange); // set up ban table ui->banlistWidget->setModel(model->getBanTableModel()); ui->banlistWidget->verticalHeader()->hide(); ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH); ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH); ui->banlistWidget->horizontalHeader()->setStretchLastSection(true); // create ban table context menu action QAction* unbanAction = new QAction(tr("&Unban"), this); // create ban table context menu banTableContextMenu = new QMenu(this); banTableContextMenu->addAction(unbanAction); // ban table context menu signals connect(ui->banlistWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showBanTableContextMenu); connect(unbanAction, &QAction::triggered, this, &RPCConsole::unbanSelectedNode); // ban table signal handling - clear peer details when clicking a peer in the ban table connect(ui->banlistWidget, &QTableView::clicked, this, &RPCConsole::clearSelectedNode); // ban table signal handling - ensure ban table is shown or hidden (if empty) connect(model->getBanTableModel(), &BanTableModel::layoutChanged, this, &RPCConsole::showOrHideBanTableIfRequired); showOrHideBanTableIfRequired(); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientUserAgent->setText(model->formatSubVersion()); ui->dataDir->setText(model->dataDir()); ui->blocksDir->setText(model->blocksDir()); ui->startupTime->setText(model->formatClientStartupTime()); ui->networkName->setText(QString::fromStdString(Params().NetworkIDString())); //Setup autocomplete and attach it QStringList wordList; std::vector<std::string> commandList = m_node.listRpcCommands(); for (size_t i = 0; i < commandList.size(); ++i) { wordList << commandList[i].c_str(); wordList << ("help " + commandList[i]).c_str(); } wordList << "help-console"; wordList.sort(); autoCompleter = new QCompleter(wordList, this); autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel); // ui->lineEdit is initially disabled because running commands is only // possible from now on. ui->lineEdit->setEnabled(true); ui->lineEdit->setCompleter(autoCompleter); autoCompleter->popup()->installEventFilter(this); // Start thread to execute RPC commands. startExecutor(); } if (!model) { // Client model is being set to 0, this means shutdown() is about to be called. thread.quit(); thread.wait(); } } #ifdef ENABLE_WALLET void RPCConsole::addWallet(WalletModel * const walletModel) { // use name for text and wallet model for internal data object (to allow to move to a wallet id later) ui->WalletSelector->addItem(walletModel->getDisplayName(), QVariant::fromValue(walletModel)); if (ui->WalletSelector->count() == 2 && !isVisible()) { // First wallet added, set to default so long as the window isn't presently visible (and potentially in use) ui->WalletSelector->setCurrentIndex(1); } if (ui->WalletSelector->count() > 2) { ui->WalletSelector->setVisible(true); ui->WalletSelectorLabel->setVisible(true); } } void RPCConsole::removeWallet(WalletModel * const walletModel) { ui->WalletSelector->removeItem(ui->WalletSelector->findData(QVariant::fromValue(walletModel))); if (ui->WalletSelector->count() == 2) { ui->WalletSelector->setVisible(false); ui->WalletSelectorLabel->setVisible(false); } } #endif static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::fontBigger() { setFontSize(consoleFontSize+1); } void RPCConsole::fontSmaller() { setFontSize(consoleFontSize-1); } void RPCConsole::setFontSize(int newSize) { QSettings settings; //don't allow an insane font size if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height()) return; // temp. store the console content QString str = ui->messagesWidget->toHtml(); // replace font tags size in current content str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize)); // store the new font size consoleFontSize = newSize; settings.setValue(fontSizeSettingsKey, consoleFontSize); // clear console (reset icon sizes, default stylesheet) and re-add the content float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value(); clear(false); ui->messagesWidget->setHtml(str); ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum()); } void RPCConsole::clear(bool clearHistory) { ui->messagesWidget->clear(); if(clearHistory) { history.clear(); historyPtr = 0; } ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont()); ui->messagesWidget->document()->setDefaultStyleSheet( QString( "table { }" "td.time { color: #808080; font-size: %2; padding-top: 3px; } " "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " ".secwarning { color: red; }" "b { color: #006060; } " ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize)) ); #ifdef Q_OS_MAC QString clsKey = "(⌘)-L"; #else QString clsKey = "Ctrl-L"; #endif message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(PACKAGE_NAME) + "<br>" + tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" + tr("Type %1 for an overview of available commands.").arg("<b>help</b>") + "<br>" + tr("For more information on using this console type %1.").arg("<b>help-console</b>") + "<br><span class=\"secwarning\"><br>" + tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") + "</span>"), true); } void RPCConsole::keyPressEvent(QKeyEvent *event) { if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape) { close(); } } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, false); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::updateNetworkState() { QString connections = QString::number(clientModel->getNumConnections()) + " ("; connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / "; connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")"; if(!clientModel->node().getNetworkActive()) { connections += " (" + tr("Network activity disabled") + ")"; } ui->numberOfConnections->setText(connections); } void RPCConsole::setNumConnections(int count) { if (!clientModel) return; updateNetworkState(); } void RPCConsole::setNetworkActive(bool networkActive) { updateNetworkState(); } void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers) { if (!headers) { ui->numberOfBlocks->setText(QString::number(count)); ui->lastBlockTime->setText(blockDate.toString()); } } void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage) { ui->mempoolNumberTxs->setText(QString::number(numberOfTxs)); if (dynUsage < 1000000) ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB"); else ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB"); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); if(!cmd.isEmpty()) { std::string strFilteredCmd; try { std::string dummy; if (!RPCParseCommandLine(nullptr, dummy, cmd.toStdString(), false, &strFilteredCmd)) { // Failed to parse command, so we cannot even filter it for the history throw std::runtime_error("Invalid command line"); } } catch (const std::exception& e) { QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what())); return; } ui->lineEdit->clear(); cmdBeforeBrowsing = QString(); #ifdef ENABLE_WALLET WalletModel* wallet_model = ui->WalletSelector->currentData().value<WalletModel*>(); if (m_last_wallet_model != wallet_model) { if (wallet_model) { message(CMD_REQUEST, tr("Executing command using \"%1\" wallet").arg(wallet_model->getWalletName())); } else { message(CMD_REQUEST, tr("Executing command without any wallet")); } m_last_wallet_model = wallet_model; } #endif message(CMD_REQUEST, QString::fromStdString(strFilteredCmd)); Q_EMIT cmdRequest(cmd, m_last_wallet_model); cmd = QString::fromStdString(strFilteredCmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { // store current text when start browsing through the history if (historyPtr == history.size()) { cmdBeforeBrowsing = ui->lineEdit->text(); } historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); else if (!cmdBeforeBrowsing.isNull()) { cmd = cmdBeforeBrowsing; } ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { RPCExecutor *executor = new RPCExecutor(m_node); executor->moveToThread(&thread); // Replies from executor object must go to this object connect(executor, &RPCExecutor::reply, this, static_cast<void (RPCConsole::*)(int, const QString&)>(&RPCConsole::message)); // Requests from this object must go to executor connect(this, &RPCConsole::cmdRequest, executor, &RPCExecutor::request); // Make sure executor object is deleted in its own thread connect(&thread, &QThread::finished, executor, &RPCExecutor::deleteLater); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread.start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if (ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_sldGraphRange_valueChanged(int value) { const int multiplier = 5; // each position on the slider represents 5 min int mins = value * multiplier; setTrafficGraphRange(mins); } void RPCConsole::setTrafficGraphRange(int mins) { ui->trafficGraph->setGraphRangeMins(mins); ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60)); } void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut) { ui->lblBytesIn->setText(GUIUtil::formatBytes(totalBytesIn)); ui->lblBytesOut->setText(GUIUtil::formatBytes(totalBytesOut)); } void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected) { Q_UNUSED(deselected); if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty()) return; const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row()); if (stats) updateNodeDetail(stats); } void RPCConsole::peerLayoutAboutToChange() { QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes(); cachedNodeids.clear(); for(int i = 0; i < selected.size(); i++) { const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row()); cachedNodeids.append(stats->nodeStats.nodeid); } } void RPCConsole::peerLayoutChanged() { if (!clientModel || !clientModel->getPeerTableModel()) return; const CNodeCombinedStats *stats = nullptr; bool fUnselect = false; bool fReselect = false; if (cachedNodeids.empty()) // no node selected yet return; // find the currently selected row int selectedRow = -1; QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes(); if (!selectedModelIndex.isEmpty()) { selectedRow = selectedModelIndex.first().row(); } // check if our detail node has a row in the table (it may not necessarily // be at selectedRow since its position can change after a layout change) int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first()); if (detailNodeRow < 0) { // detail node disappeared from table (node disconnected) fUnselect = true; } else { if (detailNodeRow != selectedRow) { // detail node moved position fUnselect = true; fReselect = true; } // get fresh stats on the detail node. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); } if (fUnselect && selectedRow >= 0) { clearSelectedNode(); } if (fReselect) { for(int i = 0; i < cachedNodeids.size(); i++) { ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i))); } } if (stats) updateNodeDetail(stats); } void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats) { // update the detail ui with latest node information QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " "); peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid)); if (!stats->nodeStats.addrLocal.empty()) peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal)); ui->peerHeading->setText(peerAddrDetails); ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices)); ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never")); ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never")); ui->peerBytesSent->setText(GUIUtil::formatBytes(stats->nodeStats.nSendBytes)); ui->peerBytesRecv->setText(GUIUtil::formatBytes(stats->nodeStats.nRecvBytes)); ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected)); ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.m_ping_usec)); ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.m_ping_wait_usec)); ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.m_min_ping_usec)); ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset)); ui->peerVersion->setText(QString::number(stats->nodeStats.nVersion)); ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer)); ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound")); ui->peerHeight->setText(QString::number(stats->nodeStats.nStartingHeight)); ui->peerWhitelisted->setText(stats->nodeStats.m_legacyWhitelisted ? tr("Yes") : tr("No")); ui->peerMappedAS->setText(stats->nodeStats.m_mapped_as != 0 ? QString::number(stats->nodeStats.m_mapped_as) : tr("N/A")); // This check fails for example if the lock was busy and // nodeStateStats couldn't be fetched. if (stats->fNodeStateStatsAvailable) { // Ban score is init to 0 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior)); // Sync height is init to -1 if (stats->nodeStateStats.nSyncHeight > -1) ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight)); else ui->peerSyncHeight->setText(tr("Unknown")); // Common height is init to -1 if (stats->nodeStateStats.nCommonHeight > -1) ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight)); else ui->peerCommonHeight->setText(tr("Unknown")); } ui->detailWidget->show(); } void RPCConsole::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); } void RPCConsole::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // start PeerTableModel auto refresh clientModel->getPeerTableModel()->startAutoRefresh(); } void RPCConsole::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // stop PeerTableModel auto refresh clientModel->getPeerTableModel()->stopAutoRefresh(); } void RPCConsole::showPeersTableContextMenu(const QPoint& point) { QModelIndex index = ui->peerWidget->indexAt(point); if (index.isValid()) peersTableContextMenu->exec(QCursor::pos()); } void RPCConsole::showBanTableContextMenu(const QPoint& point) { QModelIndex index = ui->banlistWidget->indexAt(point); if (index.isValid()) banTableContextMenu->exec(QCursor::pos()); } void RPCConsole::disconnectSelectedNode() { // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Find the node, disconnect it and clear the selected node if(m_node.disconnectById(id)) clearSelectedNode(); } } void RPCConsole::banSelectedNode(int bantime) { if (!clientModel) return; // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Get currently selected peer address int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id); if (detailNodeRow < 0) return; // Find possible nodes, ban it and clear the selected node const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); if (stats) { m_node.ban(stats->nodeStats.addr, bantime); m_node.disconnectByAddress(stats->nodeStats.addr); } } clearSelectedNode(); clientModel->getBanTableModel()->refresh(); } void RPCConsole::unbanSelectedNode() { if (!clientModel) return; // Get selected ban addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address); for(int i = 0; i < nodes.count(); i++) { // Get currently selected ban address QString strNode = nodes.at(i).data().toString(); CSubNet possibleSubnet; LookupSubNet(strNode.toStdString(), possibleSubnet); if (possibleSubnet.IsValid() && m_node.unban(possibleSubnet)) { clientModel->getBanTableModel()->refresh(); } } } void RPCConsole::clearSelectedNode() { ui->peerWidget->selectionModel()->clearSelection(); cachedNodeids.clear(); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } void RPCConsole::showOrHideBanTableIfRequired() { if (!clientModel) return; bool visible = clientModel->getBanTableModel()->shouldShow(); ui->banlistWidget->setVisible(visible); ui->banHeading->setVisible(visible); } void RPCConsole::setTabFocus(enum TabTypes tabType) { ui->tabWidget->setCurrentIndex(int(tabType)); } QString RPCConsole::tabTitle(TabTypes tab_type) const { return ui->tabWidget->tabText(int(tab_type)); } QKeySequence RPCConsole::tabShortcut(TabTypes tab_type) const { switch (tab_type) { case TabTypes::INFO: return QKeySequence(Qt::CTRL + Qt::Key_I); case TabTypes::CONSOLE: return QKeySequence(Qt::CTRL + Qt::Key_T); case TabTypes::GRAPH: return QKeySequence(Qt::CTRL + Qt::Key_N); case TabTypes::PEERS: return QKeySequence(Qt::CTRL + Qt::Key_P); } // no default case, so the compiler can warn about missing cases assert(false); } void RPCConsole::updateAlerts(const QString& warnings) { this->ui->label_alerts->setVisible(!warnings.isEmpty()); this->ui->label_alerts->setText(warnings); }
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <proxygen/lib/http/codec/compress/HPACKDecoder.h> #include <proxygen/lib/http/codec/compress/HeaderCodec.h> using folly::IOBuf; using folly::io::Cursor; using std::unique_ptr; using proxygen::HPACK::DecodeError; namespace proxygen { void HPACKDecoder::decodeStreaming( Cursor& cursor, uint32_t totalBytes, HPACK::StreamingCallback* streamingCb) { HPACKDecodeBuffer dbuf(cursor, totalBytes, maxUncompressed_); uint32_t emittedSize = 0; while (!hasError() && !dbuf.empty()) { emittedSize += decodeHeader(dbuf, streamingCb, nullptr); if (emittedSize > maxUncompressed_) { LOG(ERROR) << "exceeded uncompressed size limit of " << maxUncompressed_ << " bytes"; err_ = HPACK::DecodeError::HEADERS_TOO_LARGE; break; } emittedSize += 2; } auto compressedSize = dbuf.consumedBytes(); completeDecode(HeaderCodec::Type::HPACK, streamingCb, compressedSize, compressedSize, emittedSize); } uint32_t HPACKDecoder::decodeLiteralHeader( HPACKDecodeBuffer& dbuf, HPACK::StreamingCallback* streamingCb, headers_t* emitted) { uint8_t byte = dbuf.peek(); bool indexing = byte & HPACK::LITERAL_INC_INDEX.code; HPACKHeader header; uint8_t indexMask = 0x3F; // 0011 1111 uint8_t length = HPACK::LITERAL_INC_INDEX.prefixLength; if (!indexing) { // bool neverIndex = byte & HPACK::LITERAL_NEV_INDEX.code; // TODO: we need to emit this flag with the headers indexMask = 0x0F; // 0000 1111 length = HPACK::LITERAL.prefixLength; } if (byte & indexMask) { uint64_t index; err_ = dbuf.decodeInteger(length, index); if (err_ != HPACK::DecodeError::NONE) { LOG(ERROR) << "Decode error decoding index err_=" << err_; return 0; } // validate the index if (!isValid(index)) { LOG(ERROR) << "received invalid index: " << index; err_ = HPACK::DecodeError::INVALID_INDEX; return 0; } header.name = getHeader(index).name; } else { // skip current byte dbuf.next(); folly::fbstring headerName; err_ = dbuf.decodeLiteral(headerName); header.name = headerName; if (err_ != HPACK::DecodeError::NONE) { LOG(ERROR) << "Error decoding header name err_=" << err_; return 0; } } // value err_ = dbuf.decodeLiteral(header.value); if (err_ != HPACK::DecodeError::NONE) { LOG(ERROR) << "Error decoding header value name=" << header.name << " err_=" << err_; return 0; } uint32_t emittedSize = emit(header, streamingCb, emitted); if (indexing) { table_.add(std::move(header)); } return emittedSize; } uint32_t HPACKDecoder::decodeIndexedHeader( HPACKDecodeBuffer& dbuf, HPACK::StreamingCallback* streamingCb, headers_t* emitted) { uint64_t index; err_ = dbuf.decodeInteger(HPACK::INDEX_REF.prefixLength, index); if (err_ != HPACK::DecodeError::NONE) { LOG(ERROR) << "Decode error decoding index err_=" << err_; return 0; } // validate the index if (index == 0 || !isValid(index)) { LOG(ERROR) << "received invalid index: " << index; err_ = HPACK::DecodeError::INVALID_INDEX; return 0; } auto& header = getHeader(index); return emit(header, streamingCb, emitted); } bool HPACKDecoder::isValid(uint32_t index) { if (isStatic(index)) { return getStaticTable().isValid(globalToStaticIndex(index)); } else { return table_.isValid(globalToDynamicIndex(index)); } } uint32_t HPACKDecoder::decodeHeader( HPACKDecodeBuffer& dbuf, HPACK::StreamingCallback* streamingCb, headers_t* emitted) { uint8_t byte = dbuf.peek(); if (byte & HPACK::INDEX_REF.code) { return decodeIndexedHeader(dbuf, streamingCb, emitted); } else if (byte & HPACK::LITERAL_INC_INDEX.code) { // else it's fine, fall through to decodeLiteralHeader } else if (byte & HPACK::TABLE_SIZE_UPDATE.code) { handleTableSizeUpdate(dbuf, table_); return 0; } // else LITERAL // LITERAL_NO_INDEXING or LITERAL_INCR_INDEXING return decodeLiteralHeader(dbuf, streamingCb, emitted); } }
// prebeep.cpp : source file that includes just the standard includes // prebeep.pch will be the pre-compiled header // prebeep.obj will contain the pre-compiled type information // // This is a part of the Active Template Library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #include "prebeep.h"
/* * Copyright (c) 2014, Oculus VR, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /// \file /// \brief Test the command console implementations #include "TCPInterface.h" #include "ConsoleServer.h" #include "RakNetCommandParser.h" #include "TelnetTransport.h" #include "RakPeerInterface.h" #include "LogCommandParser.h" #include "GetTime.h" #include "RakNetTransport2.h" #include "LinuxStrings.h" #include <stdio.h> void TestTCPInterface(void); void TestCommandServer(RakNet::TransportInterface *ti, unsigned short port, RakNet::RakPeerInterface *rakPeer); int main(void) { RakNet::RakPeerInterface *rakPeer = RakNet::RakPeerInterface::GetInstance(); RakNet::SocketDescriptor sd(60000,0); rakPeer->Startup(128,&sd,1); rakPeer->SetMaximumIncomingConnections(128); RakNet::TelnetTransport tt; TestCommandServer(&tt, 23, rakPeer); // Uncomment to use Telnet as a client. Telnet uses port 23 by default. // RakNet::RakNetTransport2 rt2; // rakPeer->AttachPlugin(&rt2); // TestCommandServer(&rt2, 60000,rakPeer); // Uncomment to use RakNet as a client return 1; } void TestCommandServer(RakNet::TransportInterface *ti, unsigned short port, RakNet::RakPeerInterface *rakPeer) { RakNet::ConsoleServer consoleServer; RakNet::RakNetCommandParser rcp; RakNet::LogCommandParser lcp; RakNet::TimeMS lastLog=0; printf("This sample demonstrates the command console server, which can be.\n"); printf("a standalone application or part of your game server. It allows you to\n"); printf("easily parse text strings sent from a client using either secure RakNet\n"); printf("or Telnet.\n"); printf("See the 'CommandConsoleClient' project for the RakNet client.\n"); printf("Difficulty: Intermediate\n\n"); printf("Command server started on port %i.\n", port); consoleServer.AddCommandParser(&rcp); consoleServer.AddCommandParser(&lcp); consoleServer.SetTransportProvider(ti, port); consoleServer.SetPrompt("> "); // Show this character when waiting for user input rcp.SetRakPeerInterface(rakPeer); lcp.AddChannel("TestChannel"); while (1) { consoleServer.Update(); // Ignore raknet packets for this sample. rakPeer->DeallocatePacket(rakPeer->Receive()); if (RakNet::GetTimeMS() > lastLog + 4000) { lcp.WriteLog("TestChannel", "Test of logger"); lastLog=RakNet::GetTimeMS(); } #ifdef _WIN32 Sleep( 30 ); #else usleep( 30 * 1000 ); #endif } }
#include <iostream> // IMPORT THIRD-PARTY LIBRARIES #include <pxr/usd/usd/clipsAPI.h> #include <pxr/usd/usd/stage.h> int main() { auto stage = pxr::UsdStage::CreateInMemory(); stage->SetStartTimeCode(0); stage->SetEndTimeCode(12); auto prim = stage->DefinePrim(pxr::SdfPath("/Prim")); auto model = pxr::UsdClipsAPI(prim); model.SetClipActive({{0, 0}, {2, 1}}); model.SetClipAssetPaths( {pxr::SdfAssetPath{"./clip_1.usda"}, pxr::SdfAssetPath{"./clip_2.usda"}} ); model.SetClipPrimPath("/Clip"); model.SetClipTimes({{0, 0}, {1, 1}, {2, 0}, {3, 1}}); model.SetClipManifestAssetPath(pxr::SdfAssetPath{"./clip_manifest.usda"}); prim.GetReferences().AddReference( "./ref.usda", pxr::SdfPath{"/Ref"} ); auto* result = new std::string(); stage->GetRootLayer()->ExportToString(result); std::cout << *result << std::endl; delete result; result = nullptr; return 0; }
// Copyright 2018 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gmock/gmock.h" #include "osrf_testing_tools_cpp/memory_tools/testing_helpers.hpp" #include "rcutils/allocator.h" #include "rmw/error_handling.h" #include "rmw/types.h" #include "./time_bomb_allocator_testing_utils.h" TEST(test_serialized_message, default_initialization) { auto serialized_msg = rmw_get_zero_initialized_serialized_message(); auto allocator = rcutils_get_default_allocator(); EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_init(&serialized_msg, 0, &allocator)); EXPECT_EQ(0u, serialized_msg.buffer_capacity); EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_msg)); EXPECT_EQ(0u, serialized_msg.buffer_capacity); EXPECT_FALSE(serialized_msg.buffer); } TEST(test_serialized_message, bad_allocation_on_init) { rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); rcutils_allocator_t failing_allocator = get_time_bomb_allocator(); set_time_bomb_allocator_malloc_count(failing_allocator, 0); set_time_bomb_allocator_realloc_count(failing_allocator, 0); EXPECT_EQ( RMW_RET_BAD_ALLOC, rmw_serialized_message_init( &serialized_message, 1lu, &failing_allocator)); rmw_reset_error(); } TEST(test_serialized_message, init_with_bad_arguments) { rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); rcutils_allocator_t default_allocator = rcutils_get_default_allocator(); EXPECT_EQ( RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_init( nullptr, 0lu, &default_allocator)); rmw_reset_error(); rcutils_allocator_t invalid_allocator = rcutils_get_zero_initialized_allocator(); EXPECT_EQ( RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_init( &serialized_message, 0lu, &invalid_allocator)); rmw_reset_error(); } TEST(test_serialized_message, fini_with_bad_arguments) { EXPECT_EQ(RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_fini(nullptr)); rmw_reset_error(); rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); EXPECT_EQ(RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_fini(&serialized_message)); rmw_reset_error(); } TEST(test_serialized_message, resize_with_bad_arguments) { EXPECT_EQ(RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_resize(nullptr, 1lu)); rmw_reset_error(); rmw_serialized_message_t zero_initialized_serialized_message = rmw_get_zero_initialized_serialized_message(); EXPECT_EQ( RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_resize(&zero_initialized_serialized_message, 1lu)); rmw_reset_error(); rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); rcutils_allocator_t default_allocator = rcutils_get_default_allocator(); ASSERT_EQ( RMW_RET_OK, rmw_serialized_message_init( &serialized_message, 1lu, &default_allocator)) << rmw_get_error_string().str; EXPECT_EQ( RMW_RET_INVALID_ARGUMENT, rmw_serialized_message_resize(&serialized_message, 0lu)); rmw_reset_error(); EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) << rmw_get_error_string().str; } TEST(test_serialized_message, bad_allocation_on_resize) { rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); rcutils_allocator_t failing_allocator = get_time_bomb_allocator(); set_time_bomb_allocator_malloc_count(failing_allocator, 0); set_time_bomb_allocator_realloc_count(failing_allocator, 0); ASSERT_EQ( RMW_RET_OK, rmw_serialized_message_init( &serialized_message, 0lu, &failing_allocator)) << rmw_get_error_string().str; EXPECT_EQ( RMW_RET_BAD_ALLOC, rmw_serialized_message_resize(&serialized_message, 1lu)); rmw_reset_error(); EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) << rmw_get_error_string().str; } TEST(test_serialized_message, init_resize_fini) { rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message(); rcutils_allocator_t default_allocator = rcutils_get_default_allocator(); constexpr size_t serialized_message_size = 5lu; rmw_ret_t ret = rmw_serialized_message_init( &serialized_message, serialized_message_size, &default_allocator); ASSERT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str; EXPECT_EQ(serialized_message_size, serialized_message.buffer_capacity); EXPECT_EQ(0lu, serialized_message.buffer_length); for (size_t i = 0; i < serialized_message_size; ++i) { uint8_t c = 1u << i; memcpy(serialized_message.buffer + i, &c, 1); } serialized_message.buffer_length = serialized_message_size; for (size_t i = 0; i < serialized_message.buffer_length; ++i) { EXPECT_EQ(1u << i, serialized_message.buffer[i]); } EXPECT_NO_MEMORY_OPERATIONS( { ret = rmw_serialized_message_resize(&serialized_message, serialized_message_size); }); EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str; EXPECT_EQ(serialized_message_size, serialized_message.buffer_capacity); EXPECT_EQ(serialized_message_size, serialized_message.buffer_length); for (size_t i = 0; i < serialized_message.buffer_length; ++i) { EXPECT_EQ(1u << i, serialized_message.buffer[i]); } constexpr size_t serialized_message_new_size = 2 * serialized_message_size; ret = rmw_serialized_message_resize(&serialized_message, serialized_message_new_size); EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str; EXPECT_EQ(serialized_message_new_size, serialized_message.buffer_capacity); EXPECT_EQ(serialized_message_size, serialized_message.buffer_length); for (size_t i = 0; i < serialized_message_new_size; ++i) { uint8_t c = 0xFF - static_cast<uint8_t>(i); memcpy(serialized_message.buffer + i, &c, 1); } serialized_message.buffer_length = serialized_message_new_size; for (size_t i = 0; i < serialized_message_new_size; ++i) { EXPECT_EQ(0xFF - i, serialized_message.buffer[i]); } ret = rmw_serialized_message_resize(&serialized_message, 3); ASSERT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str; EXPECT_EQ(3u, serialized_message.buffer_capacity); EXPECT_EQ(3u, serialized_message.buffer_length); EXPECT_EQ(0xFF, serialized_message.buffer[0]); EXPECT_EQ(0xFF - 1, serialized_message.buffer[1]); EXPECT_EQ(0xFF - 2, serialized_message.buffer[2]); // the other fields are garbage. // cleanup only 3 fields EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) << rmw_get_error_string().str; }
//Q102: Ecological Bin Packing //accepted at 2011-08-27 12:59:38 //run time = 0.116 #include <iostream> using namespace std; bool compareLower(int moves, int currentmin); int main(){ struct bin{ char bname; int B,C,G; }; int min, totalmoves, currentMoves; min = 0; totalmoves = 0; currentMoves = 0; bin binA, binB, binC; while(cin >> binA.B >> binA.G >> binA.C >> binB.B >> binB.G >> binB.C >> binC.B >> binC.G >> binC.C){ totalmoves = binA.B + binA.C + binA.G + binB.B + binB.C + binB.G + binC.B + binC.C + binC.G; min = totalmoves; currentMoves = totalmoves - binA.B - binB.C - binC.G; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'B'; binB.bname = 'C'; binC.bname = 'G'; } currentMoves = totalmoves - binA.B - binB.G - binC.C; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'B'; binB.bname = 'G'; binC.bname = 'C'; } currentMoves = totalmoves - binA.C - binB.B - binC.G; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'C'; binB.bname = 'B'; binC.bname = 'G'; } currentMoves = totalmoves - binA.C - binB.G - binC.B; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'C'; binB.bname = 'G'; binC.bname = 'B'; } currentMoves = totalmoves - binA.G - binB.B - binC.C; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'G'; binB.bname = 'B'; binC.bname = 'C'; } currentMoves = totalmoves - binA.G - binB.C - binC.B; if (compareLower(currentMoves, min)) { min = currentMoves; binA.bname = 'G'; binB.bname = 'C'; binC.bname = 'B'; } cout << binA.bname << binB.bname << binC.bname << " " << min << endl; } return 0; } bool compareLower(int moves,int currentmin) { if ( moves < currentmin) { return true; }else{ return false; } }
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/platform/cloud/google_auth_provider.h" #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include <fstream> #include "include/json/json.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/strings/base64.h" #include "tensorflow/core/platform/cloud/http_request.h" #include "tensorflow/core/platform/cloud/retrying_utils.h" #include "tensorflow/core/platform/env.h" namespace tensorflow { namespace { // The environment variable pointing to the file with local // Application Default Credentials. constexpr char kGoogleApplicationCredentials[] = "GOOGLE_APPLICATION_CREDENTIALS"; // The environment variable to override token generation for testing. constexpr char kGoogleAuthTokenForTesting[] = "GOOGLE_AUTH_TOKEN_FOR_TESTING"; // The environment variable which can override '~/.config/gcloud' if set. constexpr char kCloudSdkConfig[] = "CLOUDSDK_CONFIG"; // The default path to the gcloud config folder, relative to the home folder. constexpr char kGCloudConfigFolder[] = ".config/gcloud/"; // The name of the well-known credentials JSON file in the gcloud config folder. constexpr char kWellKnownCredentialsFile[] = "application_default_credentials.json"; // The minimum time delta between now and the token expiration time // for the token to be re-used. constexpr int kExpirationTimeMarginSec = 60; // The URL to retrieve the auth bearer token via OAuth with a refresh token. constexpr char kOAuthV3Url[] = "https://www.googleapis.com/oauth2/v3/token"; // The URL to retrieve the auth bearer token via OAuth with a private key. constexpr char kOAuthV4Url[] = "https://www.googleapis.com/oauth2/v4/token"; // The URL to retrieve the auth bearer token when running in Google Compute // Engine. constexpr char kGceTokenUrl[] = "http://metadata/computeMetadata/v1/instance/service-accounts/default/" "token"; // The authentication token scope to request. constexpr char kOAuthScope[] = "https://www.googleapis.com/auth/cloud-platform"; // The default initial delay between retries with exponential backoff. constexpr int kInitialRetryDelayUsec = 500000; // 0.5 sec /// Returns whether the given path points to a readable file. bool IsFile(const string& filename) { std::ifstream fstream(filename.c_str()); return fstream.good(); } /// Returns the credentials file name from the env variable. Status GetEnvironmentVariableFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } const char* result = std::getenv(kGoogleApplicationCredentials); if (!result || !IsFile(result)) { return errors::NotFound(strings::StrCat("$", kGoogleApplicationCredentials, " is not set or corrupt.")); } *filename = result; return Status::OK(); } /// Returns the well known file produced by command 'gcloud auth login'. Status GetWellKnownFileName(string* filename) { if (!filename) { return errors::FailedPrecondition("'filename' cannot be nullptr."); } string config_dir; const char* config_dir_override = std::getenv(kCloudSdkConfig); if (config_dir_override) { config_dir = config_dir_override; } else { // Determine the home dir path. const char* home_dir = std::getenv("HOME"); if (!home_dir) { return errors::FailedPrecondition("Could not read $HOME."); } config_dir = io::JoinPath(home_dir, kGCloudConfigFolder); } auto result = io::JoinPath(config_dir, kWellKnownCredentialsFile); if (!IsFile(result)) { return errors::NotFound( "Could not find the credentials file in the standard gcloud location."); } *filename = result; return Status::OK(); } } // namespace GoogleAuthProvider::GoogleAuthProvider() : GoogleAuthProvider( std::unique_ptr<OAuthClient>(new OAuthClient()), std::unique_ptr<HttpRequest::Factory>(new HttpRequest::Factory()), Env::Default(), kInitialRetryDelayUsec) {} GoogleAuthProvider::GoogleAuthProvider( std::unique_ptr<OAuthClient> oauth_client, std::unique_ptr<HttpRequest::Factory> http_request_factory, Env* env, int64 initial_retry_delay_usec) : oauth_client_(std::move(oauth_client)), http_request_factory_(std::move(http_request_factory)), env_(env), initial_retry_delay_usec_(initial_retry_delay_usec) {} Status GoogleAuthProvider::GetToken(string* t) { mutex_lock lock(mu_); const uint64 now_sec = env_->NowSeconds(); if (!current_token_.empty() && now_sec + kExpirationTimeMarginSec < expiration_timestamp_sec_) { *t = current_token_; return Status::OK(); } if (GetTokenForTesting().ok()) { *t = current_token_; return Status::OK(); } auto token_from_files_status = GetTokenFromFiles(); auto token_from_gce_status = token_from_files_status.ok() ? Status::OK() : GetTokenFromGce(); if (token_from_files_status.ok() || token_from_gce_status.ok()) { *t = current_token_; return Status::OK(); } LOG(WARNING) << "All attempts to get a Google authentication bearer token failed, " << "returning an empty token. Retrieving token from files failed with \"" << token_from_files_status.ToString() << "\"." << " Retrieving token from GCE failed with \"" << token_from_gce_status.ToString() << "\"."; // Public objects can still be accessed with an empty bearer token, // so return an empty token instead of failing. *t = ""; // From now on, always return the empty token. expiration_timestamp_sec_ = UINT64_MAX; current_token_ = ""; return Status::OK(); } Status GoogleAuthProvider::GetTokenFromFiles() { string credentials_filename; if (!GetEnvironmentVariableFileName(&credentials_filename).ok() && !GetWellKnownFileName(&credentials_filename).ok()) { return errors::NotFound("Could not locate the credentials file."); } Json::Value json; Json::Reader reader; std::ifstream credentials_fstream(credentials_filename); if (!reader.parse(credentials_fstream, json)) { return errors::FailedPrecondition( "Couldn't parse the JSON credentials file."); } if (json.isMember("refresh_token")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromRefreshTokenJson( json, kOAuthV3Url, &current_token_, &expiration_timestamp_sec_)); } else if (json.isMember("private_key")) { TF_RETURN_IF_ERROR(oauth_client_->GetTokenFromServiceAccountJson( json, kOAuthV4Url, kOAuthScope, &current_token_, &expiration_timestamp_sec_)); } else { return errors::FailedPrecondition( "Unexpected content of the JSON credentials file."); } return Status::OK(); } Status GoogleAuthProvider::GetTokenFromGce() { const auto get_token_from_gce = [this]() { std::unique_ptr<HttpRequest> request(http_request_factory_->Create()); std::vector<char> response_buffer; const uint64 request_timestamp_sec = env_->NowSeconds(); TF_RETURN_IF_ERROR(request->Init()); TF_RETURN_IF_ERROR(request->SetUri(kGceTokenUrl)); TF_RETURN_IF_ERROR(request->AddHeader("Metadata-Flavor", "Google")); TF_RETURN_IF_ERROR(request->SetResultBuffer(&response_buffer)); TF_RETURN_IF_ERROR(request->Send()); StringPiece response = StringPiece(&response_buffer[0], response_buffer.size()); TF_RETURN_IF_ERROR(oauth_client_->ParseOAuthResponse( response, request_timestamp_sec, &current_token_, &expiration_timestamp_sec_)); return Status::OK(); }; return RetryingUtils::CallWithRetries(get_token_from_gce, initial_retry_delay_usec_); } Status GoogleAuthProvider::GetTokenForTesting() { const char* token = std::getenv(kGoogleAuthTokenForTesting); if (!token) { return errors::NotFound("The env variable for testing was not set."); } expiration_timestamp_sec_ = UINT64_MAX; current_token_ = token; return Status::OK(); } } // namespace tensorflow
/**************************************************************************** * * Copyright 2018 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <unordered_map> // template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, // class Alloc = allocator<pair<const Key, T>>> // class unordered_map // { // public: // // types // typedef Key key_type; // typedef T mapped_type; // typedef Hash hasher; // typedef Pred key_equal; // typedef Alloc allocator_type; // typedef pair<const key_type, mapped_type> value_type; // typedef value_type& reference; // typedef const value_type& const_reference; // typedef typename allocator_traits<allocator_type>::pointer pointer; // typedef typename allocator_traits<allocator_type>::const_pointer const_pointer; // typedef typename allocator_traits<allocator_type>::size_type size_type; // typedef typename allocator_traits<allocator_type>::difference_type difference_type; #include <unordered_map> #include <type_traits> #include "libcxx_tc_common.h" int tc_libcxx_containers_unord_map_types(void) { { typedef std::unordered_map<char, short> C; static_assert((std::is_same<C::key_type, char>::value), ""); static_assert((std::is_same<C::mapped_type, short>::value), ""); static_assert((std::is_same<C::hasher, std::hash<C::key_type> >::value), ""); static_assert((std::is_same<C::key_equal, std::equal_to<C::key_type> >::value), ""); static_assert((std::is_same<C::allocator_type, std::allocator<C::value_type> >::value), ""); static_assert((std::is_same<C::value_type, std::pair<const C::key_type, C::mapped_type> >::value), ""); static_assert((std::is_same<C::reference, C::value_type&>::value), ""); static_assert((std::is_same<C::const_reference, const C::value_type&>::value), ""); static_assert((std::is_same<C::pointer, C::value_type*>::value), ""); static_assert((std::is_same<C::const_pointer, const C::value_type*>::value), ""); static_assert((std::is_same<C::size_type, std::size_t>::value), ""); static_assert((std::is_same<C::difference_type, std::ptrdiff_t>::value), ""); } TC_SUCCESS_RESULT(); return 0; }
#include "ID2D1DeviceContext2.h" #include "ID2D1Device2.h" #include "ID2D1Ink.h" #include "ID2D1InkStyle.h" #include "ID2D1GradientMesh.h" #include "ID2D1LookupTable3D.h" #include "ID2D1ImageSource.h" #include "ID2D1ImageSourceFromWic.h" #include "ID2D1Brush.h" #include "ID2D1GdiMetafile.h" #include "ID2D1TransformedImageSource.h" namespace D2DNet { namespace Direct2DNet { ID2D1DeviceContext2::ID2D1DeviceContext2( Direct2DNet::ID2D1Device3 ^device, Direct2DNet::D2D1_DEVICE_CONTEXT_OPTIONS options) : Direct2DNet::ID2D1DeviceContext1((Direct2DNet::ID2D1Device2 ^)device, options) { } ID2D1DeviceContext2::ID2D1DeviceContext2( Direct2DNet::ID2D1Device2 ^device, Direct2DNet::D2D1_DEVICE_CONTEXT_OPTIONS options) : Direct2DNet::ID2D1DeviceContext1(device, options) { HRESULT hr = S_OK; pin_ptr<::ID2D1Resource *> ppRenderTarget = &m_pResource; hr = ((::ID2D1Device2 *)device->m_pResource)->CreateDeviceContext( (::D2D1_DEVICE_CONTEXT_OPTIONS)((int)options), (::ID2D1DeviceContext2 **)ppRenderTarget ); ppRenderTarget = nullptr; if(FAILED(hr)) throw gcnew Direct2DNet::Exception::DxException("Failed to create ID2D1DeviceContext2", (int)hr); } Direct2DNet::ID2D1Ink ^ID2D1DeviceContext2::CreateInk(Direct2DNet::D2D1_INK_POINT %startPoint) { return gcnew Direct2DNet::ID2D1Ink(this, startPoint); } Direct2DNet::ID2D1InkStyle ^ID2D1DeviceContext2::CreateInkStyle( System::Nullable<Direct2DNet::D2D1_INK_STYLE_PROPERTIES> inkStyleProperties) { return gcnew Direct2DNet::ID2D1InkStyle(this, inkStyleProperties); } Direct2DNet::ID2D1GradientMesh ^ID2D1DeviceContext2::CreateGradientMesh( ...array<Direct2DNet::D2D1_GRADIENT_MESH_PATCH> ^patches) { return gcnew Direct2DNet::ID2D1GradientMesh(this, patches); } Direct2DNet::ID2D1ImageSourceFromWic ^ID2D1DeviceContext2::CreateImageSourceFromWic( D2DNet::WICNet::IWICBitmapSource ^wicBitmapSource, Direct2DNet::D2D1_IMAGE_SOURCE_LOADING_OPTIONS loadingOptions, Direct2DNet::D2D1_ALPHA_MODE alphaMode) { return gcnew Direct2DNet::ID2D1ImageSourceFromWic(this, wicBitmapSource, loadingOptions, alphaMode); } Direct2DNet::Effects::ID2D1LookupTable3D ^ID2D1DeviceContext2::CreateLookupTable3D( Direct2DNet::D2D1_BUFFER_PRECISION precision, System::ValueTuple<UINT32, UINT32, UINT32> %extents, array<BYTE> ^data, System::ValueTuple<UINT32, UINT32> %strides) { return gcnew Direct2DNet::Effects::ID2D1LookupTable3D( this, precision, extents, data, strides ); } Direct2DNet::ID2D1ImageSource ^ID2D1DeviceContext2::CreateImageSourceFromDxgi( array<DXGINet::IDXGISurface ^> ^surfaces, DXGINet::DXGI_COLOR_SPACE_TYPE colorSpace, Direct2DNet::D2D1_IMAGE_SOURCE_FROM_DXGI_OPTIONS options) { return gcnew Direct2DNet::ID2D1ImageSource(this, surfaces, colorSpace, options); } HRESULT ID2D1DeviceContext2::GetGradientMeshWorldBounds( Direct2DNet::ID2D1GradientMesh ^gradientMesh, Direct2DNet::D2D1_RECT_F %bounds) { pin_ptr<Direct2DNet::D2D1_RECT_F> pBounds = &bounds; return ((::ID2D1DeviceContext2 *)m_pResource)->GetGradientMeshWorldBounds( (::ID2D1GradientMesh *)gradientMesh->m_pResource, reinterpret_cast<::D2D1_RECT_F *>(pBounds) ); } System::ValueTuple<HRESULT, Direct2DNet::D2D1_RECT_F> ID2D1DeviceContext2::GetGradientMeshWorldBounds( Direct2DNet::ID2D1GradientMesh ^gradientMesh) { Direct2DNet::D2D1_RECT_F bounds; HRESULT hr = ((::ID2D1DeviceContext2 *)m_pResource)->GetGradientMeshWorldBounds( (::ID2D1GradientMesh *)gradientMesh->m_pResource, reinterpret_cast<::D2D1_RECT_F *>(&bounds) ); return System::ValueTuple<HRESULT, Direct2DNet::D2D1_RECT_F>(hr, bounds); } void ID2D1DeviceContext2::DrawInk( Direct2DNet::ID2D1Ink ^ink, Direct2DNet::ID2D1Brush ^brush, Direct2DNet::ID2D1InkStyle ^inkStyle) { ((::ID2D1DeviceContext2 *)m_pResource)->DrawInk( (::ID2D1Ink *)ink->m_pResource, (::ID2D1Brush *)brush->m_pResource, inkStyle ? (::ID2D1InkStyle *)inkStyle->m_pResource : __nullptr ); } void ID2D1DeviceContext2::DrawGradientMesh(Direct2DNet::ID2D1GradientMesh ^gradientMesh) { ((::ID2D1DeviceContext2 *)m_pResource)->DrawGradientMesh( (::ID2D1GradientMesh *)gradientMesh->m_pResource ); } void ID2D1DeviceContext2::DrawGdiMetafile( Direct2DNet::ID2D1GdiMetafile ^gdiMetafile, System::Nullable<Direct2DNet::D2D1_RECT_F> destinationRectangle, System::Nullable<Direct2DNet::D2D1_RECT_F> sourceRectangle) { ((::ID2D1DeviceContext2 *)m_pResource)->DrawGdiMetafile( (::ID2D1GdiMetafile *)gdiMetafile->m_pResource, destinationRectangle.HasValue ? (::D2D1_RECT_F *)&destinationRectangle.Value : __nullptr, sourceRectangle.HasValue ? (::D2D1_RECT_F *)&sourceRectangle.Value : __nullptr ); } Direct2DNet::ID2D1TransformedImageSource ^ID2D1DeviceContext2::CreateTransformedImageSource( Direct2DNet::ID2D1ImageSource ^imageSource, Direct2DNet::D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES %properties) { return gcnew Direct2DNet::ID2D1TransformedImageSource(this, imageSource, properties); } } }
#include "Core.h" Core::Core(QObject *parent) : QTcpServer(parent){ Write("Server Started!"); } void Core::incomingConnection(int Socket){ QTcpSocket *client = new QTcpSocket(this); client->setSocketDescriptor(Socket); Clients.insert(client); connect(client, SIGNAL(readyRead()), this, SLOT(ReadyRead())); connect(client, SIGNAL(disconnected()), this, SLOT(Disconnected())); } void Core::Write(QString Data){ QString format = "HH:mm / dd.MM.yyyy"; QDateTime time = QDateTime::currentDateTime(); QString newdata = "["+ time.toString(format) + "] " + Data; qDebug() << (const char *)newdata.toStdString().c_str(); } void Core::SendReplay(QString User, QString Data){ foreach(QTcpSocket *client, Clients){ client->write(QString("Server-Replay | (" + User + ") : " + Data + "\n").toUtf8()); } } void Core::CheckCommand(QString Line) { QList<QString> Commands; Commands << "say"; for(int x = 0; x < Commands.count(); x++){ if(Line.lastIndexOf(Commands[x]) > 0){ QString ReplaceCommand = Line.replace("/" + Commands[x] + ":" , ""); QString FindUser = ReplaceCommand.replace("|","\n"); QList<int> list; QStringList slist; slist = FindUser.split("\n"); for (int x = 0; x <= slist.count()-1; x++) { list.append(slist.at(x).toInt()); } QString UserName = slist[0]; QString Message = slist[1]; if(Commands[x] == "say") { Write("New Request: Command-" + Commands[x] + " [UserName: " + UserName + "]"); SendReplay(UserName, Message); } } } } void Core::ReadyRead(){ QTcpSocket *client = (QTcpSocket*)sender(); while(client->canReadLine()) { QString line = QString::fromUtf8(client->readLine()).trimmed(); CheckCommand(line); } } void Core::Disconnected(){ QTcpSocket *client = (QTcpSocket*)sender(); Clients.remove(client); }
/*========================================================================= Program: MAF2 Module: mafGUIGizmoScaleTest Authors: Stefano Perticoni Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include <cppunit/config/SourcePrefix.h> #include "mafGUIGizmoScaleTest.h" #include "mafVMESurface.h" #include "mafDecl.h" #include "mafGUIGizmoScale.h" #include "mafTransform.h" #include "vtkCubeSource.h" #include <iostream> void DummyObserver::OnEvent(mafEventBase *maf_event) { m_LastReceivedEventID = maf_event->GetId(); } int DummyObserver::GetLastReceivedEventID() { return m_LastReceivedEventID; } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::TestFixture() //---------------------------------------------------------------------------- { } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::setUp() //---------------------------------------------------------------------------- { m_VMECube = mafVMESurface::New(); m_VMECube->SetName("m_VMECube"); m_VTKCube = vtkCubeSource::New(); m_VMECube->SetData(m_VTKCube->GetOutput(), -1); } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::tearDown() //---------------------------------------------------------------------------- { mafDEL(m_VMECube); vtkDEL(m_VTKCube); } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::TestConstructorDestructor() //---------------------------------------------------------------------------- { mafGUIGizmoScale *guiGizmoScale = new mafGUIGizmoScale(NULL, true); CPPUNIT_ASSERT(guiGizmoScale->m_Listener == NULL); cppDEL(guiGizmoScale); guiGizmoScale = new mafGUIGizmoScale(m_VMECube, true); CPPUNIT_ASSERT(guiGizmoScale->m_Listener == m_VMECube); cppDEL(guiGizmoScale); } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::TestSetAbsScaling() //---------------------------------------------------------------------------- { mafGUIGizmoScale *guiGizmoScale = new mafGUIGizmoScale(NULL, true); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[0], 1.0); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[1], 1.0); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[2], 1.0); mafMatrix absScaling; mafTransform::Scale(absScaling, 2, 3, 4, PRE_MULTIPLY); absScaling.Print(cout); guiGizmoScale->SetAbsScaling(&absScaling); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[0], 2.0); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[1], 3.0); CPPUNIT_ASSERT_EQUAL(guiGizmoScale->m_Scaling[2], 4.0); cppDEL(guiGizmoScale); } //---------------------------------------------------------------------------- void mafGUIGizmoScaleTest::TestOnEvent() //---------------------------------------------------------------------------- { DummyObserver *dummy = new DummyObserver(); mafGUIGizmoScale *guiGizmoScale = new mafGUIGizmoScale(dummy, true); mafEvent eventSent(this, mafGUIGizmoScale::ID_SCALE_X); guiGizmoScale->OnEvent(&eventSent); int dummyReceivedEventID = dummy->GetLastReceivedEventID(); CPPUNIT_ASSERT(dummyReceivedEventID == mafGUIGizmoScale::ID_SCALE_X); eventSent.SetId(mafGUIGizmoScale::ID_SCALE_Y); guiGizmoScale->OnEvent(&eventSent); dummyReceivedEventID = dummy->GetLastReceivedEventID(); CPPUNIT_ASSERT(dummyReceivedEventID == mafGUIGizmoScale::ID_SCALE_Y); eventSent.SetId(mafGUIGizmoScale::ID_SCALE_Z); guiGizmoScale->OnEvent(&eventSent); dummyReceivedEventID = dummy->GetLastReceivedEventID(); CPPUNIT_ASSERT(dummyReceivedEventID == mafGUIGizmoScale::ID_SCALE_Z); cppDEL(guiGizmoScale); cppDEL(dummy); }
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_5_B" #include "../../library/template.hpp" #include "../../library/tree/rerooting.hpp" #include "../../library/monoid/max_monoid.hpp" int main(){ int n; scanf("%d",&n); weighted_graph<int> T(n); rep(i,n-1){ int u,v,c; scanf("%d%d%d",&u,&v,&c); add_undirected_edge(T,u,v,c); } using monoid=max_monoid<int>; auto f=[](monoid m,int wt,int v)->monoid{ return m.get()+wt; }; auto g=[](monoid m,int u)->monoid{ return m*0; }; for(auto m:rerooting<monoid>(T,f,g)){ printf("%d\n",m.get()); } return 0; }
// // Created by mzy on 2021-06-03. // #include "Simp.hpp" Tree<ASTNode>* simp(Tree<ASTNode>* n,Tree<ASTNode>* l,Tree<ASTNode>* r){ switch (n->root.type) { case NodeType_t::LogicAnd: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return r; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return l; return n; case NodeType_t::LogicOr: if(l->root.type==NodeType_t::True || r->root.type==NodeType_t::False)return l; if(l->root.type==NodeType_t::False || r->root.type==NodeType_t::True)return r; return n; } }
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "get_gc_status_wbt_command.h" #include <cstdint> #include <iomanip> #include <sstream> #include <string> #include "src/allocator_service/allocator_service.h" #include "src/allocator/i_context_manager.h" #include "src/array_mgmt/array_manager.h" #include "src/array_models/interface/i_array_info.h" #include "src/gc/garbage_collector.h" namespace pos { GetGcStatusWbtCommand::GetGcStatusWbtCommand(void) : GcWbtCommand(GET_GC_STATUS, "get_gc_status") { } GetGcStatusWbtCommand::~GetGcStatusWbtCommand(void) { } int GetGcStatusWbtCommand::Execute(Args &argv, JsonElement &elem) { if (!argv.contains("array")) { return -1; } std::string arrayName = argv["array"].get<std::string>(); GarbageCollector* gc = _GetGC(arrayName); if (gc == nullptr) { return -1; } int isEnabled = gc->IsEnabled(); if (0 != isEnabled) { return -1; } bool gcRunning = gc->GetGcRunning(); IContextManager* iContextManager = AllocatorServiceSingleton::Instance()->GetIContextManager(arrayName); uint32_t freeSegments = iContextManager->GetNumOfFreeSegment(true); uint32_t numGcThreshold = iContextManager->GetGcThreshold(MODE_NORMAL_GC); uint32_t numUrgentThreshold = iContextManager->GetGcThreshold(MODE_URGENT_GC); std::string gcActive; std::string gcMode; gcActive = (false == gcRunning) ? "done" : "active"; if (freeSegments <= numUrgentThreshold) { gcMode = "urgent"; } else if (freeSegments < numGcThreshold) { gcMode = "normal"; } else { gcMode = "none"; } JsonElement gcElem("gc"); JsonElement statusElem("status"); statusElem.SetAttribute(JsonAttribute("active", "\"" + gcActive + "\"")); statusElem.SetAttribute(JsonAttribute("mode", "\"" + gcMode + "\"")); gcElem.SetElement(statusElem); JsonElement timeElem("time"); struct timeval startTv = gc->GetStartTime(); std::ostringstream oss; if (startTv.tv_sec == 0 && startTv.tv_usec == 0) { oss << "N/A"; } else { std::tm tm; localtime_r(&startTv.tv_sec, &tm); oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S"); } timeElem.SetAttribute(JsonAttribute("start", "\"" + oss.str() + "\"")); oss.str(""); oss.clear(); uint32_t elapsed = 0; if (false == gcRunning) { struct timeval endTv = gc->GetEndTime(); if (endTv.tv_sec == 0 && endTv.tv_usec == 0) { oss << "N/A"; } else { std::tm tm; localtime_r(&endTv.tv_sec, &tm); oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S"); } elapsed = ((endTv.tv_sec - startTv.tv_sec) * 1000) + ((endTv.tv_usec - startTv.tv_usec) / 1000); } timeElem.SetAttribute(JsonAttribute("end", "\"" + oss.str() + "\"")); timeElem.SetAttribute(JsonAttribute("elapsed", elapsed)); gcElem.SetElement(timeElem); const PartitionLogicalSize* udSize; IArrayInfo* info = ArrayMgr()->GetInfo(arrayName)->arrayInfo; udSize = info->GetSizeInfo(PartitionType::USER_DATA); uint32_t totalSegments = udSize->totalSegments; JsonElement segElem("segment"); segElem.SetAttribute(JsonAttribute("total", totalSegments)); segElem.SetAttribute(JsonAttribute("used", totalSegments - freeSegments)); segElem.SetAttribute(JsonAttribute("free", freeSegments)); gcElem.SetElement(segElem); elem.SetElement(gcElem); return 0; } } // namespace pos
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/src/foxitlib.h" #define FWLTHEME_CAPACITY_CXFormBorder 3 #define FWLTHEME_CAPACITY_CYFormBorder 3 #define FWLTHEME_CAPACITY_CYNarrowCaption 18 #define FWLTHEME_CAPACITY_CYCaption 29 #define FWLTHEME_CAPACITY_BigIconSize 32 #define FWLTHEME_CAPACITY_SmallIconSize 16 #define FWLTHEME_CAPACITY_FormTextColor 0xFFFFFFFF #define FWLTHEME_FORMBTN_Margin 5 #define FWLTHEME_FORMBTN_Span 2 #define FWLTHEME_FORMBTN_Size 21 CFWL_FormTP::CFWL_FormTP() : m_pActiveBitmap(NULL), m_pDeactivebitmap(NULL) { m_pThemeData = new SBThemeData; SetThemeData(0); m_rtDisLBorder.Reset(); m_rtDisRBorder.Reset(); m_rtDisBBorder.Reset(); m_rtDisCaption.Reset(); } CFWL_FormTP::~CFWL_FormTP() { if (m_pThemeData) { delete m_pThemeData; m_pThemeData = NULL; } } FWL_ERR CFWL_FormTP::Initialize() { InitTTO(); InitCaption(TRUE); InitCaption(FALSE); return CFWL_WidgetTP::Initialize(); } FWL_ERR CFWL_FormTP::Finalize() { FinalizeTTO(); if (m_pActiveBitmap) { delete m_pActiveBitmap; m_pActiveBitmap = NULL; } if (m_pDeactivebitmap) { delete m_pDeactivebitmap; m_pDeactivebitmap = NULL; } return CFWL_WidgetTP::Finalize(); } FX_BOOL CFWL_FormTP::IsValidWidget(IFWL_Widget* pWidget) { if (!pWidget) return FALSE; FX_DWORD dwHash = pWidget->GetClassID(); return dwHash == FWL_CLASSHASH_Form; } FX_DWORD CFWL_FormTP::SetThemeID(IFWL_Widget* pWidget, FX_DWORD dwThemeID, FX_BOOL bChildren) { if (m_pThemeData) { SetThemeData(FWL_GetThemeColor(dwThemeID)); } InitCaption(TRUE); InitCaption(FALSE); return CFWL_WidgetTP::SetThemeID(pWidget, dwThemeID, bChildren); } FX_BOOL CFWL_FormTP::DrawBackground(CFWL_ThemeBackground* pParams) { if (!pParams) return FALSE; int32_t iActive = 0; if (pParams->m_dwStates & FWL_PARTSTATE_FRM_Inactive) { iActive = 1; } FWLTHEME_STATE eState = FWLTHEME_STATE_Normal; switch (pParams->m_dwStates & 0x03) { case FWL_PARTSTATE_FRM_Hover: { eState = FWLTHEME_STATE_Hover; break; } case FWL_PARTSTATE_FRM_Pressed: { eState = FWLTHEME_STATE_Pressed; break; } case FWL_PARTSTATE_FRM_Disabled: { eState = FWLTHEME_STATE_Disabale; break; } default: {} } switch (pParams->m_iPart) { case FWL_PART_FRM_Border: { DrawFormBorder(pParams->m_pGraphics, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_Edge: { DrawEdge(pParams->m_pGraphics, pParams->m_pWidget->GetStyles(), &pParams->m_rtPart, &pParams->m_matrix); break; } case FWL_PART_FRM_Background: { FillBackground(pParams->m_pGraphics, &pParams->m_rtPart, &pParams->m_matrix); break; } case FWL_PART_FRM_Caption: { DrawCaption(pParams->m_pGraphics, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_NarrowCaption: { DrawNarrowCaption(pParams->m_pGraphics, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_CloseBox: { DrawCloseBox(pParams->m_pGraphics, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_MinimizeBox: { DrawMinimizeBox(pParams->m_pGraphics, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_MaximizeBox: { DrawMaximizeBox(pParams->m_pGraphics, &pParams->m_rtPart, eState, pParams->m_dwData, &pParams->m_matrix, iActive); break; } case FWL_PART_FRM_Icon: { DrawIconImage(pParams->m_pGraphics, pParams->m_pImage, &pParams->m_rtPart, eState, &pParams->m_matrix, iActive); break; } default: {} } return TRUE; } FX_BOOL CFWL_FormTP::DrawText(CFWL_ThemeText* pParams) { if (!m_pTextOut) return FALSE; if (pParams->m_iPart == FWL_PART_FRM_Caption) { m_pTextOut->SetTextColor(0xFFFFFFFF); } else { m_pTextOut->SetTextColor(0xFF000000); } return CFWL_WidgetTP::DrawText(pParams); } void* CFWL_FormTP::GetCapacity(CFWL_ThemePart* pThemePart, FX_DWORD dwCapacity) { FX_BOOL bDefPro = FALSE; FX_BOOL bDwordVal = FALSE; switch (dwCapacity) { case FWL_WGTCAPACITY_CXBorder: { m_fValue = FWLTHEME_CAPACITY_CXFormBorder; break; } case FWL_WGTCAPACITY_CYBorder: { m_fValue = FWLTHEME_CAPACITY_CYFormBorder; break; } case FWL_WGTCAPACITY_FRM_CYCaption: { m_fValue = FWLTHEME_CAPACITY_CYCaption; break; } case FWL_WGTCAPACITY_FRM_CYNarrowCaption: { m_fValue = FWLTHEME_CAPACITY_CYCaption; break; } case FWL_WGTCAPACITY_TextColor: { bDwordVal = TRUE; m_dwValue = FWLTHEME_CAPACITY_FormTextColor; break; } case FWL_WGTCAPACITY_FRM_BigIcon: { m_fValue = FWLTHEME_CAPACITY_BigIconSize; break; } case FWL_WGTCAPACITY_FRM_SmallIcon: { m_fValue = FWLTHEME_CAPACITY_SmallIconSize; break; } default: { bDefPro = TRUE; } } if (!bDefPro) { if (bDwordVal) { return &m_dwValue; } return &m_fValue; } return CFWL_WidgetTP::GetCapacity(pThemePart, dwCapacity); } FWL_ERR CFWL_FormTP::GetPartRect(CFWL_ThemePart* pThemePart, CFX_RectF& rtPart) { switch (pThemePart->m_iPart) { case FWL_PART_FRM_CloseBox: { CalCloseBox(pThemePart->m_pWidget, rtPart); break; } case FWL_PART_FRM_MaximizeBox: { CalMaxBox(pThemePart->m_pWidget, rtPart); break; } case FWL_PART_FRM_MinimizeBox: { CalMinBox(pThemePart->m_pWidget, rtPart); break; } case FWL_PART_FRM_HeadText: { CalCaption(pThemePart->m_pWidget, rtPart); break; } case FWL_PART_FRM_Icon: { CalIcon(pThemePart->m_pWidget, rtPart); break; } default: {} } return FWL_ERR_Succeeded; } void CFWL_FormTP::CalCloseBox(IFWL_Widget* pWidget, CFX_RectF& rect) { FX_DWORD dwStyles = pWidget->GetStyles(); CFX_RectF rtWidget; pWidget->GetWidgetRect(rtWidget); rtWidget.Offset(-rtWidget.left, -rtWidget.top); if (dwStyles & FWL_WGTSTYLE_CloseBox) { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Span, rtWidget.top + FWLTHEME_FORMBTN_Margin, FWLTHEME_FORMBTN_Size, FWLTHEME_FORMBTN_Size); } else { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Span, rtWidget.top + FWLTHEME_FORMBTN_Margin, 0, 0); } } void CFWL_FormTP::CalMaxBox(IFWL_Widget* pWidget, CFX_RectF& rect) { FX_DWORD dwStyles = pWidget->GetStyles(); CFX_RectF rtWidget; pWidget->GetWidgetRect(rtWidget); rtWidget.Offset(-rtWidget.left, -rtWidget.top); if (dwStyles & FWL_WGTSTYLE_MaximizeBox) { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Size + FWLTHEME_FORMBTN_Span * 2, rtWidget.top + FWLTHEME_FORMBTN_Margin, FWLTHEME_FORMBTN_Size, FWLTHEME_FORMBTN_Size); } else { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Size + FWLTHEME_FORMBTN_Span * 2, rtWidget.top + FWLTHEME_FORMBTN_Margin, 0, 0); } } void CFWL_FormTP::CalMinBox(IFWL_Widget* pWidget, CFX_RectF& rect) { FX_DWORD dwStyles = pWidget->GetStyles(); CFX_RectF rtWidget; pWidget->GetWidgetRect(rtWidget); rtWidget.Offset(-rtWidget.left, -rtWidget.top); if (dwStyles & FWL_WGTSTYLE_MinimizeBox) { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Size * 2 + FWLTHEME_FORMBTN_Span * 3, rtWidget.top + FWLTHEME_FORMBTN_Margin, FWLTHEME_FORMBTN_Size, FWLTHEME_FORMBTN_Size); } else { rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin + FWLTHEME_FORMBTN_Size * 2 + FWLTHEME_FORMBTN_Span * 3, rtWidget.top + FWLTHEME_FORMBTN_Margin, 0, 0); } } void CFWL_FormTP::CalCaption(IFWL_Widget* pWidget, CFX_RectF& rect) { CFX_RectF rtWidget; pWidget->GetWidgetRect(rtWidget); rtWidget.Offset(-rtWidget.left, -rtWidget.top); rect.Set(rtWidget.left + FWLTHEME_FORMBTN_Margin, rtWidget.top + FWLTHEME_FORMBTN_Margin - 2, rtWidget.width - FWLTHEME_FORMBTN_Margin * 2, FWLTHEME_FORMBTN_Size + 2 * FWLTHEME_FORMBTN_Margin + 4); } void CFWL_FormTP::CalIcon(IFWL_Widget* pWidget, CFX_RectF& rect) {} void CFWL_FormTP::DrawFormBorder(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { CFX_RectF rt; rt.Set(pRect->left, pRect->top, 1, pRect->height); FX_FLOAT fBottom, fRight; fBottom = pRect->bottom(); fRight = pRect->right(); CFX_Path path; path.Create(); CFX_Color clrLine; path.Clear(); path.MoveTo(pRect->left, pRect->top); path.LineTo(pRect->left, fBottom - 1); path.LineTo(fRight - 1, fBottom - 1); path.LineTo(fRight - 1, pRect->top); clrLine = m_pThemeData->clrFormBorder[iActive][2]; pGraphics->SetStrokeColor(&clrLine); pGraphics->StrokePath(&path, pMatrix); path.Clear(); path.MoveTo(pRect->left + 1, pRect->top); path.LineTo(pRect->left + 1, fBottom - 2); path.LineTo(fRight - 2, fBottom - 2); path.LineTo(fRight - 2, pRect->top); clrLine = m_pThemeData->clrFormBorder[iActive][1]; pGraphics->SetStrokeColor(&clrLine); pGraphics->StrokePath(&path, pMatrix); path.Clear(); path.MoveTo(pRect->left + 2, pRect->top); path.LineTo(pRect->left + 2, fBottom - 3); path.LineTo(fRight - 3, fBottom - 3); path.LineTo(fRight - 3, pRect->top); clrLine = m_pThemeData->clrFormBorder[iActive][0]; pGraphics->SetStrokeColor(&clrLine); pGraphics->StrokePath(&path, pMatrix); path.Clear(); path.MoveTo(pRect->left + 3, pRect->top); path.LineTo(pRect->left + 3, fBottom - 4); path.LineTo(fRight - 4, fBottom - 4); path.LineTo(fRight - 4, pRect->top); clrLine = m_pThemeData->clrFormBorder[iActive][4]; pGraphics->SetStrokeColor(&clrLine); pGraphics->StrokePath(&path, pMatrix); m_rtDisLBorder.Set(pRect->left, pRect->top + 29, 4, pRect->height - 29); m_rtDisRBorder.Set(pRect->right() - 4, pRect->top + 29, 4, pRect->height - 29); m_rtDisBBorder.Set(pRect->left, pRect->bottom() - 4, pRect->width, 4); m_rtDisCaption.Set(pRect->left, pRect->top, pRect->width, 29); } void CFWL_FormTP::DrawCaption(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { CFX_RectF rt; FX_FLOAT fBottom, fRight; fBottom = pRect->bottom(); fRight = pRect->right(); rt.Set(pRect->left, pRect->top, pRect->width, 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeTop[iActive][0], &rt, pMatrix); rt.Offset(0, 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeTop[iActive][1], &rt, pMatrix); rt.Offset(0, 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeTop[iActive][2], &rt, pMatrix); rt.Set(pRect->left, pRect->bottom() - 1, pRect->width, 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeBottom[iActive][2], &rt, pMatrix); rt.Offset(0, -1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeBottom[iActive][1], &rt, pMatrix); rt.Set(pRect->left, pRect->top, 1, pRect->height); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeLeft[iActive][2], &rt, pMatrix); rt.Set(pRect->left + 1, pRect->top + 1, 1, fBottom - 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeLeft[iActive][1], &rt, pMatrix); rt.Set(pRect->left + 2, pRect->top + 2, 1, fBottom - 2); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeLeft[iActive][0], &rt, pMatrix); rt.Set(fRight - 1, pRect->top, pRect->width, pRect->height); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeRight[iActive][2], &rt, pMatrix); rt.Set(fRight - 2, pRect->top + 1, 1, fBottom - 1); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeRight[iActive][1], &rt, pMatrix); rt.Set(fRight - 3, pRect->top + 2, 1, fBottom - 2); FillSoildRect(pGraphics, m_pThemeData->clrHeadEdgeRight[iActive][0], &rt, pMatrix); CFX_RectF rect(*pRect); rect.Set(rect.left + 3, rect.top + 3, rect.width - 6, rect.height - 5); if (iActive == 0) { pGraphics->StretchImage(m_pActiveBitmap, rect, pMatrix); } else { pGraphics->StretchImage(m_pDeactivebitmap, rect, pMatrix); } } void CFWL_FormTP::DrawNarrowCaption(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) {} void CFWL_FormTP::DrawCloseBox(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { FX_FLOAT fRight = pRect->right(); FX_FLOAT fBottom = pRect->bottom(); FX_FLOAT fWidth = pRect->width; FX_FLOAT fHeight = pRect->height; pGraphics->SaveGraphState(); CFX_RectF rt(*pRect); pGraphics->SetLineWidth(1.0f); CFX_Path path; path.Create(); path.AddRectangle(rt.left + 1, rt.top, fWidth - 2, 1); path.AddRectangle(rt.left, rt.top + 1, 1, fHeight - 2); path.AddRectangle(fRight - 1, rt.top + 1, 1, fHeight - 2); path.AddRectangle(rt.left + 1, fBottom - 1, fWidth - 2, 1); CFX_Color crFill; crFill = m_pThemeData->clrBtnEdgeOut[iActive]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(rt.left + 1, rt.top + 1, 1, 1); path.AddRectangle(fRight - 2, rt.top + 1, 1, 1); path.AddRectangle(rt.left + 1, fBottom - 2, 1, 1); path.AddRectangle(fRight - 2, fBottom - 2, 1, 1); crFill = m_pThemeData->clrBtnCornerLight[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(rt.left + 2, rt.top + 1, fWidth - 4, 1); path.AddRectangle(rt.left + 1, rt.top + 2, 1, fHeight - 4); crFill = m_pThemeData->clrCloseBtEdgeLight[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(fRight - 2, rt.top + 2, 1, fHeight - 4); path.AddRectangle(rt.left + 2, fBottom - 2, fWidth - 4, 1); crFill = m_pThemeData->clrCloseBtEdgeDark[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(pRect->left + 2, pRect->top + 2, fWidth - 4, fHeight - 4); DrawAxialShading(pGraphics, pRect->left + 2, pRect->top + 2, fRight - 2, fBottom - 2, m_pThemeData->clrCloseBtBKStart[iActive][eState - 1], m_pThemeData->clrCloseBtBKEnd[iActive][eState - 1], &path, FXFILL_WINDING, pMatrix); CFX_RectF rtX(*pRect); rtX.Inflate(-5, -5); path.Clear(); FX_FLOAT frtXRight = rtX.right(); FX_FLOAT frtXBottom = rtX.bottom(); path.AddLine(rtX.left, rtX.top + 1, frtXRight - 1, frtXBottom); path.AddLine(rtX.left, rtX.top, frtXRight, frtXBottom); path.AddLine(rtX.left + 1, rtX.top, frtXRight, frtXBottom - 1); path.AddLine(rtX.left, frtXBottom - 1, frtXRight - 1, rtX.top); path.AddLine(rtX.left, frtXBottom, frtXRight, rtX.top); path.AddLine(rtX.left + 1, frtXBottom, frtXRight, rtX.top + 1); CFX_Color clrLine(0xffffffff); pGraphics->SetLineWidth(1.0f); pGraphics->SetStrokeColor(&clrLine); pGraphics->StrokePath(&path, pMatrix); pGraphics->RestoreGraphState(); } void CFWL_FormTP::DrawMinMaxBoxCommon(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { pGraphics->SaveGraphState(); FX_FLOAT fRight = pRect->right(); FX_FLOAT fBottom = pRect->bottom(); FX_FLOAT fWidth = pRect->width; FX_FLOAT fHeight = pRect->height; CFX_RectF rt(*pRect); pGraphics->SetLineWidth(1.0f); CFX_Path path; path.Create(); path.AddRectangle(rt.left + 1, rt.top, fWidth - 2, 1); path.AddRectangle(rt.left, rt.top + 1, 1, fHeight - 2); path.AddRectangle(fRight - 1, rt.top + 1, 1, fHeight - 2); path.AddRectangle(rt.left + 1, fBottom - 1, fWidth - 2, 1); CFX_Color crFill; crFill = m_pThemeData->clrBtnEdgeOut[iActive]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(rt.left + 1, rt.top + 1, 1, 1); path.AddRectangle(fRight - 2, rt.top + 1, 1, 1); path.AddRectangle(rt.left + 1, fBottom - 2, 1, 1); path.AddRectangle(fRight - 2, fBottom - 2, 1, 1); crFill = m_pThemeData->clrBtnCornerLight[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(rt.left + 2, rt.top + 1, fWidth - 4, 1); path.AddRectangle(rt.left + 1, rt.top + 2, 1, fHeight - 4); crFill = m_pThemeData->clrNormalBtEdgeLight[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); path.Clear(); path.AddRectangle(fRight - 2, rt.top + 2, 1, fHeight - 4); path.AddRectangle(rt.left + 2, fBottom - 2, fWidth - 4, 1); crFill = m_pThemeData->clrNormalBtEdgeDark[iActive][eState - 1]; pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_WINDING, pMatrix); pGraphics->RestoreGraphState(); path.Clear(); path.AddRectangle(pRect->left + 2, pRect->top + 2, fWidth - 4, fHeight - 4); DrawAxialShading(pGraphics, pRect->left + 2, pRect->top + 2, fRight - 2, fBottom - 2, m_pThemeData->clrNormalBtBKStart[iActive][eState - 1], m_pThemeData->clrNormalBtBKEnd[iActive][eState - 1], &path, FXFILL_WINDING, pMatrix); } void CFWL_FormTP::DrawMinimizeBox(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { DrawMinMaxBoxCommon(pGraphics, pRect, eState, pMatrix); CFX_RectF rtMin; rtMin.Set(pRect->left + 5, pRect->top + 13, pRect->width - 14, pRect->height - 18); FillSoildRect(pGraphics, 0xFFFFFFFF, &rtMin, pMatrix); } void CFWL_FormTP::DrawMaximizeBox(CFX_Graphics* pGraphics, const CFX_RectF* pRect, FWLTHEME_STATE eState, FX_BOOL bMax, CFX_Matrix* pMatrix, int32_t iActive) { DrawMinMaxBoxCommon(pGraphics, pRect, eState, pMatrix); FX_FLOAT fWidth = pRect->width; FX_FLOAT fHeight = pRect->height; if (bMax) { CFX_Path path; path.Create(); path.AddLine(pRect->left + 7, pRect->top + 6, pRect->left + 14, pRect->top + 6); path.AddLine(pRect->left + 4, pRect->top + 9, pRect->left + 11, pRect->top + 9); pGraphics->SaveGraphState(); pGraphics->SetLineWidth(2); CFX_Color crStroke(0xFFFFFFFF); pGraphics->SetStrokeColor(&crStroke); pGraphics->StrokePath(&path, pMatrix); pGraphics->SetLineWidth(1); path.Clear(); path.AddLine(pRect->left + 4, pRect->top + 10, pRect->left + 4, pRect->top + 14); path.AddLine(pRect->left + 10, pRect->top + 10, pRect->left + 10, pRect->top + 14); path.AddLine(pRect->left + 13, pRect->top + 7, pRect->left + 13, pRect->top + 11); path.AddLine(pRect->left + 4, pRect->top + 14, pRect->left + 10, pRect->top + 14); path.AddLine(pRect->left + 12, pRect->top + 11, pRect->left + 12, pRect->top + 11); pGraphics->StrokePath(&path, pMatrix); pGraphics->RestoreGraphState(); } else { CFX_RectF rtMax(*pRect); rtMax.Inflate(-5, -5); CFX_Path path; path.Create(); path.AddRectangle(pRect->left + 5, pRect->top + 5, fWidth - 10, fHeight - 10); path.AddRectangle(pRect->left + 6, pRect->top + 8, fWidth - 12, fHeight - 14); pGraphics->SaveGraphState(); CFX_Color crFill(0xFFFFFFFF); pGraphics->SetFillColor(&crFill); pGraphics->FillPath(&path, FXFILL_ALTERNATE, pMatrix); pGraphics->RestoreGraphState(); } } void CFWL_FormTP::DrawIconImage(CFX_Graphics* pGraphics, CFX_DIBitmap* pDIBitmap, const CFX_RectF* pRect, FWLTHEME_STATE eState, CFX_Matrix* pMatrix, int32_t iActive) { pGraphics->StretchImage(pDIBitmap, *pRect, pMatrix); } void CFWL_FormTP::SetThemeData(FX_DWORD dwID) { m_pThemeData->clrTransWhite = ArgbEncode(0x65, 255, 255, 255); m_pThemeData->clrCloseBtBKStart[0][0] = ArgbEncode(0xff, 240, 166, 148); m_pThemeData->clrCloseBtBKEnd[0][0] = ArgbEncode(0xff, 228, 61, 5); m_pThemeData->clrCloseBtBKStart[0][1] = ArgbEncode(0xff, 255, 184, 176); m_pThemeData->clrCloseBtBKEnd[0][1] = ArgbEncode(0xff, 252, 107, 71); m_pThemeData->clrCloseBtBKStart[0][2] = ArgbEncode(0xff, 141, 44, 20); m_pThemeData->clrCloseBtBKEnd[0][2] = ArgbEncode(0xff, 202, 72, 33); m_pThemeData->clrCloseBtEdgeLight[0][0] = ArgbEncode(0xff, 255, 122, 107); m_pThemeData->clrCloseBtEdgeDark[0][0] = ArgbEncode(0xff, 218, 77, 54); m_pThemeData->clrCloseBtEdgeLight[0][1] = ArgbEncode(0xff, 255, 93, 74); m_pThemeData->clrCloseBtEdgeDark[0][1] = ArgbEncode(0xff, 218, 74, 51); m_pThemeData->clrCloseBtEdgeLight[0][2] = ArgbEncode(0xff, 191, 61, 28); m_pThemeData->clrCloseBtEdgeDark[0][2] = ArgbEncode(0xff, 93, 30, 13); if (dwID) { m_pThemeData->clrHeadBK[0][0] = ArgbEncode(0xff, 194, 205, 149); m_pThemeData->clrHeadBK[0][1] = ArgbEncode(0xff, 170, 184, 131); m_pThemeData->clrHeadBK[0][2] = ArgbEncode(0xff, 168, 182, 128); m_pThemeData->clrHeadBK[0][3] = ArgbEncode(0xff, 194, 205, 149); m_pThemeData->clrHeadEdgeLeft[0][0] = ArgbEncode(0xff, 117, 141, 94); m_pThemeData->clrHeadEdgeLeft[0][1] = ArgbEncode(0xff, 139, 161, 105); m_pThemeData->clrHeadEdgeLeft[0][2] = ArgbEncode(0xff, 171, 189, 133); m_pThemeData->clrHeadEdgeRight[0][0] = ArgbEncode(0xff, 155, 175, 125); m_pThemeData->clrHeadEdgeRight[0][1] = ArgbEncode(0xff, 128, 146, 103); m_pThemeData->clrHeadEdgeRight[0][2] = ArgbEncode(0xff, 94, 118, 79); m_pThemeData->clrHeadEdgeTop[0][0] = ArgbEncode(0xff, 139, 161, 105); m_pThemeData->clrHeadEdgeTop[0][1] = ArgbEncode(0xff, 234, 245, 201); m_pThemeData->clrHeadEdgeTop[0][2] = ArgbEncode(0xff, 194, 205, 149); m_pThemeData->clrHeadEdgeBottom[0][0] = ArgbEncode(0xff, 175, 189, 133); m_pThemeData->clrHeadEdgeBottom[0][1] = ArgbEncode(0xff, 153, 168, 121); m_pThemeData->clrHeadEdgeBottom[0][2] = ArgbEncode(0xff, 150, 168, 103); m_pThemeData->clrNormalBtBKStart[0][0] = ArgbEncode(0xff, 182, 195, 162); m_pThemeData->clrNormalBtBKEnd[0][0] = ArgbEncode(0xff, 128, 144, 84); m_pThemeData->clrNormalBtBKStart[0][1] = ArgbEncode(0xff, 234, 241, 208); m_pThemeData->clrNormalBtBKEnd[0][1] = ArgbEncode(0xff, 169, 186, 112); m_pThemeData->clrNormalBtBKStart[0][2] = ArgbEncode(0xff, 199, 199, 190); m_pThemeData->clrNormalBtBKEnd[0][2] = ArgbEncode(0xff, 133, 148, 88); m_pThemeData->clrNormalBtEdgeLight[0][0] = ArgbEncode(0xff, 163, 176, 137); m_pThemeData->clrNormalBtEdgeDark[0][0] = ArgbEncode(0xff, 118, 135, 83); m_pThemeData->clrNormalBtEdgeLight[0][1] = ArgbEncode(0xff, 154, 174, 105); m_pThemeData->clrNormalBtEdgeDark[0][1] = ArgbEncode(0xff, 154, 174, 105); m_pThemeData->clrNormalBtEdgeLight[0][2] = ArgbEncode(0xff, 172, 193, 123); m_pThemeData->clrNormalBtEdgeDark[0][2] = ArgbEncode(0xff, 154, 174, 105); m_pThemeData->clrBtnCornerLight[0][0] = ArgbEncode(0xff, 220, 220, 220); m_pThemeData->clrBtnCornerLight[0][1] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrBtnCornerLight[0][2] = ArgbEncode(0xff, 225, 225, 225); m_pThemeData->clrBtnEdgeOut[0] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrFormBorder[0][0] = ArgbEncode(0xff, 117, 141, 94); m_pThemeData->clrFormBorder[0][1] = ArgbEncode(0xff, 139, 161, 105); m_pThemeData->clrFormBorder[0][2] = ArgbEncode(0xff, 171, 189, 133); m_pThemeData->clrFormBorder[0][3] = ArgbEncode(0xff, 164, 178, 127); m_pThemeData->clrFormBorder[0][4] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrFormBorderLight[0] = ArgbEncode(0xff, 171, 189, 133); } else { m_pThemeData->clrHeadBK[0][0] = ArgbEncode(0xff, 3, 114, 255); m_pThemeData->clrHeadBK[0][1] = ArgbEncode(0xff, 0, 85, 226); m_pThemeData->clrHeadBK[0][2] = ArgbEncode(0xff, 0, 85, 226); m_pThemeData->clrHeadBK[0][3] = ArgbEncode(0xff, 3, 114, 255); m_pThemeData->clrHeadEdgeLeft[0][2] = ArgbEncode(0xff, 0, 32, 200); m_pThemeData->clrHeadEdgeLeft[0][1] = ArgbEncode(0xff, 0, 61, 220); m_pThemeData->clrHeadEdgeLeft[0][0] = ArgbEncode(0xff, 0, 54, 210); m_pThemeData->clrHeadEdgeRight[0][0] = ArgbEncode(0xff, 0, 56, 234); m_pThemeData->clrHeadEdgeRight[0][1] = ArgbEncode(0xff, 0, 50, 193); m_pThemeData->clrHeadEdgeRight[0][2] = ArgbEncode(0xff, 0, 19, 139); m_pThemeData->clrHeadEdgeTop[0][0] = ArgbEncode(0xff, 0, 88, 238); m_pThemeData->clrHeadEdgeTop[0][1] = ArgbEncode(0xff, 63, 151, 255); m_pThemeData->clrHeadEdgeTop[0][2] = ArgbEncode(0xff, 3, 114, 255); m_pThemeData->clrHeadEdgeBottom[0][0] = ArgbEncode(0xff, 0, 96, 252); m_pThemeData->clrHeadEdgeBottom[0][1] = ArgbEncode(0xff, 63, 151, 255); m_pThemeData->clrHeadEdgeBottom[0][2] = ArgbEncode(0xff, 0, 67, 207); m_pThemeData->clrNormalBtBKStart[0][2] = ArgbEncode(0xff, 0, 49, 112); m_pThemeData->clrNormalBtBKEnd[0][2] = ArgbEncode(0xff, 0, 87, 188); m_pThemeData->clrNormalBtBKStart[0][0] = ArgbEncode(0xff, 154, 183, 250); m_pThemeData->clrNormalBtBKEnd[0][0] = ArgbEncode(0xff, 17, 110, 248); m_pThemeData->clrNormalBtBKStart[0][1] = ArgbEncode(0xff, 164, 194, 255); m_pThemeData->clrNormalBtBKEnd[0][1] = ArgbEncode(0xff, 29, 158, 255); m_pThemeData->clrNormalBtEdgeLight[0][0] = ArgbEncode(0xff, 68, 120, 245); m_pThemeData->clrNormalBtEdgeDark[0][0] = ArgbEncode(0xff, 24, 72, 187); m_pThemeData->clrNormalBtEdgeLight[0][1] = ArgbEncode(0xff, 72, 122, 245); m_pThemeData->clrNormalBtEdgeDark[0][1] = ArgbEncode(0xff, 35, 87, 195); m_pThemeData->clrNormalBtEdgeLight[0][2] = ArgbEncode(0xff, 60, 114, 244); m_pThemeData->clrNormalBtEdgeDark[0][2] = ArgbEncode(0xff, 21, 70, 185); m_pThemeData->clrBtnCornerLight[0][0] = ArgbEncode(0xff, 220, 220, 220); m_pThemeData->clrBtnCornerLight[0][1] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrBtnCornerLight[0][2] = ArgbEncode(0xff, 225, 225, 225); m_pThemeData->clrBtnEdgeOut[0] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrFormBorder[0][0] = ArgbEncode(0xff, 0, 72, 241); m_pThemeData->clrFormBorder[0][1] = ArgbEncode(0xff, 0, 61, 220); m_pThemeData->clrFormBorder[0][2] = ArgbEncode(0xff, 0, 30, 160); m_pThemeData->clrFormBorder[0][3] = ArgbEncode(0xff, 0, 19, 140); m_pThemeData->clrFormBorder[0][4] = ArgbEncode(0xff, 255, 255, 255); m_pThemeData->clrFormBorderLight[0] = ArgbEncode(0xff, 22, 106, 239); } m_pThemeData->clrCloseBtBKStart[1][0] = m_pThemeData->clrCloseBtBKStart[0][0]; m_pThemeData->clrCloseBtBKEnd[1][0] = m_pThemeData->clrCloseBtBKEnd[0][0]; m_pThemeData->clrCloseBtBKStart[1][1] = m_pThemeData->clrCloseBtBKStart[0][1]; m_pThemeData->clrCloseBtBKEnd[1][1] = m_pThemeData->clrCloseBtBKEnd[0][1]; m_pThemeData->clrCloseBtBKStart[1][2] = m_pThemeData->clrCloseBtBKStart[0][2]; m_pThemeData->clrCloseBtBKEnd[1][2] = m_pThemeData->clrCloseBtBKEnd[0][2]; m_pThemeData->clrCloseBtEdgeLight[1][0] = m_pThemeData->clrCloseBtEdgeLight[0][0]; m_pThemeData->clrCloseBtEdgeDark[1][0] = m_pThemeData->clrCloseBtEdgeDark[0][0]; m_pThemeData->clrCloseBtEdgeLight[1][1] = m_pThemeData->clrCloseBtEdgeLight[0][1]; m_pThemeData->clrCloseBtEdgeDark[1][1] = m_pThemeData->clrCloseBtEdgeDark[0][1]; m_pThemeData->clrCloseBtEdgeLight[1][2] = m_pThemeData->clrCloseBtEdgeLight[0][2]; m_pThemeData->clrCloseBtEdgeDark[1][2] = m_pThemeData->clrCloseBtEdgeDark[0][2]; m_pThemeData->clrHeadBK[1][0] = m_pThemeData->clrHeadBK[0][0]; m_pThemeData->clrHeadBK[1][1] = m_pThemeData->clrHeadBK[0][1]; m_pThemeData->clrHeadBK[1][2] = m_pThemeData->clrHeadBK[0][2]; m_pThemeData->clrHeadBK[1][3] = m_pThemeData->clrHeadBK[0][3]; m_pThemeData->clrHeadEdgeLeft[1][2] = m_pThemeData->clrHeadEdgeLeft[0][2]; m_pThemeData->clrHeadEdgeLeft[1][1] = m_pThemeData->clrHeadEdgeLeft[0][1]; m_pThemeData->clrHeadEdgeLeft[1][0] = m_pThemeData->clrHeadEdgeLeft[0][0]; m_pThemeData->clrHeadEdgeRight[1][0] = m_pThemeData->clrHeadEdgeRight[0][0]; m_pThemeData->clrHeadEdgeRight[1][1] = m_pThemeData->clrHeadEdgeRight[0][1]; m_pThemeData->clrHeadEdgeRight[1][2] = m_pThemeData->clrHeadEdgeRight[0][2]; m_pThemeData->clrHeadEdgeTop[1][0] = m_pThemeData->clrHeadEdgeTop[0][0]; m_pThemeData->clrHeadEdgeTop[1][1] = m_pThemeData->clrHeadEdgeTop[0][1]; m_pThemeData->clrHeadEdgeTop[1][2] = m_pThemeData->clrHeadEdgeTop[0][2]; m_pThemeData->clrHeadEdgeBottom[1][0] = m_pThemeData->clrHeadEdgeBottom[0][0]; m_pThemeData->clrHeadEdgeBottom[1][1] = m_pThemeData->clrHeadEdgeBottom[0][1]; m_pThemeData->clrHeadEdgeBottom[1][2] = m_pThemeData->clrHeadEdgeBottom[0][2]; m_pThemeData->clrNormalBtBKStart[1][2] = m_pThemeData->clrNormalBtBKStart[0][2]; m_pThemeData->clrNormalBtBKEnd[1][2] = m_pThemeData->clrNormalBtBKEnd[0][2]; m_pThemeData->clrNormalBtBKStart[1][0] = m_pThemeData->clrNormalBtBKStart[0][0]; m_pThemeData->clrNormalBtBKEnd[1][0] = m_pThemeData->clrNormalBtBKEnd[1][0]; m_pThemeData->clrNormalBtBKStart[1][1] = m_pThemeData->clrNormalBtBKStart[0][1]; m_pThemeData->clrNormalBtBKEnd[1][1] = m_pThemeData->clrNormalBtBKEnd[0][1]; m_pThemeData->clrNormalBtEdgeLight[1][0] = m_pThemeData->clrNormalBtEdgeLight[0][0]; m_pThemeData->clrNormalBtEdgeDark[1][0] = m_pThemeData->clrNormalBtEdgeDark[0][0]; m_pThemeData->clrNormalBtEdgeLight[1][1] = m_pThemeData->clrNormalBtEdgeLight[0][1]; m_pThemeData->clrNormalBtEdgeDark[1][1] = m_pThemeData->clrNormalBtEdgeDark[0][1]; m_pThemeData->clrNormalBtEdgeLight[1][2] = m_pThemeData->clrNormalBtEdgeLight[0][2]; m_pThemeData->clrNormalBtEdgeDark[1][2] = m_pThemeData->clrNormalBtEdgeDark[0][2]; m_pThemeData->clrBtnCornerLight[1][0] = m_pThemeData->clrBtnCornerLight[0][0]; m_pThemeData->clrBtnCornerLight[1][1] = m_pThemeData->clrBtnCornerLight[0][1]; m_pThemeData->clrBtnCornerLight[1][2] = m_pThemeData->clrBtnCornerLight[0][2]; m_pThemeData->clrBtnEdgeOut[1] = m_pThemeData->clrBtnEdgeOut[0]; m_pThemeData->clrFormBorder[1][0] = m_pThemeData->clrFormBorder[0][0]; m_pThemeData->clrFormBorder[1][1] = m_pThemeData->clrFormBorder[0][1]; m_pThemeData->clrFormBorder[1][2] = m_pThemeData->clrFormBorder[0][2]; m_pThemeData->clrFormBorder[1][3] = m_pThemeData->clrFormBorder[0][3]; m_pThemeData->clrFormBorder[1][4] = m_pThemeData->clrFormBorder[0][4]; m_pThemeData->clrFormBorderLight[1] = m_pThemeData->clrFormBorderLight[0]; DeactiveForm(); } void CFWL_FormTP::DeactiveForm() { TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadBK[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadBK[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadBK[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadBK[1][3]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeLeft[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeLeft[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeLeft[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeRight[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeRight[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeRight[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeTop[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeTop[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeTop[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeBottom[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeBottom[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrHeadEdgeBottom[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKStart[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKStart[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKStart[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKEnd[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKEnd[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtBKEnd[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeLight[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeLight[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeLight[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeDark[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeDark[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrNormalBtEdgeDark[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrBtnCornerLight[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrBtnCornerLight[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrBtnCornerLight[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrBtnEdgeOut[1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorder[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorder[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorder[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorder[1][3]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorder[1][4]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrFormBorderLight[1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKStart[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKStart[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKStart[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKEnd[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKEnd[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtBKEnd[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeLight[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeLight[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeLight[1][2]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeDark[1][0]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeDark[1][1]); TransModeColor(m_pThemeData->clrTransWhite, m_pThemeData->clrCloseBtEdgeDark[1][2]); } void CFWL_FormTP::TransModeColor(FX_ARGB clrFore, FX_ARGB& clrBack) { int32_t iAlfaF, iRF, iGF, iBF; int32_t iAlfaB, iRB, iGB, iBB; ArgbDecode(clrFore, iAlfaF, iRF, iGF, iBF); ArgbDecode(clrBack, iAlfaB, iRB, iGB, iBB); clrBack = ArgbEncode(0xff, iRB + (iRF - iRB) * iAlfaF / 255, iGB + (iGF - iGB) * iAlfaF / 255, iBB + (iBF - iBB) * iAlfaF / 255); } void CFWL_FormTP::InitCaption(FX_BOOL bActive) { if (bActive) { CFX_FxgeDevice dev; CFX_Graphics gs; CFX_Path path; path.Create(); if (m_pActiveBitmap) { delete m_pActiveBitmap; m_pActiveBitmap = NULL; } m_pActiveBitmap = new CFX_DIBitmap; m_pActiveBitmap->Create(1, FWLTHEME_CAPACITY_CYCaption, FXDIB_Argb); dev.Attach(m_pActiveBitmap); gs.Create(&dev); path.AddRectangle(0, 0, 1, 5); DrawAxialShading(&gs, 0, 0, 0, 5, m_pThemeData->clrHeadBK[0][0], m_pThemeData->clrHeadBK[0][1], &path); path.Clear(); path.AddRectangle(0, 5, 1, 15); DrawAxialShading(&gs, 0, 5, 0, 20, m_pThemeData->clrHeadBK[0][1], m_pThemeData->clrHeadBK[0][2], &path); path.Clear(); path.AddRectangle(0, 20, 1, FWLTHEME_CAPACITY_CYCaption - 19); DrawAxialShading(&gs, 0, 20, 0, FWLTHEME_CAPACITY_CYCaption, m_pThemeData->clrHeadBK[0][2], m_pThemeData->clrHeadBK[0][3], &path); } else { CFX_FxgeDevice dev; CFX_Graphics gs; CFX_Path path; path.Create(); if (m_pDeactivebitmap) { delete m_pDeactivebitmap; m_pDeactivebitmap = NULL; } m_pDeactivebitmap = new CFX_DIBitmap; m_pDeactivebitmap->Create(1, FWLTHEME_CAPACITY_CYCaption, FXDIB_Argb); dev.Attach(m_pDeactivebitmap); gs.Create(&dev); path.AddRectangle(0, 0, 1, 5); DrawAxialShading(&gs, 0, 0, 0, 5, m_pThemeData->clrHeadBK[1][0], m_pThemeData->clrHeadBK[1][1], &path); path.Clear(); path.AddRectangle(0, 5, 1, 15); DrawAxialShading(&gs, 0, 5, 0, 20, m_pThemeData->clrHeadBK[1][1], m_pThemeData->clrHeadBK[1][2], &path); path.Clear(); path.AddRectangle(0, 20, 1, FWLTHEME_CAPACITY_CYCaption - 19); DrawAxialShading(&gs, 0, 20, 0, FWLTHEME_CAPACITY_CYCaption, m_pThemeData->clrHeadBK[1][2], m_pThemeData->clrHeadBK[1][3], &path); } }
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/client/World.h" #include "carla/Logging.h" #include "carla/client/Actor.h" #include "carla/client/ActorBlueprint.h" #include "carla/client/ActorList.h" #include "carla/client/detail/Simulator.h" #include <exception> namespace carla { namespace client { uint32_t World::GetId() const { return _episode.Lock()->GetCurrentEpisodeId(); } const std::string &World::GetMapName() const { return _episode.Lock()->GetCurrentMapName(); } SharedPtr<BlueprintLibrary> World::GetBlueprintLibrary() const { return _episode.Lock()->GetBlueprintLibrary(); } SharedPtr<Actor> World::GetSpectator() const { return _episode.Lock()->GetSpectator(); } rpc::WeatherParameters World::GetWeather() const { return _episode.Lock()->GetWeatherParameters(); } void World::SetWeather(const rpc::WeatherParameters &weather) { _episode.Lock()->SetWeatherParameters(weather); } SharedPtr<ActorList> World::GetActors() const { return SharedPtr<ActorList>{new ActorList{ _episode, _episode.Lock()->GetAllTheActorsInTheEpisode()}}; } SharedPtr<Actor> World::SpawnActor( const ActorBlueprint &blueprint, const geom::Transform &transform, Actor *parent_actor) { try { return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor); } catch (const std::exception &e) { log_warning("SpawnActor: failed with:", e.what()); throw; } } SharedPtr<Actor> World::TrySpawnActor( const ActorBlueprint &blueprint, const geom::Transform &transform, Actor *parent_actor) noexcept { try { return SpawnActor(blueprint, transform, parent_actor); } catch (const std::exception &) { return nullptr; } } Timestamp World::WaitForTick(time_duration timeout) const { return _episode.Lock()->WaitForTick(timeout); } void World::OnTick(std::function<void(Timestamp)> callback) { return _episode.Lock()->RegisterOnTickEvent(std::move(callback)); } } // namespace client } // namespace carla
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSurfaceSource.h" #include "mitkSurface.h" mitk::SurfaceSource::SurfaceSource() { // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputImage itk::DataObject::Pointer output = this->MakeOutput(0); Superclass::SetNumberOfRequiredOutputs(1); Superclass::SetNthOutput(0, output); } mitk::SurfaceSource::~SurfaceSource() { } itk::DataObject::Pointer mitk::SurfaceSource::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ ) { return OutputType::New().GetPointer(); } itk::DataObject::Pointer mitk::SurfaceSource::MakeOutput( const DataObjectIdentifierType & name ) { itkDebugMacro("MakeOutput(" << name << ")"); if( this->IsIndexedOutputName(name) ) { return this->MakeOutput( this->MakeIndexFromOutputName(name) ); } return static_cast<itk::DataObject *>(mitk::Surface::New().GetPointer()); } mitkBaseDataSourceGetOutputDefinitions(mitk::SurfaceSource)
/* * Copyright (C) 2018 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstring> #include <utility> #include <uri.h> namespace ydsh::uri { #define ERROR() \ do { \ return URI(); \ } while (false) static std::string create(const char *begin, const char *end) { if (begin == nullptr || end == nullptr) { return ""; } return URI::decode(begin, end); } using Range = std::pair<const char *, const char *>; static std::string createPath(Range &&r1, Range &&r2) { if (r1.first != nullptr && r1.second != nullptr) { return create(r1.first, r1.second); } return create(r2.first, r2.second); } URI URI::fromString(const std::string &str) { // for scheme const char *s0 = nullptr; const char *s1 = nullptr; // for user_info const char *u0 = nullptr; const char *u1 = nullptr; // for host const char *h0 = nullptr; const char *h1 = nullptr; // for port const char *o0 = nullptr; const char *o1 = nullptr; // for path const char *p0 = nullptr; const char *p1 = nullptr; const char *p2 = nullptr; const char *p3 = nullptr; // for query const char *q0 = nullptr; const char *q1 = nullptr; // for fragment const char *f0 = nullptr; const char *f1 = nullptr; /*!stags:re2c format = "const char *@@;\n"; */ const char *cursor = str.c_str(); const char *marker = nullptr; /** * see. http://re2c.org/examples/example_10.html * https://tools.ietf.org/html/rfc3986 */ /*!re2c re2c:define:YYCTYPE = "char"; re2c:define:YYCURSOR = cursor; re2c:define:YYLIMIT = limit; re2c:define:YYMARKER = marker; re2c:define:YYFILL:naked = 1; re2c:define:YYFILL@len = #; re2c:yyfill:enable = 0; re2c:indent:top = 1; re2c:indent:string = " "; ALPHA = [a-zA-Z]; CR = "\r"; DIGIT = [0-9]; DQUOTE = ["]; HEXDIG = DIGIT | [a-fA-F]; LF = "\n"; SP = " "; pct_encoded = "%" HEXDIG HEXDIG; gen_delims = [:/?#[\]@]; sub_delims = [!$&'()*+,;=]; reserved = gen_delims | sub_delims; unreserved = ALPHA | DIGIT | [-._~]; pchar = unreserved | pct_encoded | sub_delims | ":" | "@"; scheme = @s0 ALPHA ( ALPHA | DIGIT | "+" | "-" | "." )* @s1; user_info = @u0 (unreserved | pct_encoded | sub_delims | ":")* @u1; port = @o0 DIGIT* @o1; dec_octet = DIGIT | [\x31-\x39] DIGIT | "1" DIGIT{2} | "2" [\x30-\x34] DIGIT | "25" [\x30-\x35]; IPv4address = dec_octet "." dec_octet "." dec_octet "." dec_octet; IPvFuture = "v" HEXDIG+ "." (unreserved | sub_delims | ":")+; h16 = HEXDIG{1,4}; ls32 = (h16 ":" h16) | IPv4address; IPv6address = (h16 ":"){6} ls32 | "::" (h16 ":"){5} ls32 | ( h16)? "::" (h16 ":"){4} ls32 | ((h16 ":"){0,1} h16)? "::" (h16 ":"){3} ls32 | ((h16 ":"){0,2} h16)? "::" (h16 ":"){2} ls32 | ((h16 ":"){0,3} h16)? "::" h16 ":" ls32 | ((h16 ":"){0,4} h16)? "::" ls32 | ((h16 ":"){0,5} h16)? "::" h16 | ((h16 ":"){0,6} h16)? "::"; IP_literal = "[" (IPv6address | IPvFuture) "]"; reg_name = (unreserved | pct_encoded | sub_delims)*; host = @h0 (IP_literal | IPv4address | reg_name) @h1; authority = (user_info "@")? host (":" port)?; segment = pchar*; segment_nz = pchar+; segment_nz_nc = (unreserved | pct_encoded | sub_delims | "@")+; path_abempty = ("/" segment)*; path_absolute = "/" (segment_nz ("/" segment)* )?; path_rootless = segment_nz ("/" segment)*; path_empty = ""; hier_part = "//" authority @p0 path_abempty @p1 | @p2 (path_absolute | path_rootless | path_empty) @p3; query = @q0 (pchar | "/" | "?")* @q1; fragment = @f0 (pchar | "/" | "?")* @f1; uri = scheme ":" hier_part ("?" query)? ("#" fragment)?; uri { auto auth = Authority(create(u0, u1), create(h0, h1), create(o0, o1)); auto path = createPath({p0, p1}, {p2, p3}); return URI(create(s0, s1), std::move(auth), std::move(path), create(q0, q1), create(f0, f1)); } "\000" { ERROR(); } * { ERROR(); } */ } } // namespace ydsh::uri
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <sstream> #include <iomanip> #include <deque> #include <unordered_set> #include <list> #include <forward_list> #include <iostream> #include <algorithm> #include <tuple> #include <boost/tuple/tuple.hpp> #include <boost/circular_buffer.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/multi_index/tag.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/logic/tribool.hpp> #include <boost/range/algorithm_ext/push_back.hpp> #include <boost/range/algorithm/find.hpp> #include <boost/range/numeric.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> #include <boost/accumulators/statistics/min.hpp> #include <boost/accumulators/statistics/max.hpp> #include <boost/accumulators/statistics/sum.hpp> #include <boost/accumulators/statistics/count.hpp> #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/stringize.hpp> #include <fc/thread/thread.hpp> #include <fc/thread/future.hpp> #include <fc/thread/non_preemptable_scope_check.hpp> #include <fc/thread/mutex.hpp> #include <fc/thread/scoped_lock.hpp> #include <fc/log/logger.hpp> #include <fc/io/json.hpp> #include <fc/io/enum_type.hpp> #include <fc/crypto/rand.hpp> #include <fc/network/rate_limiting.hpp> #include <fc/network/ip.hpp> #include <fc/smart_ref_impl.hpp> #include <graphene/net/node_configuration.hpp> #include <graphene/net/node.hpp> #include <graphene/net/peer_database.hpp> #include <graphene/net/peer_connection.hpp> #include <graphene/net/stcp_socket.hpp> #include <graphene/net/config.hpp> #include <graphene/net/exceptions.hpp> #include <steem/protocol/config.hpp> #include <fc/git_revision.hpp> //#define ENABLE_DEBUG_ULOGS #ifdef DEFAULT_LOGGER # undef DEFAULT_LOGGER #endif #define DEFAULT_LOGGER "p2p" #define P2P_IN_DEDICATED_THREAD 1 #define INVOCATION_COUNTER(name) \ static unsigned total_ ## name ## _counter = 0; \ static unsigned active_ ## name ## _counter = 0; \ struct name ## _invocation_logger { \ unsigned *total; \ unsigned *active; \ name ## _invocation_logger(unsigned *total, unsigned *active) : \ total(total), active(active) \ { \ ++*total; \ ++*active; \ dlog("NEWDEBUG: Entering " #name ", now ${total} total calls, ${active} active calls", ("total", *total)("active", *active)); \ } \ ~name ## _invocation_logger() \ { \ --*active; \ dlog("NEWDEBUG: Leaving " #name ", now ${total} total calls, ${active} active calls", ("total", *total)("active", *active)); \ } \ } invocation_logger(&total_ ## name ## _counter, &active_ ## name ## _counter) //log these messages even at warn level when operating on the test network #ifdef GRAPHENE_TEST_NETWORK #define testnetlog wlog #else #define testnetlog(...) do {} while (0) #endif namespace graphene { namespace net { namespace detail { namespace bmi = boost::multi_index; class blockchain_tied_message_cache { private: static const uint32_t cache_duration_in_blocks = GRAPHENE_NET_MESSAGE_CACHE_DURATION_IN_BLOCKS; struct message_hash_index{}; struct message_contents_hash_index{}; struct block_clock_index{}; struct message_info { message_hash_type message_hash; message message_body; uint32_t block_clock_when_received; // for network performance stats message_propagation_data propagation_data; fc::uint160_t message_contents_hash; // hash of whatever the message contains (if it's a transaction, this is the transaction id, if it's a block, it's the block_id) message_info( const message_hash_type& message_hash, const message& message_body, uint32_t block_clock_when_received, const message_propagation_data& propagation_data, fc::uint160_t message_contents_hash ) : message_hash( message_hash ), message_body( message_body ), block_clock_when_received( block_clock_when_received ), propagation_data( propagation_data ), message_contents_hash( message_contents_hash ) {} }; typedef boost::multi_index_container < message_info, bmi::indexed_by< bmi::ordered_unique< bmi::tag<message_hash_index>, bmi::member<message_info, message_hash_type, &message_info::message_hash> >, bmi::ordered_non_unique< bmi::tag<message_contents_hash_index>, bmi::member<message_info, fc::uint160_t, &message_info::message_contents_hash> >, bmi::ordered_non_unique< bmi::tag<block_clock_index>, bmi::member<message_info, uint32_t, &message_info::block_clock_when_received> > > > message_cache_container; message_cache_container _message_cache; uint32_t block_clock; public: blockchain_tied_message_cache() : block_clock( 0 ) {} void block_accepted(); void cache_message( const message& message_to_cache, const message_hash_type& hash_of_message_to_cache, const message_propagation_data& propagation_data, const fc::uint160_t& message_content_hash ); message get_message( const message_hash_type& hash_of_message_to_lookup ); message_propagation_data get_message_propagation_data( const fc::uint160_t& hash_of_message_contents_to_lookup ) const; size_t size() const { return _message_cache.size(); } }; void blockchain_tied_message_cache::block_accepted() { ++block_clock; if( block_clock > cache_duration_in_blocks ) _message_cache.get<block_clock_index>().erase(_message_cache.get<block_clock_index>().begin(), _message_cache.get<block_clock_index>().lower_bound(block_clock - cache_duration_in_blocks ) ); } void blockchain_tied_message_cache::cache_message( const message& message_to_cache, const message_hash_type& hash_of_message_to_cache, const message_propagation_data& propagation_data, const fc::uint160_t& message_content_hash ) { _message_cache.insert( message_info(hash_of_message_to_cache, message_to_cache, block_clock, propagation_data, message_content_hash ) ); } message blockchain_tied_message_cache::get_message( const message_hash_type& hash_of_message_to_lookup ) { message_cache_container::index<message_hash_index>::type::const_iterator iter = _message_cache.get<message_hash_index>().find(hash_of_message_to_lookup ); if( iter != _message_cache.get<message_hash_index>().end() ) return iter->message_body; FC_THROW_EXCEPTION( fc::key_not_found_exception, "Requested message not in cache" ); } message_propagation_data blockchain_tied_message_cache::get_message_propagation_data( const fc::uint160_t& hash_of_message_contents_to_lookup ) const { if( hash_of_message_contents_to_lookup != fc::uint160_t() ) { message_cache_container::index<message_contents_hash_index>::type::const_iterator iter = _message_cache.get<message_contents_hash_index>().find(hash_of_message_contents_to_lookup ); if( iter != _message_cache.get<message_contents_hash_index>().end() ) return iter->propagation_data; } FC_THROW_EXCEPTION( fc::key_not_found_exception, "Requested message not in cache" ); } // when requesting items from peers, we want to prioritize any blocks before // transactions, but otherwise request items in the order we heard about them struct prioritized_item_id { item_id item; unsigned sequence_number; fc::time_point timestamp; // the time we last heard about this item in an inventory message prioritized_item_id(const item_id& item, unsigned sequence_number) : item(item), sequence_number(sequence_number), timestamp(fc::time_point::now()) {} bool operator<(const prioritized_item_id& rhs) const { static_assert(graphene::net::block_message_type > graphene::net::trx_message_type, "block_message_type must be greater than trx_message_type for prioritized_item_ids to sort correctly"); if (item.item_type != rhs.item.item_type) return item.item_type > rhs.item.item_type; return (signed)(rhs.sequence_number - sequence_number) > 0; } }; ///////////////////////////////////////////////////////////////////////////////////////////////////////// class statistics_gathering_node_delegate_wrapper : public node_delegate { private: node_delegate *_node_delegate; fc::thread *_thread; typedef boost::accumulators::accumulator_set<int64_t, boost::accumulators::stats<boost::accumulators::tag::min, boost::accumulators::tag::rolling_mean, boost::accumulators::tag::max, boost::accumulators::tag::sum, boost::accumulators::tag::count> > call_stats_accumulator; #define NODE_DELEGATE_METHOD_NAMES (has_item) \ (handle_message) \ (handle_block) \ (handle_transaction) \ (get_block_ids) \ (get_item) \ (get_blockchain_synopsis) \ (sync_status) \ (connection_count_changed) \ (get_block_number) \ (get_block_time) \ (get_head_block_id) \ (estimate_last_known_fork_from_git_revision_timestamp) \ (error_encountered) \ (get_chain_id) #define DECLARE_ACCUMULATOR(r, data, method_name) \ mutable call_stats_accumulator BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator)); \ mutable call_stats_accumulator BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator)); \ mutable call_stats_accumulator BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator)); BOOST_PP_SEQ_FOR_EACH(DECLARE_ACCUMULATOR, unused, NODE_DELEGATE_METHOD_NAMES) #undef DECLARE_ACCUMULATOR class call_statistics_collector { private: fc::time_point _call_requested_time; fc::time_point _begin_execution_time; fc::time_point _execution_completed_time; const char* _method_name; call_stats_accumulator* _execution_accumulator; call_stats_accumulator* _delay_before_accumulator; call_stats_accumulator* _delay_after_accumulator; public: class actual_execution_measurement_helper { call_statistics_collector &_collector; public: actual_execution_measurement_helper(call_statistics_collector& collector) : _collector(collector) { _collector.starting_execution(); } ~actual_execution_measurement_helper() { _collector.execution_completed(); } }; call_statistics_collector(const char* method_name, call_stats_accumulator* execution_accumulator, call_stats_accumulator* delay_before_accumulator, call_stats_accumulator* delay_after_accumulator) : _call_requested_time(fc::time_point::now()), _method_name(method_name), _execution_accumulator(execution_accumulator), _delay_before_accumulator(delay_before_accumulator), _delay_after_accumulator(delay_after_accumulator) {} ~call_statistics_collector() { fc::time_point end_time(fc::time_point::now()); fc::microseconds actual_execution_time(_execution_completed_time - _begin_execution_time); fc::microseconds delay_before(_begin_execution_time - _call_requested_time); fc::microseconds delay_after(end_time - _execution_completed_time); fc::microseconds total_duration(actual_execution_time + delay_before + delay_after); (*_execution_accumulator)(actual_execution_time.count()); (*_delay_before_accumulator)(delay_before.count()); (*_delay_after_accumulator)(delay_after.count()); if (total_duration > fc::milliseconds(500)) { ilog("Call to method node_delegate::${method} took ${total_duration}us, longer than our target maximum of 500ms", ("method", _method_name) ("total_duration", total_duration.count())); ilog("Actual execution took ${execution_duration}us, with a ${delegate_delay}us delay before the delegate thread started " "executing the method, and a ${p2p_delay}us delay after it finished before the p2p thread started processing the response", ("execution_duration", actual_execution_time) ("delegate_delay", delay_before) ("p2p_delay", delay_after)); } } void starting_execution() { _begin_execution_time = fc::time_point::now(); } void execution_completed() { _execution_completed_time = fc::time_point::now(); } }; public: statistics_gathering_node_delegate_wrapper(node_delegate* delegate, fc::thread* thread_for_delegate_calls); fc::variant_object get_call_statistics(); steem::protocol::chain_id_type get_chain_id() const override; bool has_item( const net::item_id& id ) override; void handle_message( const message& ) override; bool handle_block( const graphene::net::block_message& block_message, bool sync_mode, std::vector<fc::uint160_t>& contained_transaction_message_ids ) override; void handle_transaction( const graphene::net::trx_message& transaction_message ) override; std::vector<item_hash_t> get_block_ids(const std::vector<item_hash_t>& blockchain_synopsis, uint32_t& remaining_item_count, uint32_t limit = 2000) override; message get_item( const item_id& id ) override; std::vector<item_hash_t> get_blockchain_synopsis(const item_hash_t& reference_point, uint32_t number_of_blocks_after_reference_point) override; void sync_status( uint32_t item_type, uint32_t item_count ) override; void connection_count_changed( uint32_t c ) override; uint32_t get_block_number(const item_hash_t& block_id) override; fc::time_point_sec get_block_time(const item_hash_t& block_id) override; fc::time_point_sec get_blockchain_now() override; item_hash_t get_head_block_id() const override; uint32_t estimate_last_known_fork_from_git_revision_timestamp(uint32_t unix_timestamp) const override; void error_encountered(const std::string& message, const fc::oexception& error) override; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////// class node_impl : public peer_connection_delegate { public: #ifdef P2P_IN_DEDICATED_THREAD std::shared_ptr<fc::thread> _thread; #endif // P2P_IN_DEDICATED_THREAD std::unique_ptr<statistics_gathering_node_delegate_wrapper> _delegate; #define NODE_CONFIGURATION_FILENAME "node_config.json" #define POTENTIAL_PEER_DATABASE_FILENAME "peers.json" fc::path _node_configuration_directory; node_configuration _node_configuration; /// stores the endpoint we're listening on. This will be the same as // _node_configuration.listen_endpoint, unless that endpoint was already // in use. fc::ip::endpoint _actual_listening_endpoint; /// we determine whether we're firewalled by asking other nodes. Store the result here: firewalled_state _is_firewalled; /// if we're behind NAT, our listening endpoint address will appear different to the rest of the world. store it here. fc::optional<fc::ip::endpoint> _publicly_visible_listening_endpoint; fc::time_point _last_firewall_check_message_sent; /// used by the task that manages connecting to peers // @{ std::list<potential_peer_record> _add_once_node_list; /// list of peers we want to connect to as soon as possible peer_database _potential_peer_db; fc::promise<void>::ptr _retrigger_connect_loop_promise; bool _potential_peer_database_updated; fc::future<void> _p2p_network_connect_loop_done; // @} /// used by the task that fetches sync items during synchronization // @{ fc::promise<void>::ptr _retrigger_fetch_sync_items_loop_promise; bool _sync_items_to_fetch_updated; fc::future<void> _fetch_sync_items_loop_done; typedef std::unordered_map<graphene::net::block_id_type, fc::time_point> active_sync_requests_map; active_sync_requests_map _active_sync_requests; /// list of sync blocks we've asked for from peers but have not yet received std::list<graphene::net::block_message> _new_received_sync_items; /// list of sync blocks we've just received but haven't yet tried to process std::list<graphene::net::block_message> _received_sync_items; /// list of sync blocks we've received, but can't yet process because we are still missing blocks that come earlier in the chain // @} fc::future<void> _process_backlog_of_sync_blocks_done; bool _suspend_fetching_sync_blocks; /// used by the task that fetches items during normal operation // @{ fc::promise<void>::ptr _retrigger_fetch_item_loop_promise; bool _items_to_fetch_updated; fc::future<void> _fetch_item_loop_done; struct item_id_index{}; typedef boost::multi_index_container<prioritized_item_id, boost::multi_index::indexed_by<boost::multi_index::ordered_unique<boost::multi_index::identity<prioritized_item_id> >, boost::multi_index::hashed_unique<boost::multi_index::tag<item_id_index>, boost::multi_index::member<prioritized_item_id, item_id, &prioritized_item_id::item>, std::hash<item_id> > > > items_to_fetch_set_type; unsigned _items_to_fetch_sequence_counter; items_to_fetch_set_type _items_to_fetch; /// list of items we know another peer has and we want peer_connection::timestamped_items_set_type _recently_failed_items; /// list of transactions we've recently pushed and had rejected by the delegate // @} /// used by the task that advertises inventory during normal operation // @{ fc::promise<void>::ptr _retrigger_advertise_inventory_loop_promise; fc::future<void> _advertise_inventory_loop_done; std::unordered_set<item_id> _new_inventory; /// list of items we have received but not yet advertised to our peers // @} fc::future<void> _terminate_inactive_connections_loop_done; uint8_t _recent_block_interval_in_seconds; // a cached copy of the block interval, to avoid a thread hop to the blockchain to get the current value std::string _user_agent_string; /** _node_public_key is a key automatically generated when the client is first run, stored in * node_config.json. It doesn't really have much of a purpose yet, there was just some thought * that we might someday have a use for nodes having a private key (sent in hello messages) */ node_id_t _node_public_key; /** * _node_id is a random number generated each time the client is launched, used to prevent us * from connecting to the same client multiple times (sent in hello messages). * Since this was introduced after the hello_message was finalized, this is sent in the * user_data field. * While this shares the same underlying type as a public key, it is really just a random * number. */ node_id_t _node_id; fc::tcp_server _tcp_server; fc::future<void> _accept_loop_complete; /** Stores all connections which have not yet finished key exchange or are still sending initial handshaking messages * back and forth (not yet ready to initiate syncing) */ std::unordered_set<peer_connection_ptr> _handshaking_connections; /** stores fully established connections we're either syncing with or in normal operation with */ std::unordered_set<peer_connection_ptr> _active_connections; /** stores connections we've closed (sent closing message, not actually closed), but are still waiting for the remote end to close before we delete them */ std::unordered_set<peer_connection_ptr> _closing_connections; /** stores connections we've closed, but are still waiting for the OS to notify us that the socket is really closed */ std::unordered_set<peer_connection_ptr> _terminating_connections; boost::circular_buffer<item_hash_t> _most_recent_blocks_accepted; // the /n/ most recent blocks we've accepted (currently tuned to the max number of connections) uint32_t _sync_item_type; uint32_t _total_number_of_unfetched_items; /// the number of items we still need to fetch while syncing std::vector<uint32_t> _hard_fork_block_numbers; /// list of all block numbers where there are hard forks blockchain_tied_message_cache _message_cache; /// cache message we have received and might be required to provide to other peers via inventory requests fc::rate_limiting_group _rate_limiter; uint32_t _last_reported_number_of_connections; // number of connections last reported to the client (to avoid sending duplicate messages) fc::future<void> _fetch_updated_peer_lists_loop_done; boost::circular_buffer<uint32_t> _average_network_read_speed_seconds; boost::circular_buffer<uint32_t> _average_network_write_speed_seconds; boost::circular_buffer<uint32_t> _average_network_read_speed_minutes; boost::circular_buffer<uint32_t> _average_network_write_speed_minutes; boost::circular_buffer<uint32_t> _average_network_read_speed_hours; boost::circular_buffer<uint32_t> _average_network_write_speed_hours; unsigned _average_network_usage_second_counter; unsigned _average_network_usage_minute_counter; fc::time_point_sec _bandwidth_monitor_last_update_time; fc::future<void> _bandwidth_monitor_loop_done; fc::future<void> _dump_node_status_task_done; /* We have two alternate paths through the schedule_peer_for_deletion code -- one that * uses a mutex to prevent one fiber from adding items to the queue while another is deleting * items from it, and one that doesn't. The one that doesn't is simpler and more efficient * code, but we're keeping around the version that uses the mutex because it crashes, and * this crash probably indicates a bug in our underlying threading code that needs * fixing. To produce the bug, define USE_PEERS_TO_DELETE_MUTEX and then connect up * to the network and set your desired/max connection counts high */ //#define USE_PEERS_TO_DELETE_MUTEX 1 #ifdef USE_PEERS_TO_DELETE_MUTEX fc::mutex _peers_to_delete_mutex; #endif std::list<peer_connection_ptr> _peers_to_delete; fc::future<void> _delayed_peer_deletion_task_done; #ifdef ENABLE_P2P_DEBUGGING_API std::set<node_id_t> _allowed_peers; #endif // ENABLE_P2P_DEBUGGING_API bool _node_is_shutting_down; // set to true when we begin our destructor, used to prevent us from starting new tasks while we're shutting down std::list<fc::future<void> > _handle_message_calls_in_progress; std::set<message_hash_type> _message_ids_currently_being_processed; node_impl(const std::string& user_agent); virtual ~node_impl(); void save_node_configuration(); void p2p_network_connect_loop(); void trigger_p2p_network_connect_loop(); bool have_already_received_sync_item( const item_hash_t& item_hash ); void request_sync_item_from_peer( const peer_connection_ptr& peer, const item_hash_t& item_to_request ); void request_sync_items_from_peer( const peer_connection_ptr& peer, const std::vector<item_hash_t>& items_to_request ); void fetch_sync_items_loop(); void trigger_fetch_sync_items_loop(); bool is_item_in_any_peers_inventory(const item_id& item) const; void fetch_items_loop(); void trigger_fetch_items_loop(); void advertise_inventory_loop(); void trigger_advertise_inventory_loop(); void terminate_inactive_connections_loop(); void fetch_updated_peer_lists_loop(); void update_bandwidth_data(uint32_t bytes_read_this_second, uint32_t bytes_written_this_second); void bandwidth_monitor_loop(); void dump_node_status_task(); bool is_accepting_new_connections(); bool is_wanting_new_connections(); uint32_t get_number_of_connections(); peer_connection_ptr get_peer_by_node_id(const node_id_t& id); bool is_already_connected_to_id(const node_id_t& node_id); bool merge_address_info_with_potential_peer_database( const std::vector<address_info> addresses ); void display_current_connections(); uint32_t calculate_unsynced_block_count_from_all_peers(); std::vector<item_hash_t> create_blockchain_synopsis_for_peer( const peer_connection* peer ); void fetch_next_batch_of_item_ids_from_peer( peer_connection* peer, bool reset_fork_tracking_data_for_peer = false ); fc::variant_object generate_hello_user_data(); void parse_hello_user_data_for_peer( peer_connection* originating_peer, const fc::variant_object& user_data ); void on_message( peer_connection* originating_peer, const message& received_message ) override; void on_hello_message( peer_connection* originating_peer, const hello_message& hello_message_received ); void on_connection_accepted_message( peer_connection* originating_peer, const connection_accepted_message& connection_accepted_message_received ); void on_connection_rejected_message( peer_connection* originating_peer, const connection_rejected_message& connection_rejected_message_received ); void on_address_request_message( peer_connection* originating_peer, const address_request_message& address_request_message_received ); void on_address_message( peer_connection* originating_peer, const address_message& address_message_received ); void on_fetch_blockchain_item_ids_message( peer_connection* originating_peer, const fetch_blockchain_item_ids_message& fetch_blockchain_item_ids_message_received ); void on_blockchain_item_ids_inventory_message( peer_connection* originating_peer, const blockchain_item_ids_inventory_message& blockchain_item_ids_inventory_message_received ); void on_fetch_items_message( peer_connection* originating_peer, const fetch_items_message& fetch_items_message_received ); void on_item_not_available_message( peer_connection* originating_peer, const item_not_available_message& item_not_available_message_received ); void on_item_ids_inventory_message( peer_connection* originating_peer, const item_ids_inventory_message& item_ids_inventory_message_received ); void on_closing_connection_message( peer_connection* originating_peer, const closing_connection_message& closing_connection_message_received ); void on_current_time_request_message( peer_connection* originating_peer, const current_time_request_message& current_time_request_message_received ); void on_current_time_reply_message( peer_connection* originating_peer, const current_time_reply_message& current_time_reply_message_received ); void forward_firewall_check_to_next_available_peer(firewall_check_state_data* firewall_check_state); void on_check_firewall_message(peer_connection* originating_peer, const check_firewall_message& check_firewall_message_received); void on_check_firewall_reply_message(peer_connection* originating_peer, const check_firewall_reply_message& check_firewall_reply_message_received); void on_get_current_connections_request_message(peer_connection* originating_peer, const get_current_connections_request_message& get_current_connections_request_message_received); void on_get_current_connections_reply_message(peer_connection* originating_peer, const get_current_connections_reply_message& get_current_connections_reply_message_received); void on_connection_closed(peer_connection* originating_peer) override; void send_sync_block_to_node_delegate(const graphene::net::block_message& block_message_to_send); void process_backlog_of_sync_blocks(); void trigger_process_backlog_of_sync_blocks(); void process_block_during_sync(peer_connection* originating_peer, const graphene::net::block_message& block_message, const message_hash_type& message_hash); void process_block_during_normal_operation(peer_connection* originating_peer, const graphene::net::block_message& block_message, const message_hash_type& message_hash); void process_block_message(peer_connection* originating_peer, const message& message_to_process, const message_hash_type& message_hash); void process_ordinary_message(peer_connection* originating_peer, const message& message_to_process, const message_hash_type& message_hash); void start_synchronizing(); void start_synchronizing_with_peer(const peer_connection_ptr& peer); void new_peer_just_added(const peer_connection_ptr& peer); /// called after a peer finishes handshaking, kicks off syncing void close(); void accept_connection_task(peer_connection_ptr new_peer); void accept_loop(); void send_hello_message(const peer_connection_ptr& peer); void connect_to_task(peer_connection_ptr new_peer, const fc::ip::endpoint& remote_endpoint); bool is_connection_to_endpoint_in_progress(const fc::ip::endpoint& remote_endpoint); void move_peer_to_active_list(const peer_connection_ptr& peer); void move_peer_to_closing_list(const peer_connection_ptr& peer); void move_peer_to_terminating_list(const peer_connection_ptr& peer); peer_connection_ptr get_connection_to_endpoint( const fc::ip::endpoint& remote_endpoint ); void dump_node_status(); void delayed_peer_deletion_task(); void schedule_peer_for_deletion(const peer_connection_ptr& peer_to_delete); void disconnect_from_peer( peer_connection* originating_peer, const std::string& reason_for_disconnect, bool caused_by_error = false, const fc::oexception& additional_data = fc::oexception() ); // methods implementing node's public interface void set_node_delegate(node_delegate* del, fc::thread* thread_for_delegate_calls); void load_configuration( const fc::path& configuration_directory ); void listen_to_p2p_network(); void connect_to_p2p_network(); void add_node( const fc::ip::endpoint& ep ); void initiate_connect_to(const peer_connection_ptr& peer); void connect_to_endpoint(const fc::ip::endpoint& ep); void listen_on_endpoint(const fc::ip::endpoint& ep , bool wait_if_not_available); void accept_incoming_connections(bool accept); void listen_on_port( uint16_t port, bool wait_if_not_available ); fc::ip::endpoint get_actual_listening_endpoint() const; std::vector<peer_status> get_connected_peers() const; uint32_t get_connection_count() const; void broadcast(const message& item_to_broadcast, const message_propagation_data& propagation_data); void broadcast(const message& item_to_broadcast); void sync_from(const item_id& current_head_block, const std::vector<uint32_t>& hard_fork_block_numbers); bool is_connected() const; std::vector<potential_peer_record> get_potential_peers() const; void set_advanced_node_parameters( const fc::variant_object& params ); node_configuration get_advanced_node_parameters()const; message_propagation_data get_transaction_propagation_data( const graphene::net::transaction_id_type& transaction_id ); message_propagation_data get_block_propagation_data( const graphene::net::block_id_type& block_id ); node_id_t get_node_id() const; void set_allowed_peers( const std::vector<node_id_t>& allowed_peers ); void clear_peer_database(); void set_total_bandwidth_limit( uint32_t upload_bytes_per_second, uint32_t download_bytes_per_second ); fc::variant_object get_call_statistics() const; message get_message_for_item(const item_id& item) override; fc::variant_object network_get_info() const; fc::variant_object network_get_usage_stats() const; bool is_hard_fork_block(uint32_t block_number) const; uint32_t get_next_known_hard_fork_block_number(uint32_t block_number) const; }; // end class node_impl //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void node_impl_deleter::operator()(node_impl* impl_to_delete) { #ifdef P2P_IN_DEDICATED_THREAD std::weak_ptr<fc::thread> weak_thread; if (impl_to_delete) { std::shared_ptr<fc::thread> impl_thread(impl_to_delete->_thread); weak_thread = impl_thread; impl_thread->async([impl_to_delete](){ delete impl_to_delete; }, "delete node_impl").wait(); dlog("deleting the p2p thread"); } if (weak_thread.expired()) dlog("done deleting the p2p thread"); else dlog("failed to delete the p2p thread, we must be leaking a smart pointer somewhere"); #else // P2P_IN_DEDICATED_THREAD delete impl_to_delete; #endif // P2P_IN_DEDICATED_THREAD } #ifdef P2P_IN_DEDICATED_THREAD # define VERIFY_CORRECT_THREAD() assert(_thread->is_current()) #else # define VERIFY_CORRECT_THREAD() do {} while (0) #endif node_impl::node_impl(const std::string& user_agent) : #ifdef P2P_IN_DEDICATED_THREAD _thread(std::make_shared<fc::thread>("p2p")), #endif // P2P_IN_DEDICATED_THREAD _delegate(nullptr), _is_firewalled(firewalled_state::unknown), _potential_peer_database_updated(false), _sync_items_to_fetch_updated(false), _suspend_fetching_sync_blocks(false), _items_to_fetch_updated(false), _items_to_fetch_sequence_counter(0), _recent_block_interval_in_seconds(STEEM_BLOCK_INTERVAL), _user_agent_string(user_agent), _most_recent_blocks_accepted(GRAPHENE_NET_DEFAULT_MAX_CONNECTIONS), _total_number_of_unfetched_items(0), _rate_limiter(0, 0), _last_reported_number_of_connections(0), _average_network_read_speed_seconds(60), _average_network_write_speed_seconds(60), _average_network_read_speed_minutes(60), _average_network_write_speed_minutes(60), _average_network_read_speed_hours(72), _average_network_write_speed_hours(72), _average_network_usage_second_counter(0), _average_network_usage_minute_counter(0), _node_is_shutting_down(false) { _rate_limiter.set_actual_rate_time_constant(fc::seconds(2)); fc::rand_pseudo_bytes(&_node_id.data[0], (int)_node_id.size()); } node_impl::~node_impl() { VERIFY_CORRECT_THREAD(); ilog( "cleaning up node" ); _node_is_shutting_down = true; for (const peer_connection_ptr& active_peer : _active_connections) { fc::optional<fc::ip::endpoint> inbound_endpoint = active_peer->get_endpoint_for_connecting(); if (inbound_endpoint) { fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*inbound_endpoint); if (updated_peer_record) { updated_peer_record->last_seen_time = fc::time_point::now(); _potential_peer_db.update_entry(*updated_peer_record); } } } try { ilog( "close" ); close(); } catch ( const fc::exception& e ) { wlog( "unexpected exception on close ${e}", ("e", e) ); } ilog( "done" ); } void node_impl::save_node_configuration() { VERIFY_CORRECT_THREAD(); if( fc::exists(_node_configuration_directory ) ) { fc::path configuration_file_name( _node_configuration_directory / NODE_CONFIGURATION_FILENAME ); try { fc::json::save_to_file( _node_configuration, configuration_file_name ); } catch (const fc::canceled_exception&) { throw; } catch ( const fc::exception& except ) { elog( "error writing node configuration to file ${filename}: ${error}", ( "filename", configuration_file_name )("error", except.to_detail_string() ) ); } } } void node_impl::p2p_network_connect_loop() { VERIFY_CORRECT_THREAD(); while (!_p2p_network_connect_loop_done.canceled()) { try { dlog("Starting an iteration of p2p_network_connect_loop()."); display_current_connections(); // add-once peers bypass our checks on the maximum/desired number of connections (but they will still be counted against the totals once they're connected) if (!_add_once_node_list.empty()) { std::list<potential_peer_record> add_once_node_list; add_once_node_list.swap(_add_once_node_list); dlog("Processing \"add once\" node list containing ${count} peers:", ("count", add_once_node_list.size())); for (const potential_peer_record& add_once_peer : add_once_node_list) { dlog(" ${peer}", ("peer", add_once_peer.endpoint)); } for (const potential_peer_record& add_once_peer : add_once_node_list) { // see if we have an existing connection to that peer. If we do, disconnect them and // then try to connect the next time through the loop peer_connection_ptr existing_connection_ptr = get_connection_to_endpoint( add_once_peer.endpoint ); if(!existing_connection_ptr) connect_to_endpoint(add_once_peer.endpoint); } dlog("Done processing \"add once\" node list"); } while (is_wanting_new_connections()) { bool initiated_connection_this_pass = false; _potential_peer_database_updated = false; for (peer_database::iterator iter = _potential_peer_db.begin(); iter != _potential_peer_db.end() && is_wanting_new_connections(); ++iter) { fc::microseconds delay_until_retry = fc::seconds((iter->number_of_failed_connection_attempts + 1) * _node_configuration.peer_connection_retry_timeout); if (!is_connection_to_endpoint_in_progress(iter->endpoint) && ((iter->last_connection_disposition != last_connection_failed && iter->last_connection_disposition != last_connection_rejected && iter->last_connection_disposition != last_connection_handshaking_failed) || (fc::time_point::now() - iter->last_connection_attempt_time) > delay_until_retry)) { connect_to_endpoint(iter->endpoint); initiated_connection_this_pass = true; } } if (!initiated_connection_this_pass && !_potential_peer_database_updated) break; } display_current_connections(); // if we broke out of the while loop, that means either we have connected to enough nodes, or // we don't have any good candidates to connect to right now. #if 0 try { _retrigger_connect_loop_promise = fc::promise<void>::ptr( new fc::promise<void>("graphene::net::retrigger_connect_loop") ); if( is_wanting_new_connections() || !_add_once_node_list.empty() ) { if( is_wanting_new_connections() ) dlog( "Still want to connect to more nodes, but I don't have any good candidates. Trying again in 15 seconds" ); else dlog( "I still have some \"add once\" nodes to connect to. Trying again in 15 seconds" ); _retrigger_connect_loop_promise->wait_until( fc::time_point::now() + fc::seconds(GRAPHENE_PEER_DATABASE_RETRY_DELAY ) ); } else { dlog( "I don't need any more connections, waiting forever until something changes" ); _retrigger_connect_loop_promise->wait(); } } catch ( fc::timeout_exception& ) //intentionally not logged { } // catch #else fc::usleep(fc::seconds(10)); #endif } catch (const fc::canceled_exception&) { throw; } catch (const fc::exception& e) { elog("${e}", ("e", e)); } }// while(!canceled) } void node_impl::trigger_p2p_network_connect_loop() { VERIFY_CORRECT_THREAD(); dlog( "Triggering connect loop now" ); _potential_peer_database_updated = true; //if( _retrigger_connect_loop_promise ) // _retrigger_connect_loop_promise->set_value(); } bool node_impl::have_already_received_sync_item( const item_hash_t& item_hash ) { VERIFY_CORRECT_THREAD(); return std::find_if(_received_sync_items.begin(), _received_sync_items.end(), [&item_hash]( const graphene::net::block_message& message ) { return message.block_id == item_hash; } ) != _received_sync_items.end() || std::find_if(_new_received_sync_items.begin(), _new_received_sync_items.end(), [&item_hash]( const graphene::net::block_message& message ) { return message.block_id == item_hash; } ) != _new_received_sync_items.end(); ; } void node_impl::request_sync_item_from_peer( const peer_connection_ptr& peer, const item_hash_t& item_to_request ) { VERIFY_CORRECT_THREAD(); dlog( "requesting item ${item_hash} from peer ${endpoint}", ("item_hash", item_to_request )("endpoint", peer->get_remote_endpoint() ) ); item_id item_id_to_request( graphene::net::block_message_type, item_to_request ); _active_sync_requests.insert( active_sync_requests_map::value_type(item_to_request, fc::time_point::now() ) ); peer->last_sync_item_received_time = fc::time_point::now(); peer->sync_items_requested_from_peer.insert(item_to_request); peer->send_message( fetch_items_message(item_id_to_request.item_type, std::vector<item_hash_t>{item_id_to_request.item_hash} ) ); } void node_impl::request_sync_items_from_peer( const peer_connection_ptr& peer, const std::vector<item_hash_t>& items_to_request ) { VERIFY_CORRECT_THREAD(); dlog( "requesting ${item_count} item(s) ${items_to_request} from peer ${endpoint}", ("item_count", items_to_request.size())("items_to_request", items_to_request)("endpoint", peer->get_remote_endpoint()) ); for (const item_hash_t& item_to_request : items_to_request) { _active_sync_requests.insert( active_sync_requests_map::value_type(item_to_request, fc::time_point::now() ) ); peer->last_sync_item_received_time = fc::time_point::now(); peer->sync_items_requested_from_peer.insert(item_to_request); } peer->send_message(fetch_items_message(graphene::net::block_message_type, items_to_request)); } void node_impl::fetch_sync_items_loop() { VERIFY_CORRECT_THREAD(); while( !_fetch_sync_items_loop_done.canceled() ) { _sync_items_to_fetch_updated = false; dlog( "beginning another iteration of the sync items loop" ); if (!_suspend_fetching_sync_blocks) { std::map<peer_connection_ptr, std::vector<item_hash_t> > sync_item_requests_to_send; { ASSERT_TASK_NOT_PREEMPTED(); std::set<item_hash_t> sync_items_to_request; // for each idle peer that we're syncing with for( const peer_connection_ptr& peer : _active_connections ) { if( peer->we_need_sync_items_from_peer && sync_item_requests_to_send.find(peer) == sync_item_requests_to_send.end() && // if we've already scheduled a request for this peer, don't consider scheduling another peer->idle() ) { if (!peer->inhibit_fetching_sync_blocks) { // loop through the items it has that we don't yet have on our blockchain for( unsigned i = 0; i < peer->ids_of_items_to_get.size(); ++i ) { item_hash_t item_to_potentially_request = peer->ids_of_items_to_get[i]; // if we don't already have this item in our temporary storage and we haven't requested from another syncing peer if( !have_already_received_sync_item(item_to_potentially_request) && // already got it, but for some reson it's still in our list of items to fetch sync_items_to_request.find(item_to_potentially_request) == sync_items_to_request.end() && // we have already decided to request it from another peer during this iteration _active_sync_requests.find(item_to_potentially_request) == _active_sync_requests.end() ) // we've requested it in a previous iteration and we're still waiting for it to arrive { // then schedule a request from this peer sync_item_requests_to_send[peer].push_back(item_to_potentially_request); sync_items_to_request.insert( item_to_potentially_request ); if (sync_item_requests_to_send[peer].size() >= _node_configuration.maximum_blocks_per_peer_during_syncing) break; } } } } } } // end non-preemptable section // make all the requests we scheduled in the loop above for( const auto& sync_item_request : sync_item_requests_to_send ) request_sync_items_from_peer( sync_item_request.first, sync_item_request.second ); sync_item_requests_to_send.clear(); } else dlog("fetch_sync_items_loop is suspended pending backlog processing"); if( !_sync_items_to_fetch_updated ) { dlog( "no sync items to fetch right now, going to sleep" ); _retrigger_fetch_sync_items_loop_promise = fc::promise<void>::ptr( new fc::promise<void>("graphene::net::retrigger_fetch_sync_items_loop") ); _retrigger_fetch_sync_items_loop_promise->wait(); _retrigger_fetch_sync_items_loop_promise.reset(); } } // while( !canceled ) } void node_impl::trigger_fetch_sync_items_loop() { VERIFY_CORRECT_THREAD(); dlog( "Triggering fetch sync items loop now" ); _sync_items_to_fetch_updated = true; if( _retrigger_fetch_sync_items_loop_promise ) _retrigger_fetch_sync_items_loop_promise->set_value(); } bool node_impl::is_item_in_any_peers_inventory(const item_id& item) const { for( const peer_connection_ptr& peer : _active_connections ) { if (peer->inventory_peer_advertised_to_us.find(item) != peer->inventory_peer_advertised_to_us.end() ) return true; } return false; } void node_impl::fetch_items_loop() { VERIFY_CORRECT_THREAD(); while (!_fetch_item_loop_done.canceled()) { _items_to_fetch_updated = false; dlog("beginning an iteration of fetch items (${count} items to fetch)", ("count", _items_to_fetch.size())); fc::time_point oldest_timestamp_to_fetch = fc::time_point::now() - fc::seconds(_recent_block_interval_in_seconds * GRAPHENE_NET_MESSAGE_CACHE_DURATION_IN_BLOCKS); fc::time_point next_peer_unblocked_time = fc::time_point::maximum(); // we need to construct a list of items to request from each peer first, // then send the messages (in two steps, to avoid yielding while iterating) // we want to evenly distribute our requests among our peers. struct requested_item_count_index {}; struct peer_and_items_to_fetch { peer_connection_ptr peer; std::vector<item_id> item_ids; peer_and_items_to_fetch(const peer_connection_ptr& peer) : peer(peer) {} bool operator<(const peer_and_items_to_fetch& rhs) const { return peer < rhs.peer; } size_t number_of_items() const { return item_ids.size(); } }; typedef boost::multi_index_container<peer_and_items_to_fetch, boost::multi_index::indexed_by<boost::multi_index::ordered_unique<boost::multi_index::member<peer_and_items_to_fetch, peer_connection_ptr, &peer_and_items_to_fetch::peer> >, boost::multi_index::ordered_non_unique<boost::multi_index::tag<requested_item_count_index>, boost::multi_index::const_mem_fun<peer_and_items_to_fetch, size_t, &peer_and_items_to_fetch::number_of_items> > > > fetch_messages_to_send_set; fetch_messages_to_send_set items_by_peer; // initialize the fetch_messages_to_send with an empty set of items for all idle peers for (const peer_connection_ptr& peer : _active_connections) if (peer->idle()) items_by_peer.insert(peer_and_items_to_fetch(peer)); // now loop over all items we want to fetch for (auto item_iter = _items_to_fetch.begin(); item_iter != _items_to_fetch.end();) { if (item_iter->timestamp < oldest_timestamp_to_fetch) { // this item has probably already fallen out of our peers' caches, we'll just ignore it. // this can happen during flooding, and the _items_to_fetch could otherwise get clogged // with a bunch of items that we'll never be able to request from any peer wlog("Unable to fetch item ${item} before its likely expiration time, removing it from our list of items to fetch", ("item", item_iter->item)); item_iter = _items_to_fetch.erase(item_iter); } else { // find a peer that has it, we'll use the one who has the least requests going to it to load balance bool item_fetched = false; for (auto peer_iter = items_by_peer.get<requested_item_count_index>().begin(); peer_iter != items_by_peer.get<requested_item_count_index>().end(); ++peer_iter) { const peer_connection_ptr& peer = peer_iter->peer; // if they have the item and we haven't already decided to ask them for too many other items if (peer_iter->item_ids.size() < GRAPHENE_NET_MAX_ITEMS_PER_PEER_DURING_NORMAL_OPERATION && peer->inventory_peer_advertised_to_us.find(item_iter->item) != peer->inventory_peer_advertised_to_us.end()) { if (item_iter->item.item_type == graphene::net::trx_message_type && peer->is_transaction_fetching_inhibited()) next_peer_unblocked_time = std::min(peer->transaction_fetching_inhibited_until, next_peer_unblocked_time); else { //dlog("requesting item ${hash} from peer ${endpoint}", // ("hash", iter->item.item_hash)("endpoint", peer->get_remote_endpoint())); item_id item_id_to_fetch = item_iter->item; peer->items_requested_from_peer.insert(peer_connection::item_to_time_map_type::value_type(item_id_to_fetch, fc::time_point::now())); item_iter = _items_to_fetch.erase(item_iter); item_fetched = true; items_by_peer.get<requested_item_count_index>().modify(peer_iter, [&item_id_to_fetch](peer_and_items_to_fetch& peer_and_items) { peer_and_items.item_ids.push_back(item_id_to_fetch); }); break; } } } if (!item_fetched) ++item_iter; } } // we've figured out which peer will be providing each item, now send the messages. for (const peer_and_items_to_fetch& peer_and_items : items_by_peer) { // the item lists are heterogenous and // the fetch_items_message can only deal with one item type at a time. std::map<uint32_t, std::vector<item_hash_t> > items_to_fetch_by_type; for (const item_id& item : peer_and_items.item_ids) items_to_fetch_by_type[item.item_type].push_back(item.item_hash); for (auto& items_by_type : items_to_fetch_by_type) { dlog("requesting ${count} items of type ${type} from peer ${endpoint}: ${hashes}", ("count", items_by_type.second.size())("type", (uint32_t)items_by_type.first) ("endpoint", peer_and_items.peer->get_remote_endpoint()) ("hashes", items_by_type.second)); if (items_by_type.first == core_message_type_enum::block_message_type) for (const item_hash_t& id : items_by_type.second) { fc_dlog(fc::logger::get("sync"), "requesting a block from peer ${endpoint} (message_id is ${id})", ("endpoint", peer_and_items.peer->get_remote_endpoint())("id", id)); } peer_and_items.peer->send_message(fetch_items_message(items_by_type.first, items_by_type.second)); } } items_by_peer.clear(); if (!_items_to_fetch_updated) { _retrigger_fetch_item_loop_promise = fc::promise<void>::ptr(new fc::promise<void>("graphene::net::retrigger_fetch_item_loop")); fc::microseconds time_until_retrigger = fc::microseconds::maximum(); if (next_peer_unblocked_time != fc::time_point::maximum()) time_until_retrigger = next_peer_unblocked_time - fc::time_point::now(); try { if (time_until_retrigger > fc::microseconds(0)) _retrigger_fetch_item_loop_promise->wait(time_until_retrigger); } catch (const fc::timeout_exception&) { dlog("Resuming fetch_items_loop due to timeout -- one of our peers should no longer be throttled"); } _retrigger_fetch_item_loop_promise.reset(); } } // while (!canceled) } void node_impl::trigger_fetch_items_loop() { VERIFY_CORRECT_THREAD(); _items_to_fetch_updated = true; if( _retrigger_fetch_item_loop_promise ) _retrigger_fetch_item_loop_promise->set_value(); } void node_impl::advertise_inventory_loop() { VERIFY_CORRECT_THREAD(); while (!_advertise_inventory_loop_done.canceled()) { dlog("beginning an iteration of advertise inventory"); // swap inventory into local variable, clearing the node's copy std::unordered_set<item_id> inventory_to_advertise; inventory_to_advertise.swap(_new_inventory); // process all inventory to advertise and construct the inventory messages we'll send // first, then send them all in a batch (to avoid any fiber interruption points while // we're computing the messages) std::list<std::pair<peer_connection_ptr, item_ids_inventory_message> > inventory_messages_to_send; for (const peer_connection_ptr& peer : _active_connections) { // only advertise to peers who are in sync with us //wdump((peer->peer_needs_sync_items_from_us)); if( !peer->peer_needs_sync_items_from_us ) { std::map<uint32_t, std::vector<item_hash_t> > items_to_advertise_by_type; // don't send the peer anything we've already advertised to it // or anything it has advertised to us // group the items we need to send by type, because we'll need to send one inventory message per type unsigned total_items_to_send_to_this_peer = 0; //wdump((inventory_to_advertise)); for (const item_id& item_to_advertise : inventory_to_advertise) { //if (peer->inventory_advertised_to_peer.find(item_to_advertise) != peer->inventory_advertised_to_peer.end() ) // wdump((*peer->inventory_advertised_to_peer.find(item_to_advertise))); //if (peer->inventory_peer_advertised_to_us.find(item_to_advertise) != peer->inventory_peer_advertised_to_us.end() ) // wdump((*peer->inventory_peer_advertised_to_us.find(item_to_advertise))); if (peer->inventory_advertised_to_peer.find(item_to_advertise) == peer->inventory_advertised_to_peer.end() && peer->inventory_peer_advertised_to_us.find(item_to_advertise) == peer->inventory_peer_advertised_to_us.end()) { items_to_advertise_by_type[item_to_advertise.item_type].push_back(item_to_advertise.item_hash); peer->inventory_advertised_to_peer.insert(peer_connection::timestamped_item_id(item_to_advertise, fc::time_point::now())); ++total_items_to_send_to_this_peer; if (item_to_advertise.item_type == trx_message_type) testnetlog("advertising transaction ${id} to peer ${endpoint}", ("id", item_to_advertise.item_hash)("endpoint", peer->get_remote_endpoint())); dlog("advertising item ${id} to peer ${endpoint}", ("id", item_to_advertise.item_hash)("endpoint", peer->get_remote_endpoint())); } } dlog("advertising ${count} new item(s) of ${types} type(s) to peer ${endpoint}", ("count", total_items_to_send_to_this_peer) ("types", items_to_advertise_by_type.size()) ("endpoint", peer->get_remote_endpoint())); for (const auto& items_group : items_to_advertise_by_type) inventory_messages_to_send.push_back(std::make_pair(peer, item_ids_inventory_message(items_group.first, items_group.second))); } peer->clear_old_inventory(); } for (auto iter = inventory_messages_to_send.begin(); iter != inventory_messages_to_send.end(); ++iter) iter->first->send_message(iter->second); inventory_messages_to_send.clear(); if (_new_inventory.empty()) { _retrigger_advertise_inventory_loop_promise = fc::promise<void>::ptr(new fc::promise<void>("graphene::net::retrigger_advertise_inventory_loop")); _retrigger_advertise_inventory_loop_promise->wait(); _retrigger_advertise_inventory_loop_promise.reset(); } } // while(!canceled) } void node_impl::trigger_advertise_inventory_loop() { VERIFY_CORRECT_THREAD(); if( _retrigger_advertise_inventory_loop_promise ) _retrigger_advertise_inventory_loop_promise->set_value(); } void node_impl::terminate_inactive_connections_loop() { VERIFY_CORRECT_THREAD(); std::list<peer_connection_ptr> peers_to_disconnect_gently; std::list<peer_connection_ptr> peers_to_disconnect_forcibly; std::list<peer_connection_ptr> peers_to_send_keep_alive; std::list<peer_connection_ptr> peers_to_terminate; // Disconnect peers that haven't sent us any data recently // These numbers are just guesses and we need to think through how this works better. // If we and our peers get disconnected from the rest of the network, we will not // receive any blocks or transactions from the rest of the world, and that will // probably make us disconnect from our peers even though we have working connections to // them (but they won't have sent us anything since they aren't getting blocks either). // This might not be so bad because it could make us initiate more connections and // reconnect with the rest of the network, or it might just futher isolate us. { // As usual, the first step is to walk through all our peers and figure out which // peers need action (disconneting, sending keepalives, etc), then we walk through // those lists yielding at our leisure later. ASSERT_TASK_NOT_PREEMPTED(); uint32_t handshaking_timeout = _node_configuration.peer_inactivity_timeout; fc::time_point handshaking_disconnect_threshold = fc::time_point::now() - fc::seconds(handshaking_timeout); for( const peer_connection_ptr handshaking_peer : _handshaking_connections ) if( handshaking_peer->connection_initiation_time < handshaking_disconnect_threshold && handshaking_peer->get_last_message_received_time() < handshaking_disconnect_threshold && handshaking_peer->get_last_message_sent_time() < handshaking_disconnect_threshold ) { wlog( "Forcibly disconnecting from handshaking peer ${peer} due to inactivity of at least ${timeout} seconds", ( "peer", handshaking_peer->get_remote_endpoint() )("timeout", handshaking_timeout ) ); wlog("Peer's negotiating status: ${status}, bytes sent: ${sent}, bytes received: ${received}", ("status", handshaking_peer->negotiation_status) ("sent", handshaking_peer->get_total_bytes_sent()) ("received", handshaking_peer->get_total_bytes_received())); handshaking_peer->connection_closed_error = fc::exception(FC_LOG_MESSAGE(warn, "Terminating handshaking connection due to inactivity of ${timeout} seconds. Negotiating status: ${status}, bytes sent: ${sent}, bytes received: ${received}", ("peer", handshaking_peer->get_remote_endpoint()) ("timeout", handshaking_timeout) ("status", handshaking_peer->negotiation_status) ("sent", handshaking_peer->get_total_bytes_sent()) ("received", handshaking_peer->get_total_bytes_received()))); peers_to_disconnect_forcibly.push_back( handshaking_peer ); } // timeout for any active peers is two block intervals uint32_t active_disconnect_timeout = 10 * _recent_block_interval_in_seconds; uint32_t active_send_keepalive_timeout = active_disconnect_timeout / 2; // set the ignored request time out to 6 second. When we request a block // or transaction from a peer, this timeout determines how long we wait for them // to reply before we give up and ask another peer for the item. // Ideally this should be significantly shorter than the block interval, because // we'd like to realize the block isn't coming and fetch it from a different // peer before the next block comes in. // Increased to 6 from 1 in #1660 due to heavy load. May need to adjust further fc::microseconds active_ignored_request_timeout = fc::microseconds( _node_configuration.active_ignored_request_timeout_microseconds ); fc::time_point active_disconnect_threshold = fc::time_point::now() - fc::seconds(active_disconnect_timeout); fc::time_point active_send_keepalive_threshold = fc::time_point::now() - fc::seconds(active_send_keepalive_timeout); fc::time_point active_ignored_request_threshold = fc::time_point::now() - active_ignored_request_timeout; for( const peer_connection_ptr& active_peer : _active_connections ) { if( active_peer->connection_initiation_time < active_disconnect_threshold && active_peer->get_last_message_received_time() < active_disconnect_threshold ) { wlog( "Closing connection with peer ${peer} due to inactivity of at least ${timeout} seconds", ( "peer", active_peer->get_remote_endpoint() )("timeout", active_disconnect_timeout ) ); peers_to_disconnect_gently.push_back( active_peer ); } else { bool disconnect_due_to_request_timeout = false; if (!active_peer->sync_items_requested_from_peer.empty() && active_peer->last_sync_item_received_time < active_ignored_request_threshold) { fc_wlog(fc::logger::get("sync"), "disconnecting peer ${peer} because they haven't made any progress on my remaining ${count} sync item requests", ("peer", active_peer->get_remote_endpoint())("count", active_peer->sync_items_requested_from_peer.size())); wlog("Disconnecting peer ${peer} because they haven't made any progress on my remaining ${count} sync item requests", ("peer", active_peer->get_remote_endpoint())("count", active_peer->sync_items_requested_from_peer.size())); disconnect_due_to_request_timeout = true; break; } if (!disconnect_due_to_request_timeout && active_peer->item_ids_requested_from_peer && active_peer->item_ids_requested_from_peer->get<1>() < active_ignored_request_threshold) { fc_wlog(fc::logger::get("sync"), "Disconnecting peer ${peer} because they didn't respond to my request for sync item ids after ${synopsis}", ("peer", active_peer->get_remote_endpoint()) ("synopsis", active_peer->item_ids_requested_from_peer->get<0>())); wlog("Disconnecting peer ${peer} because they didn't respond to my request for sync item ids after ${synopsis}", ("peer", active_peer->get_remote_endpoint()) ("synopsis", active_peer->item_ids_requested_from_peer->get<0>())); disconnect_due_to_request_timeout = true; } if (!disconnect_due_to_request_timeout) for (const peer_connection::item_to_time_map_type::value_type& item_and_time : active_peer->items_requested_from_peer) if (item_and_time.second < active_ignored_request_threshold) { fc_wlog(fc::logger::get("sync"), "Disconnecting peer ${peer} because they didn't respond to my request for item ${id}", ("peer", active_peer->get_remote_endpoint())("id", item_and_time.first.item_hash)); wlog("Disconnecting peer ${peer} because they didn't respond to my request for item ${id}", ("peer", active_peer->get_remote_endpoint())("id", item_and_time.first.item_hash)); disconnect_due_to_request_timeout = true; break; } if (disconnect_due_to_request_timeout) { // we should probably disconnect nicely and give them a reason, but right now the logic // for rescheduling the requests only executes when the connection is fully closed, // and we want to get those requests rescheduled as soon as possible peers_to_disconnect_forcibly.push_back(active_peer); } else if (active_peer->connection_initiation_time < active_send_keepalive_threshold && active_peer->get_last_message_received_time() < active_send_keepalive_threshold) { wlog( "Sending a keepalive message to peer ${peer} who hasn't sent us any messages in the last ${timeout} seconds", ( "peer", active_peer->get_remote_endpoint() )("timeout", active_send_keepalive_timeout ) ); peers_to_send_keep_alive.push_back(active_peer); } else if (active_peer->we_need_sync_items_from_peer && !active_peer->is_currently_handling_message() && !active_peer->item_ids_requested_from_peer && active_peer->ids_of_items_to_get.empty()) { // This is a state we should never get into in the first place, but if we do, we should disconnect the peer // to re-establish the connection. fc_wlog(fc::logger::get("sync"), "Disconnecting peer ${peer} because we think we need blocks from them but sync has stalled.", ("peer", active_peer->get_remote_endpoint())); wlog("Disconnecting peer ${peer} because we think we need blocks from them but sync has stalled.", ("peer", active_peer->get_remote_endpoint())); peers_to_disconnect_forcibly.push_back(active_peer); } } } fc::time_point closing_disconnect_threshold = fc::time_point::now() - fc::seconds(GRAPHENE_NET_PEER_DISCONNECT_TIMEOUT); for( const peer_connection_ptr& closing_peer : _closing_connections ) if( closing_peer->connection_closed_time < closing_disconnect_threshold ) { // we asked this peer to close their connectoin to us at least GRAPHENE_NET_PEER_DISCONNECT_TIMEOUT // seconds ago, but they haven't done it yet. Terminate the connection now wlog( "Forcibly disconnecting peer ${peer} who failed to close their connection in a timely manner", ( "peer", closing_peer->get_remote_endpoint() ) ); peers_to_disconnect_forcibly.push_back( closing_peer ); } fc::time_point failed_terminate_threshold = fc::time_point::now() - fc::seconds(GRAPHENE_NET_FAILED_TERMINATE_TIMEOUT_SECONDS); for (const peer_connection_ptr& peer : _terminating_connections ) if (peer->get_connection_terminated_time() != fc::time_point::min() && peer->get_connection_terminated_time() < failed_terminate_threshold) { wlog("Terminating connection with peer ${peer}, closing the connection didn't work", ("peer", peer->get_remote_endpoint())); peers_to_terminate.push_back(peer); } // That's the end of the sorting step; now all peers that require further processing are now in one of the // lists peers_to_disconnect_gently, peers_to_disconnect_forcibly, peers_to_send_keep_alive, or peers_to_terminate // if we've decided to delete any peers, do it now; in its current implementation this doesn't yield, // and once we start yielding, we may find that we've moved that peer to another list (closed or active) // and that triggers assertions, maybe even errors for (const peer_connection_ptr& peer : peers_to_terminate ) { assert(_terminating_connections.find(peer) != _terminating_connections.end()); _terminating_connections.erase(peer); schedule_peer_for_deletion(peer); } peers_to_terminate.clear(); // if we're going to abruptly disconnect anyone, do it here // (it doesn't yield). I don't think there would be any harm if this were // moved to the yielding section for( const peer_connection_ptr& peer : peers_to_disconnect_forcibly ) { move_peer_to_terminating_list(peer); peer->close_connection(); } peers_to_disconnect_forcibly.clear(); } // end ASSERT_TASK_NOT_PREEMPTED() // Now process the peers that we need to do yielding functions with (disconnect sends a message with the // disconnect reason, so it may yield) for( const peer_connection_ptr& peer : peers_to_disconnect_gently ) { fc::exception detailed_error( FC_LOG_MESSAGE(warn, "Disconnecting due to inactivity", ( "last_message_received_seconds_ago", (peer->get_last_message_received_time() - fc::time_point::now() ).count() / fc::seconds(1 ).count() ) ( "last_message_sent_seconds_ago", (peer->get_last_message_sent_time() - fc::time_point::now() ).count() / fc::seconds(1 ).count() ) ( "inactivity_timeout", _active_connections.find(peer ) != _active_connections.end() ? _node_configuration.peer_inactivity_timeout * 10 : _node_configuration.peer_inactivity_timeout ) ) ); disconnect_from_peer( peer.get(), "Disconnecting due to inactivity", false, detailed_error ); } peers_to_disconnect_gently.clear(); for( const peer_connection_ptr& peer : peers_to_send_keep_alive ) peer->send_message(current_time_request_message(), offsetof(current_time_request_message, request_sent_time)); peers_to_send_keep_alive.clear(); if (!_node_is_shutting_down && !_terminate_inactive_connections_loop_done.canceled()) _terminate_inactive_connections_loop_done = fc::schedule( [this](){ terminate_inactive_connections_loop(); }, fc::time_point::now() + fc::seconds(1), "terminate_inactive_connections_loop" ); } void node_impl::fetch_updated_peer_lists_loop() { VERIFY_CORRECT_THREAD(); std::list<peer_connection_ptr> original_active_peers(_active_connections.begin(), _active_connections.end()); for( const peer_connection_ptr& active_peer : original_active_peers ) { try { active_peer->send_message(address_request_message()); } catch ( const fc::canceled_exception& ) { throw; } catch (const fc::exception& e) { dlog("Caught exception while sending address request message to peer ${peer} : ${e}", ("peer", active_peer->get_remote_endpoint())("e", e)); } } // this has nothing to do with updating the peer list, but we need to prune this list // at regular intervals, this is a fine place to do it. fc::time_point_sec oldest_failed_ids_to_keep(fc::time_point::now() - fc::minutes(GRAPHENE_NET_PRUNE_FAILED_IDS_MINUTES)); auto oldest_failed_ids_to_keep_iter = _recently_failed_items.get<peer_connection::timestamp_index>().lower_bound(oldest_failed_ids_to_keep); auto begin_iter = _recently_failed_items.get<peer_connection::timestamp_index>().begin(); _recently_failed_items.get<peer_connection::timestamp_index>().erase(begin_iter, oldest_failed_ids_to_keep_iter); if (!_node_is_shutting_down && !_fetch_updated_peer_lists_loop_done.canceled() ) _fetch_updated_peer_lists_loop_done = fc::schedule( [this](){ fetch_updated_peer_lists_loop(); }, fc::time_point::now() + fc::minutes(GRAPHENE_NET_FETCH_UPDATED_PEER_LISTS_INTERVAL_MINUTES), "fetch_updated_peer_lists_loop" ); } void node_impl::update_bandwidth_data(uint32_t bytes_read_this_second, uint32_t bytes_written_this_second) { VERIFY_CORRECT_THREAD(); _average_network_read_speed_seconds.push_back(bytes_read_this_second); _average_network_write_speed_seconds.push_back(bytes_written_this_second); ++_average_network_usage_second_counter; if (_average_network_usage_second_counter >= 60) { _average_network_usage_second_counter = 0; ++_average_network_usage_minute_counter; uint32_t average_read_this_minute = (uint32_t)boost::accumulate(_average_network_read_speed_seconds, uint64_t(0)) / (uint32_t)_average_network_read_speed_seconds.size(); _average_network_read_speed_minutes.push_back(average_read_this_minute); uint32_t average_written_this_minute = (uint32_t)boost::accumulate(_average_network_write_speed_seconds, uint64_t(0)) / (uint32_t)_average_network_write_speed_seconds.size(); _average_network_write_speed_minutes.push_back(average_written_this_minute); if (_average_network_usage_minute_counter >= 60) { _average_network_usage_minute_counter = 0; uint32_t average_read_this_hour = (uint32_t)boost::accumulate(_average_network_read_speed_minutes, uint64_t(0)) / (uint32_t)_average_network_read_speed_minutes.size(); _average_network_read_speed_hours.push_back(average_read_this_hour); uint32_t average_written_this_hour = (uint32_t)boost::accumulate(_average_network_write_speed_minutes, uint64_t(0)) / (uint32_t)_average_network_write_speed_minutes.size(); _average_network_write_speed_hours.push_back(average_written_this_hour); } } } void node_impl::bandwidth_monitor_loop() { VERIFY_CORRECT_THREAD(); fc::time_point_sec current_time = fc::time_point::now(); if (_bandwidth_monitor_last_update_time == fc::time_point_sec::min()) _bandwidth_monitor_last_update_time = current_time; uint32_t seconds_since_last_update = current_time.sec_since_epoch() - _bandwidth_monitor_last_update_time.sec_since_epoch(); seconds_since_last_update = std::max(UINT32_C(1), seconds_since_last_update); uint32_t bytes_read_this_second = _rate_limiter.get_actual_download_rate(); uint32_t bytes_written_this_second = _rate_limiter.get_actual_upload_rate(); for (uint32_t i = 0; i < seconds_since_last_update - 1; ++i) update_bandwidth_data(0, 0); update_bandwidth_data(bytes_read_this_second, bytes_written_this_second); _bandwidth_monitor_last_update_time = current_time; if (!_node_is_shutting_down && !_bandwidth_monitor_loop_done.canceled()) _bandwidth_monitor_loop_done = fc::schedule( [=](){ bandwidth_monitor_loop(); }, fc::time_point::now() + fc::seconds(GRAPHENE_NET_BANDWIDTH_MONITOR_INTERVAL_SECONDS), "bandwidth_monitor_loop" ); } void node_impl::dump_node_status_task() { VERIFY_CORRECT_THREAD(); dump_node_status(); if (!_node_is_shutting_down && !_dump_node_status_task_done.canceled()) _dump_node_status_task_done = fc::schedule([=](){ dump_node_status_task(); }, fc::time_point::now() + fc::minutes(GRAPHENE_NET_DUMP_NODE_STATUS_INTERVAL_MINUTES), "dump_node_status_task"); } void node_impl::delayed_peer_deletion_task() { VERIFY_CORRECT_THREAD(); #ifdef USE_PEERS_TO_DELETE_MUTEX fc::scoped_lock<fc::mutex> lock(_peers_to_delete_mutex); dlog("in delayed_peer_deletion_task with ${count} in queue", ("count", _peers_to_delete.size())); _peers_to_delete.clear(); dlog("_peers_to_delete cleared"); #else while (!_peers_to_delete.empty()) { std::list<peer_connection_ptr> peers_to_delete_copy; dlog("beginning an iteration of delayed_peer_deletion_task with ${count} in queue", ("count", _peers_to_delete.size())); peers_to_delete_copy.swap(_peers_to_delete); } dlog("leaving delayed_peer_deletion_task"); #endif } void node_impl::schedule_peer_for_deletion(const peer_connection_ptr& peer_to_delete) { VERIFY_CORRECT_THREAD(); assert(_handshaking_connections.find(peer_to_delete) == _handshaking_connections.end()); assert(_active_connections.find(peer_to_delete) == _active_connections.end()); assert(_closing_connections.find(peer_to_delete) == _closing_connections.end()); assert(_terminating_connections.find(peer_to_delete) == _terminating_connections.end()); #ifdef USE_PEERS_TO_DELETE_MUTEX dlog("scheduling peer for deletion: ${peer} (may block on a mutex here)", ("peer", peer_to_delete->get_remote_endpoint())); unsigned number_of_peers_to_delete; { fc::scoped_lock<fc::mutex> lock(_peers_to_delete_mutex); _peers_to_delete.emplace_back(peer_to_delete); number_of_peers_to_delete = _peers_to_delete.size(); } dlog("peer scheduled for deletion: ${peer}", ("peer", peer_to_delete->get_remote_endpoint())); if (!_node_is_shutting_down && (!_delayed_peer_deletion_task_done.valid() || _delayed_peer_deletion_task_done.ready())) { dlog("asyncing delayed_peer_deletion_task to delete ${size} peers", ("size", number_of_peers_to_delete)); _delayed_peer_deletion_task_done = fc::async([this](){ delayed_peer_deletion_task(); }, "delayed_peer_deletion_task" ); } else dlog("delayed_peer_deletion_task is already scheduled (current size of _peers_to_delete is ${size})", ("size", number_of_peers_to_delete)); #else dlog("scheduling peer for deletion: ${peer} (this will not block)", ("peer", peer_to_delete->get_remote_endpoint())); _peers_to_delete.push_back(peer_to_delete); if (!_node_is_shutting_down && (!_delayed_peer_deletion_task_done.valid() || _delayed_peer_deletion_task_done.ready())) { dlog("asyncing delayed_peer_deletion_task to delete ${size} peers", ("size", _peers_to_delete.size())); _delayed_peer_deletion_task_done = fc::async([this](){ delayed_peer_deletion_task(); }, "delayed_peer_deletion_task" ); } else dlog("delayed_peer_deletion_task is already scheduled (current size of _peers_to_delete is ${size})", ("size", _peers_to_delete.size())); #endif } bool node_impl::is_accepting_new_connections() { VERIFY_CORRECT_THREAD(); return !_p2p_network_connect_loop_done.canceled() && get_number_of_connections() <= _node_configuration.maximum_number_of_connections; } bool node_impl::is_wanting_new_connections() { VERIFY_CORRECT_THREAD(); return !_p2p_network_connect_loop_done.canceled() && get_number_of_connections() < _node_configuration.desired_number_of_connections; } uint32_t node_impl::get_number_of_connections() { VERIFY_CORRECT_THREAD(); return (uint32_t)(_handshaking_connections.size() + _active_connections.size()); } peer_connection_ptr node_impl::get_peer_by_node_id(const node_id_t& node_id) { for (const peer_connection_ptr& active_peer : _active_connections) if (node_id == active_peer->node_id) return active_peer; for (const peer_connection_ptr& handshaking_peer : _handshaking_connections) if (node_id == handshaking_peer->node_id) return handshaking_peer; return peer_connection_ptr(); } bool node_impl::is_already_connected_to_id(const node_id_t& node_id) { VERIFY_CORRECT_THREAD(); if (node_id == _node_id) { dlog("is_already_connected_to_id returning true because the peer is us"); return true; } for (const peer_connection_ptr active_peer : _active_connections) if (node_id == active_peer->node_id) { dlog("is_already_connected_to_id returning true because the peer is already in our active list"); return true; } for (const peer_connection_ptr handshaking_peer : _handshaking_connections) if (node_id == handshaking_peer->node_id) { dlog("is_already_connected_to_id returning true because the peer is already in our handshaking list"); return true; } return false; } // merge addresses received from a peer into our database bool node_impl::merge_address_info_with_potential_peer_database(const std::vector<address_info> addresses) { VERIFY_CORRECT_THREAD(); bool new_information_received = false; for (const address_info& address : addresses) { if (address.firewalled == graphene::net::firewalled_state::not_firewalled) { potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(address.remote_endpoint); if (address.last_seen_time > updated_peer_record.last_seen_time) new_information_received = true; updated_peer_record.last_seen_time = std::max(address.last_seen_time, updated_peer_record.last_seen_time); _potential_peer_db.update_entry(updated_peer_record); } } return new_information_received; } void node_impl::display_current_connections() { VERIFY_CORRECT_THREAD(); dlog("Currently have ${current} of [${desired}/${max}] connections", ("current", get_number_of_connections()) ("desired", _node_configuration.desired_number_of_connections) ("max", _node_configuration.maximum_number_of_connections)); dlog(" my id is ${id}", ("id", _node_id)); for (const peer_connection_ptr& active_connection : _active_connections) { dlog(" active: ${endpoint} with ${id} [${direction}]", ("endpoint", active_connection->get_remote_endpoint()) ("id", active_connection->node_id) ("direction", active_connection->direction)); } for (const peer_connection_ptr& handshaking_connection : _handshaking_connections) { dlog(" handshaking: ${endpoint} with ${id} [${direction}]", ("endpoint", handshaking_connection->get_remote_endpoint()) ("id", handshaking_connection->node_id) ("direction", handshaking_connection->direction)); } } void node_impl::on_message( peer_connection* originating_peer, const message& received_message ) { VERIFY_CORRECT_THREAD(); message_hash_type message_hash = received_message.id(); dlog("handling message ${type} ${hash} size ${size} from peer ${endpoint}", ("type", graphene::net::core_message_type_enum(received_message.msg_type))("hash", message_hash) ("size", received_message.size) ("endpoint", originating_peer->get_remote_endpoint())); switch ( received_message.msg_type ) { case core_message_type_enum::hello_message_type: on_hello_message(originating_peer, received_message.as<hello_message>()); break; case core_message_type_enum::connection_accepted_message_type: on_connection_accepted_message(originating_peer, received_message.as<connection_accepted_message>()); break; case core_message_type_enum::connection_rejected_message_type: on_connection_rejected_message(originating_peer, received_message.as<connection_rejected_message>()); break; case core_message_type_enum::address_request_message_type: on_address_request_message(originating_peer, received_message.as<address_request_message>()); break; case core_message_type_enum::address_message_type: on_address_message(originating_peer, received_message.as<address_message>()); break; case core_message_type_enum::fetch_blockchain_item_ids_message_type: on_fetch_blockchain_item_ids_message(originating_peer, received_message.as<fetch_blockchain_item_ids_message>()); break; case core_message_type_enum::blockchain_item_ids_inventory_message_type: on_blockchain_item_ids_inventory_message(originating_peer, received_message.as<blockchain_item_ids_inventory_message>()); break; case core_message_type_enum::fetch_items_message_type: on_fetch_items_message(originating_peer, received_message.as<fetch_items_message>()); break; case core_message_type_enum::item_not_available_message_type: on_item_not_available_message(originating_peer, received_message.as<item_not_available_message>()); break; case core_message_type_enum::item_ids_inventory_message_type: on_item_ids_inventory_message(originating_peer, received_message.as<item_ids_inventory_message>()); break; case core_message_type_enum::closing_connection_message_type: on_closing_connection_message(originating_peer, received_message.as<closing_connection_message>()); break; case core_message_type_enum::block_message_type: process_block_message(originating_peer, received_message, message_hash); break; case core_message_type_enum::current_time_request_message_type: on_current_time_request_message(originating_peer, received_message.as<current_time_request_message>()); break; case core_message_type_enum::current_time_reply_message_type: on_current_time_reply_message(originating_peer, received_message.as<current_time_reply_message>()); break; case core_message_type_enum::check_firewall_message_type: on_check_firewall_message(originating_peer, received_message.as<check_firewall_message>()); break; case core_message_type_enum::check_firewall_reply_message_type: on_check_firewall_reply_message(originating_peer, received_message.as<check_firewall_reply_message>()); break; case core_message_type_enum::get_current_connections_request_message_type: on_get_current_connections_request_message(originating_peer, received_message.as<get_current_connections_request_message>()); break; case core_message_type_enum::get_current_connections_reply_message_type: on_get_current_connections_reply_message(originating_peer, received_message.as<get_current_connections_reply_message>()); break; default: // ignore any message in between core_message_type_first and _last that we don't handle above // to allow us to add messages in the future if (received_message.msg_type < core_message_type_enum::core_message_type_first || received_message.msg_type > core_message_type_enum::core_message_type_last) process_ordinary_message(originating_peer, received_message, message_hash); break; } } fc::variant_object node_impl::generate_hello_user_data() { VERIFY_CORRECT_THREAD(); // for the time being, shoehorn a bunch of properties into the user_data variant object, // which lets us add and remove fields without changing the protocol. Once we // settle on what we really want in there, we'll likely promote them to first // class fields in the hello message fc::mutable_variant_object user_data; user_data["fc_git_revision_sha"] = fc::git_revision_sha; user_data["fc_git_revision_unix_timestamp"] = fc::git_revision_unix_timestamp; #if defined( __APPLE__ ) user_data["platform"] = "osx"; #elif defined( __linux__ ) user_data["platform"] = "linux"; #elif defined( _MSC_VER ) user_data["platform"] = "win32"; #else user_data["platform"] = "other"; #endif user_data["bitness"] = sizeof(void*) * 8; user_data["node_id"] = _node_id; item_hash_t head_block_id = _delegate->get_head_block_id(); user_data["last_known_block_hash"] = head_block_id; user_data["last_known_block_number"] = _delegate->get_block_number(head_block_id); user_data["last_known_block_time"] = _delegate->get_block_time(head_block_id); if (!_hard_fork_block_numbers.empty()) user_data["last_known_fork_block_number"] = _hard_fork_block_numbers.back(); user_data["chain_id"] = _delegate->get_chain_id(); return user_data; } void node_impl::parse_hello_user_data_for_peer(peer_connection* originating_peer, const fc::variant_object& user_data) { VERIFY_CORRECT_THREAD(); // try to parse data out of the user_agent string if (user_data.contains("graphene_git_revision_sha")) originating_peer->graphene_git_revision_sha = user_data["graphene_git_revision_sha"].as_string(); if (user_data.contains("graphene_git_revision_unix_timestamp")) originating_peer->graphene_git_revision_unix_timestamp = fc::time_point_sec(user_data["graphene_git_revision_unix_timestamp"].as<uint32_t>()); if (user_data.contains("fc_git_revision_sha")) originating_peer->fc_git_revision_sha = user_data["fc_git_revision_sha"].as_string(); if (user_data.contains("fc_git_revision_unix_timestamp")) originating_peer->fc_git_revision_unix_timestamp = fc::time_point_sec(user_data["fc_git_revision_unix_timestamp"].as<uint32_t>()); if (user_data.contains("platform")) originating_peer->platform = user_data["platform"].as_string(); if (user_data.contains("bitness")) originating_peer->bitness = user_data["bitness"].as<uint32_t>(); if (user_data.contains("node_id")) originating_peer->node_id = user_data["node_id"].as<node_id_t>(); if (user_data.contains("last_known_fork_block_number")) originating_peer->last_known_fork_block_number = user_data["last_known_fork_block_number"].as<uint32_t>(); if (user_data.contains("chain_id")) originating_peer->chain_id = user_data["chain_id"].as<steem::protocol::chain_id_type>(); } void node_impl::on_hello_message( peer_connection* originating_peer, const hello_message& hello_message_received ) { VERIFY_CORRECT_THREAD(); // this already_connected check must come before we fill in peer data below node_id_t peer_node_id = hello_message_received.node_public_key; try { peer_node_id = hello_message_received.user_data["node_id"].as<node_id_t>(); } catch (const fc::exception&) { // either it's not there or it's not a valid session id. either way, ignore. } bool already_connected_to_this_peer = is_already_connected_to_id(peer_node_id); // validate the node id fc::sha256::encoder shared_secret_encoder; fc::sha512 shared_secret = originating_peer->get_shared_secret(); shared_secret_encoder.write(shared_secret.data(), sizeof(shared_secret)); fc::ecc::public_key expected_node_public_key(hello_message_received.signed_shared_secret, shared_secret_encoder.result(), false); // store off the data provided in the hello message originating_peer->user_agent = hello_message_received.user_agent; originating_peer->node_public_key = hello_message_received.node_public_key; originating_peer->node_id = hello_message_received.node_public_key; // will probably be overwritten in parse_hello_user_data_for_peer() originating_peer->core_protocol_version = hello_message_received.core_protocol_version; originating_peer->inbound_address = hello_message_received.inbound_address; originating_peer->inbound_port = hello_message_received.inbound_port; originating_peer->outbound_port = hello_message_received.outbound_port; parse_hello_user_data_for_peer(originating_peer, hello_message_received.user_data); // if they didn't provide a last known fork, try to guess it if (originating_peer->last_known_fork_block_number == 0 && originating_peer->graphene_git_revision_unix_timestamp) { uint32_t unix_timestamp = originating_peer->graphene_git_revision_unix_timestamp->sec_since_epoch(); originating_peer->last_known_fork_block_number = _delegate->estimate_last_known_fork_from_git_revision_timestamp(unix_timestamp); } // now decide what to do with it if (originating_peer->their_state == peer_connection::their_connection_state::just_connected) { if (hello_message_received.node_public_key != expected_node_public_key.serialize()) { wlog("Invalid signature in hello message from peer ${peer}", ("peer", originating_peer->get_remote_endpoint())); std::string rejection_message("Invalid signature in hello message"); connection_rejected_message connection_rejected(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::invalid_hello_message, rejection_message); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message( message(connection_rejected ) ); // for this type of message, we're immediately disconnecting this peer disconnect_from_peer( originating_peer, "Invalid signature in hello message" ); return; } if (originating_peer->last_known_fork_block_number != 0) { uint32_t next_fork_block_number = get_next_known_hard_fork_block_number(originating_peer->last_known_fork_block_number); if (next_fork_block_number != 0) { // we know about a fork they don't. See if we've already passed that block. If we have, don't let them // connect because we won't be able to give them anything useful uint32_t head_block_num = _delegate->get_block_number(_delegate->get_head_block_id()); if (next_fork_block_number < head_block_num) { #ifdef ENABLE_DEBUG_ULOGS ulog("Rejecting connection from peer because their version is too old. Their version date: ${date}", ("date", originating_peer->graphene_git_revision_unix_timestamp)); #endif wlog("Received hello message from peer running a version of that can only understand blocks up to #${their_hard_fork}, but I'm at head block number #${my_block_number}", ("their_hard_fork", next_fork_block_number)("my_block_number", head_block_num)); std::ostringstream rejection_message; rejection_message << "Your client is outdated -- you can only understand blocks up to #" << next_fork_block_number << ", but I'm already on block #" << head_block_num; connection_rejected_message connection_rejected(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::unspecified, rejection_message.str() ); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message(message(connection_rejected)); // for this type of message, we're immediately disconnecting this peer, instead of trying to // allowing her to ask us for peers (any of our peers will be on the same chain as us, so there's no // benefit of sharing them) disconnect_from_peer(originating_peer, "Your client is too old, please upgrade"); return; } } } if ( !originating_peer->chain_id || *originating_peer->chain_id != _delegate->get_chain_id() ) { wlog("Received hello message from peer running a node for different blockchain.", ("my_chain_id", _delegate->get_chain_id())("their_chain_id", originating_peer->chain_id) ); std::ostringstream rejection_message; rejection_message << "Your client is running a different chain id"; connection_rejected_message connection_rejected(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::different_chain, rejection_message.str() ); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message( message( connection_rejected ) ); // for this type of message, we're immediately disconnecting this peer, instead of trying to // allowing her to ask us for peers (any of our peers will be on the same chain as us, so there's no // benefit of sharing them) disconnect_from_peer(originating_peer, "Your client is on a different chain, please specify different seed nodes"); return; } if (already_connected_to_this_peer) { connection_rejected_message connection_rejected; if (_node_id == originating_peer->node_id) connection_rejected = connection_rejected_message(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::connected_to_self, "I'm connecting to myself"); else connection_rejected = connection_rejected_message(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::already_connected, "I'm already connected to you"); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message(message(connection_rejected)); dlog("Received a hello_message from peer ${peer} that I'm already connected to (with id ${id}), rejection", ("peer", originating_peer->get_remote_endpoint()) ("id", originating_peer->node_id)); } #ifdef ENABLE_P2P_DEBUGGING_API else if(!_allowed_peers.empty() && _allowed_peers.find(originating_peer->node_id) == _allowed_peers.end()) { connection_rejected_message connection_rejected(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::blocked, "you are not in my allowed_peers list"); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message( message(connection_rejected ) ); dlog( "Received a hello_message from peer ${peer} who isn't in my allowed_peers list, rejection", ("peer", originating_peer->get_remote_endpoint() ) ); } #endif // ENABLE_P2P_DEBUGGING_API else { // whether we're planning on accepting them as a peer or not, they seem to be a valid node, // so add them to our database if they're not firewalled // in the hello message, the peer sent us the IP address and port it thought it was connecting from. // If they match the IP and port we see, we assume that they're actually on the internet and they're not // firewalled. fc::ip::endpoint peers_actual_outbound_endpoint = originating_peer->get_socket().remote_endpoint(); if( peers_actual_outbound_endpoint.get_address() == originating_peer->inbound_address && peers_actual_outbound_endpoint.port() == originating_peer->outbound_port ) { if( originating_peer->inbound_port == 0 ) { dlog( "peer does not appear to be firewalled, but they did not give an inbound port so I'm treating them as if they are." ); originating_peer->is_firewalled = firewalled_state::firewalled; } else { // peer is not firewalled, add it to our database fc::ip::endpoint peers_inbound_endpoint(originating_peer->inbound_address, originating_peer->inbound_port); potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(peers_inbound_endpoint); _potential_peer_db.update_entry(updated_peer_record); originating_peer->is_firewalled = firewalled_state::not_firewalled; } } else { dlog("peer is firewalled: they think their outbound endpoint is ${reported_endpoint}, but I see it as ${actual_endpoint}", ("reported_endpoint", fc::ip::endpoint(originating_peer->inbound_address, originating_peer->outbound_port)) ("actual_endpoint", peers_actual_outbound_endpoint)); originating_peer->is_firewalled = firewalled_state::firewalled; } if (!is_accepting_new_connections()) { connection_rejected_message connection_rejected(_user_agent_string, core_protocol_version, originating_peer->get_socket().remote_endpoint(), rejection_reason_code::not_accepting_connections, "not accepting any more incoming connections"); originating_peer->their_state = peer_connection::their_connection_state::connection_rejected; originating_peer->send_message(message(connection_rejected)); dlog("Received a hello_message from peer ${peer}, but I'm not accepting any more connections, rejection", ("peer", originating_peer->get_remote_endpoint())); } else { originating_peer->their_state = peer_connection::their_connection_state::connection_accepted; originating_peer->send_message(message(connection_accepted_message())); dlog("Received a hello_message from peer ${peer}, sending reply to accept connection", ("peer", originating_peer->get_remote_endpoint())); } } } else { // we can wind up here if we've connected to ourself, and the source and // destination endpoints are the same, causing messages we send out // to arrive back on the initiating socket instead of the receiving // socket. If we did a complete job of enumerating local addresses, // we could avoid directly connecting to ourselves, or at least detect // immediately when we did it and disconnect. // The only way I know of that we'd get an unexpected hello that we // can't really guard against is if we do a simulatenous open, we // probably need to think through that case. We're not attempting that // yet, though, so it's ok to just disconnect here. wlog("unexpected hello_message from peer, disconnecting"); disconnect_from_peer(originating_peer, "Received a unexpected hello_message"); } } void node_impl::on_connection_accepted_message(peer_connection* originating_peer, const connection_accepted_message& connection_accepted_message_received) { VERIFY_CORRECT_THREAD(); dlog("Received a connection_accepted in response to my \"hello\" from ${peer}", ("peer", originating_peer->get_remote_endpoint())); originating_peer->negotiation_status = peer_connection::connection_negotiation_status::peer_connection_accepted; originating_peer->our_state = peer_connection::our_connection_state::connection_accepted; originating_peer->send_message(address_request_message()); fc::time_point now = fc::time_point::now(); if (_is_firewalled == firewalled_state::unknown && _last_firewall_check_message_sent < now - fc::minutes(GRAPHENE_NET_FIREWALL_CHECK_MESSAGE_INTERVAL_MINUTES) && originating_peer->core_protocol_version >= 106) { wlog("I don't know if I'm firewalled. Sending a firewall check message to peer ${peer}", ("peer", originating_peer->get_remote_endpoint())); originating_peer->firewall_check_state = new firewall_check_state_data; originating_peer->send_message(check_firewall_message()); _last_firewall_check_message_sent = now; } } void node_impl::on_connection_rejected_message(peer_connection* originating_peer, const connection_rejected_message& connection_rejected_message_received) { VERIFY_CORRECT_THREAD(); if (originating_peer->our_state == peer_connection::our_connection_state::just_connected) { ilog("Received a rejection from ${peer} in response to my \"hello\", reason: \"${reason}\"", ("peer", originating_peer->get_remote_endpoint()) ("reason", connection_rejected_message_received.reason_string)); if (connection_rejected_message_received.reason_code == rejection_reason_code::connected_to_self) { _potential_peer_db.erase(originating_peer->get_socket().remote_endpoint()); move_peer_to_closing_list(originating_peer->shared_from_this()); originating_peer->close_connection(); } else { // update our database to record that we were rejected so we won't try to connect again for a while // this only happens on connections we originate, so we should already know that peer is not firewalled fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(originating_peer->get_socket().remote_endpoint()); if (updated_peer_record) { updated_peer_record->last_connection_disposition = last_connection_rejected; updated_peer_record->last_connection_attempt_time = fc::time_point::now(); _potential_peer_db.update_entry(*updated_peer_record); } } originating_peer->negotiation_status = peer_connection::connection_negotiation_status::peer_connection_rejected; originating_peer->our_state = peer_connection::our_connection_state::connection_rejected; originating_peer->send_message(address_request_message()); } else FC_THROW( "unexpected connection_rejected_message from peer" ); } void node_impl::on_address_request_message(peer_connection* originating_peer, const address_request_message& address_request_message_received) { VERIFY_CORRECT_THREAD(); dlog("Received an address request message"); address_message reply; if (!_node_configuration.peer_advertising_disabled) { reply.addresses.reserve(_active_connections.size()); for (const peer_connection_ptr& active_peer : _active_connections) { fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*active_peer->get_remote_endpoint()); if (updated_peer_record) { updated_peer_record->last_seen_time = fc::time_point::now(); _potential_peer_db.update_entry(*updated_peer_record); } reply.addresses.emplace_back(address_info(*active_peer->get_remote_endpoint(), fc::time_point::now(), active_peer->round_trip_delay, active_peer->node_id, active_peer->direction, active_peer->is_firewalled)); } } originating_peer->send_message(reply); } void node_impl::on_address_message(peer_connection* originating_peer, const address_message& address_message_received) { VERIFY_CORRECT_THREAD(); dlog("Received an address message containing ${size} addresses", ("size", address_message_received.addresses.size())); for (const address_info& address : address_message_received.addresses) { dlog(" ${endpoint} last seen ${time}", ("endpoint", address.remote_endpoint)("time", address.last_seen_time)); } std::vector<graphene::net::address_info> updated_addresses = address_message_received.addresses; for (address_info& address : updated_addresses) address.last_seen_time = fc::time_point_sec(fc::time_point::now()); bool new_information_received = merge_address_info_with_potential_peer_database(updated_addresses); if (new_information_received) trigger_p2p_network_connect_loop(); if (_handshaking_connections.find(originating_peer->shared_from_this()) != _handshaking_connections.end()) { // if we were handshaking, we need to continue with the next step in handshaking (which is either // ending handshaking and starting synchronization or disconnecting) if( originating_peer->our_state == peer_connection::our_connection_state::connection_rejected) disconnect_from_peer(originating_peer, "You rejected my connection request (hello message) so I'm disconnecting"); else if (originating_peer->their_state == peer_connection::their_connection_state::connection_rejected) disconnect_from_peer(originating_peer, "I rejected your connection request (hello message) so I'm disconnecting"); else { fc::optional<fc::ip::endpoint> inbound_endpoint = originating_peer->get_endpoint_for_connecting(); if (inbound_endpoint) { // mark the connection as successful in the database fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*inbound_endpoint); if (updated_peer_record) { updated_peer_record->last_connection_disposition = last_connection_succeeded; _potential_peer_db.update_entry(*updated_peer_record); } } originating_peer->negotiation_status = peer_connection::connection_negotiation_status::negotiation_complete; move_peer_to_active_list(originating_peer->shared_from_this()); new_peer_just_added(originating_peer->shared_from_this()); } } // else if this was an active connection, then this was just a reply to our periodic address requests. // we've processed it, there's nothing else to do } void node_impl::on_fetch_blockchain_item_ids_message(peer_connection* originating_peer, const fetch_blockchain_item_ids_message& fetch_blockchain_item_ids_message_received) { VERIFY_CORRECT_THREAD(); item_id peers_last_item_seen = item_id(fetch_blockchain_item_ids_message_received.item_type, item_hash_t()); if (fetch_blockchain_item_ids_message_received.blockchain_synopsis.empty()) { dlog("sync: received a request for item ids starting at the beginning of the chain from peer ${peer_endpoint} (full request: ${synopsis})", ("peer_endpoint", originating_peer->get_remote_endpoint()) ("synopsis", fetch_blockchain_item_ids_message_received.blockchain_synopsis)); } else { item_hash_t peers_last_item_hash_seen = fetch_blockchain_item_ids_message_received.blockchain_synopsis.back(); dlog("sync: received a request for item ids after ${last_item_seen} from peer ${peer_endpoint} (full request: ${synopsis})", ("last_item_seen", peers_last_item_hash_seen) ("peer_endpoint", originating_peer->get_remote_endpoint()) ("synopsis", fetch_blockchain_item_ids_message_received.blockchain_synopsis)); peers_last_item_seen.item_hash = peers_last_item_hash_seen; } blockchain_item_ids_inventory_message reply_message; reply_message.item_type = fetch_blockchain_item_ids_message_received.item_type; reply_message.total_remaining_item_count = 0; try { reply_message.item_hashes_available = _delegate->get_block_ids(fetch_blockchain_item_ids_message_received.blockchain_synopsis, reply_message.total_remaining_item_count); } catch (const peer_is_on_an_unreachable_fork&) { dlog("Peer is on a fork and there's no set of blocks we can provide to switch them to our fork"); // we reply with an empty list as if we had an empty blockchain; // we don't want to disconnect because they may be able to provide // us with blocks on their chain } bool disconnect_from_inhibited_peer = false; // if our client doesn't have any items after the item the peer requested, it will send back // a list containing the last item the peer requested //wdump((reply_message)(fetch_blockchain_item_ids_message_received.blockchain_synopsis)); if( reply_message.item_hashes_available.empty() ) originating_peer->peer_needs_sync_items_from_us = false; /* I have no items in my blockchain */ else if( !fetch_blockchain_item_ids_message_received.blockchain_synopsis.empty() && reply_message.item_hashes_available.size() == 1 && std::find(fetch_blockchain_item_ids_message_received.blockchain_synopsis.begin(), fetch_blockchain_item_ids_message_received.blockchain_synopsis.end(), reply_message.item_hashes_available.back() ) != fetch_blockchain_item_ids_message_received.blockchain_synopsis.end() ) { /* the last item in the peer's list matches the last item in our list */ originating_peer->peer_needs_sync_items_from_us = false; if (originating_peer->inhibit_fetching_sync_blocks) disconnect_from_inhibited_peer = true; // delay disconnecting until after we send our reply to this fetch_blockchain_item_ids_message } else originating_peer->peer_needs_sync_items_from_us = true; if (!originating_peer->peer_needs_sync_items_from_us) { dlog("sync: peer is already in sync with us"); // if we thought we had all the items this peer had, but now it turns out that we don't // have the last item it requested to send from, // we need to kick off another round of synchronization if (!originating_peer->we_need_sync_items_from_peer && !fetch_blockchain_item_ids_message_received.blockchain_synopsis.empty() && !_delegate->has_item(peers_last_item_seen)) { dlog("sync: restarting sync with peer ${peer}", ("peer", originating_peer->get_remote_endpoint())); start_synchronizing_with_peer(originating_peer->shared_from_this()); } } else { dlog("sync: peer is out of sync, sending peer ${count} items ids: first: ${first_item_id}, last: ${last_item_id}", ("count", reply_message.item_hashes_available.size()) ("first_item_id", reply_message.item_hashes_available.front()) ("last_item_id", reply_message.item_hashes_available.back())); if (!originating_peer->we_need_sync_items_from_peer && !fetch_blockchain_item_ids_message_received.blockchain_synopsis.empty() && !_delegate->has_item(peers_last_item_seen)) { dlog("sync: restarting sync with peer ${peer}", ("peer", originating_peer->get_remote_endpoint())); start_synchronizing_with_peer(originating_peer->shared_from_this()); } } originating_peer->send_message(reply_message); if (disconnect_from_inhibited_peer) { // the peer has all of our blocks, and we don't want any of theirs, so disconnect them disconnect_from_peer(originating_peer, "you are on a fork that I'm unable to switch to"); return; } if (originating_peer->direction == peer_connection_direction::inbound && _handshaking_connections.find(originating_peer->shared_from_this()) != _handshaking_connections.end()) { // handshaking is done, move the connection to fully active status and start synchronizing dlog("peer ${endpoint} which was handshaking with us has started synchronizing with us, start syncing with it", ("endpoint", originating_peer->get_remote_endpoint())); fc::optional<fc::ip::endpoint> inbound_endpoint = originating_peer->get_endpoint_for_connecting(); if (inbound_endpoint) { // mark the connection as successful in the database potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(*inbound_endpoint); updated_peer_record.last_connection_disposition = last_connection_succeeded; _potential_peer_db.update_entry(updated_peer_record); } // transition it to our active list move_peer_to_active_list(originating_peer->shared_from_this()); new_peer_just_added(originating_peer->shared_from_this()); } } uint32_t node_impl::calculate_unsynced_block_count_from_all_peers() { VERIFY_CORRECT_THREAD(); uint32_t max_number_of_unfetched_items = 0; for( const peer_connection_ptr& peer : _active_connections ) { uint32_t this_peer_number_of_unfetched_items = (uint32_t)peer->ids_of_items_to_get.size() + peer->number_of_unfetched_item_ids; max_number_of_unfetched_items = std::max(max_number_of_unfetched_items, this_peer_number_of_unfetched_items); } return max_number_of_unfetched_items; } // get a blockchain synopsis that makes sense to send to the given peer. // If the peer isn't yet syncing with us, this is just a synopsis of our active blockchain // If the peer is syncing with us, it is a synopsis of our active blockchain plus the // blocks the peer has already told us it has std::vector<item_hash_t> node_impl::create_blockchain_synopsis_for_peer( const peer_connection* peer ) { VERIFY_CORRECT_THREAD(); item_hash_t reference_point = peer->last_block_delegate_has_seen; // when we call _delegate->get_blockchain_synopsis(), we may yield and there's a // chance this peer's state will change before we get control back. Save off // the stuff necessary for generating the synopsis. // This is pretty expensive, we should find a better way to do this std::vector<item_hash_t> original_ids_of_items_to_get(peer->ids_of_items_to_get.begin(), peer->ids_of_items_to_get.end()); uint32_t number_of_blocks_after_reference_point = original_ids_of_items_to_get.size(); std::vector<item_hash_t> synopsis = _delegate->get_blockchain_synopsis(reference_point, number_of_blocks_after_reference_point); #if 0 // just for debugging, enable this and set a breakpoint to step through if (synopsis.empty()) synopsis = _delegate->get_blockchain_synopsis(reference_point, number_of_blocks_after_reference_point); // TODO: it's possible that the returned synopsis is empty if the blockchain is empty (that's fine) // or if the reference point is now past our undo history (that's not). // in the second case, we should mark this peer as one we're unable to sync with and // disconnect them. if (reference_point != item_hash_t() && synopsis.empty()) FC_THROW_EXCEPTION(block_older_than_undo_history, "You are on a fork I'm unable to switch to"); #endif if( number_of_blocks_after_reference_point ) { // then the synopsis is incomplete, add the missing elements from ids_of_items_to_get uint32_t first_block_num_in_ids_to_get = _delegate->get_block_number(original_ids_of_items_to_get.front()); uint32_t true_high_block_num = first_block_num_in_ids_to_get + original_ids_of_items_to_get.size() - 1; // in order to generate a seamless synopsis, we need to be using the same low_block_num as the // backend code; the first block in the synopsis will be the low block number it used uint32_t low_block_num = synopsis.empty() ? 1 : _delegate->get_block_number(synopsis.front()); do { if( low_block_num >= first_block_num_in_ids_to_get ) synopsis.push_back(original_ids_of_items_to_get[low_block_num - first_block_num_in_ids_to_get]); low_block_num += (true_high_block_num - low_block_num + 2 ) / 2; } while ( low_block_num <= true_high_block_num ); assert(synopsis.back() == original_ids_of_items_to_get.back()); } return synopsis; } void node_impl::fetch_next_batch_of_item_ids_from_peer( peer_connection* peer, bool reset_fork_tracking_data_for_peer /* = false */ ) { VERIFY_CORRECT_THREAD(); if( reset_fork_tracking_data_for_peer ) { peer->last_block_delegate_has_seen = item_hash_t(); peer->last_block_time_delegate_has_seen = _delegate->get_block_time(item_hash_t()); } fc::oexception synopsis_exception; try { std::vector<item_hash_t> blockchain_synopsis = create_blockchain_synopsis_for_peer( peer ); item_hash_t last_item_seen = blockchain_synopsis.empty() ? item_hash_t() : blockchain_synopsis.back(); dlog( "sync: sending a request for the next items after ${last_item_seen} to peer ${peer}, (full request is ${blockchain_synopsis})", ( "last_item_seen", last_item_seen ) ( "peer", peer->get_remote_endpoint() ) ( "blockchain_synopsis", blockchain_synopsis ) ); peer->item_ids_requested_from_peer = boost::make_tuple( blockchain_synopsis, fc::time_point::now() ); peer->send_message( fetch_blockchain_item_ids_message(_sync_item_type, blockchain_synopsis ) ); } catch (const block_older_than_undo_history& e) { synopsis_exception = e; } if (synopsis_exception) disconnect_from_peer(peer, "You are on a fork I'm unable to switch to"); } void node_impl::on_blockchain_item_ids_inventory_message(peer_connection* originating_peer, const blockchain_item_ids_inventory_message& blockchain_item_ids_inventory_message_received ) { VERIFY_CORRECT_THREAD(); // ignore unless we asked for the data if( originating_peer->item_ids_requested_from_peer ) { // verify that the peer's the block ids the peer sent is a valid response to our request; // It should either be an empty list of blocks, or a list of blocks that builds off of one of // the blocks in the synopsis we sent if (!blockchain_item_ids_inventory_message_received.item_hashes_available.empty()) { // what's more, it should be a sequential list of blocks, verify that first uint32_t first_block_number_in_reponse = _delegate->get_block_number(blockchain_item_ids_inventory_message_received.item_hashes_available.front()); for (unsigned i = 1; i < blockchain_item_ids_inventory_message_received.item_hashes_available.size(); ++i) { uint32_t actual_num = _delegate->get_block_number(blockchain_item_ids_inventory_message_received.item_hashes_available[i]); uint32_t expected_num = first_block_number_in_reponse + i; if (actual_num != expected_num) { wlog("Invalid response from peer ${peer_endpoint}. The list of blocks they provided is not sequential, " "the ${position}th block in their reply was block number ${actual_num}, " "but it should have been number ${expected_num}", ("peer_endpoint", originating_peer->get_remote_endpoint()) ("position", i) ("actual_num", actual_num) ("expected_num", expected_num)); fc::exception error_for_peer(FC_LOG_MESSAGE(error, "You gave an invalid response to my request for sync blocks. The list of blocks you provided is not sequential, " "the ${position}th block in their reply was block number ${actual_num}, " "but it should have been number ${expected_num}", ("position", i) ("actual_num", actual_num) ("expected_num", expected_num))); disconnect_from_peer(originating_peer, "You gave an invalid response to my request for sync blocks", true, error_for_peer); return; } } const std::vector<item_hash_t>& synopsis_sent_in_request = originating_peer->item_ids_requested_from_peer->get<0>(); const item_hash_t& first_item_hash = blockchain_item_ids_inventory_message_received.item_hashes_available.front(); if (synopsis_sent_in_request.empty()) { // if we sent an empty synopsis, we were asking for all blocks, so the first block should be block 1 if (_delegate->get_block_number(first_item_hash) != 1) { wlog("Invalid response from peer ${peer_endpoint}. We requested a list of sync blocks starting from the beginning of the chain, " "but they provided a list of blocks starting with ${first_block}", ("peer_endpoint", originating_peer->get_remote_endpoint()) ("first_block", first_item_hash)); fc::exception error_for_peer(FC_LOG_MESSAGE(error, "You gave an invalid response for my request for sync blocks. I asked for blocks starting from the beginning of the chain, " "but you returned a list of blocks starting with ${first_block}", ("first_block", first_item_hash))); disconnect_from_peer(originating_peer, "You gave an invalid response to my request for sync blocks", true, error_for_peer); return; } } else // synopsis was not empty, we expect a response building off one of the blocks we sent { if (boost::range::find(synopsis_sent_in_request, first_item_hash) == synopsis_sent_in_request.end()) { wlog("Invalid response from peer ${peer_endpoint}. We requested a list of sync blocks based on the synopsis ${synopsis}, but they " "provided a list of blocks starting with ${first_block}", ("peer_endpoint", originating_peer->get_remote_endpoint()) ("synopsis", synopsis_sent_in_request) ("first_block", first_item_hash)); fc::exception error_for_peer(FC_LOG_MESSAGE(error, "You gave an invalid response for my request for sync blocks. I asked for blocks following something in " "${synopsis}, but you returned a list of blocks starting with ${first_block} which wasn't one of your choices", ("synopsis", synopsis_sent_in_request) ("first_block", first_item_hash))); disconnect_from_peer(originating_peer, "You gave an invalid response to my request for sync blocks", true, error_for_peer); return; } } } originating_peer->item_ids_requested_from_peer.reset(); // if exceptions are throw after clearing the item_ids_requested_from_peer (above), // it could leave our sync in a stalled state. Wrap a try/catch around the rest // of the function so we can log if this ever happens. try { dlog( "sync: received a list of ${count} available items from ${peer_endpoint}", ( "count", blockchain_item_ids_inventory_message_received.item_hashes_available.size() ) ( "peer_endpoint", originating_peer->get_remote_endpoint() ) ); //for( const item_hash_t& item_hash : blockchain_item_ids_inventory_message_received.item_hashes_available ) //{ // dlog( "sync: ${hash}", ("hash", item_hash ) ); //} // if the peer doesn't have any items after the one we asked for if( blockchain_item_ids_inventory_message_received.total_remaining_item_count == 0 && ( blockchain_item_ids_inventory_message_received.item_hashes_available.empty() || // there are no items in the peer's blockchain. this should only happen if our blockchain was empty when we requested, might want to verify that. ( blockchain_item_ids_inventory_message_received.item_hashes_available.size() == 1 && _delegate->has_item( item_id(blockchain_item_ids_inventory_message_received.item_type, blockchain_item_ids_inventory_message_received.item_hashes_available.front() ) ) ) ) && // we've already seen the last item in the peer's blockchain originating_peer->ids_of_items_to_get.empty() && originating_peer->number_of_unfetched_item_ids == 0 ) // <-- is the last check necessary? { dlog( "sync: peer said we're up-to-date, entering normal operation with this peer" ); originating_peer->we_need_sync_items_from_peer = false; uint32_t new_number_of_unfetched_items = calculate_unsynced_block_count_from_all_peers(); _total_number_of_unfetched_items = new_number_of_unfetched_items; if( new_number_of_unfetched_items == 0 ) _delegate->sync_status( blockchain_item_ids_inventory_message_received.item_type, 0 ); return; } std::deque<item_hash_t> item_hashes_received( blockchain_item_ids_inventory_message_received.item_hashes_available.begin(), blockchain_item_ids_inventory_message_received.item_hashes_available.end() ); originating_peer->number_of_unfetched_item_ids = blockchain_item_ids_inventory_message_received.total_remaining_item_count; // flush any items this peer sent us that we've already received and processed from another peer if (!item_hashes_received.empty() && originating_peer->ids_of_items_to_get.empty()) { bool is_first_item_for_other_peer = false; for (const peer_connection_ptr& peer : _active_connections) if (peer != originating_peer->shared_from_this() && !peer->ids_of_items_to_get.empty() && peer->ids_of_items_to_get.front() == blockchain_item_ids_inventory_message_received.item_hashes_available.front()) { dlog("The item ${newitem} is the first item for peer ${peer}", ("newitem", blockchain_item_ids_inventory_message_received.item_hashes_available.front()) ("peer", peer->get_remote_endpoint())); is_first_item_for_other_peer = true; break; } dlog("is_first_item_for_other_peer: ${is_first}. item_hashes_received.size() = ${size}", ("is_first", is_first_item_for_other_peer)("size", item_hashes_received.size())); if (!is_first_item_for_other_peer) { while (!item_hashes_received.empty() && _delegate->has_item(item_id(blockchain_item_ids_inventory_message_received.item_type, item_hashes_received.front()))) { assert(item_hashes_received.front() != item_hash_t()); originating_peer->last_block_delegate_has_seen = item_hashes_received.front(); originating_peer->last_block_time_delegate_has_seen = _delegate->get_block_time(item_hashes_received.front()); dlog("popping item because delegate has already seen it. peer ${peer}'s last block the delegate has seen is now ${block_id} (actual block #${actual_block_num})", ("peer", originating_peer->get_remote_endpoint()) ("block_id", originating_peer->last_block_delegate_has_seen) ("actual_block_num", _delegate->get_block_number(item_hashes_received.front()))); item_hashes_received.pop_front(); } dlog("after removing all items we have already seen, item_hashes_received.size() = ${size}", ("size", item_hashes_received.size())); } } else if (!item_hashes_received.empty()) { // we received a list of items and we already have a list of items to fetch from this peer. // In the normal case, this list will immediately follow the existing list, meaning the // last hash of our existing list will match the first hash of the new list. // In the much less likely case, we've received a partial list of items from the peer, then // the peer switched forks before sending us the remaining list. In this case, the first // hash in the new list may not be the last hash in the existing list (it may be earlier, or // it may not exist at all. // In either case, pop items off the back of our existing list until we find our first // item, then append our list. while (!originating_peer->ids_of_items_to_get.empty()) { if (item_hashes_received.front() != originating_peer->ids_of_items_to_get.back()) originating_peer->ids_of_items_to_get.pop_back(); else break; } if (originating_peer->ids_of_items_to_get.empty()) { // this happens when the peer has switched forks between the last inventory message and // this one, and there weren't any unfetched items in common // We don't know where in the blockchain the new front() actually falls, all we can // expect is that it is a block that we knew about because it should be one of the // blocks we sent in the initial synopsis. assert(_delegate->has_item(item_id(_sync_item_type, item_hashes_received.front()))); originating_peer->last_block_delegate_has_seen = item_hashes_received.front(); originating_peer->last_block_time_delegate_has_seen = _delegate->get_block_time(item_hashes_received.front()); item_hashes_received.pop_front(); } else { // the common simple case: the new list extends the old. pop off the duplicate element originating_peer->ids_of_items_to_get.pop_back(); } } if (!item_hashes_received.empty() && !originating_peer->ids_of_items_to_get.empty()) assert(item_hashes_received.front() != originating_peer->ids_of_items_to_get.back()); // append the remaining items to the peer's list boost::push_back(originating_peer->ids_of_items_to_get, item_hashes_received); originating_peer->number_of_unfetched_item_ids = blockchain_item_ids_inventory_message_received.total_remaining_item_count; // at any given time, there's a maximum number of blocks that can possibly be out there // [(now - genesis time) / block interval]. If they offer us more blocks than that, // they must be an attacker or have a buggy client. fc::time_point_sec minimum_time_of_last_offered_block = originating_peer->last_block_time_delegate_has_seen + // timestamp of the block immediately before the first unfetched block originating_peer->number_of_unfetched_item_ids * STEEM_BLOCK_INTERVAL; if (minimum_time_of_last_offered_block > _delegate->get_blockchain_now() + GRAPHENE_NET_FUTURE_SYNC_BLOCKS_GRACE_PERIOD_SEC) { wlog("Disconnecting from peer ${peer} who offered us an implausible number of blocks, their last block would be in the future (${timestamp})", ("peer", originating_peer->get_remote_endpoint()) ("timestamp", minimum_time_of_last_offered_block)); fc::exception error_for_peer(FC_LOG_MESSAGE(error, "You offered me a list of more sync blocks than could possibly exist. Total blocks offered: ${blocks}, Minimum time of the last block you offered: ${minimum_time_of_last_offered_block}, Now: ${now}", ("blocks", originating_peer->number_of_unfetched_item_ids) ("minimum_time_of_last_offered_block", minimum_time_of_last_offered_block) ("now", _delegate->get_blockchain_now()))); disconnect_from_peer(originating_peer, "You offered me a list of more sync blocks than could possibly exist", true, error_for_peer); return; } uint32_t new_number_of_unfetched_items = calculate_unsynced_block_count_from_all_peers(); if (new_number_of_unfetched_items != _total_number_of_unfetched_items) _delegate->sync_status(blockchain_item_ids_inventory_message_received.item_type, new_number_of_unfetched_items); _total_number_of_unfetched_items = new_number_of_unfetched_items; if (blockchain_item_ids_inventory_message_received.total_remaining_item_count != 0) { // the peer hasn't sent us all the items it knows about. if (originating_peer->ids_of_items_to_get.size() > GRAPHENE_NET_MIN_BLOCK_IDS_TO_PREFETCH) { // we have a good number of item ids from this peer, start fetching blocks from it; // we'll switch back later to finish the job. trigger_fetch_sync_items_loop(); } else { // keep fetching the peer's list of sync items until we get enough to switch into block- // fetchimg mode fetch_next_batch_of_item_ids_from_peer(originating_peer); } } else { // the peer has told us about all of the items it knows if (!originating_peer->ids_of_items_to_get.empty()) { // we now know about all of the items the peer knows about, and there are some items on the list // that we should try to fetch. Kick off the fetch loop. trigger_fetch_sync_items_loop(); } else { // If we get here, the peer has sent us a non-empty list of items, but we have already // received all of the items from other peers. Send a new request to the peer to // see if we're really in sync fetch_next_batch_of_item_ids_from_peer(originating_peer); } } } catch (const fc::canceled_exception&) { throw; } catch (const fc::exception& e) { elog("Caught unexpected exception: ${e}", ("e", e)); assert(false && "exceptions not expected here"); } catch (const std::exception& e) { elog("Caught unexpected exception: ${e}", ("e", e.what())); assert(false && "exceptions not expected here"); } catch (...) { elog("Caught unexpected exception, could break sync operation"); } } else { wlog("sync: received a list of sync items available, but I didn't ask for any!"); } } message node_impl::get_message_for_item(const item_id& item) { try { return _message_cache.get_message(item.item_hash); } catch (fc::key_not_found_exception&) {} try { return _delegate->get_item(item); } catch (fc::key_not_found_exception&) {} return item_not_available_message(item); } void node_impl::on_fetch_items_message(peer_connection* originating_peer, const fetch_items_message& fetch_items_message_received) { VERIFY_CORRECT_THREAD(); dlog("received items request for ids ${ids} of type ${type} from peer ${endpoint}", ("ids", fetch_items_message_received.items_to_fetch) ("type", fetch_items_message_received.item_type) ("endpoint", originating_peer->get_remote_endpoint())); fc::optional<message> last_block_message_sent; std::list<message> reply_messages; for (const item_hash_t& item_hash : fetch_items_message_received.items_to_fetch) { try { message requested_message = _message_cache.get_message(item_hash); dlog("received item request for item ${id} from peer ${endpoint}, returning the item from my message cache", ("endpoint", originating_peer->get_remote_endpoint()) ("id", requested_message.id())); reply_messages.push_back(requested_message); if (fetch_items_message_received.item_type == block_message_type) last_block_message_sent = requested_message; continue; } catch (fc::key_not_found_exception&) { // it wasn't in our local cache, that's ok ask the client } item_id item_to_fetch(fetch_items_message_received.item_type, item_hash); try { message requested_message = _delegate->get_item(item_to_fetch); dlog("received item request from peer ${endpoint}, returning the item from delegate with id ${id} size ${size}", ("id", requested_message.id()) ("size", requested_message.size) ("endpoint", originating_peer->get_remote_endpoint())); reply_messages.push_back(requested_message); if (fetch_items_message_received.item_type == block_message_type) last_block_message_sent = requested_message; continue; } catch (fc::key_not_found_exception&) { reply_messages.push_back(item_not_available_message(item_to_fetch)); dlog("received item request from peer ${endpoint} but we don't have it", ("endpoint", originating_peer->get_remote_endpoint())); } } // if we sent them a block, update our record of the last block they've seen accordingly if (last_block_message_sent) { graphene::net::block_message block = last_block_message_sent->as<graphene::net::block_message>(); originating_peer->last_block_delegate_has_seen = block.block_id; originating_peer->last_block_time_delegate_has_seen = _delegate->get_block_time(block.block_id); } for (const message& reply : reply_messages) { if (reply.msg_type == block_message_type) originating_peer->send_item(item_id(block_message_type, reply.as<graphene::net::block_message>().block_id)); else originating_peer->send_message(reply); } } void node_impl::on_item_not_available_message( peer_connection* originating_peer, const item_not_available_message& item_not_available_message_received ) { VERIFY_CORRECT_THREAD(); const item_id& requested_item = item_not_available_message_received.requested_item; auto regular_item_iter = originating_peer->items_requested_from_peer.find(requested_item); if (regular_item_iter != originating_peer->items_requested_from_peer.end()) { originating_peer->items_requested_from_peer.erase( regular_item_iter ); originating_peer->inventory_peer_advertised_to_us.erase( requested_item ); if (is_item_in_any_peers_inventory(requested_item)) _items_to_fetch.insert(prioritized_item_id(requested_item, _items_to_fetch_sequence_counter++)); wlog("Peer doesn't have the requested item."); trigger_fetch_items_loop(); return; } auto sync_item_iter = originating_peer->sync_items_requested_from_peer.find(requested_item.item_hash); if (sync_item_iter != originating_peer->sync_items_requested_from_peer.end()) { originating_peer->sync_items_requested_from_peer.erase(sync_item_iter); if (originating_peer->peer_needs_sync_items_from_us) originating_peer->inhibit_fetching_sync_blocks = true; else disconnect_from_peer(originating_peer, "You are missing a sync item you claim to have, your database is probably corrupted. Try --rebuild-index.",true, fc::exception(FC_LOG_MESSAGE(error,"You are missing a sync item you claim to have, your database is probably corrupted. Try --rebuild-index.", ("item_id", requested_item)))); wlog("Peer doesn't have the requested sync item. This really shouldn't happen"); trigger_fetch_sync_items_loop(); return; } dlog("Peer doesn't have an item we're looking for, which is fine because we weren't looking for it"); } void node_impl::on_item_ids_inventory_message(peer_connection* originating_peer, const item_ids_inventory_message& item_ids_inventory_message_received) { VERIFY_CORRECT_THREAD(); // expire old inventory so we'll be making decisions our about whether to fetch blocks below based only on recent inventory originating_peer->clear_old_inventory(); dlog( "received inventory of ${count} items from peer ${endpoint}", ( "count", item_ids_inventory_message_received.item_hashes_available.size() )("endpoint", originating_peer->get_remote_endpoint() ) ); for( const item_hash_t& item_hash : item_ids_inventory_message_received.item_hashes_available ) { if (_message_ids_currently_being_processed.find(item_hash) != _message_ids_currently_being_processed.end()) // we're in the middle of processing this item, no need to fetch it again continue; item_id advertised_item_id(item_ids_inventory_message_received.item_type, item_hash); if (_new_inventory.find(advertised_item_id) != _new_inventory.end()) // we've processed this item but haven't advertised it to our peers yet, don't fetch it again continue; bool we_advertised_this_item_to_a_peer = false; bool we_requested_this_item_from_a_peer = false; for (const peer_connection_ptr peer : _active_connections) { if (peer->inventory_advertised_to_peer.find(advertised_item_id) != peer->inventory_advertised_to_peer.end()) { we_advertised_this_item_to_a_peer = true; break; } if (peer->items_requested_from_peer.find(advertised_item_id) != peer->items_requested_from_peer.end()) we_requested_this_item_from_a_peer = true; } // if we have already advertised it to a peer, we must have it, no need to do anything else if (!we_advertised_this_item_to_a_peer) { // if the peer has flooded us with transactions, don't add these to the inventory to prevent our // inventory list from growing without bound. We try to allow fetching blocks even when // we've stopped fetching transactions. if ((item_ids_inventory_message_received.item_type == graphene::net::trx_message_type && originating_peer->is_inventory_advertised_to_us_list_full_for_transactions()) || originating_peer->is_inventory_advertised_to_us_list_full()) break; originating_peer->inventory_peer_advertised_to_us.insert(peer_connection::timestamped_item_id(advertised_item_id, fc::time_point::now())); if (!we_requested_this_item_from_a_peer) { if (_recently_failed_items.find(item_id(item_ids_inventory_message_received.item_type, item_hash)) != _recently_failed_items.end()) { dlog("not adding ${item_hash} to our list of items to fetch because we've recently fetched a copy and it failed to push", ("item_hash", item_hash)); } else { auto items_to_fetch_iter = _items_to_fetch.get<item_id_index>().find(advertised_item_id); if (items_to_fetch_iter == _items_to_fetch.get<item_id_index>().end()) { // it's new to us _items_to_fetch.insert(prioritized_item_id(advertised_item_id, _items_to_fetch_sequence_counter++)); dlog("adding item ${item_hash} from inventory message to our list of items to fetch", ("item_hash", item_hash)); trigger_fetch_items_loop(); } else { // another peer has told us about this item already, but this peer just told us it has the item // too, we can expect it to be around in this peer's cache for longer, so update its timestamp _items_to_fetch.get<item_id_index>().modify(items_to_fetch_iter, [](prioritized_item_id& item) { item.timestamp = fc::time_point::now(); }); } } } } } } void node_impl::on_closing_connection_message( peer_connection* originating_peer, const closing_connection_message& closing_connection_message_received ) { VERIFY_CORRECT_THREAD(); originating_peer->they_have_requested_close = true; if( closing_connection_message_received.closing_due_to_error ) { elog( "Peer ${peer} is disconnecting us because of an error: ${msg}, exception: ${error}", ( "peer", originating_peer->get_remote_endpoint() ) ( "msg", closing_connection_message_received.reason_for_closing ) ( "error", closing_connection_message_received.error ) ); std::ostringstream message; message << "Peer " << fc::variant( originating_peer->get_remote_endpoint() ).as_string() << " disconnected us: " << closing_connection_message_received.reason_for_closing; fc::exception detailed_error(FC_LOG_MESSAGE(warn, "Peer ${peer} is disconnecting us because of an error: ${msg}, exception: ${error}", ( "peer", originating_peer->get_remote_endpoint() ) ( "msg", closing_connection_message_received.reason_for_closing ) ( "error", closing_connection_message_received.error ) )); _delegate->error_encountered( message.str(), detailed_error ); } else { wlog( "Peer ${peer} is disconnecting us because: ${msg}", ( "peer", originating_peer->get_remote_endpoint() ) ( "msg", closing_connection_message_received.reason_for_closing ) ); } if( originating_peer->we_have_requested_close ) originating_peer->close_connection(); } void node_impl::on_connection_closed(peer_connection* originating_peer) { VERIFY_CORRECT_THREAD(); peer_connection_ptr originating_peer_ptr = originating_peer->shared_from_this(); _rate_limiter.remove_tcp_socket( &originating_peer->get_socket() ); // if we closed the connection (due to timeout or handshake failure), we should have recorded an // error message to store in the peer database when we closed the connection fc::optional<fc::ip::endpoint> inbound_endpoint = originating_peer->get_endpoint_for_connecting(); if (originating_peer->connection_closed_error && inbound_endpoint) { fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*inbound_endpoint); if (updated_peer_record) { updated_peer_record->last_error = *originating_peer->connection_closed_error; _potential_peer_db.update_entry(*updated_peer_record); } } _closing_connections.erase(originating_peer_ptr); _handshaking_connections.erase(originating_peer_ptr); _terminating_connections.erase(originating_peer_ptr); if (_active_connections.find(originating_peer_ptr) != _active_connections.end()) { _active_connections.erase(originating_peer_ptr); if (inbound_endpoint && originating_peer_ptr->get_remote_endpoint()) { fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*inbound_endpoint); if (updated_peer_record) { updated_peer_record->last_seen_time = fc::time_point::now(); _potential_peer_db.update_entry(*updated_peer_record); } } } ilog("Remote peer ${endpoint} closed their connection to us", ("endpoint", originating_peer->get_remote_endpoint())); display_current_connections(); trigger_p2p_network_connect_loop(); // notify the node delegate so it can update the display if( _active_connections.size() != _last_reported_number_of_connections ) { _last_reported_number_of_connections = (uint32_t)_active_connections.size(); _delegate->connection_count_changed( _last_reported_number_of_connections ); } // if we had delegated a firewall check to this peer, send it to another peer if (originating_peer->firewall_check_state) { if (originating_peer->firewall_check_state->requesting_peer != node_id_t()) { // it's a check we're doing for another node firewall_check_state_data* firewall_check_state = originating_peer->firewall_check_state; originating_peer->firewall_check_state = nullptr; forward_firewall_check_to_next_available_peer(firewall_check_state); } else { // we were asking them to check whether we're firewalled. we'll just let it // go for now delete originating_peer->firewall_check_state; } } // if we had requested any sync or regular items from this peer that we haven't // received yet, reschedule them to be fetched from another peer if (!originating_peer->sync_items_requested_from_peer.empty()) { for (const auto& sync_item : originating_peer->sync_items_requested_from_peer) _active_sync_requests.erase(sync_item); trigger_fetch_sync_items_loop(); } if (!originating_peer->items_requested_from_peer.empty()) { for (const auto& item_and_time : originating_peer->items_requested_from_peer) { if (is_item_in_any_peers_inventory(item_and_time.first)) _items_to_fetch.insert(prioritized_item_id(item_and_time.first, _items_to_fetch_sequence_counter++)); } trigger_fetch_items_loop(); } schedule_peer_for_deletion(originating_peer_ptr); } void node_impl::send_sync_block_to_node_delegate(const graphene::net::block_message& block_message_to_send) { dlog("in send_sync_block_to_node_delegate()"); bool client_accepted_block = false; bool discontinue_fetching_blocks_from_peer = false; fc::oexception handle_message_exception; try { std::vector<fc::uint160_t> contained_transaction_message_ids; fc_ilog(fc::logger::get("sync"), "p2p pushing sync block #${block_num} ${block_hash}", ("block_num", block_message_to_send.block.block_num()) ("block_hash", block_message_to_send.block_id)); _delegate->handle_block(block_message_to_send, true, contained_transaction_message_ids); ilog("Successfully pushed sync block ${num} (id:${id})", ("num", block_message_to_send.block.block_num()) ("id", block_message_to_send.block_id)); _most_recent_blocks_accepted.push_back(block_message_to_send.block_id); client_accepted_block = true; } catch (const block_older_than_undo_history& e) { fc_wlog(fc::logger::get("sync"), "p2p failed to push sync block #${block_num} ${block_hash}: block is on a fork older than our undo history would " "allow us to switch to: ${e}", ("block_num", block_message_to_send.block.block_num()) ("block_hash", block_message_to_send.block_id) ("e", (fc::exception)e)); wlog("Failed to push sync block ${num} (id:${id}): block is on a fork older than our undo history would " "allow us to switch to: ${e}", ("num", block_message_to_send.block.block_num()) ("id", block_message_to_send.block_id) ("e", (fc::exception)e)); handle_message_exception = e; discontinue_fetching_blocks_from_peer = true; } catch (const fc::canceled_exception&) { throw; } catch (const fc::exception& e) { fc_wlog(fc::logger::get("sync"), "p2p failed to push sync block #${block_num} ${block_hash}: client rejected sync block sent by peer: ${e}", ("block_num", block_message_to_send.block.block_num()) ("block_hash", block_message_to_send.block_id)("e", e)); wlog("Failed to push sync block ${num} (id:${id}): client rejected sync block sent by peer: ${e}", ("num", block_message_to_send.block.block_num()) ("id", block_message_to_send.block_id) ("e", e)); handle_message_exception = e; } // build up lists for any potentially-blocking operations we need to do, then do them // at the end of this function std::set<peer_connection_ptr> peers_with_newly_empty_item_lists; std::set<peer_connection_ptr> peers_we_need_to_sync_to; std::map<peer_connection_ptr, std::pair<std::string, fc::oexception> > peers_to_disconnect; // map peer -> pair<reason_string, exception> if( client_accepted_block ) { --_total_number_of_unfetched_items; dlog("sync: client accpted the block, we now have only ${count} items left to fetch before we're in sync", ("count", _total_number_of_unfetched_items)); bool is_fork_block = is_hard_fork_block(block_message_to_send.block.block_num()); for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections bool disconnecting_this_peer = false; if (is_fork_block) { // we just pushed a hard fork block. Find out if this peer is running a client // that will be unable to process future blocks if (peer->last_known_fork_block_number != 0) { uint32_t next_fork_block_number = get_next_known_hard_fork_block_number(peer->last_known_fork_block_number); if (next_fork_block_number != 0 && next_fork_block_number <= block_message_to_send.block.block_num()) { std::ostringstream disconnect_reason_stream; disconnect_reason_stream << "You need to upgrade your client due to hard fork at block " << block_message_to_send.block.block_num(); peers_to_disconnect[peer] = std::make_pair(disconnect_reason_stream.str(), fc::oexception(fc::exception(FC_LOG_MESSAGE(error, "You need to upgrade your client due to hard fork at block ${block_number}", ("block_number", block_message_to_send.block.block_num()))))); #ifdef ENABLE_DEBUG_ULOGS ulog("Disconnecting from peer during sync because their version is too old. Their version date: ${date}", ("date", peer->graphene_git_revision_unix_timestamp)); #endif disconnecting_this_peer = true; } } } if (!disconnecting_this_peer && peer->ids_of_items_to_get.empty() && peer->ids_of_items_being_processed.empty()) { dlog( "Cannot pop first element off peer ${peer}'s list, its list is empty", ("peer", peer->get_remote_endpoint() ) ); // we don't know for sure that this peer has the item we just received. // If peer is still syncing to us, we know they will ask us for // sync item ids at least one more time and we'll notify them about // the item then, so there's no need to do anything. If we still need items // from them, we'll be asking them for more items at some point, and // that will clue them in that they are out of sync. If we're fully in sync // we need to kick off another round of synchronization with them so they can // find out about the new item. if (!peer->peer_needs_sync_items_from_us && !peer->we_need_sync_items_from_peer) { dlog("We will be restarting synchronization with peer ${peer}", ("peer", peer->get_remote_endpoint())); peers_we_need_to_sync_to.insert(peer); } } else if (!disconnecting_this_peer) { auto items_being_processed_iter = peer->ids_of_items_being_processed.find(block_message_to_send.block_id); if (items_being_processed_iter != peer->ids_of_items_being_processed.end()) { peer->last_block_delegate_has_seen = block_message_to_send.block_id; peer->last_block_time_delegate_has_seen = block_message_to_send.block.timestamp; peer->ids_of_items_being_processed.erase(items_being_processed_iter); dlog("Removed item from ${endpoint}'s list of items being processed, still processing ${len} blocks", ("endpoint", peer->get_remote_endpoint())("len", peer->ids_of_items_being_processed.size())); // if we just received the last item in our list from this peer, we will want to // send another request to find out if we are in sync, but we can't do this yet // (we don't want to allow a fiber swap in the middle of popping items off the list) if (peer->ids_of_items_to_get.empty() && peer->number_of_unfetched_item_ids == 0 && peer->ids_of_items_being_processed.empty()) peers_with_newly_empty_item_lists.insert(peer); // in this case, we know the peer was offering us this exact item, no need to // try to inform them of its existence } } } } else { // invalid message received for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections if (peer->ids_of_items_being_processed.find(block_message_to_send.block_id) != peer->ids_of_items_being_processed.end()) { if (discontinue_fetching_blocks_from_peer) { wlog("inhibiting fetching sync blocks from peer ${endpoint} because it is on a fork that's too old", ("endpoint", peer->get_remote_endpoint())); peer->inhibit_fetching_sync_blocks = true; } else peers_to_disconnect[peer] = std::make_pair(std::string("You offered us a block that we reject as invalid"), fc::oexception(handle_message_exception)); } } } for (auto& peer_to_disconnect : peers_to_disconnect) { const peer_connection_ptr& peer = peer_to_disconnect.first; std::string reason_string; fc::oexception reason_exception; std::tie(reason_string, reason_exception) = peer_to_disconnect.second; wlog("disconnecting client ${endpoint} because it offered us the rejected block", ("endpoint", peer->get_remote_endpoint())); disconnect_from_peer(peer.get(), reason_string, true, reason_exception); } for (const peer_connection_ptr& peer : peers_with_newly_empty_item_lists) fetch_next_batch_of_item_ids_from_peer(peer.get()); for (const peer_connection_ptr& peer : peers_we_need_to_sync_to) start_synchronizing_with_peer(peer); dlog("Leaving send_sync_block_to_node_delegate"); if (// _suspend_fetching_sync_blocks && <-- you can use this if "maximum_number_of_blocks_to_handle_at_one_time" == "maximum_number_of_sync_blocks_to_prefetch" !_node_is_shutting_down && (!_process_backlog_of_sync_blocks_done.valid() || _process_backlog_of_sync_blocks_done.ready())) _process_backlog_of_sync_blocks_done = fc::async([=](){ process_backlog_of_sync_blocks(); }, "process_backlog_of_sync_blocks"); } void node_impl::process_backlog_of_sync_blocks() { VERIFY_CORRECT_THREAD(); // garbage-collect the list of async tasks here for lack of a better place for (auto calls_iter = _handle_message_calls_in_progress.begin(); calls_iter != _handle_message_calls_in_progress.end();) { if (calls_iter->ready()) calls_iter = _handle_message_calls_in_progress.erase(calls_iter); else ++calls_iter; } dlog("in process_backlog_of_sync_blocks"); if (_handle_message_calls_in_progress.size() >= _node_configuration.maximum_number_of_blocks_to_handle_at_one_time) { dlog("leaving process_backlog_of_sync_blocks because we're already processing too many blocks"); return; // we will be rescheduled when the next block finishes its processing } dlog("currently ${count} blocks in the process of being handled", ("count", _handle_message_calls_in_progress.size())); if (_suspend_fetching_sync_blocks) { dlog("resuming processing sync block backlog because we only ${count} blocks in progress", ("count", _handle_message_calls_in_progress.size())); _suspend_fetching_sync_blocks = false; } // when syncing with multiple peers, it's possible that we'll have hundreds of blocks ready to push // to the client at once. This can be slow, and we need to limit the number we push at any given // time to allow network traffic to continue so we don't end up disconnecting from peers //fc::time_point start_time = fc::time_point::now(); //fc::time_point when_we_should_yield = start_time + fc::seconds(1); bool block_processed_this_iteration; unsigned blocks_processed = 0; std::set<peer_connection_ptr> peers_with_newly_empty_item_lists; std::set<peer_connection_ptr> peers_we_need_to_sync_to; std::map<peer_connection_ptr, fc::oexception> peers_with_rejected_block; do { std::copy(std::make_move_iterator(_new_received_sync_items.begin()), std::make_move_iterator(_new_received_sync_items.end()), std::front_inserter(_received_sync_items)); _new_received_sync_items.clear(); dlog("currently ${count} sync items to consider", ("count", _received_sync_items.size())); block_processed_this_iteration = false; for (auto received_block_iter = _received_sync_items.begin(); received_block_iter != _received_sync_items.end(); ++received_block_iter) { // find out if this block is the next block on the active chain or one of the forks bool potential_first_block = false; for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections if (!peer->ids_of_items_to_get.empty() && peer->ids_of_items_to_get.front() == received_block_iter->block_id) { potential_first_block = true; peer->ids_of_items_to_get.pop_front(); peer->ids_of_items_being_processed.insert(received_block_iter->block_id); } } // if it is, process it, remove it from all sync peers lists if (potential_first_block) { // we can get into an interesting situation near the end of synchronization. We can be in // sync with one peer who is sending us the last block on the chain via a regular inventory // message, while at the same time still be synchronizing with a peer who is sending us the // block through the sync mechanism. Further, we must request both blocks because // we don't know they're the same (for the peer in normal operation, it has only told us the // message id, for the peer in the sync case we only known the block_id). if (std::find(_most_recent_blocks_accepted.begin(), _most_recent_blocks_accepted.end(), received_block_iter->block_id) == _most_recent_blocks_accepted.end()) { graphene::net::block_message block_message_to_process = *received_block_iter; _received_sync_items.erase(received_block_iter); _handle_message_calls_in_progress.emplace_back(fc::async([this, block_message_to_process](){ send_sync_block_to_node_delegate(block_message_to_process); }, "send_sync_block_to_node_delegate")); ++blocks_processed; block_processed_this_iteration = true; } else { dlog("Already received and accepted this block (presumably through normal inventory mechanism), treating it as accepted"); std::vector< peer_connection_ptr > peers_needing_next_batch; for (const peer_connection_ptr& peer : _active_connections) { auto items_being_processed_iter = peer->ids_of_items_being_processed.find(received_block_iter->block_id); if (items_being_processed_iter != peer->ids_of_items_being_processed.end()) { peer->ids_of_items_being_processed.erase(items_being_processed_iter); dlog("Removed item from ${endpoint}'s list of items being processed, still processing ${len} blocks", ("endpoint", peer->get_remote_endpoint())("len", peer->ids_of_items_being_processed.size())); // if we just processed the last item in our list from this peer, we will want to // send another request to find out if we are now in sync (this is normally handled in // send_sync_block_to_node_delegate) if (peer->ids_of_items_to_get.empty() && peer->number_of_unfetched_item_ids == 0 && peer->ids_of_items_being_processed.empty()) { dlog("We received last item in our list for peer ${endpoint}, setup to do a sync check", ("endpoint", peer->get_remote_endpoint())); peers_needing_next_batch.push_back( peer ); } } } for( const peer_connection_ptr& peer : peers_needing_next_batch ) fetch_next_batch_of_item_ids_from_peer(peer.get()); } break; // start iterating _received_sync_items from the beginning } // end if potential_first_block } // end for each block in _received_sync_items if (_handle_message_calls_in_progress.size() >= _node_configuration.maximum_number_of_blocks_to_handle_at_one_time) { dlog("stopping processing sync block backlog because we have ${count} blocks in progress", ("count", _handle_message_calls_in_progress.size())); //ulog("stopping processing sync block backlog because we have ${count} blocks in progress, total on hand: ${received}", // ("count", _handle_message_calls_in_progress.size())("received", _received_sync_items.size())); if (_received_sync_items.size() >= _node_configuration.maximum_number_of_sync_blocks_to_prefetch) _suspend_fetching_sync_blocks = true; break; } } while (block_processed_this_iteration); dlog("leaving process_backlog_of_sync_blocks, ${count} processed", ("count", blocks_processed)); if (!_suspend_fetching_sync_blocks) trigger_fetch_sync_items_loop(); } void node_impl::trigger_process_backlog_of_sync_blocks() { if (!_node_is_shutting_down && (!_process_backlog_of_sync_blocks_done.valid() || _process_backlog_of_sync_blocks_done.ready())) _process_backlog_of_sync_blocks_done = fc::async([=](){ process_backlog_of_sync_blocks(); }, "process_backlog_of_sync_blocks"); } void node_impl::process_block_during_sync( peer_connection* originating_peer, const graphene::net::block_message& block_message_to_process, const message_hash_type& message_hash ) { VERIFY_CORRECT_THREAD(); dlog( "received a sync block from peer ${endpoint}", ("endpoint", originating_peer->get_remote_endpoint() ) ); // add it to the front of _received_sync_items, then process _received_sync_items to try to // pass as many messages as possible to the client. _new_received_sync_items.push_front( block_message_to_process ); trigger_process_backlog_of_sync_blocks(); } void node_impl::process_block_during_normal_operation( peer_connection* originating_peer, const graphene::net::block_message& block_message_to_process, const message_hash_type& message_hash ) { fc::time_point message_receive_time = fc::time_point::now(); dlog( "received a block from peer ${endpoint}, passing it to client", ("endpoint", originating_peer->get_remote_endpoint() ) ); std::set<peer_connection_ptr> peers_to_disconnect; std::string disconnect_reason; fc::oexception disconnect_exception; fc::oexception restart_sync_exception; try { // we can get into an intersting situation near the end of synchronization. We can be in // sync with one peer who is sending us the last block on the chain via a regular inventory // message, while at the same time still be synchronizing with a peer who is sending us the // block through the sync mechanism. Further, we must request both blocks because // we don't know they're the same (for the peer in normal operation, it has only told us the // message id, for the peer in the sync case we only known the block_id). fc::time_point message_validated_time; if (std::find(_most_recent_blocks_accepted.begin(), _most_recent_blocks_accepted.end(), block_message_to_process.block_id) == _most_recent_blocks_accepted.end()) { std::vector<fc::uint160_t> contained_transaction_message_ids; _message_ids_currently_being_processed.insert(message_hash); fc_ilog(fc::logger::get("sync"), "p2p pushing block #${block_num} ${block_hash} from ${peer} (message_id was ${id})", ("block_num", block_message_to_process.block.block_num()) ("block_hash", block_message_to_process.block_id) ("peer", originating_peer->get_remote_endpoint())("id", message_hash)); _delegate->handle_block(block_message_to_process, false, contained_transaction_message_ids); _message_ids_currently_being_processed.erase(message_hash); message_validated_time = fc::time_point::now(); ilog("Successfully pushed block ${num} (id:${id})", ("num", block_message_to_process.block.block_num()) ("id", block_message_to_process.block_id)); _most_recent_blocks_accepted.push_back(block_message_to_process.block_id); bool new_transaction_discovered = false; for (const item_hash_t& transaction_message_hash : contained_transaction_message_ids) { _items_to_fetch.get<item_id_index>().erase(item_id(trx_message_type, transaction_message_hash)); // there are two ways we could behave here: we could either act as if we received // the transaction outside the block and offer it to our peers, or we could just // forget about it (we would still advertise this block to our peers so they should // get the transaction through that mechanism). // We take the second approach, bring in the next if block to try the first approach //if (items_erased) //{ // new_transaction_discovered = true; // _new_inventory.insert(item_id(trx_message_type, transaction_message_hash)); //} } if (new_transaction_discovered) trigger_advertise_inventory_loop(); } else { fc_ilog(fc::logger::get("sync"), "p2p NOT pushing block #${block_num} ${block_hash} from ${peer} because we recently pushed it", ("block_num", block_message_to_process.block.block_num()) ("block_hash", block_message_to_process.block_id) ("peer", originating_peer->get_remote_endpoint())("id", message_hash)); dlog( "Already received and accepted this block (presumably through sync mechanism), treating it as accepted" ); } dlog( "client validated the block, advertising it to other peers" ); item_id block_message_item_id(core_message_type_enum::block_message_type, message_hash); uint32_t block_number = block_message_to_process.block.block_num(); fc::time_point_sec block_time = block_message_to_process.block.timestamp; for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections auto iter = peer->inventory_peer_advertised_to_us.find(block_message_item_id); if (iter != peer->inventory_peer_advertised_to_us.end()) { // this peer offered us the item. It will eventually expire from the peer's // inventory_peer_advertised_to_us list after some time has passed (currently 2 minutes). // For now, it will remain there, which will prevent us from offering the peer this // block back when we rebroadcast the block below peer->last_block_delegate_has_seen = block_message_to_process.block_id; peer->last_block_time_delegate_has_seen = block_time; } peer->clear_old_inventory(); } message_propagation_data propagation_data{message_receive_time, message_validated_time, originating_peer->node_id}; broadcast( block_message_to_process, propagation_data ); _message_cache.block_accepted(); if (is_hard_fork_block(block_number)) { // we just pushed a hard fork block. Find out if any of our peers are running clients // that will be unable to process future blocks for (const peer_connection_ptr& peer : _active_connections) { if (peer->last_known_fork_block_number != 0) { uint32_t next_fork_block_number = get_next_known_hard_fork_block_number(peer->last_known_fork_block_number); if (next_fork_block_number != 0 && next_fork_block_number <= block_number) { peers_to_disconnect.insert(peer); #ifdef ENABLE_DEBUG_ULOGS ulog("Disconnecting from peer because their version is too old. Their version date: ${date}", ("date", peer->graphene_git_revision_unix_timestamp)); #endif } } } if (!peers_to_disconnect.empty()) { std::ostringstream disconnect_reason_stream; disconnect_reason_stream << "You need to upgrade your client due to hard fork at block " << block_number; disconnect_reason = disconnect_reason_stream.str(); disconnect_exception = fc::exception(FC_LOG_MESSAGE(error, "You need to upgrade your client due to hard fork at block ${block_number}", ("block_number", block_number))); } } } catch (const fc::canceled_exception&) { throw; } catch (const unlinkable_block_exception& e) { restart_sync_exception = e; } catch (const fc::exception& e) { // client rejected the block. Disconnect the client and any other clients that offered us this block wlog("Failed to push block ${num} (id:${id}), client rejected block sent by peer", ("num", block_message_to_process.block.block_num()) ("id", block_message_to_process.block_id)); disconnect_exception = e; disconnect_reason = "You offered me a block that I have deemed to be invalid"; peers_to_disconnect.insert( originating_peer->shared_from_this() ); for (const peer_connection_ptr& peer : _active_connections) if (!peer->ids_of_items_to_get.empty() && peer->ids_of_items_to_get.front() == block_message_to_process.block_id) peers_to_disconnect.insert(peer); } if (restart_sync_exception) { wlog("Peer ${peer} sent me a block that didn't link to our blockchain. Restarting sync mode with them to get the missing block. " "Error pushing block was: ${e}", ("peer", originating_peer->get_remote_endpoint()) ("e", *restart_sync_exception)); start_synchronizing_with_peer(originating_peer->shared_from_this()); } for (const peer_connection_ptr& peer : peers_to_disconnect) { wlog("disconnecting client ${endpoint} because it offered us the rejected block", ("endpoint", peer->get_remote_endpoint())); disconnect_from_peer(peer.get(), disconnect_reason, true, *disconnect_exception); } } void node_impl::process_block_message(peer_connection* originating_peer, const message& message_to_process, const message_hash_type& message_hash) { VERIFY_CORRECT_THREAD(); // find out whether we requested this item while we were synchronizing or during normal operation // (it's possible that we request an item during normal operation and then get kicked into sync // mode before we receive and process the item. In that case, we should process the item as a normal // item to avoid confusing the sync code) graphene::net::block_message block_message_to_process(message_to_process.as<graphene::net::block_message>()); auto item_iter = originating_peer->items_requested_from_peer.find(item_id(graphene::net::block_message_type, message_hash)); if (item_iter != originating_peer->items_requested_from_peer.end()) { originating_peer->items_requested_from_peer.erase(item_iter); process_block_during_normal_operation(originating_peer, block_message_to_process, message_hash); if (originating_peer->idle()) trigger_fetch_items_loop(); return; } else { // not during normal operation. see if we requested it during sync auto sync_item_iter = originating_peer->sync_items_requested_from_peer.find( block_message_to_process.block_id); if (sync_item_iter != originating_peer->sync_items_requested_from_peer.end()) { originating_peer->sync_items_requested_from_peer.erase(sync_item_iter); // if exceptions are throw here after removing the sync item from the list (above), // it could leave our sync in a stalled state. Wrap a try/catch around the rest // of the function so we can log if this ever happens. try { originating_peer->last_sync_item_received_time = fc::time_point::now(); _active_sync_requests.erase(block_message_to_process.block_id); process_block_during_sync(originating_peer, block_message_to_process, message_hash); if (originating_peer->idle()) { // we have finished fetching a batch of items, so we either need to grab another batch of items // or we need to get another list of item ids. if (originating_peer->number_of_unfetched_item_ids > 0 && originating_peer->ids_of_items_to_get.size() < GRAPHENE_NET_MIN_BLOCK_IDS_TO_PREFETCH) fetch_next_batch_of_item_ids_from_peer(originating_peer); else trigger_fetch_sync_items_loop(); } return; } catch (const fc::canceled_exception& e) { throw; } catch (const fc::exception& e) { elog("Caught unexpected exception: ${e}", ("e", e)); assert(false && "exceptions not expected here"); } catch (const std::exception& e) { elog("Caught unexpected exception: ${e}", ("e", e.what())); assert(false && "exceptions not expected here"); } catch (...) { elog("Caught unexpected exception, could break sync operation"); } } } // if we get here, we didn't request the message, we must have a misbehaving peer wlog("received a block ${block_id} I didn't ask for from peer ${endpoint}, disconnecting from peer", ("endpoint", originating_peer->get_remote_endpoint()) ("block_id", block_message_to_process.block_id)); fc::exception detailed_error(FC_LOG_MESSAGE(error, "You sent me a block that I didn't ask for, block_id: ${block_id}", ("block_id", block_message_to_process.block_id) ("graphene_git_revision_sha", originating_peer->graphene_git_revision_sha) ("graphene_git_revision_unix_timestamp", originating_peer->graphene_git_revision_unix_timestamp) ("fc_git_revision_sha", originating_peer->fc_git_revision_sha) ("fc_git_revision_unix_timestamp", originating_peer->fc_git_revision_unix_timestamp))); disconnect_from_peer(originating_peer, "You sent me a block that I didn't ask for", true, detailed_error); } void node_impl::on_current_time_request_message(peer_connection* originating_peer, const current_time_request_message& current_time_request_message_received) { VERIFY_CORRECT_THREAD(); fc::time_point request_received_time(fc::time_point::now()); current_time_reply_message reply(current_time_request_message_received.request_sent_time, request_received_time); originating_peer->send_message(reply, offsetof(current_time_reply_message, reply_transmitted_time)); } void node_impl::on_current_time_reply_message(peer_connection* originating_peer, const current_time_reply_message& current_time_reply_message_received) { VERIFY_CORRECT_THREAD(); fc::time_point reply_received_time = fc::time_point::now(); originating_peer->clock_offset = fc::microseconds(((current_time_reply_message_received.request_received_time - current_time_reply_message_received.request_sent_time) + (current_time_reply_message_received.reply_transmitted_time - reply_received_time)).count() / 2); originating_peer->round_trip_delay = (reply_received_time - current_time_reply_message_received.request_sent_time) - (current_time_reply_message_received.reply_transmitted_time - current_time_reply_message_received.request_received_time); } void node_impl::forward_firewall_check_to_next_available_peer(firewall_check_state_data* firewall_check_state) { for (const peer_connection_ptr& peer : _active_connections) { if (firewall_check_state->expected_node_id != peer->node_id && // it's not the node who is asking us to test !peer->firewall_check_state && // the peer isn't already performing a check for another node firewall_check_state->nodes_already_tested.find(peer->node_id) == firewall_check_state->nodes_already_tested.end() && peer->core_protocol_version >= 106) { wlog("forwarding firewall check for node ${to_check} to peer ${checker}", ("to_check", firewall_check_state->endpoint_to_test) ("checker", peer->get_remote_endpoint())); firewall_check_state->nodes_already_tested.insert(peer->node_id); peer->firewall_check_state = firewall_check_state; check_firewall_message check_request; check_request.endpoint_to_check = firewall_check_state->endpoint_to_test; check_request.node_id = firewall_check_state->expected_node_id; peer->send_message(check_request); return; } } wlog("Unable to forward firewall check for node ${to_check} to any other peers, returning 'unable'", ("to_check", firewall_check_state->endpoint_to_test)); peer_connection_ptr originating_peer = get_peer_by_node_id(firewall_check_state->expected_node_id); if (originating_peer) { check_firewall_reply_message reply; reply.node_id = firewall_check_state->expected_node_id; reply.endpoint_checked = firewall_check_state->endpoint_to_test; reply.result = firewall_check_result::unable_to_check; originating_peer->send_message(reply); } delete firewall_check_state; } void node_impl::on_check_firewall_message(peer_connection* originating_peer, const check_firewall_message& check_firewall_message_received) { VERIFY_CORRECT_THREAD(); if (check_firewall_message_received.node_id == node_id_t() && check_firewall_message_received.endpoint_to_check == fc::ip::endpoint()) { // originating_peer is asking us to test whether it is firewalled // we're not going to try to connect back to the originating peer directly, // instead, we're going to coordinate requests by asking some of our peers // to try to connect to the originating peer, and relay the results back wlog("Peer ${peer} wants us to check whether it is firewalled", ("peer", originating_peer->get_remote_endpoint())); firewall_check_state_data* firewall_check_state = new firewall_check_state_data; // if they are using the same inbound and outbound port, try connecting to their outbound endpoint. // if they are using a different inbound port, use their outbound address but the inbound port they reported fc::ip::endpoint endpoint_to_check = originating_peer->get_socket().remote_endpoint(); if (originating_peer->inbound_port != originating_peer->outbound_port) endpoint_to_check = fc::ip::endpoint(endpoint_to_check.get_address(), originating_peer->inbound_port); firewall_check_state->endpoint_to_test = endpoint_to_check; firewall_check_state->expected_node_id = originating_peer->node_id; firewall_check_state->requesting_peer = originating_peer->node_id; forward_firewall_check_to_next_available_peer(firewall_check_state); } else { // we're being asked to check another node // first, find out if we're currently connected to that node. If we are, we // can't perform the test if (is_already_connected_to_id(check_firewall_message_received.node_id) || is_connection_to_endpoint_in_progress(check_firewall_message_received.endpoint_to_check)) { check_firewall_reply_message reply; reply.node_id = check_firewall_message_received.node_id; reply.endpoint_checked = check_firewall_message_received.endpoint_to_check; reply.result = firewall_check_result::unable_to_check; } else { // we're not connected to them, so we need to set up a connection to them // to test. peer_connection_ptr peer_for_testing(peer_connection::make_shared(this)); peer_for_testing->firewall_check_state = new firewall_check_state_data; peer_for_testing->firewall_check_state->endpoint_to_test = check_firewall_message_received.endpoint_to_check; peer_for_testing->firewall_check_state->expected_node_id = check_firewall_message_received.node_id; peer_for_testing->firewall_check_state->requesting_peer = originating_peer->node_id; peer_for_testing->set_remote_endpoint(check_firewall_message_received.endpoint_to_check); initiate_connect_to(peer_for_testing); } } } void node_impl::on_check_firewall_reply_message(peer_connection* originating_peer, const check_firewall_reply_message& check_firewall_reply_message_received) { VERIFY_CORRECT_THREAD(); if (originating_peer->firewall_check_state && originating_peer->firewall_check_state->requesting_peer != node_id_t()) { // then this is a peer that is helping us check the firewalled state of one of our other peers // and they're reporting back // if they got a result, return it to the original peer. if they were unable to check, // we'll try another peer. wlog("Peer ${reporter} reports firewall check status ${status} for ${peer}", ("reporter", originating_peer->get_remote_endpoint()) ("status", check_firewall_reply_message_received.result) ("peer", check_firewall_reply_message_received.endpoint_checked)); if (check_firewall_reply_message_received.result == firewall_check_result::unable_to_connect || check_firewall_reply_message_received.result == firewall_check_result::connection_successful) { peer_connection_ptr original_peer = get_peer_by_node_id(originating_peer->firewall_check_state->requesting_peer); if (original_peer) { if (check_firewall_reply_message_received.result == firewall_check_result::connection_successful) { // if we previously thought this peer was firewalled, mark them as not firewalled if (original_peer->is_firewalled != firewalled_state::not_firewalled) { original_peer->is_firewalled = firewalled_state::not_firewalled; // there should be no old entry if we thought they were firewalled, so just create a new one fc::optional<fc::ip::endpoint> inbound_endpoint = originating_peer->get_endpoint_for_connecting(); if (inbound_endpoint) { potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(*inbound_endpoint); updated_peer_record.last_seen_time = fc::time_point::now(); _potential_peer_db.update_entry(updated_peer_record); } } } original_peer->send_message(check_firewall_reply_message_received); } delete originating_peer->firewall_check_state; originating_peer->firewall_check_state = nullptr; } else { // they were unable to check for us, ask another peer firewall_check_state_data* firewall_check_state = originating_peer->firewall_check_state; originating_peer->firewall_check_state = nullptr; forward_firewall_check_to_next_available_peer(firewall_check_state); } } else if (originating_peer->firewall_check_state) { // this is a reply to a firewall check we initiated. wlog("Firewall check we initiated has returned with result: ${result}, endpoint = ${endpoint}", ("result", check_firewall_reply_message_received.result) ("endpoint", check_firewall_reply_message_received.endpoint_checked)); if (check_firewall_reply_message_received.result == firewall_check_result::connection_successful) { _is_firewalled = firewalled_state::not_firewalled; _publicly_visible_listening_endpoint = check_firewall_reply_message_received.endpoint_checked; } else if (check_firewall_reply_message_received.result == firewall_check_result::unable_to_connect) { _is_firewalled = firewalled_state::firewalled; _publicly_visible_listening_endpoint = fc::optional<fc::ip::endpoint>(); } delete originating_peer->firewall_check_state; originating_peer->firewall_check_state = nullptr; } else { wlog("Received a firewall check reply to a request I never sent"); } } void node_impl::on_get_current_connections_request_message(peer_connection* originating_peer, const get_current_connections_request_message& get_current_connections_request_message_received) { VERIFY_CORRECT_THREAD(); get_current_connections_reply_message reply; if (!_average_network_read_speed_minutes.empty()) { reply.upload_rate_one_minute = _average_network_write_speed_minutes.back(); reply.download_rate_one_minute = _average_network_read_speed_minutes.back(); size_t minutes_to_average = std::min(_average_network_write_speed_minutes.size(), (size_t)15); boost::circular_buffer<uint32_t>::iterator start_iter = _average_network_write_speed_minutes.end() - minutes_to_average; reply.upload_rate_fifteen_minutes = std::accumulate(start_iter, _average_network_write_speed_minutes.end(), 0) / (uint32_t)minutes_to_average; start_iter = _average_network_read_speed_minutes.end() - minutes_to_average; reply.download_rate_fifteen_minutes = std::accumulate(start_iter, _average_network_read_speed_minutes.end(), 0) / (uint32_t)minutes_to_average; minutes_to_average = std::min(_average_network_write_speed_minutes.size(), (size_t)60); start_iter = _average_network_write_speed_minutes.end() - minutes_to_average; reply.upload_rate_one_hour = std::accumulate(start_iter, _average_network_write_speed_minutes.end(), 0) / (uint32_t)minutes_to_average; start_iter = _average_network_read_speed_minutes.end() - minutes_to_average; reply.download_rate_one_hour = std::accumulate(start_iter, _average_network_read_speed_minutes.end(), 0) / (uint32_t)minutes_to_average; } fc::time_point now = fc::time_point::now(); for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections current_connection_data data_for_this_peer; data_for_this_peer.connection_duration = now.sec_since_epoch() - peer->connection_initiation_time.sec_since_epoch(); if (peer->get_remote_endpoint()) // should always be set for anyone we're actively connected to data_for_this_peer.remote_endpoint = *peer->get_remote_endpoint(); data_for_this_peer.clock_offset = peer->clock_offset; data_for_this_peer.round_trip_delay = peer->round_trip_delay; data_for_this_peer.node_id = peer->node_id; data_for_this_peer.connection_direction = peer->direction; data_for_this_peer.firewalled = peer->is_firewalled; fc::mutable_variant_object user_data; if (peer->graphene_git_revision_sha) user_data["graphene_git_revision_sha"] = *peer->graphene_git_revision_sha; if (peer->graphene_git_revision_unix_timestamp) user_data["graphene_git_revision_unix_timestamp"] = *peer->graphene_git_revision_unix_timestamp; if (peer->fc_git_revision_sha) user_data["fc_git_revision_sha"] = *peer->fc_git_revision_sha; if (peer->fc_git_revision_unix_timestamp) user_data["fc_git_revision_unix_timestamp"] = *peer->fc_git_revision_unix_timestamp; if (peer->platform) user_data["platform"] = *peer->platform; if (peer->bitness) user_data["bitness"] = *peer->bitness; user_data["user_agent"] = peer->user_agent; user_data["last_known_block_hash"] = peer->last_block_delegate_has_seen; user_data["last_known_block_number"] = _delegate->get_block_number(peer->last_block_delegate_has_seen); user_data["last_known_block_time"] = peer->last_block_time_delegate_has_seen; data_for_this_peer.user_data = user_data; reply.current_connections.emplace_back(data_for_this_peer); } originating_peer->send_message(reply); } void node_impl::on_get_current_connections_reply_message(peer_connection* originating_peer, const get_current_connections_reply_message& get_current_connections_reply_message_received) { VERIFY_CORRECT_THREAD(); } // this handles any message we get that doesn't require any special processing. // currently, this is any message other than block messages and p2p-specific // messages. (transaction messages would be handled here, for example) // this just passes the message to the client, and does the bookkeeping // related to requesting and rebroadcasting the message. void node_impl::process_ordinary_message( peer_connection* originating_peer, const message& message_to_process, const message_hash_type& message_hash ) { VERIFY_CORRECT_THREAD(); fc::time_point message_receive_time = fc::time_point::now(); // only process it if we asked for it auto iter = originating_peer->items_requested_from_peer.find( item_id(message_to_process.msg_type, message_hash) ); if( iter == originating_peer->items_requested_from_peer.end() ) { wlog( "received a message I didn't ask for from peer ${endpoint}, disconnecting from peer", ( "endpoint", originating_peer->get_remote_endpoint() ) ); fc::exception detailed_error( FC_LOG_MESSAGE(error, "You sent me a message that I didn't ask for, message_hash: ${message_hash}", ( "message_hash", message_hash ) ) ); disconnect_from_peer( originating_peer, "You sent me a message that I didn't request", true, detailed_error ); return; } else { originating_peer->items_requested_from_peer.erase( iter ); if (originating_peer->idle()) trigger_fetch_items_loop(); // Next: have the delegate process the message fc::time_point message_validated_time; try { if (message_to_process.msg_type == trx_message_type) { trx_message transaction_message_to_process = message_to_process.as<trx_message>(); dlog("passing message containing transaction ${trx} to client", ("trx", transaction_message_to_process.trx.id())); _delegate->handle_transaction(transaction_message_to_process); } else _delegate->handle_message( message_to_process ); message_validated_time = fc::time_point::now(); } catch ( const fc::canceled_exception& ) { throw; } catch ( const fc::exception& e ) { wlog( "client rejected message sent by peer ${peer}, ${e}", ("peer", originating_peer->get_remote_endpoint() )("e", e) ); // record it so we don't try to fetch this item again _recently_failed_items.insert(peer_connection::timestamped_item_id(item_id(message_to_process.msg_type, message_hash ), fc::time_point::now())); return; } // finally, if the delegate validated the message, broadcast it to our other peers message_propagation_data propagation_data{message_receive_time, message_validated_time, originating_peer->node_id}; broadcast( message_to_process, propagation_data ); } } void node_impl::start_synchronizing_with_peer( const peer_connection_ptr& peer ) { VERIFY_CORRECT_THREAD(); peer->ids_of_items_to_get.clear(); peer->number_of_unfetched_item_ids = 0; peer->we_need_sync_items_from_peer = true; peer->last_block_delegate_has_seen = item_hash_t(); peer->last_block_time_delegate_has_seen = _delegate->get_block_time(item_hash_t()); peer->inhibit_fetching_sync_blocks = false; fetch_next_batch_of_item_ids_from_peer( peer.get() ); } void node_impl::start_synchronizing() { for( const peer_connection_ptr& peer : _active_connections ) start_synchronizing_with_peer( peer ); } void node_impl::new_peer_just_added( const peer_connection_ptr& peer ) { VERIFY_CORRECT_THREAD(); peer->send_message(current_time_request_message(), offsetof(current_time_request_message, request_sent_time)); start_synchronizing_with_peer( peer ); if( _active_connections.size() != _last_reported_number_of_connections ) { _last_reported_number_of_connections = (uint32_t)_active_connections.size(); _delegate->connection_count_changed( _last_reported_number_of_connections ); } } void node_impl::close() { VERIFY_CORRECT_THREAD(); try { _potential_peer_db.close(); } catch ( const fc::exception& e ) { wlog( "Exception thrown while closing P2P peer database, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while closing P2P peer database, ignoring" ); } // First, stop accepting incoming network connections try { _tcp_server.close(); dlog("P2P TCP server closed"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while closing P2P TCP server, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while closing P2P TCP server, ignoring" ); } try { _accept_loop_complete.cancel_and_wait("node_impl::close()"); dlog("P2P accept loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating P2P accept loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating P2P accept loop, ignoring" ); } // terminate all of our long-running loops (these run continuously instead of rescheduling themselves) try { _p2p_network_connect_loop_done.cancel("node_impl::close()"); // cancel() is currently broken, so we need to wake up the task to allow it to finish trigger_p2p_network_connect_loop(); _p2p_network_connect_loop_done.wait(); dlog("P2P connect loop terminated"); } catch ( const fc::canceled_exception& ) { dlog("P2P connect loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating P2P connect loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating P2P connect loop, ignoring" ); } try { _process_backlog_of_sync_blocks_done.cancel_and_wait("node_impl::close()"); dlog("Process backlog of sync items task terminated"); } catch ( const fc::canceled_exception& ) { dlog("Process backlog of sync items task terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Process backlog of sync items task, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Process backlog of sync items task, ignoring" ); } unsigned handle_message_call_count = 0; while( true ) { auto it = _handle_message_calls_in_progress.begin(); if( it == _handle_message_calls_in_progress.end() ) break; if( it->ready() || it->error() || it->canceled() ) { _handle_message_calls_in_progress.erase( it ); continue; } ++handle_message_call_count; try { it->cancel_and_wait("node_impl::close()"); dlog("handle_message call #${count} task terminated", ("count", handle_message_call_count)); } catch ( const fc::canceled_exception& ) { dlog("handle_message call #${count} task terminated", ("count", handle_message_call_count)); } catch ( const fc::exception& e ) { wlog("Exception thrown while terminating handle_message call #${count} task, ignoring: ${e}", ("e", e)("count", handle_message_call_count)); } catch (...) { wlog("Exception thrown while terminating handle_message call #${count} task, ignoring",("count", handle_message_call_count)); } } try { _fetch_sync_items_loop_done.cancel("node_impl::close()"); // cancel() is currently broken, so we need to wake up the task to allow it to finish trigger_fetch_sync_items_loop(); _fetch_sync_items_loop_done.wait(); dlog("Fetch sync items loop terminated"); } catch ( const fc::canceled_exception& ) { dlog("Fetch sync items loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Fetch sync items loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Fetch sync items loop, ignoring" ); } try { _fetch_item_loop_done.cancel("node_impl::close()"); // cancel() is currently broken, so we need to wake up the task to allow it to finish trigger_fetch_items_loop(); _fetch_item_loop_done.wait(); dlog("Fetch items loop terminated"); } catch ( const fc::canceled_exception& ) { dlog("Fetch items loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Fetch items loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Fetch items loop, ignoring" ); } try { _advertise_inventory_loop_done.cancel("node_impl::close()"); // cancel() is currently broken, so we need to wake up the task to allow it to finish trigger_advertise_inventory_loop(); _advertise_inventory_loop_done.wait(); dlog("Advertise inventory loop terminated"); } catch ( const fc::canceled_exception& ) { dlog("Advertise inventory loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Advertise inventory loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Advertise inventory loop, ignoring" ); } // Next, terminate our existing connections. First, close all of the connections nicely. // This will close the sockets and may result in calls to our "on_connection_closing" // method to inform us that the connection really closed (or may not if we manage to cancel // the read loop before it gets an EOF). // operate off copies of the lists in case they change during iteration std::list<peer_connection_ptr> all_peers; boost::push_back(all_peers, _active_connections); boost::push_back(all_peers, _handshaking_connections); boost::push_back(all_peers, _closing_connections); for (const peer_connection_ptr& peer : all_peers) { try { peer->destroy_connection(); } catch ( const fc::exception& e ) { wlog( "Exception thrown while closing peer connection, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while closing peer connection, ignoring" ); } } // and delete all of the peer_connection objects _active_connections.clear(); _handshaking_connections.clear(); _closing_connections.clear(); all_peers.clear(); { #ifdef USE_PEERS_TO_DELETE_MUTEX fc::scoped_lock<fc::mutex> lock(_peers_to_delete_mutex); #endif try { _delayed_peer_deletion_task_done.cancel_and_wait("node_impl::close()"); dlog("Delayed peer deletion task terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Delayed peer deletion task, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Delayed peer deletion task, ignoring" ); } _peers_to_delete.clear(); } // Now that there are no more peers that can call methods on us, there should be no // chance for one of our loops to be rescheduled, so we can safely terminate all of // our loops now try { _terminate_inactive_connections_loop_done.cancel_and_wait("node_impl::close()"); dlog("Terminate inactive connections loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Terminate inactive connections loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Terminate inactive connections loop, ignoring" ); } try { _fetch_updated_peer_lists_loop_done.cancel_and_wait("node_impl::close()"); dlog("Fetch updated peer lists loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Fetch updated peer lists loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Fetch updated peer lists loop, ignoring" ); } try { _bandwidth_monitor_loop_done.cancel_and_wait("node_impl::close()"); dlog("Bandwidth monitor loop terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Bandwidth monitor loop, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Bandwidth monitor loop, ignoring" ); } try { _dump_node_status_task_done.cancel_and_wait("node_impl::close()"); dlog("Dump node status task terminated"); } catch ( const fc::exception& e ) { wlog( "Exception thrown while terminating Dump node status task, ignoring: ${e}", ("e", e) ); } catch (...) { wlog( "Exception thrown while terminating Dump node status task, ignoring" ); } } // node_impl::close() void node_impl::accept_connection_task( peer_connection_ptr new_peer ) { VERIFY_CORRECT_THREAD(); new_peer->accept_connection(); // this blocks until the secure connection is fully negotiated send_hello_message(new_peer); } void node_impl::accept_loop() { VERIFY_CORRECT_THREAD(); while ( !_accept_loop_complete.canceled() ) { peer_connection_ptr new_peer(peer_connection::make_shared(this)); try { _tcp_server.accept( new_peer->get_socket() ); ilog( "accepted inbound connection from ${remote_endpoint}", ("remote_endpoint", new_peer->get_socket().remote_endpoint() ) ); if (_node_is_shutting_down) return; new_peer->connection_initiation_time = fc::time_point::now(); _handshaking_connections.insert( new_peer ); _rate_limiter.add_tcp_socket( &new_peer->get_socket() ); std::weak_ptr<peer_connection> new_weak_peer(new_peer); new_peer->accept_or_connect_task_done = fc::async( [this, new_weak_peer]() { peer_connection_ptr new_peer(new_weak_peer.lock()); assert(new_peer); if (!new_peer) return; accept_connection_task(new_peer); }, "accept_connection_task" ); // limit the rate at which we accept connections to mitigate DOS attacks fc::usleep( fc::milliseconds(10) ); } FC_CAPTURE_AND_LOG( () ) } } // accept_loop() void node_impl::send_hello_message(const peer_connection_ptr& peer) { VERIFY_CORRECT_THREAD(); peer->negotiation_status = peer_connection::connection_negotiation_status::hello_sent; fc::sha256::encoder shared_secret_encoder; fc::sha512 shared_secret = peer->get_shared_secret(); shared_secret_encoder.write(shared_secret.data(), sizeof(shared_secret)); fc::ecc::compact_signature signature = _node_configuration.private_key.sign_compact(shared_secret_encoder.result()); // in the hello messsage, we send three things: // ip address // outbound port // inbound port // The peer we're connecting to will assume we're firewalled if the // ip address and outbound port we send don't match the values it sees on its remote endpoint // // if we know that we're behind a NAT that will allow incoming connections because our firewall // detection figured it out, send those values instead. fc::ip::endpoint local_endpoint(peer->get_socket().local_endpoint()); uint16_t listening_port = _node_configuration.accept_incoming_connections ? _actual_listening_endpoint.port() : 0; if (_is_firewalled == firewalled_state::not_firewalled && _publicly_visible_listening_endpoint) { local_endpoint = *_publicly_visible_listening_endpoint; listening_port = _publicly_visible_listening_endpoint->port(); } hello_message hello(_user_agent_string, core_protocol_version, local_endpoint.get_address(), listening_port, local_endpoint.port(), _node_public_key, signature, generate_hello_user_data()); peer->send_message(message(hello)); } void node_impl::connect_to_task(peer_connection_ptr new_peer, const fc::ip::endpoint& remote_endpoint) { VERIFY_CORRECT_THREAD(); if (!new_peer->performing_firewall_check()) { // create or find the database entry for the new peer // if we're connecting to them, we believe they're not firewalled potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(remote_endpoint); updated_peer_record.last_connection_disposition = last_connection_failed; updated_peer_record.last_connection_attempt_time = fc::time_point::now();; _potential_peer_db.update_entry(updated_peer_record); } else { wlog("connecting to peer ${peer} for firewall check", ("peer", new_peer->get_remote_endpoint())); } fc::oexception connect_failed_exception; try { new_peer->connect_to(remote_endpoint, _actual_listening_endpoint); // blocks until the connection is established and secure connection is negotiated // we connected to the peer. guess they're not firewalled.... new_peer->is_firewalled = firewalled_state::not_firewalled; // connection succeeded, we've started handshaking. record that in our database potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(remote_endpoint); updated_peer_record.last_connection_disposition = last_connection_handshaking_failed; updated_peer_record.number_of_successful_connection_attempts++; updated_peer_record.last_seen_time = fc::time_point::now(); _potential_peer_db.update_entry(updated_peer_record); } catch (const fc::exception& except) { connect_failed_exception = except; } if (connect_failed_exception && !new_peer->performing_firewall_check()) { // connection failed. record that in our database potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(remote_endpoint); updated_peer_record.last_connection_disposition = last_connection_failed; updated_peer_record.number_of_failed_connection_attempts++; if (new_peer->connection_closed_error) updated_peer_record.last_error = *new_peer->connection_closed_error; else updated_peer_record.last_error = *connect_failed_exception; _potential_peer_db.update_entry(updated_peer_record); } if (new_peer->performing_firewall_check()) { // we were connecting to test whether the node is firewalled, and we now know the result. // send a message back to the requester peer_connection_ptr requesting_peer = get_peer_by_node_id(new_peer->firewall_check_state->requesting_peer); if (requesting_peer) { check_firewall_reply_message reply; reply.endpoint_checked = new_peer->firewall_check_state->endpoint_to_test; reply.node_id = new_peer->firewall_check_state->expected_node_id; reply.result = connect_failed_exception ? firewall_check_result::unable_to_connect : firewall_check_result::connection_successful; wlog("firewall check of ${peer_checked} ${success_or_failure}, sending reply to ${requester}", ("peer_checked", new_peer->get_remote_endpoint()) ("success_or_failure", connect_failed_exception ? "failed" : "succeeded" ) ("requester", requesting_peer->get_remote_endpoint())); requesting_peer->send_message(reply); } } if (connect_failed_exception || new_peer->performing_firewall_check()) { // if the connection failed or if this connection was just intended to check // whether the peer is firewalled, we want to disconnect now. _handshaking_connections.erase(new_peer); _terminating_connections.erase(new_peer); assert(_active_connections.find(new_peer) == _active_connections.end()); _active_connections.erase(new_peer); assert(_closing_connections.find(new_peer) == _closing_connections.end()); _closing_connections.erase(new_peer); display_current_connections(); trigger_p2p_network_connect_loop(); schedule_peer_for_deletion(new_peer); if (connect_failed_exception) throw *connect_failed_exception; } else { // connection was successful and we want to stay connected fc::ip::endpoint local_endpoint = new_peer->get_local_endpoint(); new_peer->inbound_address = local_endpoint.get_address(); new_peer->inbound_port = _node_configuration.accept_incoming_connections ? _actual_listening_endpoint.port() : 0; new_peer->outbound_port = local_endpoint.port(); new_peer->our_state = peer_connection::our_connection_state::just_connected; new_peer->their_state = peer_connection::their_connection_state::just_connected; send_hello_message(new_peer); dlog("Sent \"hello\" to peer ${peer}", ("peer", new_peer->get_remote_endpoint())); } } // methods implementing node's public interface void node_impl::set_node_delegate(node_delegate* del, fc::thread* thread_for_delegate_calls) { VERIFY_CORRECT_THREAD(); _delegate.reset(); if (del) _delegate.reset(new statistics_gathering_node_delegate_wrapper(del, thread_for_delegate_calls)); } void node_impl::load_configuration( const fc::path& configuration_directory ) { VERIFY_CORRECT_THREAD(); _node_configuration_directory = configuration_directory; fc::path configuration_file_name( _node_configuration_directory / NODE_CONFIGURATION_FILENAME ); bool node_configuration_loaded = false; if( fc::exists(configuration_file_name ) ) { try { _node_configuration = fc::json::from_file( configuration_file_name ).as<node_configuration>(); ilog( "Loaded configuration from file ${filename}", ("filename", configuration_file_name ) ); if( _node_configuration.private_key == fc::ecc::private_key() ) { ilog( "generating new private key for this node" ); _node_configuration.private_key = fc::ecc::private_key::generate(); } node_configuration_loaded = true; } catch ( fc::parse_error_exception& parse_error ) { elog( "malformed node configuration file ${filename}: ${error}", ( "filename", configuration_file_name )("error", parse_error.to_detail_string() ) ); } catch ( fc::exception& except ) { elog( "unexpected exception while reading configuration file ${filename}: ${error}", ( "filename", configuration_file_name )("error", except.to_detail_string() ) ); } } if( !node_configuration_loaded ) { _node_configuration = node_configuration(); #ifdef GRAPHENE_TEST_NETWORK uint32_t port = GRAPHENE_NET_TEST_P2P_PORT + GRAPHENE_TEST_NETWORK_VERSION; #else uint32_t port = GRAPHENE_NET_DEFAULT_P2P_PORT; #endif _node_configuration.listen_endpoint.set_port( port ); _node_configuration.accept_incoming_connections = true; _node_configuration.wait_if_endpoint_is_busy = false; ilog( "generating new private key for this node" ); _node_configuration.private_key = fc::ecc::private_key::generate(); } _node_public_key = _node_configuration.private_key.get_public_key().serialize(); fc::path potential_peer_database_file_name(_node_configuration_directory / POTENTIAL_PEER_DATABASE_FILENAME); try { _potential_peer_db.open(potential_peer_database_file_name); // push back the time on all peers loaded from the database so we will be able to retry them immediately for (peer_database::iterator itr = _potential_peer_db.begin(); itr != _potential_peer_db.end(); ++itr) { potential_peer_record updated_peer_record = *itr; updated_peer_record.last_connection_attempt_time = std::min<fc::time_point_sec>(updated_peer_record.last_connection_attempt_time, fc::time_point::now() - fc::seconds(_node_configuration.peer_connection_retry_timeout)); _potential_peer_db.update_entry(updated_peer_record); } trigger_p2p_network_connect_loop(); } catch (fc::exception& except) { elog("unable to open peer database ${filename}: ${error}", ("filename", potential_peer_database_file_name)("error", except.to_detail_string())); throw; } } void node_impl::listen_to_p2p_network() { VERIFY_CORRECT_THREAD(); if (!_node_configuration.accept_incoming_connections) { wlog("accept_incoming_connections is false, p2p network will not accept any incoming connections"); return; } assert(_node_public_key != fc::ecc::public_key_data()); fc::ip::endpoint listen_endpoint = _node_configuration.listen_endpoint; if( listen_endpoint.port() != 0 ) { // if the user specified a port, we only want to bind to it if it's not already // being used by another application. During normal operation, we set the // SO_REUSEADDR/SO_REUSEPORT flags so that we can bind outbound sockets to the // same local endpoint as we're listening on here. On some platforms, setting // those flags will prevent us from detecting that other applications are // listening on that port. We'd like to detect that, so we'll set up a temporary // tcp server without that flag to see if we can listen on that port. bool first = true; for( ;; ) { bool listen_failed = false; try { fc::tcp_server temporary_server; if( listen_endpoint.get_address() != fc::ip::address() ) temporary_server.listen( listen_endpoint ); else temporary_server.listen( listen_endpoint.port() ); break; } catch ( const fc::exception&) { listen_failed = true; } if (listen_failed) { if( _node_configuration.wait_if_endpoint_is_busy ) { std::ostringstream error_message_stream; if( first ) { error_message_stream << "Unable to listen for connections on port " << listen_endpoint.port() << ", retrying in a few seconds\n"; error_message_stream << "You can wait for it to become available, or restart this program using\n"; error_message_stream << "the --p2p-port option to specify another port\n"; first = false; } else { error_message_stream << "\nStill waiting for port " << listen_endpoint.port() << " to become available\n"; } std::string error_message = error_message_stream.str(); ulog(error_message); _delegate->error_encountered( error_message, fc::oexception() ); fc::usleep( fc::seconds(GRAPHENE_NET_PORT_WAIT_DELAY_SECONDS) ); } else // don't wait, just find a random port { wlog( "unable to bind on the requested endpoint ${endpoint}, which probably means that endpoint is already in use", ( "endpoint", listen_endpoint ) ); listen_endpoint.set_port( 0 ); } } // if (listen_failed) } // for(;;) } // if (listen_endpoint.port() != 0) else // port is 0 { // if they requested a random port, we'll just assume it's available // (it may not be due to ip address, but we'll detect that in the next step) } _tcp_server.set_reuse_address(); try { if( listen_endpoint.get_address() != fc::ip::address() ) _tcp_server.listen( listen_endpoint ); else _tcp_server.listen( listen_endpoint.port() ); _actual_listening_endpoint = _tcp_server.get_local_endpoint(); ilog( "listening for connections on endpoint ${endpoint} (our first choice)", ( "endpoint", _actual_listening_endpoint ) ); } catch ( fc::exception& e ) { FC_RETHROW_EXCEPTION( e, error, "unable to listen on ${endpoint}", ("endpoint",listen_endpoint ) ); } } void node_impl::connect_to_p2p_network() { VERIFY_CORRECT_THREAD(); assert(_node_public_key != fc::ecc::public_key_data()); assert(!_accept_loop_complete.valid() && !_p2p_network_connect_loop_done.valid() && !_fetch_sync_items_loop_done.valid() && !_fetch_item_loop_done.valid() && !_advertise_inventory_loop_done.valid() && !_terminate_inactive_connections_loop_done.valid() && !_fetch_updated_peer_lists_loop_done.valid() && !_bandwidth_monitor_loop_done.valid() && !_dump_node_status_task_done.valid()); if (_node_configuration.accept_incoming_connections) _accept_loop_complete = fc::async( [=](){ accept_loop(); }, "accept_loop"); _p2p_network_connect_loop_done = fc::async( [=]() { p2p_network_connect_loop(); }, "p2p_network_connect_loop" ); _fetch_sync_items_loop_done = fc::async( [=]() { fetch_sync_items_loop(); }, "fetch_sync_items_loop" ); _fetch_item_loop_done = fc::async( [=]() { fetch_items_loop(); }, "fetch_items_loop" ); _advertise_inventory_loop_done = fc::async( [=]() { advertise_inventory_loop(); }, "advertise_inventory_loop" ); _terminate_inactive_connections_loop_done = fc::async( [=]() { terminate_inactive_connections_loop(); }, "terminate_inactive_connections_loop" ); _fetch_updated_peer_lists_loop_done = fc::async([=](){ fetch_updated_peer_lists_loop(); }, "fetch_updated_peer_lists_loop"); _bandwidth_monitor_loop_done = fc::async([=](){ bandwidth_monitor_loop(); }, "bandwidth_monitor_loop"); _dump_node_status_task_done = fc::async([=](){ dump_node_status_task(); }, "dump_node_status_task"); } void node_impl::add_node(const fc::ip::endpoint& ep) { VERIFY_CORRECT_THREAD(); // if we're connecting to them, we believe they're not firewalled potential_peer_record updated_peer_record = _potential_peer_db.lookup_or_create_entry_for_endpoint(ep); // if we've recently connected to this peer, reset the last_connection_attempt_time to allow // us to immediately retry this peer updated_peer_record.last_connection_attempt_time = std::min<fc::time_point_sec>(updated_peer_record.last_connection_attempt_time, fc::time_point::now() - fc::seconds(_node_configuration.peer_connection_retry_timeout)); _add_once_node_list.push_back(updated_peer_record); _potential_peer_db.update_entry(updated_peer_record); trigger_p2p_network_connect_loop(); } void node_impl::initiate_connect_to(const peer_connection_ptr& new_peer) { new_peer->get_socket().open(); new_peer->get_socket().set_reuse_address(); new_peer->connection_initiation_time = fc::time_point::now(); _handshaking_connections.insert(new_peer); _rate_limiter.add_tcp_socket(&new_peer->get_socket()); if (_node_is_shutting_down) return; std::weak_ptr<peer_connection> new_weak_peer(new_peer); new_peer->accept_or_connect_task_done = fc::async([this, new_weak_peer](){ peer_connection_ptr new_peer(new_weak_peer.lock()); assert(new_peer); if (!new_peer) return; connect_to_task(new_peer, *new_peer->get_remote_endpoint()); }, "connect_to_task"); } void node_impl::connect_to_endpoint(const fc::ip::endpoint& remote_endpoint) { VERIFY_CORRECT_THREAD(); if (is_connection_to_endpoint_in_progress(remote_endpoint)) FC_THROW_EXCEPTION(already_connected_to_requested_peer, "already connected to requested endpoint ${endpoint}", ("endpoint", remote_endpoint)); dlog("node_impl::connect_to_endpoint(${endpoint})", ("endpoint", remote_endpoint)); peer_connection_ptr new_peer(peer_connection::make_shared(this)); new_peer->set_remote_endpoint(remote_endpoint); initiate_connect_to(new_peer); } peer_connection_ptr node_impl::get_connection_to_endpoint( const fc::ip::endpoint& remote_endpoint ) { VERIFY_CORRECT_THREAD(); for( const peer_connection_ptr& active_peer : _active_connections ) { fc::optional<fc::ip::endpoint> endpoint_for_this_peer( active_peer->get_remote_endpoint() ); if( endpoint_for_this_peer && *endpoint_for_this_peer == remote_endpoint ) return active_peer; } for( const peer_connection_ptr& handshaking_peer : _handshaking_connections ) { fc::optional<fc::ip::endpoint> endpoint_for_this_peer( handshaking_peer->get_remote_endpoint() ); if( endpoint_for_this_peer && *endpoint_for_this_peer == remote_endpoint ) return handshaking_peer; } return peer_connection_ptr(); } bool node_impl::is_connection_to_endpoint_in_progress( const fc::ip::endpoint& remote_endpoint ) { VERIFY_CORRECT_THREAD(); return get_connection_to_endpoint( remote_endpoint ) != peer_connection_ptr(); } void node_impl::move_peer_to_active_list(const peer_connection_ptr& peer) { VERIFY_CORRECT_THREAD(); _active_connections.insert(peer); _handshaking_connections.erase(peer); _closing_connections.erase(peer); _terminating_connections.erase(peer); fc_ilog(fc::logger::get("sync"), "New peer is connected (${peer}), now ${count} active peers", ("peer", peer->get_remote_endpoint()) ("count", _active_connections.size())); } void node_impl::move_peer_to_closing_list(const peer_connection_ptr& peer) { VERIFY_CORRECT_THREAD(); _active_connections.erase(peer); _handshaking_connections.erase(peer); _closing_connections.insert(peer); _terminating_connections.erase(peer); fc_ilog(fc::logger::get("sync"), "Peer connection closing (${peer}), now ${count} active peers", ("peer", peer->get_remote_endpoint()) ("count", _active_connections.size())); } void node_impl::move_peer_to_terminating_list(const peer_connection_ptr& peer) { VERIFY_CORRECT_THREAD(); _active_connections.erase(peer); _handshaking_connections.erase(peer); _closing_connections.erase(peer); _terminating_connections.insert(peer); fc_ilog(fc::logger::get("sync"), "Peer connection terminating (${peer}), now ${count} active peers", ("peer", peer->get_remote_endpoint()) ("count", _active_connections.size())); } void node_impl::dump_node_status() { VERIFY_CORRECT_THREAD(); ilog( "----------------- PEER STATUS UPDATE --------------------" ); ilog( " number of peers: ${active} active, ${handshaking}, ${closing} closing. attempting to maintain ${desired} - ${maximum} peers", ( "active", _active_connections.size() )("handshaking", _handshaking_connections.size() )("closing",_closing_connections.size() ) ( "desired", _node_configuration.desired_number_of_connections )("maximum", _node_configuration.maximum_number_of_connections ) ); for( const peer_connection_ptr& peer : _active_connections ) { ilog( " active peer ${endpoint} peer_is_in_sync_with_us:${in_sync_with_us} we_are_in_sync_with_peer:${in_sync_with_them}", ( "endpoint", peer->get_remote_endpoint() ) ( "in_sync_with_us", !peer->peer_needs_sync_items_from_us )("in_sync_with_them", !peer->we_need_sync_items_from_peer ) ); if( peer->we_need_sync_items_from_peer ) ilog( " above peer has ${count} sync items we might need", ("count", peer->ids_of_items_to_get.size() ) ); if (peer->inhibit_fetching_sync_blocks) ilog( " we are not fetching sync blocks from the above peer (inhibit_fetching_sync_blocks == true)" ); } for( const peer_connection_ptr& peer : _handshaking_connections ) { ilog( " handshaking peer ${endpoint} in state ours(${our_state}) theirs(${their_state})", ( "endpoint", peer->get_remote_endpoint() )("our_state", peer->our_state )("their_state", peer->their_state ) ); } ilog( "--------- MEMORY USAGE ------------" ); ilog( "node._active_sync_requests size: ${size}", ("size", _active_sync_requests.size() ) ); ilog( "node._received_sync_items size: ${size}", ("size", _received_sync_items.size() ) ); ilog( "node._new_received_sync_items size: ${size}", ("size", _new_received_sync_items.size() ) ); ilog( "node._items_to_fetch size: ${size}", ("size", _items_to_fetch.size() ) ); ilog( "node._new_inventory size: ${size}", ("size", _new_inventory.size() ) ); ilog( "node._message_cache size: ${size}", ("size", _message_cache.size() ) ); for( const peer_connection_ptr& peer : _active_connections ) { ilog( " peer ${endpoint}", ("endpoint", peer->get_remote_endpoint() ) ); ilog( " peer.ids_of_items_to_get size: ${size}", ("size", peer->ids_of_items_to_get.size() ) ); ilog( " peer.inventory_peer_advertised_to_us size: ${size}", ("size", peer->inventory_peer_advertised_to_us.size() ) ); ilog( " peer.inventory_advertised_to_peer size: ${size}", ("size", peer->inventory_advertised_to_peer.size() ) ); ilog( " peer.items_requested_from_peer size: ${size}", ("size", peer->items_requested_from_peer.size() ) ); ilog( " peer.sync_items_requested_from_peer size: ${size}", ("size", peer->sync_items_requested_from_peer.size() ) ); } ilog( "--------- END MEMORY USAGE ------------" ); } void node_impl::disconnect_from_peer( peer_connection* peer_to_disconnect, const std::string& reason_for_disconnect, bool caused_by_error /* = false */, const fc::oexception& error /* = fc::oexception() */ ) { VERIFY_CORRECT_THREAD(); move_peer_to_closing_list(peer_to_disconnect->shared_from_this()); if (peer_to_disconnect->they_have_requested_close) { // the peer has already told us that it's ready to close the connection, so just close the connection peer_to_disconnect->close_connection(); } else { // we're the first to try to want to close the connection fc::optional<fc::ip::endpoint> inbound_endpoint = peer_to_disconnect->get_endpoint_for_connecting(); if (inbound_endpoint) { fc::optional<potential_peer_record> updated_peer_record = _potential_peer_db.lookup_entry_for_endpoint(*inbound_endpoint); if (updated_peer_record) { updated_peer_record->last_seen_time = fc::time_point::now(); if (error) updated_peer_record->last_error = error; else updated_peer_record->last_error = fc::exception(FC_LOG_MESSAGE(info, reason_for_disconnect.c_str())); _potential_peer_db.update_entry(*updated_peer_record); } } peer_to_disconnect->we_have_requested_close = true; peer_to_disconnect->connection_closed_time = fc::time_point::now(); closing_connection_message closing_message( reason_for_disconnect, caused_by_error, error ); peer_to_disconnect->send_message( closing_message ); } // notify the user. This will be useful in testing, but we might want to remove it later; // it makes good sense to notify the user if other nodes think she is behaving badly, but // if we're just detecting and dissconnecting other badly-behaving nodes, they don't really care. if (caused_by_error) { std::ostringstream error_message; error_message << "I am disconnecting peer " << fc::variant( peer_to_disconnect->get_remote_endpoint() ).as_string() << " for reason: " << reason_for_disconnect; _delegate->error_encountered(error_message.str(), fc::oexception()); dlog(error_message.str()); } else dlog("Disconnecting from ${peer} for ${reason}", ("peer",peer_to_disconnect->get_remote_endpoint()) ("reason",reason_for_disconnect)); // peer_to_disconnect->close_connection(); } void node_impl::listen_on_endpoint( const fc::ip::endpoint& ep, bool wait_if_not_available ) { VERIFY_CORRECT_THREAD(); _node_configuration.listen_endpoint = ep; _node_configuration.wait_if_endpoint_is_busy = wait_if_not_available; save_node_configuration(); } void node_impl::accept_incoming_connections(bool accept) { VERIFY_CORRECT_THREAD(); _node_configuration.accept_incoming_connections = accept; save_node_configuration(); } void node_impl::listen_on_port( uint16_t port, bool wait_if_not_available ) { VERIFY_CORRECT_THREAD(); _node_configuration.listen_endpoint = fc::ip::endpoint( fc::ip::address(), port ); _node_configuration.wait_if_endpoint_is_busy = wait_if_not_available; save_node_configuration(); } fc::ip::endpoint node_impl::get_actual_listening_endpoint() const { VERIFY_CORRECT_THREAD(); return _actual_listening_endpoint; } std::vector<peer_status> node_impl::get_connected_peers() const { VERIFY_CORRECT_THREAD(); std::vector<peer_status> statuses; for (const peer_connection_ptr& peer : _active_connections) { ASSERT_TASK_NOT_PREEMPTED(); // don't yield while iterating over _active_connections peer_status this_peer_status; this_peer_status.version = 0; fc::optional<fc::ip::endpoint> endpoint = peer->get_remote_endpoint(); if (endpoint) this_peer_status.host = *endpoint; fc::mutable_variant_object peer_details; peer_details["addr"] = endpoint ? (std::string)*endpoint : std::string(); peer_details["addrlocal"] = (std::string)peer->get_local_endpoint(); peer_details["services"] = "00000001"; peer_details["lastsend"] = peer->get_last_message_sent_time().sec_since_epoch(); peer_details["lastrecv"] = peer->get_last_message_received_time().sec_since_epoch(); peer_details["bytessent"] = peer->get_total_bytes_sent(); peer_details["bytesrecv"] = peer->get_total_bytes_received(); peer_details["conntime"] = peer->get_connection_time(); peer_details["pingtime"] = ""; peer_details["pingwait"] = ""; peer_details["version"] = ""; peer_details["subver"] = peer->user_agent; peer_details["inbound"] = peer->direction == peer_connection_direction::inbound; peer_details["firewall_status"] = peer->is_firewalled; peer_details["startingheight"] = ""; peer_details["banscore"] = ""; peer_details["syncnode"] = ""; if (peer->fc_git_revision_sha) { std::string revision_string = *peer->fc_git_revision_sha; if (*peer->fc_git_revision_sha == fc::git_revision_sha) revision_string += " (same as ours)"; else revision_string += " (different from ours)"; peer_details["fc_git_revision_sha"] = revision_string; } if (peer->fc_git_revision_unix_timestamp) { peer_details["fc_git_revision_unix_timestamp"] = *peer->fc_git_revision_unix_timestamp; std::string age_string = fc::get_approximate_relative_time_string( *peer->fc_git_revision_unix_timestamp); if (*peer->fc_git_revision_unix_timestamp == fc::time_point_sec(fc::git_revision_unix_timestamp)) age_string += " (same as ours)"; else if (*peer->fc_git_revision_unix_timestamp > fc::time_point_sec(fc::git_revision_unix_timestamp)) age_string += " (newer than ours)"; else age_string += " (older than ours)"; peer_details["fc_git_revision_age"] = age_string; } if (peer->platform) peer_details["platform"] = *peer->platform; // provide these for debugging // warning: these are just approximations, if the peer is "downstream" of us, they may // have received blocks from other peers that we are unaware of peer_details["current_head_block"] = peer->last_block_delegate_has_seen; peer_details["current_head_block_number"] = _delegate->get_block_number(peer->last_block_delegate_has_seen); peer_details["current_head_block_time"] = peer->last_block_time_delegate_has_seen; this_peer_status.info = peer_details; statuses.push_back(this_peer_status); } return statuses; } uint32_t node_impl::get_connection_count() const { VERIFY_CORRECT_THREAD(); return (uint32_t)_active_connections.size(); } void node_impl::broadcast( const message& item_to_broadcast, const message_propagation_data& propagation_data ) { VERIFY_CORRECT_THREAD(); fc::uint160_t hash_of_message_contents; if( item_to_broadcast.msg_type == graphene::net::block_message_type ) { graphene::net::block_message block_message_to_broadcast = item_to_broadcast.as<graphene::net::block_message>(); hash_of_message_contents = block_message_to_broadcast.block_id; // for debugging _most_recent_blocks_accepted.push_back( block_message_to_broadcast.block_id ); } else if( item_to_broadcast.msg_type == graphene::net::trx_message_type ) { graphene::net::trx_message transaction_message_to_broadcast = item_to_broadcast.as<graphene::net::trx_message>(); hash_of_message_contents = transaction_message_to_broadcast.trx.id(); // for debugging dlog( "broadcasting trx: ${trx}", ("trx", transaction_message_to_broadcast) ); } message_hash_type hash_of_item_to_broadcast = item_to_broadcast.id(); _message_cache.cache_message( item_to_broadcast, hash_of_item_to_broadcast, propagation_data, hash_of_message_contents ); _new_inventory.insert( item_id(item_to_broadcast.msg_type, hash_of_item_to_broadcast ) ); trigger_advertise_inventory_loop(); } void node_impl::broadcast( const message& item_to_broadcast ) { VERIFY_CORRECT_THREAD(); // this version is called directly from the client message_propagation_data propagation_data{fc::time_point::now(), fc::time_point::now(), _node_id}; broadcast( item_to_broadcast, propagation_data ); } void node_impl::sync_from(const item_id& current_head_block, const std::vector<uint32_t>& hard_fork_block_numbers) { VERIFY_CORRECT_THREAD(); _most_recent_blocks_accepted.clear(); _sync_item_type = current_head_block.item_type; _most_recent_blocks_accepted.push_back(current_head_block.item_hash); _hard_fork_block_numbers = hard_fork_block_numbers; } bool node_impl::is_connected() const { VERIFY_CORRECT_THREAD(); return !_active_connections.empty(); } std::vector<potential_peer_record> node_impl::get_potential_peers() const { VERIFY_CORRECT_THREAD(); std::vector<potential_peer_record> result; // use explicit iterators here, for some reason the mac compiler can't used ranged-based for loops here for (peer_database::iterator itr = _potential_peer_db.begin(); itr != _potential_peer_db.end(); ++itr) result.push_back(*itr); return result; } void node_impl::set_advanced_node_parameters(const fc::variant_object& params) { VERIFY_CORRECT_THREAD(); ilog( "set_advanced_node_parameters ${params}", ("params", params) ); fc::from_variant( params, _node_configuration ); if( _node_configuration.private_key == fc::ecc::private_key() ) { ilog( "generating new private key for this node" ); _node_configuration.private_key = fc::ecc::private_key::generate(); } // Private key could have been overridden at this point. Update public key just in case _node_public_key = _node_configuration.private_key.get_public_key().serialize(); if( _node_configuration.desired_number_of_connections > _node_configuration.maximum_number_of_connections ) { wlog( "Reducing desired_number_of_connections from ${x0} to maximum_number_of_connections=${x1}", ("x0", _node_configuration.desired_number_of_connections) ("x1", _node_configuration.maximum_number_of_connections) ); } while (_active_connections.size() > _node_configuration.maximum_number_of_connections) disconnect_from_peer(_active_connections.begin()->get(), "I have too many connections open"); trigger_p2p_network_connect_loop(); } node_configuration node_impl::get_advanced_node_parameters()const { VERIFY_CORRECT_THREAD(); return _node_configuration; } message_propagation_data node_impl::get_transaction_propagation_data( const graphene::net::transaction_id_type& transaction_id ) { VERIFY_CORRECT_THREAD(); return _message_cache.get_message_propagation_data( transaction_id ); } message_propagation_data node_impl::get_block_propagation_data( const graphene::net::block_id_type& block_id ) { VERIFY_CORRECT_THREAD(); return _message_cache.get_message_propagation_data( block_id ); } node_id_t node_impl::get_node_id() const { VERIFY_CORRECT_THREAD(); return _node_id; } void node_impl::set_allowed_peers(const std::vector<node_id_t>& allowed_peers) { VERIFY_CORRECT_THREAD(); #ifdef ENABLE_P2P_DEBUGGING_API _allowed_peers.clear(); _allowed_peers.insert(allowed_peers.begin(), allowed_peers.end()); std::list<peer_connection_ptr> peers_to_disconnect; if (!_allowed_peers.empty()) for (const peer_connection_ptr& peer : _active_connections) if (_allowed_peers.find(peer->node_id) == _allowed_peers.end()) peers_to_disconnect.push_back(peer); for (const peer_connection_ptr& peer : peers_to_disconnect) disconnect_from_peer(peer.get(), "My allowed_peers list has changed, and you're no longer allowed. Bye."); #endif // ENABLE_P2P_DEBUGGING_API } void node_impl::clear_peer_database() { VERIFY_CORRECT_THREAD(); _potential_peer_db.clear(); } void node_impl::set_total_bandwidth_limit( uint32_t upload_bytes_per_second, uint32_t download_bytes_per_second ) { VERIFY_CORRECT_THREAD(); _rate_limiter.set_upload_limit( upload_bytes_per_second ); _rate_limiter.set_download_limit( download_bytes_per_second ); } fc::variant_object node_impl::get_call_statistics() const { VERIFY_CORRECT_THREAD(); return _delegate->get_call_statistics(); } fc::variant_object node_impl::network_get_info() const { VERIFY_CORRECT_THREAD(); fc::mutable_variant_object info; info["listening_on"] = _actual_listening_endpoint; info["node_public_key"] = _node_public_key; info["node_id"] = _node_id; info["firewalled"] = _is_firewalled; return info; } fc::variant_object node_impl::network_get_usage_stats() const { VERIFY_CORRECT_THREAD(); std::vector<uint32_t> network_usage_by_second; network_usage_by_second.reserve(_average_network_read_speed_seconds.size()); std::transform(_average_network_read_speed_seconds.begin(), _average_network_read_speed_seconds.end(), _average_network_write_speed_seconds.begin(), std::back_inserter(network_usage_by_second), std::plus<uint32_t>()); std::vector<uint32_t> network_usage_by_minute; network_usage_by_minute.reserve(_average_network_read_speed_minutes.size()); std::transform(_average_network_read_speed_minutes.begin(), _average_network_read_speed_minutes.end(), _average_network_write_speed_minutes.begin(), std::back_inserter(network_usage_by_minute), std::plus<uint32_t>()); std::vector<uint32_t> network_usage_by_hour; network_usage_by_hour.reserve(_average_network_read_speed_hours.size()); std::transform(_average_network_read_speed_hours.begin(), _average_network_read_speed_hours.end(), _average_network_write_speed_hours.begin(), std::back_inserter(network_usage_by_hour), std::plus<uint32_t>()); fc::mutable_variant_object result; result["usage_by_second"] = network_usage_by_second; result["usage_by_minute"] = network_usage_by_minute; result["usage_by_hour"] = network_usage_by_hour; return result; } bool node_impl::is_hard_fork_block(uint32_t block_number) const { return std::binary_search(_hard_fork_block_numbers.begin(), _hard_fork_block_numbers.end(), block_number); } uint32_t node_impl::get_next_known_hard_fork_block_number(uint32_t block_number) const { auto iter = std::upper_bound(_hard_fork_block_numbers.begin(), _hard_fork_block_numbers.end(), block_number); return iter != _hard_fork_block_numbers.end() ? *iter : 0; } } // end namespace detail ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // implement node functions, they call the matching function in to detail::node_impl in the correct thread // #ifdef P2P_IN_DEDICATED_THREAD # define INVOKE_IN_IMPL(method_name, ...) \ return my->_thread->async([&](){ return my->method_name(__VA_ARGS__); }, "thread invoke for method " BOOST_PP_STRINGIZE(method_name)).wait() #else # define INVOKE_IN_IMPL(method_name, ...) \ return my->method_name(__VA_ARGS__) #endif // P2P_IN_DEDICATED_THREAD node::node(const std::string& user_agent) : my(new detail::node_impl(user_agent)) { } node::~node() { } void node::set_node_delegate( node_delegate* del ) { fc::thread* delegate_thread = &fc::thread::current(); INVOKE_IN_IMPL(set_node_delegate, del, delegate_thread); } void node::load_configuration( const fc::path& configuration_directory ) { INVOKE_IN_IMPL(load_configuration, configuration_directory); } void node::listen_to_p2p_network() { INVOKE_IN_IMPL(listen_to_p2p_network); } void node::connect_to_p2p_network() { INVOKE_IN_IMPL(connect_to_p2p_network); } void node::add_node( const fc::ip::endpoint& ep ) { INVOKE_IN_IMPL(add_node, ep); } void node::connect_to_endpoint( const fc::ip::endpoint& remote_endpoint ) { INVOKE_IN_IMPL(connect_to_endpoint, remote_endpoint); } void node::listen_on_endpoint(const fc::ip::endpoint& ep , bool wait_if_not_available) { INVOKE_IN_IMPL(listen_on_endpoint, ep, wait_if_not_available); } void node::accept_incoming_connections(bool accept) { INVOKE_IN_IMPL(accept_incoming_connections, accept); } void node::listen_on_port( uint16_t port, bool wait_if_not_available ) { INVOKE_IN_IMPL(listen_on_port, port, wait_if_not_available); } fc::ip::endpoint node::get_actual_listening_endpoint() const { INVOKE_IN_IMPL(get_actual_listening_endpoint); } std::vector<peer_status> node::get_connected_peers() const { INVOKE_IN_IMPL(get_connected_peers); } uint32_t node::get_connection_count() const { INVOKE_IN_IMPL(get_connection_count); } void node::broadcast( const message& msg ) { INVOKE_IN_IMPL(broadcast, msg); } void node::sync_from(const item_id& current_head_block, const std::vector<uint32_t>& hard_fork_block_numbers) { INVOKE_IN_IMPL(sync_from, current_head_block, hard_fork_block_numbers); } bool node::is_connected() const { INVOKE_IN_IMPL(is_connected); } std::vector<potential_peer_record> node::get_potential_peers()const { INVOKE_IN_IMPL(get_potential_peers); } void node::set_advanced_node_parameters( const fc::variant_object& params ) { INVOKE_IN_IMPL(set_advanced_node_parameters, params); } node_configuration node::get_advanced_node_parameters()const { INVOKE_IN_IMPL(get_advanced_node_parameters); } message_propagation_data node::get_transaction_propagation_data( const graphene::net::transaction_id_type& transaction_id ) { INVOKE_IN_IMPL(get_transaction_propagation_data, transaction_id); } message_propagation_data node::get_block_propagation_data( const graphene::net::block_id_type& block_id ) { INVOKE_IN_IMPL(get_block_propagation_data, block_id); } node_id_t node::get_node_id() const { INVOKE_IN_IMPL(get_node_id); } void node::set_allowed_peers( const std::vector<node_id_t>& allowed_peers ) { INVOKE_IN_IMPL(set_allowed_peers, allowed_peers); } void node::clear_peer_database() { INVOKE_IN_IMPL(clear_peer_database); } void node::set_total_bandwidth_limit(uint32_t upload_bytes_per_second, uint32_t download_bytes_per_second) { INVOKE_IN_IMPL(set_total_bandwidth_limit, upload_bytes_per_second, download_bytes_per_second); } fc::variant_object node::get_call_statistics() const { INVOKE_IN_IMPL(get_call_statistics); } fc::variant_object node::network_get_info() const { INVOKE_IN_IMPL(network_get_info); } fc::variant_object node::network_get_usage_stats() const { INVOKE_IN_IMPL(network_get_usage_stats); } void node::close() { INVOKE_IN_IMPL(close); } struct simulated_network::node_info { node_delegate* delegate; fc::future<void> message_sender_task_done; std::queue<message> messages_to_deliver; node_info(node_delegate* delegate) : delegate(delegate) {} }; simulated_network::~simulated_network() { for( node_info* network_node_info : network_nodes ) { network_node_info->message_sender_task_done.cancel_and_wait("~simulated_network()"); delete network_node_info; } } void simulated_network::message_sender(node_info* destination_node) { while (!destination_node->messages_to_deliver.empty()) { try { const message& message_to_deliver = destination_node->messages_to_deliver.front(); if (message_to_deliver.msg_type == trx_message_type) destination_node->delegate->handle_transaction(message_to_deliver.as<trx_message>()); else if (message_to_deliver.msg_type == block_message_type) { std::vector<fc::uint160_t> contained_transaction_message_ids; destination_node->delegate->handle_block(message_to_deliver.as<block_message>(), false, contained_transaction_message_ids); } else destination_node->delegate->handle_message(message_to_deliver); } catch ( const fc::exception& e ) { elog( "${r}", ("r",e) ); } destination_node->messages_to_deliver.pop(); } } void simulated_network::broadcast( const message& item_to_broadcast ) { for (node_info* network_node_info : network_nodes) { network_node_info->messages_to_deliver.emplace(item_to_broadcast); if (!network_node_info->message_sender_task_done.valid() || network_node_info->message_sender_task_done.ready()) network_node_info->message_sender_task_done = fc::async([=](){ message_sender(network_node_info); }, "simulated_network_sender"); } } void simulated_network::add_node_delegate( node_delegate* node_delegate_to_add ) { network_nodes.push_back(new node_info(node_delegate_to_add)); } namespace detail { #define ROLLING_WINDOW_SIZE 1000 #define INITIALIZE_ACCUMULATOR(r, data, method_name) \ , BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))(boost::accumulators::tag::rolling_window::window_size = ROLLING_WINDOW_SIZE) \ , BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator))(boost::accumulators::tag::rolling_window::window_size = ROLLING_WINDOW_SIZE) \ , BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator))(boost::accumulators::tag::rolling_window::window_size = ROLLING_WINDOW_SIZE) statistics_gathering_node_delegate_wrapper::statistics_gathering_node_delegate_wrapper(node_delegate* delegate, fc::thread* thread_for_delegate_calls) : _node_delegate(delegate), _thread(thread_for_delegate_calls) BOOST_PP_SEQ_FOR_EACH(INITIALIZE_ACCUMULATOR, unused, NODE_DELEGATE_METHOD_NAMES) {} #undef INITIALIZE_ACCUMULATOR fc::variant_object statistics_gathering_node_delegate_wrapper::get_call_statistics() { fc::mutable_variant_object statistics; std::ostringstream note; note << "All times are in microseconds, mean is the average of the last " << ROLLING_WINDOW_SIZE << " call times"; statistics["_note"] = note.str(); #define ADD_STATISTICS_FOR_METHOD(r, data, method_name) \ fc::mutable_variant_object BOOST_PP_CAT(method_name, _stats); \ BOOST_PP_CAT(method_name, _stats)["min"] = boost::accumulators::min(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["mean"] = boost::accumulators::rolling_mean(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["max"] = boost::accumulators::max(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["sum"] = boost::accumulators::sum(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_before_min"] = boost::accumulators::min(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_before_mean"] = boost::accumulators::rolling_mean(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_before_max"] = boost::accumulators::max(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_before_sum"] = boost::accumulators::sum(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_before_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_after_min"] = boost::accumulators::min(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_after_mean"] = boost::accumulators::rolling_mean(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_after_max"] = boost::accumulators::max(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["delay_after_sum"] = boost::accumulators::sum(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _delay_after_accumulator))); \ BOOST_PP_CAT(method_name, _stats)["count"] = boost::accumulators::count(BOOST_PP_CAT(_, BOOST_PP_CAT(method_name, _execution_accumulator))); \ statistics[BOOST_PP_STRINGIZE(method_name)] = BOOST_PP_CAT(method_name, _stats); BOOST_PP_SEQ_FOR_EACH(ADD_STATISTICS_FOR_METHOD, unused, NODE_DELEGATE_METHOD_NAMES) #undef ADD_STATISTICS_FOR_METHOD return statistics; } // define VERBOSE_NODE_DELEGATE_LOGGING to log whenever the node delegate throws exceptions //#define VERBOSE_NODE_DELEGATE_LOGGING #ifdef VERBOSE_NODE_DELEGATE_LOGGING # define INVOKE_AND_COLLECT_STATISTICS(method_name, ...) \ try \ { \ if (_thread->is_current()) \ { \ call_statistics_collector statistics_collector(#method_name, \ &_ ## method_name ## _execution_accumulator, \ &_ ## method_name ## _delay_before_accumulator, \ &_ ## method_name ## _delay_after_accumulator); \ call_statistics_collector::actual_execution_measurement_helper helper(statistics_collector); \ return _node_delegate->method_name(__VA_ARGS__); \ } \ else \ return _thread->async([&](){ \ call_statistics_collector statistics_collector(#method_name, \ &_ ## method_name ## _execution_accumulator, \ &_ ## method_name ## _delay_before_accumulator, \ &_ ## method_name ## _delay_after_accumulator); \ call_statistics_collector::actual_execution_measurement_helper helper(statistics_collector); \ return _node_delegate->method_name(__VA_ARGS__); \ }, "invoke " BOOST_STRINGIZE(method_name)).wait(); \ } \ catch (const fc::exception& e) \ { \ dlog("node_delegate threw fc::exception: ${e}", ("e", e)); \ throw; \ } \ catch (const std::exception& e) \ { \ dlog("node_delegate threw std::exception: ${e}", ("e", e.what())); \ throw; \ } \ catch (...) \ { \ dlog("node_delegate threw unrecognized exception"); \ throw; \ } #else #define INVOKE_AND_COLLECT_STATISTICS( method_name, ... ) \ FC_UNUSED( _thread ) \ return _node_delegate->method_name(__VA_ARGS__); /* # define INVOKE_AND_COLLECT_STATISTICS(method_name, ...) \ call_statistics_collector statistics_collector(#method_name, \ &_ ## method_name ## _execution_accumulator, \ &_ ## method_name ## _delay_before_accumulator, \ &_ ## method_name ## _delay_after_accumulator); \ if ( _thread->is_current()) \ { \ call_statistics_collector statistics_collector(#method_name, \ &_ ## method_name ## _execution_accumulator, \ &_ ## method_name ## _delay_before_accumulator, \ &_ ## method_name ## _delay_after_accumulator); \ call_statistics_collector::actual_execution_measurement_helper helper(statistics_collector); \ return _node_delegate->method_name(__VA_ARGS__); \ } \ else \ return _thread->async([&](){ \ call_statistics_collector statistics_collector(#method_name, \ &_ ## method_name ## _execution_accumulator, \ &_ ## method_name ## _delay_before_accumulator, \ &_ ## method_name ## _delay_after_accumulator); \ call_statistics_collector::actual_execution_measurement_helper helper(statistics_collector); \ return _node_delegate->method_name(__VA_ARGS__); \ }, "invoke " BOOST_STRINGIZE(method_name)).wait() */ #endif steem::protocol::chain_id_type statistics_gathering_node_delegate_wrapper::get_chain_id() const { INVOKE_AND_COLLECT_STATISTICS(get_chain_id); } bool statistics_gathering_node_delegate_wrapper::has_item( const net::item_id& id ) { INVOKE_AND_COLLECT_STATISTICS(has_item, id); } void statistics_gathering_node_delegate_wrapper::handle_message( const message& message_to_handle ) { INVOKE_AND_COLLECT_STATISTICS(handle_message, message_to_handle); } bool statistics_gathering_node_delegate_wrapper::handle_block( const graphene::net::block_message& block_message, bool sync_mode, std::vector<fc::uint160_t>& contained_transaction_message_ids) { INVOKE_AND_COLLECT_STATISTICS(handle_block, block_message, sync_mode, contained_transaction_message_ids); } void statistics_gathering_node_delegate_wrapper::handle_transaction( const graphene::net::trx_message& transaction_message ) { INVOKE_AND_COLLECT_STATISTICS(handle_transaction, transaction_message); } std::vector<item_hash_t> statistics_gathering_node_delegate_wrapper::get_block_ids(const std::vector<item_hash_t>& blockchain_synopsis, uint32_t& remaining_item_count, uint32_t limit /* = 2000 */) { INVOKE_AND_COLLECT_STATISTICS(get_block_ids, blockchain_synopsis, remaining_item_count, limit); } message statistics_gathering_node_delegate_wrapper::get_item( const item_id& id ) { INVOKE_AND_COLLECT_STATISTICS(get_item, id); } std::vector<item_hash_t> statistics_gathering_node_delegate_wrapper::get_blockchain_synopsis(const item_hash_t& reference_point, uint32_t number_of_blocks_after_reference_point) { INVOKE_AND_COLLECT_STATISTICS(get_blockchain_synopsis, reference_point, number_of_blocks_after_reference_point); } void statistics_gathering_node_delegate_wrapper::sync_status( uint32_t item_type, uint32_t item_count ) { INVOKE_AND_COLLECT_STATISTICS(sync_status, item_type, item_count); } void statistics_gathering_node_delegate_wrapper::connection_count_changed( uint32_t c ) { INVOKE_AND_COLLECT_STATISTICS(connection_count_changed, c); } uint32_t statistics_gathering_node_delegate_wrapper::get_block_number(const item_hash_t& block_id) { // this function doesn't need to block, ASSERT_TASK_NOT_PREEMPTED(); return _node_delegate->get_block_number(block_id); } fc::time_point_sec statistics_gathering_node_delegate_wrapper::get_block_time(const item_hash_t& block_id) { INVOKE_AND_COLLECT_STATISTICS(get_block_time, block_id); } /** returns graphene::blockchain::now() */ fc::time_point_sec statistics_gathering_node_delegate_wrapper::get_blockchain_now() { // this function doesn't need to block, ASSERT_TASK_NOT_PREEMPTED(); return _node_delegate->get_blockchain_now(); } item_hash_t statistics_gathering_node_delegate_wrapper::get_head_block_id() const { INVOKE_AND_COLLECT_STATISTICS(get_head_block_id); } uint32_t statistics_gathering_node_delegate_wrapper::estimate_last_known_fork_from_git_revision_timestamp(uint32_t unix_timestamp) const { INVOKE_AND_COLLECT_STATISTICS(estimate_last_known_fork_from_git_revision_timestamp, unix_timestamp); } void statistics_gathering_node_delegate_wrapper::error_encountered(const std::string& message, const fc::oexception& error) { INVOKE_AND_COLLECT_STATISTICS(error_encountered, message, error); } #undef INVOKE_AND_COLLECT_STATISTICS } // end namespace detail } } // end namespace graphene::net
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #ifndef UTILITIES_IDF_WORKSPACEWATCHER_HPP #define UTILITIES_IDF_WORKSPACEWATCHER_HPP #include <utilities/UtilitiesAPI.hpp> #include <utilities/idf/IdfObject.hpp> #include <utilities/idf/Workspace.hpp> namespace openstudio{ /** WorkspaceWatcher watches a Workspace for signals emitted on changes. This signals will cause the * watcher to mark the Workspace as dirty. The dirty flag will persist until reset by the user. A virtual * method onChangeWorkspace is also available to override, it is called everytime the Workspace changes. The * virtual method onBecomeDirty is called only after dirty transitions from false to true. Alternatively, the * virtual method onBecomeClean is called only after dirty transitions from true to false. * * WorkspaceWatcher an atypical QObject because it is designed to be stack allocated. In many cases it * would be preferred to connect your own heap allocated QObject to the Workspace signals directly rather * than using this convenience class. **/ class UTILITIES_API WorkspaceWatcher { public: WorkspaceWatcher(const Workspace& workspace); virtual ~WorkspaceWatcher(); /// is the watcher currently enabled bool enabled() const; /// enable the watcher void enable(); // disable watcher, returns true if it was enabled bool disable(); /// true if workspace has changed bool dirty() const; /// true if an object has been added bool objectAdded() const; /// true if an object has been removed bool objectRemoved() const; /// resets dirty, objectAdded, and objectRemoved virtual void clearState(); /// called each time the IdfObject changes if watcher enabled virtual void onChangeWorkspace(); /// called after dirty transitions from false to true if watcher enabled virtual void onBecomeDirty(); /// called after dirty transitions from true to false if watcher enabled virtual void onBecomeClean(); /// called immediately when a new object is added to the workspace if watcher enabled /// the object may not be fully constructed /// this may be called when an object is restored after a failed remove virtual void onObjectAdd(const WorkspaceObject& addedObject); /// called immediately before an object is removed from the workspace if watcher enabled /// the object is still valid when this method is called virtual void onObjectRemove(const WorkspaceObject& removedObject); // public slots: void change(); // Note: Args 2 & 3 are simply to comply with Nano::Signal template parameters void objectAdd(const WorkspaceObject& addedObject, const openstudio::IddObjectType& type, const openstudio::UUID& uuid); // Note: Args 2 & 3 are simply to comply with Nano::Signal template parameters void objectRemove(const WorkspaceObject& removedObject, const openstudio::IddObjectType& type, const openstudio::UUID& uuid); private: bool m_enabled; bool m_dirty; bool m_objectAdded; bool m_objectRemoved; }; } #endif
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: Xerces_autoconf_config.msvc.hpp 1224891 2011-12-27 10:59:21Z amassari $ */ #if !defined(XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP) #define XERCESC_INCLUDE_GUARD_XERCES_AUTOCONFIG_CONFIG_HPP // // There are two primary xerces configuration header files: // // Xerces_autoconf_config.hpp // // For configuration of items that must be accessable // through public headers. This file has limited information // and carefully works to avoid collision of macro names, etc. // // This file is included by XercesDefs.h. // This version of the file is specific for Microsoft Visual C++ // family of compilers // // config.h // // This file is not used with Microsoft Visual C++; the macros // it would specify are instead hardcoded in the makefiles // #include <basetsd.h> // silence the warning "while compiling class-template member function xxxx : identifier was truncated to '255' // characters in the browser information" #pragma warning( disable: 4786 ) // silence the warning "class 'XXXX' needs to have dll-interface to be used by clients of class 'YYYY'" #pragma warning( disable: 4251) // --------------------------------------------------------------------------- // These defines have been hardcoded for the Microsoft Visual C++ compilers // --------------------------------------------------------------------------- #undef XERCES_AUTOCONF #undef XERCES_HAVE_SYS_TYPES_H #undef XERCES_HAVE_INTTYPES_H #define XERCES_S16BIT_INT signed short #define XERCES_U16BIT_INT unsigned short #define XERCES_S32BIT_INT INT32 #define XERCES_U32BIT_INT UINT32 // While VC6 has 64-bit int, there is no support in the libraries // (e.g., iostream). So we are going to stick to 32-bit ints. // #if (_MSC_VER >= 1300) # define XERCES_S64BIT_INT INT64 # define XERCES_U64BIT_INT UINT64 #else # define XERCES_S64BIT_INT INT32 # define XERCES_U64BIT_INT UINT32 #endif #ifdef _NATIVE_WCHAR_T_DEFINED # define XERCES_XMLCH_T wchar_t #else # define XERCES_XMLCH_T unsigned short #endif #define XERCES_SIZE_T SIZE_T #define XERCES_SSIZE_T SSIZE_T #define XERCES_HAS_CPP_NAMESPACE 1 #define XERCES_STD_NAMESPACE 1 #define XERCES_NEW_IOSTREAMS 1 #undef XERCES_NO_NATIVE_BOOL #define XERCES_LSTRSUPPORT 1 #ifdef XERCES_STATIC_LIBRARY # define XERCES_PLATFORM_EXPORT # define XERCES_PLATFORM_IMPORT #else # define XERCES_PLATFORM_EXPORT __declspec(dllexport) # define XERCES_PLATFORM_IMPORT __declspec(dllimport) # define DLL_EXPORT #endif #define XERCES_MFC_SUPPORT #if (_MSC_VER >= 1400) # define XERCES_HAVE_INTRIN_H 1 # define XERCES_HAVE_EMMINTRIN_H 1 # define XERCES_HAVE_CPUID_INTRINSIC # define XERCES_HAVE_SSE2_INTRINSIC #endif // --------------------------------------------------------------------------- // XMLSize_t is the unsigned integral type. // --------------------------------------------------------------------------- typedef XERCES_SIZE_T XMLSize_t; typedef XERCES_SSIZE_T XMLSSize_t; // --------------------------------------------------------------------------- // Define our version of the XML character // --------------------------------------------------------------------------- typedef XERCES_XMLCH_T XMLCh; // --------------------------------------------------------------------------- // Define unsigned 16, 32, and 64 bit integers // --------------------------------------------------------------------------- typedef XERCES_U16BIT_INT XMLUInt16; typedef XERCES_U32BIT_INT XMLUInt32; typedef XERCES_U64BIT_INT XMLUInt64; // --------------------------------------------------------------------------- // Define signed 16, 32, and 64 bit integers // --------------------------------------------------------------------------- typedef XERCES_S16BIT_INT XMLInt16; typedef XERCES_S32BIT_INT XMLInt32; typedef XERCES_S64BIT_INT XMLInt64; // --------------------------------------------------------------------------- // XMLFilePos is the type used to represent a file position. // --------------------------------------------------------------------------- typedef XMLUInt64 XMLFilePos; // --------------------------------------------------------------------------- // XMLFileLoc is the type used to represent a file location (line/column). // --------------------------------------------------------------------------- typedef XMLUInt64 XMLFileLoc; // --------------------------------------------------------------------------- // Force on the Xerces debug token if it is on in the build environment // --------------------------------------------------------------------------- #if defined(_DEBUG) # define XERCES_DEBUG #endif #endif
/********************************************************************** Audacity: A Digital Audio Editor Effect.cpp Dominic Mazzoni Vaughan Johnson Martyn Shaw *******************************************************************//** \class Effect \brief Base class for many of the effects in Audacity. *//*******************************************************************/ #include "../Audacity.h" #include "Effect.h" #include "../Experimental.h" #include <algorithm> #include <wx/defs.h> #include <wx/sizer.h> #include "../AudioIO.h" #include "../LabelTrack.h" #include "../Mix.h" #include "../PluginManager.h" #include "../ProjectAudioManager.h" #include "../ProjectSettings.h" #include "../ShuttleGui.h" #include "../Shuttle.h" #include "../ViewInfo.h" #include "../WaveTrack.h" #include "../wxFileNameWrapper.h" #include "../widgets/ProgressDialog.h" #include "../ondemand/ODManager.h" #include "../tracks/playabletrack/wavetrack/ui/WaveTrackView.h" #include "../tracks/playabletrack/wavetrack/ui/WaveTrackViewConstants.h" #include "../widgets/NumericTextCtrl.h" #include "../widgets/AudacityMessageBox.h" #include "../widgets/ErrorDialog.h" #include <unordered_map> // Effect application counter int Effect::nEffectsDone=0; static const int kPlayID = 20102; static const int kRewindID = 20103; static const int kFFwdID = 20104; const wxString Effect::kUserPresetIdent = wxT("User Preset:"); const wxString Effect::kFactoryPresetIdent = wxT("Factory Preset:"); const wxString Effect::kCurrentSettingsIdent = wxT("<Current Settings>"); const wxString Effect::kFactoryDefaultsIdent = wxT("<Factory Defaults>"); using t2bHash = std::unordered_map< void*, bool >; namespace { Effect::VetoDialogHook &GetVetoDialogHook() { static Effect::VetoDialogHook sHook = nullptr; return sHook; } } auto Effect::SetVetoDialogHook( VetoDialogHook hook ) -> VetoDialogHook { auto &theHook = GetVetoDialogHook(); auto result = theHook; theHook = hook; return result; } Effect::Effect() { mClient = NULL; mTracks = NULL; mT0 = 0.0; mT1 = 0.0; mDuration = 0.0; mIsPreview = false; mIsLinearEffect = false; mPreviewWithNotSelected = false; mPreviewFullSelection = false; mNumTracks = 0; mNumGroups = 0; mProgress = NULL; mUIParent = NULL; mUIDialog = NULL; mNumAudioIn = 0; mNumAudioOut = 0; mBufferSize = 0; mBlockSize = 0; mNumChannels = 0; mUIDebug = false; // PRL: I think this initialization of mProjectRate doesn't matter // because it is always reassigned in DoEffect before it is used // STF: but can't call AudioIOBase::GetOptimalSupportedSampleRate() here. gPrefs->Read(wxT("/SamplingRate/DefaultProjectSampleRate"), &mProjectRate, 44100); mIsBatch = false; } Effect::~Effect() { if (mUIDialog) { mUIDialog->Close(); } } // EffectDefinitionInterface implementation EffectType Effect::GetType() { if (mClient) { return mClient->GetType(); } return EffectTypeNone; } PluginPath Effect::GetPath() { if (mClient) { return mClient->GetPath(); } return BUILTIN_EFFECT_PREFIX + GetSymbol().Internal(); } ComponentInterfaceSymbol Effect::GetSymbol() { if (mClient) { return mClient->GetSymbol(); } return {}; } VendorSymbol Effect::GetVendor() { if (mClient) { return mClient->GetVendor(); } return XO("Audacity"); } wxString Effect::GetVersion() { if (mClient) { return mClient->GetVersion(); } return AUDACITY_VERSION_STRING; } TranslatableString Effect::GetDescription() { if (mClient) { return mClient->GetDescription(); } return {}; } EffectFamilySymbol Effect::GetFamily() { if (mClient) { return mClient->GetFamily(); } // Unusually, the internal and visible strings differ for the built-in // effect family. return { wxT("Audacity"), XO("Built-in") }; } bool Effect::IsInteractive() { if (mClient) { return mClient->IsInteractive(); } return true; } bool Effect::IsDefault() { if (mClient) { return mClient->IsDefault(); } return true; } bool Effect::IsLegacy() { if (mClient) { return false; } return true; } bool Effect::SupportsRealtime() { if (mClient) { return mClient->SupportsRealtime(); } return false; } bool Effect::SupportsAutomation() { if (mClient) { return mClient->SupportsAutomation(); } return true; } // EffectClientInterface implementation bool Effect::SetHost(EffectHostInterface *host) { if (mClient) { return mClient->SetHost(host); } return true; } unsigned Effect::GetAudioInCount() { if (mClient) { return mClient->GetAudioInCount(); } return 0; } unsigned Effect::GetAudioOutCount() { if (mClient) { return mClient->GetAudioOutCount(); } return 0; } int Effect::GetMidiInCount() { if (mClient) { return mClient->GetMidiInCount(); } return 0; } int Effect::GetMidiOutCount() { if (mClient) { return mClient->GetMidiOutCount(); } return 0; } void Effect::SetSampleRate(double rate) { if (mClient) { mClient->SetSampleRate(rate); } mSampleRate = rate; } size_t Effect::SetBlockSize(size_t maxBlockSize) { if (mClient) { return mClient->SetBlockSize(maxBlockSize); } mBlockSize = maxBlockSize; return mBlockSize; } size_t Effect::GetBlockSize() const { if (mClient) { return mClient->GetBlockSize(); } return mBlockSize; } sampleCount Effect::GetLatency() { if (mClient) { return mClient->GetLatency(); } return 0; } size_t Effect::GetTailSize() { if (mClient) { return mClient->GetTailSize(); } return 0; } bool Effect::IsReady() { if (mClient) { return mClient->IsReady(); } return true; } bool Effect::ProcessInitialize(sampleCount totalLen, ChannelNames chanMap) { if (mClient) { return mClient->ProcessInitialize(totalLen, chanMap); } return true; } bool Effect::ProcessFinalize() { if (mClient) { return mClient->ProcessFinalize(); } return true; } size_t Effect::ProcessBlock(float **inBlock, float **outBlock, size_t blockLen) { if (mClient) { return mClient->ProcessBlock(inBlock, outBlock, blockLen); } return 0; } bool Effect::RealtimeInitialize() { if (mClient) { mBlockSize = mClient->SetBlockSize(512); return mClient->RealtimeInitialize(); } mBlockSize = 512; return false; } bool Effect::RealtimeAddProcessor(unsigned numChannels, float sampleRate) { if (mClient) { return mClient->RealtimeAddProcessor(numChannels, sampleRate); } return true; } bool Effect::RealtimeFinalize() { if (mClient) { return mClient->RealtimeFinalize(); } return false; } bool Effect::RealtimeSuspend() { if (mClient) return mClient->RealtimeSuspend(); return true; } bool Effect::RealtimeResume() { if (mClient) return mClient->RealtimeResume(); return true; } bool Effect::RealtimeProcessStart() { if (mClient) { return mClient->RealtimeProcessStart(); } return true; } size_t Effect::RealtimeProcess(int group, float **inbuf, float **outbuf, size_t numSamples) { if (mClient) { return mClient->RealtimeProcess(group, inbuf, outbuf, numSamples); } return 0; } bool Effect::RealtimeProcessEnd() { if (mClient) { return mClient->RealtimeProcessEnd(); } return true; } bool Effect::ShowInterface(wxWindow &parent, const EffectDialogFactory &factory, bool forceModal) { if (!IsInteractive()) { return true; } if (mUIDialog) { if ( mUIDialog->Close(true) ) mUIDialog = nullptr; return false; } if (mClient) { return mClient->ShowInterface(parent, factory, forceModal); } // mUIDialog is null auto cleanup = valueRestorer( mUIDialog ); if ( factory ) mUIDialog = factory(parent, this, this); if (!mUIDialog) { return false; } mUIDialog->Layout(); mUIDialog->Fit(); mUIDialog->SetMinSize(mUIDialog->GetSize()); auto hook = GetVetoDialogHook(); if( hook && hook( mUIDialog ) ) return false; if( SupportsRealtime() && !forceModal ) { mUIDialog->Show(); cleanup.release(); // Return false to bypass effect processing return false; } bool res = mUIDialog->ShowModal() != 0; return res; } bool Effect::GetAutomationParameters(CommandParameters & parms) { if (mClient) { return mClient->GetAutomationParameters(parms); } return true; } bool Effect::SetAutomationParameters(CommandParameters & parms) { if (mClient) { return mClient->SetAutomationParameters(parms); } return true; } bool Effect::LoadUserPreset(const RegistryPath & name) { if (mClient) { return mClient->LoadUserPreset(name); } wxString parms; if (!GetPrivateConfig(name, wxT("Parameters"), parms)) { return false; } return SetAutomationParameters(parms); } bool Effect::SaveUserPreset(const RegistryPath & name) { if (mClient) { return mClient->SaveUserPreset(name); } wxString parms; if (!GetAutomationParameters(parms)) { return false; } return SetPrivateConfig(name, wxT("Parameters"), parms); } RegistryPaths Effect::GetFactoryPresets() { if (mClient) { return mClient->GetFactoryPresets(); } return {}; } bool Effect::LoadFactoryPreset(int id) { if (mClient) { return mClient->LoadFactoryPreset(id); } return true; } bool Effect::LoadFactoryDefaults() { if (mClient) { return mClient->LoadFactoryDefaults(); } return LoadUserPreset(GetFactoryDefaultsGroup()); } // EffectUIClientInterface implementation void Effect::SetHostUI(EffectUIHostInterface *WXUNUSED(host)) { } bool Effect::PopulateUI(ShuttleGui &S) { auto parent = S.GetParent(); mUIParent = parent; mUIParent->PushEventHandler(this); // LoadUserPreset(GetCurrentSettingsGroup()); PopulateOrExchange(S); mUIParent->SetMinSize(mUIParent->GetSizer()->GetMinSize()); return true; } bool Effect::IsGraphicalUI() { return false; } bool Effect::ValidateUI() { return mUIParent->Validate(); } bool Effect::HideUI() { return true; } bool Effect::CloseUI() { if (mUIParent) mUIParent->RemoveEventHandler(this); mUIParent = NULL; mUIDialog = NULL; return true; } bool Effect::CanExportPresets() { return true; } void Effect::ExportPresets() { wxString params; GetAutomationParameters(params); params = GetSymbol().Internal() + ":" + params; auto path = FileNames::DefaultToDocumentsFolder(wxT("Presets/Path")); wxFileDialog dlog(NULL, _("Export Effect Parameters"), path.GetFullPath(), wxEmptyString, _("Presets (*.txt)|*.txt|All files|*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT | wxRESIZE_BORDER); if (dlog.ShowModal() != wxID_OK) { return; } path = dlog.GetPath(); gPrefs->Write(wxT("Presets/Path"), path.GetPath()); // Create/Open the file wxFFile f(path.GetFullPath(), wxT("wb")); if (!f.IsOpened()) { AudacityMessageBox( XO("Could not open file: \"%s\"").Format( path.GetFullPath() ), XO("Error Saving Effect Presets"), wxICON_EXCLAMATION, NULL); return; } f.Write(params); if (f.Error()) { AudacityMessageBox( XO("Error writing to file: \"%s\"").Format( path.GetFullPath() ), XO("Error Saving Effect Presets"), wxICON_EXCLAMATION, NULL); } f.Close(); //SetWindowTitle(); } void Effect::ImportPresets() { wxString params; auto path = FileNames::DefaultToDocumentsFolder(wxT("Presets/Path")); wxFileDialog dlog(NULL, _("Import Effect Parameters"), path.GetPath(), wxEmptyString, _("Presets (*.txt)|*.txt|All files|*"), wxFD_OPEN | wxRESIZE_BORDER); if (dlog.ShowModal() != wxID_OK) { return; } path = dlog.GetPath(); if( !path.IsOk()) return; gPrefs->Write(wxT("Presets/Path"), path.GetPath()); wxFFile f(path.GetFullPath()); if (f.IsOpened()) { if (f.ReadAll(&params)) { wxString ident = params.BeforeFirst(':'); params = params.AfterFirst(':'); if (ident != GetSymbol().Internal()) { // effect identifiers are a sensible length! // must also have some params. if ((params.Length() < 2 ) || (ident.Length() < 2) || (ident.Length() > 30)) { Effect::MessageBox( /* i18n-hint %s will be replaced by a file name */ XO("%s: is not a valid presets file.\n") .Format(path.GetFullName())); } else { Effect::MessageBox( /* i18n-hint %s will be replaced by a file name */ XO("%s: is for a different Effect, Generator or Analyzer.\n") .Format(path.GetFullName())); } return; } SetAutomationParameters(params); } } //SetWindowTitle(); } bool Effect::HasOptions() { return false; } void Effect::ShowOptions() { } // EffectHostInterface implementation double Effect::GetDefaultDuration() { return 30.0; } double Effect::GetDuration() { if (mDuration < 0.0) { mDuration = 0.0; } return mDuration; } NumericFormatSymbol Effect::GetDurationFormat() { return mDurationFormat; } NumericFormatSymbol Effect::GetSelectionFormat() { if( FindProject() ) return ProjectSettings::Get( *FindProject() ).GetSelectionFormat(); return NumericConverter::HoursMinsSecondsFormat(); } void Effect::SetDuration(double seconds) { if (seconds < 0.0) { seconds = 0.0; } if (GetType() == EffectTypeGenerate) { SetPrivateConfig(GetCurrentSettingsGroup(), wxT("LastUsedDuration"), seconds); } mDuration = seconds; mIsSelection = false; return; } RegistryPath Effect::GetUserPresetsGroup(const RegistryPath & name) { RegistryPath group = wxT("UserPresets"); if (!name.empty()) { group += wxCONFIG_PATH_SEPARATOR + name; } return group; } RegistryPath Effect::GetCurrentSettingsGroup() { return wxT("CurrentSettings"); } RegistryPath Effect::GetFactoryDefaultsGroup() { return wxT("FactoryDefaults"); } wxString Effect::GetSavedStateGroup() { return wxT("SavedState"); } // ConfigClientInterface implementation bool Effect::HasSharedConfigGroup(const RegistryPath & group) { return PluginManager::Get().HasSharedConfigGroup(GetID(), group); } bool Effect::GetSharedConfigSubgroups(const RegistryPath & group, RegistryPaths &subgroups) { return PluginManager::Get().GetSharedConfigSubgroups(GetID(), group, subgroups); } bool Effect::GetSharedConfig(const RegistryPath & group, const RegistryPath & key, wxString & value, const wxString & defval) { return PluginManager::Get().GetSharedConfig(GetID(), group, key, value, defval); } bool Effect::GetSharedConfig(const RegistryPath & group, const RegistryPath & key, int & value, int defval) { return PluginManager::Get().GetSharedConfig(GetID(), group, key, value, defval); } bool Effect::GetSharedConfig(const RegistryPath & group, const RegistryPath & key, bool & value, bool defval) { return PluginManager::Get().GetSharedConfig(GetID(), group, key, value, defval); } bool Effect::GetSharedConfig(const RegistryPath & group, const RegistryPath & key, float & value, float defval) { return PluginManager::Get().GetSharedConfig(GetID(), group, key, value, defval); } bool Effect::GetSharedConfig(const RegistryPath & group, const RegistryPath & key, double & value, double defval) { return PluginManager::Get().GetSharedConfig(GetID(), group, key, value, defval); } bool Effect::SetSharedConfig(const RegistryPath & group, const RegistryPath & key, const wxString & value) { return PluginManager::Get().SetSharedConfig(GetID(), group, key, value); } bool Effect::SetSharedConfig(const RegistryPath & group, const RegistryPath & key, const int & value) { return PluginManager::Get().SetSharedConfig(GetID(), group, key, value); } bool Effect::SetSharedConfig(const RegistryPath & group, const RegistryPath & key, const bool & value) { return PluginManager::Get().SetSharedConfig(GetID(), group, key, value); } bool Effect::SetSharedConfig(const RegistryPath & group, const RegistryPath & key, const float & value) { return PluginManager::Get().SetSharedConfig(GetID(), group, key, value); } bool Effect::SetSharedConfig(const RegistryPath & group, const RegistryPath & key, const double & value) { return PluginManager::Get().SetSharedConfig(GetID(), group, key, value); } bool Effect::RemoveSharedConfigSubgroup(const RegistryPath & group) { return PluginManager::Get().RemoveSharedConfigSubgroup(GetID(), group); } bool Effect::RemoveSharedConfig(const RegistryPath & group, const RegistryPath & key) { return PluginManager::Get().RemoveSharedConfig(GetID(), group, key); } bool Effect::HasPrivateConfigGroup(const RegistryPath & group) { return PluginManager::Get().HasPrivateConfigGroup(GetID(), group); } bool Effect::GetPrivateConfigSubgroups(const RegistryPath & group, RegistryPaths & subgroups) { return PluginManager::Get().GetPrivateConfigSubgroups(GetID(), group, subgroups); } bool Effect::GetPrivateConfig(const RegistryPath & group, const RegistryPath & key, wxString & value, const wxString & defval) { return PluginManager::Get().GetPrivateConfig(GetID(), group, key, value, defval); } bool Effect::GetPrivateConfig(const RegistryPath & group, const RegistryPath & key, int & value, int defval) { return PluginManager::Get().GetPrivateConfig(GetID(), group, key, value, defval); } bool Effect::GetPrivateConfig(const RegistryPath & group, const RegistryPath & key, bool & value, bool defval) { return PluginManager::Get().GetPrivateConfig(GetID(), group, key, value, defval); } bool Effect::GetPrivateConfig(const RegistryPath & group, const RegistryPath & key, float & value, float defval) { return PluginManager::Get().GetPrivateConfig(GetID(), group, key, value, defval); } bool Effect::GetPrivateConfig(const RegistryPath & group, const RegistryPath & key, double & value, double defval) { return PluginManager::Get().GetPrivateConfig(GetID(), group, key, value, defval); } bool Effect::SetPrivateConfig(const RegistryPath & group, const RegistryPath & key, const wxString & value) { return PluginManager::Get().SetPrivateConfig(GetID(), group, key, value); } bool Effect::SetPrivateConfig(const RegistryPath & group, const RegistryPath & key, const int & value) { return PluginManager::Get().SetPrivateConfig(GetID(), group, key, value); } bool Effect::SetPrivateConfig(const RegistryPath & group, const RegistryPath & key, const bool & value) { return PluginManager::Get().SetPrivateConfig(GetID(), group, key, value); } bool Effect::SetPrivateConfig(const RegistryPath & group, const RegistryPath & key, const float & value) { return PluginManager::Get().SetPrivateConfig(GetID(), group, key, value); } bool Effect::SetPrivateConfig(const RegistryPath & group, const RegistryPath & key, const double & value) { return PluginManager::Get().SetPrivateConfig(GetID(), group, key, value); } bool Effect::RemovePrivateConfigSubgroup(const RegistryPath & group) { return PluginManager::Get().RemovePrivateConfigSubgroup(GetID(), group); } bool Effect::RemovePrivateConfig(const RegistryPath & group, const RegistryPath & key) { return PluginManager::Get().RemovePrivateConfig(GetID(), group, key); } // Effect implementation PluginID Effect::GetID() { if (mClient) { return PluginManager::GetID(mClient); } return PluginManager::GetID(this); } bool Effect::Startup(EffectClientInterface *client) { // Let destructor know we need to be shutdown mClient = client; // Set host so client startup can use our services if (!SetHost(this)) { // Bail if the client startup fails mClient = NULL; return false; } mNumAudioIn = GetAudioInCount(); mNumAudioOut = GetAudioOutCount(); bool haveDefaults; GetPrivateConfig(GetFactoryDefaultsGroup(), wxT("Initialized"), haveDefaults, false); if (!haveDefaults) { SaveUserPreset(GetFactoryDefaultsGroup()); SetPrivateConfig(GetFactoryDefaultsGroup(), wxT("Initialized"), true); } LoadUserPreset(GetCurrentSettingsGroup()); return Startup(); } bool Effect::Startup() { return true; } bool Effect::GetAutomationParameters(wxString & parms) { CommandParameters eap; if (mUIDialog && !TransferDataFromWindow()) { return false; } ShuttleGetAutomation S; S.mpEap = &eap; if( DefineParams( S ) ){ ;// got eap value using DefineParams. } // Won't be needed in future else if (!GetAutomationParameters(eap)) { return false; } return eap.GetParameters(parms); } bool Effect::SetAutomationParameters(const wxString & parms) { wxString preset = parms; bool success = false; if (preset.StartsWith(kUserPresetIdent)) { preset.Replace(kUserPresetIdent, wxEmptyString, false); success = LoadUserPreset(GetUserPresetsGroup(preset)); } else if (preset.StartsWith(kFactoryPresetIdent)) { preset.Replace(kFactoryPresetIdent, wxEmptyString, false); auto presets = GetFactoryPresets(); success = LoadFactoryPreset( make_iterator_range( presets ).index( preset ) ); } else if (preset.StartsWith(kCurrentSettingsIdent)) { preset.Replace(kCurrentSettingsIdent, wxEmptyString, false); success = LoadUserPreset(GetCurrentSettingsGroup()); } else if (preset.StartsWith(kFactoryDefaultsIdent)) { preset.Replace(kFactoryDefaultsIdent, wxEmptyString, false); success = LoadUserPreset(GetFactoryDefaultsGroup()); } else { CommandParameters eap(parms); ShuttleSetAutomation S; S.SetForValidating( &eap ); // DefineParams returns false if not defined for this effect. if( !DefineParams( S ) ) // the old method... success = SetAutomationParameters(eap); else if( !S.bOK ) success = false; else{ success = true; S.SetForWriting( &eap ); DefineParams( S ); } } if (!success) { Effect::MessageBox( XO("%s: Could not load settings below. Default settings will be used.\n\n%s") .Format( GetName(), preset ) ); // We are using defualt settings and we still wish to continue. return true; //return false; } if (!mUIDialog) { return true; } return TransferDataToWindow(); } RegistryPaths Effect::GetUserPresets() { RegistryPaths presets; GetPrivateConfigSubgroups(GetUserPresetsGroup(wxEmptyString), presets); std::sort( presets.begin(), presets.end() ); return presets; } bool Effect::HasCurrentSettings() { return HasPrivateConfigGroup(GetCurrentSettingsGroup()); } bool Effect::HasFactoryDefaults() { return HasPrivateConfigGroup(GetFactoryDefaultsGroup()); } wxString Effect::ManualPage() { return wxEmptyString; } wxString Effect::HelpPage() { return wxEmptyString; } bool Effect::IsBatchProcessing() { return mIsBatch; } void Effect::SetBatchProcessing(bool start) { mIsBatch = start; if (start) { SaveUserPreset(GetSavedStateGroup()); } else { LoadUserPreset(GetSavedStateGroup()); } } bool Effect::DoEffect(double projectRate, TrackList *list, TrackFactory *factory, NotifyingSelectedRegion &selectedRegion, wxWindow *pParent, const EffectDialogFactory &dialogFactory) { wxASSERT(selectedRegion.duration() >= 0.0); mOutputTracks.reset(); mpSelectedRegion = &selectedRegion; mFactory = factory; mProjectRate = projectRate; mTracks = list; // Update track/group counts CountWaveTracks(); bool isSelection = false; mDuration = 0.0; if (GetType() == EffectTypeGenerate) { GetPrivateConfig(GetCurrentSettingsGroup(), wxT("LastUsedDuration"), mDuration, GetDefaultDuration()); } WaveTrack *newTrack{}; bool success = false; auto oldDuration = mDuration; auto cleanup = finally( [&] { if (!success) { if (newTrack) { mTracks->Remove(newTrack); } // LastUsedDuration may have been modified by Preview. SetDuration(oldDuration); } End(); ReplaceProcessedTracks( false ); } ); // We don't yet know the effect type for code in the Nyquist Prompt, so // assume it requires a track and handle errors when the effect runs. if ((GetType() == EffectTypeGenerate || GetPath() == NYQUIST_PROMPT_ID) && (mNumTracks == 0)) { newTrack = mTracks->Add(mFactory->NewWaveTrack()); newTrack->SetSelected(true); } mT0 = selectedRegion.t0(); mT1 = selectedRegion.t1(); if (mT1 > mT0) { // there is a selection: let's fit in there... // MJS: note that this is just for the TTC and is independent of the track rate // but we do need to make sure we have the right number of samples at the project rate double quantMT0 = QUANTIZED_TIME(mT0, mProjectRate); double quantMT1 = QUANTIZED_TIME(mT1, mProjectRate); mDuration = quantMT1 - quantMT0; isSelection = true; mT1 = mT0 + mDuration; } mDurationFormat = isSelection ? NumericConverter::TimeAndSampleFormat() : NumericConverter::DefaultSelectionFormat(); #ifdef EXPERIMENTAL_SPECTRAL_EDITING mF0 = selectedRegion.f0(); mF1 = selectedRegion.f1(); wxArrayString Names; if( mF0 != SelectedRegion::UndefinedFrequency ) Names.push_back(wxT("control-f0")); if( mF1 != SelectedRegion::UndefinedFrequency ) Names.push_back(wxT("control-f1")); SetPresetParameters( &Names, NULL ); #endif CountWaveTracks(); // Note: Init may read parameters from preferences if (!Init()) { return false; } // Prompting will be bypassed when applying an effect that has already // been configured, e.g. repeating the last effect on a different selection. // Prompting may call Effect::Preview if ( pParent && dialogFactory && IsInteractive() && !ShowInterface( *pParent, dialogFactory, IsBatchProcessing() ) ) { return false; } bool returnVal = true; bool skipFlag = CheckWhetherSkipEffect(); if (skipFlag == false) { auto name = GetName(); ProgressDialog progress{ name, XO("Applying %s...").Format( name ), pdlgHideStopButton }; auto vr = valueRestorer( mProgress, &progress ); returnVal = Process(); } if (returnVal && (mT1 >= mT0 )) { selectedRegion.setTimes(mT0, mT1); } success = returnVal; return returnVal; } bool Effect::Delegate( Effect &delegate ) { NotifyingSelectedRegion region; region.setTimes( mT0, mT1 ); return delegate.DoEffect( mProjectRate, mTracks, mFactory, region ); } // All legacy effects should have this overridden bool Effect::Init() { return true; } int Effect::GetPass() { return mPass; } bool Effect::InitPass1() { return true; } bool Effect::InitPass2() { return false; } bool Effect::Process() { CopyInputTracks(true); bool bGoodResult = true; // It's possible that the number of channels the effect expects changed based on // the parameters (the Audacity Reverb effect does when the stereo width is 0). mNumAudioIn = GetAudioInCount(); mNumAudioOut = GetAudioOutCount(); mPass = 1; if (InitPass1()) { bGoodResult = ProcessPass(); mPass = 2; if (bGoodResult && InitPass2()) { bGoodResult = ProcessPass(); } } ReplaceProcessedTracks(bGoodResult); return bGoodResult; } bool Effect::ProcessPass() { bool bGoodResult = true; bool isGenerator = GetType() == EffectTypeGenerate; FloatBuffers inBuffer, outBuffer; ArrayOf<float *> inBufPos, outBufPos; ChannelName map[3]; mBufferSize = 0; mBlockSize = 0; int count = 0; bool clear = false; const bool multichannel = mNumAudioIn > 1; auto range = multichannel ? mOutputTracks->Leaders() : mOutputTracks->Any(); range.VisitWhile( bGoodResult, [&](WaveTrack *left, const Track::Fallthrough &fallthrough) { if (!left->GetSelected()) return fallthrough(); sampleCount len; sampleCount leftStart; sampleCount rightStart = 0; if (!isGenerator) { GetSamples(left, &leftStart, &len); mSampleCnt = len; } else { len = 0; leftStart = 0; mSampleCnt = left->TimeToLongSamples(mDuration); } mNumChannels = 0; WaveTrack *right{}; // Iterate either over one track which could be any channel, // or if multichannel, then over all channels of left, // which is a leader. for (auto channel : TrackList::Channels(left).StartingWith(left)) { if (channel->GetChannel() == Track::LeftChannel) map[mNumChannels] = ChannelNameFrontLeft; else if (channel->GetChannel() == Track::RightChannel) map[mNumChannels] = ChannelNameFrontRight; else map[mNumChannels] = ChannelNameMono; ++ mNumChannels; map[mNumChannels] = ChannelNameEOL; if (! multichannel) break; if (mNumChannels == 2) { // TODO: more-than-two-channels right = channel; clear = false; if (!isGenerator) GetSamples(right, &rightStart, &len); // Ignore other channels break; } } // Let the client know the sample rate SetSampleRate(left->GetRate()); // Get the block size the client wants to use auto max = left->GetMaxBlockSize() * 2; mBlockSize = SetBlockSize(max); // Calculate the buffer size to be at least the max rounded up to the clients // selected block size. const auto prevBufferSize = mBufferSize; mBufferSize = ((max + (mBlockSize - 1)) / mBlockSize) * mBlockSize; // If the buffer size has changed, then (re)allocate the buffers if (prevBufferSize != mBufferSize) { // Always create the number of input buffers the client expects even if we don't have // the same number of channels. inBufPos.reinit( mNumAudioIn ); inBuffer.reinit( mNumAudioIn, mBufferSize ); // We won't be using more than the first 2 buffers, so clear the rest (if any) for (size_t i = 2; i < mNumAudioIn; i++) { for (size_t j = 0; j < mBufferSize; j++) { inBuffer[i][j] = 0.0; } } // Always create the number of output buffers the client expects even if we don't have // the same number of channels. outBufPos.reinit( mNumAudioOut ); // Output buffers get an extra mBlockSize worth to give extra room if // the plugin adds latency outBuffer.reinit( mNumAudioOut, mBufferSize + mBlockSize ); } // (Re)Set the input buffer positions for (size_t i = 0; i < mNumAudioIn; i++) { inBufPos[i] = inBuffer[i].get(); } // (Re)Set the output buffer positions for (size_t i = 0; i < mNumAudioOut; i++) { outBufPos[i] = outBuffer[i].get(); } // Clear unused input buffers if (!right && !clear && mNumAudioIn > 1) { for (size_t j = 0; j < mBufferSize; j++) { inBuffer[1][j] = 0.0; } clear = true; } // Go process the track(s) bGoodResult = ProcessTrack( count, map, left, right, leftStart, rightStart, len, inBuffer, outBuffer, inBufPos, outBufPos); if (!bGoodResult) return; count++; }, [&](Track *t) { if (t->IsSyncLockSelected()) t->SyncLockAdjust(mT1, mT0 + mDuration); } ); if (bGoodResult && GetType() == EffectTypeGenerate) { mT1 = mT0 + mDuration; } return bGoodResult; } bool Effect::ProcessTrack(int count, ChannelNames map, WaveTrack *left, WaveTrack *right, sampleCount leftStart, sampleCount rightStart, sampleCount len, FloatBuffers &inBuffer, FloatBuffers &outBuffer, ArrayOf< float * > &inBufPos, ArrayOf< float *> &outBufPos) { bool rc = true; // Give the plugin a chance to initialize if (!ProcessInitialize(len, map)) { return false; } { // Start scope for cleanup auto cleanup = finally( [&] { // Allow the plugin to cleanup if (!ProcessFinalize()) { // In case of non-exceptional flow of control, set rc rc = false; } } ); // For each input block of samples, we pass it to the effect along with a // variable output location. This output location is simply a pointer into a // much larger buffer. This reduces the number of calls required to add the // samples to the output track. // // Upon return from the effect, the output samples are "moved to the left" by // the number of samples in the current latency setting, effectively removing any // delay introduced by the effect. // // At the same time the total number of delayed samples are gathered and when // there is no further input data to process, the loop continues to call the // effect with an empty input buffer until the effect has had a chance to // return all of the remaining delayed samples. auto inLeftPos = leftStart; auto inRightPos = rightStart; auto outLeftPos = leftStart; auto outRightPos = rightStart; auto inputRemaining = len; decltype(GetLatency()) curDelay = 0, delayRemaining = 0; decltype(mBlockSize) curBlockSize = 0; decltype(mBufferSize) inputBufferCnt = 0; decltype(mBufferSize) outputBufferCnt = 0; bool cleared = false; auto chans = std::min<unsigned>(mNumAudioOut, mNumChannels); std::shared_ptr<WaveTrack> genLeft, genRight; decltype(len) genLength = 0; bool isGenerator = GetType() == EffectTypeGenerate; bool isProcessor = GetType() == EffectTypeProcess; double genDur = 0; if (isGenerator) { if (mIsPreview) { gPrefs->Read(wxT("/AudioIO/EffectsPreviewLen"), &genDur, 6.0); genDur = wxMin(mDuration, CalcPreviewInputLength(genDur)); } else { genDur = mDuration; } genLength = sampleCount((left->GetRate() * genDur) + 0.5); // round to nearest sample delayRemaining = genLength; cleared = true; // Create temporary tracks genLeft = mFactory->NewWaveTrack(left->GetSampleFormat(), left->GetRate()); if (right) genRight = mFactory->NewWaveTrack(right->GetSampleFormat(), right->GetRate()); } // Call the effect until we run out of input or delayed samples while (inputRemaining != 0 || delayRemaining != 0) { // Still working on the input samples if (inputRemaining != 0) { // Need to refill the input buffers if (inputBufferCnt == 0) { // Calculate the number of samples to get inputBufferCnt = limitSampleBufferSize( mBufferSize, inputRemaining ); // Fill the input buffers left->Get((samplePtr) inBuffer[0].get(), floatSample, inLeftPos, inputBufferCnt); if (right) { right->Get((samplePtr) inBuffer[1].get(), floatSample, inRightPos, inputBufferCnt); } // Reset the input buffer positions for (size_t i = 0; i < mNumChannels; i++) { inBufPos[i] = inBuffer[i].get(); } } // Calculate the number of samples to process curBlockSize = mBlockSize; if (curBlockSize > inputRemaining) { // We've reached the last block...set current block size to what's left // inputRemaining is positive and bounded by a size_t curBlockSize = inputRemaining.as_size_t(); inputRemaining = 0; // Clear the remainder of the buffers so that a full block can be passed // to the effect auto cnt = mBlockSize - curBlockSize; for (size_t i = 0; i < mNumChannels; i++) { for (decltype(cnt) j = 0 ; j < cnt; j++) { inBufPos[i][j + curBlockSize] = 0.0; } } // Might be able to use up some of the delayed samples if (delayRemaining != 0) { // Don't use more than needed cnt = limitSampleBufferSize(cnt, delayRemaining); delayRemaining -= cnt; curBlockSize += cnt; } } } // We've exhausted the input samples and are now working on the delay else if (delayRemaining != 0) { // Calculate the number of samples to process curBlockSize = limitSampleBufferSize( mBlockSize, delayRemaining ); delayRemaining -= curBlockSize; // From this point on, we only want to feed zeros to the plugin if (!cleared) { // Reset the input buffer positions for (size_t i = 0; i < mNumChannels; i++) { inBufPos[i] = inBuffer[i].get(); // And clear for (size_t j = 0; j < mBlockSize; j++) { inBuffer[i][j] = 0.0; } } cleared = true; } } // Finally call the plugin to process the block decltype(curBlockSize) processed; try { processed = ProcessBlock(inBufPos.get(), outBufPos.get(), curBlockSize); } catch( const AudacityException & WXUNUSED(e) ) { // PRL: Bug 437: // Pass this along to our application-level handler throw; } catch(...) { // PRL: // Exceptions for other reasons, maybe in third-party code... // Continue treating them as we used to, but I wonder if these // should now be treated the same way. return false; } wxASSERT(processed == curBlockSize); wxUnusedVar(processed); // Bump to next input buffer position if (inputRemaining != 0) { for (size_t i = 0; i < mNumChannels; i++) { inBufPos[i] += curBlockSize; } inputRemaining -= curBlockSize; inputBufferCnt -= curBlockSize; } // "ls" and "rs" serve as the input sample index for the left and // right channels when processing the input samples. If we flip // over to processing delayed samples, they simply become counters // for the progress display. inLeftPos += curBlockSize; inRightPos += curBlockSize; // Get the current number of delayed samples and accumulate if (isProcessor) { { auto delay = GetLatency(); curDelay += delay; delayRemaining += delay; } // If the plugin has delayed the output by more samples than our current // block size, then we leave the output pointers alone. This effectively // removes those delayed samples from the output buffer. if (curDelay >= curBlockSize) { curDelay -= curBlockSize; curBlockSize = 0; } // We have some delayed samples, at the beginning of the output samples, // so overlay them by shifting the remaining output samples. else if (curDelay > 0) { // curDelay is bounded by curBlockSize: auto delay = curDelay.as_size_t(); curBlockSize -= delay; for (size_t i = 0; i < chans; i++) { memmove(outBufPos[i], outBufPos[i] + delay, sizeof(float) * curBlockSize); } curDelay = 0; } } // Adjust the number of samples in the output buffers outputBufferCnt += curBlockSize; // Still have room in the output buffers if (outputBufferCnt < mBufferSize) { // Bump to next output buffer position for (size_t i = 0; i < chans; i++) { outBufPos[i] += curBlockSize; } } // Output buffers have filled else { if (isProcessor) { // Write them out left->Set((samplePtr) outBuffer[0].get(), floatSample, outLeftPos, outputBufferCnt); if (right) { if (chans >= 2) { right->Set((samplePtr) outBuffer[1].get(), floatSample, outRightPos, outputBufferCnt); } else { right->Set((samplePtr) outBuffer[0].get(), floatSample, outRightPos, outputBufferCnt); } } } else if (isGenerator) { genLeft->Append((samplePtr) outBuffer[0].get(), floatSample, outputBufferCnt); if (genRight) { genRight->Append((samplePtr) outBuffer[1].get(), floatSample, outputBufferCnt); } } // Reset the output buffer positions for (size_t i = 0; i < chans; i++) { outBufPos[i] = outBuffer[i].get(); } // Bump to the next track position outLeftPos += outputBufferCnt; outRightPos += outputBufferCnt; outputBufferCnt = 0; } if (mNumChannels > 1) { if (TrackGroupProgress(count, (inLeftPos - leftStart).as_double() / (isGenerator ? genLength : len).as_double())) { rc = false; break; } } else { if (TrackProgress(count, (inLeftPos - leftStart).as_double() / (isGenerator ? genLength : len).as_double())) { rc = false; break; } } } // Put any remaining output if (rc && outputBufferCnt) { if (isProcessor) { left->Set((samplePtr) outBuffer[0].get(), floatSample, outLeftPos, outputBufferCnt); if (right) { if (chans >= 2) { right->Set((samplePtr) outBuffer[1].get(), floatSample, outRightPos, outputBufferCnt); } else { right->Set((samplePtr) outBuffer[0].get(), floatSample, outRightPos, outputBufferCnt); } } } else if (isGenerator) { genLeft->Append((samplePtr) outBuffer[0].get(), floatSample, outputBufferCnt); if (genRight) { genRight->Append((samplePtr) outBuffer[1].get(), floatSample, outputBufferCnt); } } } if (rc && isGenerator) { auto pProject = FindProject(); // PRL: this code was here and could not have been the right // intent, mixing time and sampleCount values: // StepTimeWarper warper(mT0 + genLength, genLength - (mT1 - mT0)); // This looks like what it should have been: // StepTimeWarper warper(mT0 + genDur, genDur - (mT1 - mT0)); // But rather than fix it, I will just disable the use of it for now. // The purpose was to remap split lines inside the selected region when // a generator replaces it with sound of different duration. But // the "correct" version might have the effect of mapping some splits too // far left, to before the selection. // In practice the wrong version probably did nothing most of the time, // because the cutoff time for the step time warper was 44100 times too // far from mT0. // Transfer the data from the temporary tracks to the actual ones genLeft->Flush(); // mT1 gives us the NEW selection. We want to replace up to GetSel1(). auto &selectedRegion = ViewInfo::Get( *pProject ).selectedRegion; left->ClearAndPaste(mT0, selectedRegion.t1(), genLeft.get(), true, true, nullptr /* &warper */); if (genRight) { genRight->Flush(); right->ClearAndPaste(mT0, mT1, genRight.get(), true, true, nullptr /* &warper */); } } } // End scope for cleanup return rc; } void Effect::End() { } void Effect::PopulateOrExchange(ShuttleGui & WXUNUSED(S)) { return; } bool Effect::TransferDataToWindow() { return true; } bool Effect::TransferDataFromWindow() { return true; } bool Effect::EnableApply(bool enable) { // May be called during initialization, so try to find the dialog wxWindow *dlg = mUIDialog; if (!dlg && mUIParent) { dlg = wxGetTopLevelParent(mUIParent); } if (dlg) { wxWindow *apply = dlg->FindWindow(wxID_APPLY); // Don't allow focus to get trapped if (!enable) { wxWindow *focus = dlg->FindFocus(); if (focus == apply) { dlg->FindWindow(wxID_CLOSE)->SetFocus(); } } apply->Enable(enable); } EnablePreview(enable); return enable; } bool Effect::EnablePreview(bool enable) { // May be called during initialization, so try to find the dialog wxWindow *dlg = mUIDialog; if (!dlg && mUIParent) { dlg = wxGetTopLevelParent(mUIParent); } if (dlg) { wxWindow *play = dlg->FindWindow(kPlayID); if (play) { wxWindow *rewind = dlg->FindWindow(kRewindID); wxWindow *ffwd = dlg->FindWindow(kFFwdID); // Don't allow focus to get trapped if (!enable) { wxWindow *focus = dlg->FindFocus(); if (focus && (focus == play || focus == rewind || focus == ffwd)) { dlg->FindWindow(wxID_CLOSE)->SetFocus(); } } play->Enable(enable); if (SupportsRealtime()) { rewind->Enable(enable); ffwd->Enable(enable); } } } return enable; } void Effect::EnableDebug(bool enable) { mUIDebug = enable; } void Effect::SetLinearEffectFlag(bool linearEffectFlag) { mIsLinearEffect = linearEffectFlag; } void Effect::SetPreviewFullSelectionFlag(bool previewDurationFlag) { mPreviewFullSelection = previewDurationFlag; } void Effect::IncludeNotSelectedPreviewTracks(bool includeNotSelected) { mPreviewWithNotSelected = includeNotSelected; } bool Effect::TotalProgress(double frac, const TranslatableString &msg) { auto updateResult = (mProgress ? mProgress->Update(frac, msg) : ProgressResult::Success); return (updateResult != ProgressResult::Success); } bool Effect::TrackProgress(int whichTrack, double frac, const TranslatableString &msg) { auto updateResult = (mProgress ? mProgress->Update(whichTrack + frac, (double) mNumTracks, msg) : ProgressResult::Success); return (updateResult != ProgressResult::Success); } bool Effect::TrackGroupProgress(int whichGroup, double frac, const TranslatableString &msg) { auto updateResult = (mProgress ? mProgress->Update(whichGroup + frac, (double) mNumGroups, msg) : ProgressResult::Success); return (updateResult != ProgressResult::Success); } void Effect::GetSamples( const WaveTrack *track, sampleCount *start, sampleCount *len) { double trackStart = track->GetStartTime(); double trackEnd = track->GetEndTime(); double t0 = mT0 < trackStart ? trackStart : mT0; double t1 = mT1 > trackEnd ? trackEnd : mT1; #if 0 if (GetType() & INSERT_EFFECT) { t1 = t0 + mDuration; if (mT0 == mT1) { // Not really part of the calculation, but convenient to put here track->InsertSilence(t0, t1); } } #endif if (t1 > t0) { *start = track->TimeToLongSamples(t0); auto end = track->TimeToLongSamples(t1); *len = end - *start; } else { *start = 0; *len = 0; } } // // private methods // // Use this method to copy the input tracks to mOutputTracks, if // doing the processing on them, and replacing the originals only on success (and not cancel). // Copy the group tracks that have tracks selected // If not all sync-locked selected, then only selected wave tracks. void Effect::CopyInputTracks(bool allSyncLockSelected) { // Reset map mIMap.clear(); mOMap.clear(); mOutputTracks = TrackList::Create( nullptr ); auto trackRange = mTracks->Any() + [&] (const Track *pTrack) { return allSyncLockSelected ? pTrack->IsSelectedOrSyncLockSelected() : track_cast<const WaveTrack*>( pTrack ) && pTrack->GetSelected(); }; t2bHash added; for (auto aTrack : trackRange) { Track *o = mOutputTracks->Add(aTrack->Duplicate()); mIMap.push_back(aTrack); mOMap.push_back(o); } } Track *Effect::AddToOutputTracks(const std::shared_ptr<Track> &t) { mIMap.push_back(NULL); mOMap.push_back(t.get()); return mOutputTracks->Add(t); } Effect::AddedAnalysisTrack::AddedAnalysisTrack(Effect *pEffect, const wxString &name) : mpEffect(pEffect) { LabelTrack::Holder pTrack{ pEffect->mFactory->NewLabelTrack() }; mpTrack = pTrack.get(); if (!name.empty()) pTrack->SetName(name); pEffect->mTracks->Add( pTrack ); } Effect::AddedAnalysisTrack::AddedAnalysisTrack(AddedAnalysisTrack &&that) { mpEffect = that.mpEffect; mpTrack = that.mpTrack; that.Commit(); } void Effect::AddedAnalysisTrack::Commit() { mpEffect = nullptr; } Effect::AddedAnalysisTrack::~AddedAnalysisTrack() { if (mpEffect) { // not committed -- DELETE the label track mpEffect->mTracks->Remove(mpTrack); } } auto Effect::AddAnalysisTrack(const wxString &name) -> std::shared_ptr<AddedAnalysisTrack> { return std::shared_ptr<AddedAnalysisTrack> { safenew AddedAnalysisTrack{ this, name } }; } Effect::ModifiedAnalysisTrack::ModifiedAnalysisTrack (Effect *pEffect, const LabelTrack *pOrigTrack, const wxString &name) : mpEffect(pEffect) { // copy LabelTrack here, so it can be undone on cancel auto newTrack = pOrigTrack->Copy(pOrigTrack->GetStartTime(), pOrigTrack->GetEndTime()); mpTrack = static_cast<LabelTrack*>(newTrack.get()); // Why doesn't LabelTrack::Copy complete the job? : mpTrack->SetOffset(pOrigTrack->GetStartTime()); if (!name.empty()) mpTrack->SetName(name); // mpOrigTrack came from mTracks which we own but expose as const to subclasses // So it's okay that we cast it back to const mpOrigTrack = pEffect->mTracks->Replace(const_cast<LabelTrack*>(pOrigTrack), newTrack ); } Effect::ModifiedAnalysisTrack::ModifiedAnalysisTrack(ModifiedAnalysisTrack &&that) { mpEffect = that.mpEffect; mpTrack = that.mpTrack; mpOrigTrack = std::move(that.mpOrigTrack); that.Commit(); } void Effect::ModifiedAnalysisTrack::Commit() { mpEffect = nullptr; } Effect::ModifiedAnalysisTrack::~ModifiedAnalysisTrack() { if (mpEffect) { // not committed -- DELETE the label track // mpOrigTrack came from mTracks which we own but expose as const to subclasses // So it's okay that we cast it back to const mpEffect->mTracks->Replace(mpTrack, mpOrigTrack); } } auto Effect::ModifyAnalysisTrack (const LabelTrack *pOrigTrack, const wxString &name) -> ModifiedAnalysisTrack { return{ this, pOrigTrack, name }; } // If bGoodResult, replace mTracks tracks with successfully processed mOutputTracks copies. // Else clear and DELETE mOutputTracks copies. void Effect::ReplaceProcessedTracks(const bool bGoodResult) { if (!bGoodResult) { // Free resources, unless already freed. // Processing failed or was cancelled so throw away the processed tracks. if ( mOutputTracks ) mOutputTracks->Clear(); // Reset map mIMap.clear(); mOMap.clear(); //TODO:undo the non-gui ODTask transfer return; } // Assume resources need to be freed. wxASSERT(mOutputTracks); // Make sure we at least did the CopyInputTracks(). auto iterOut = mOutputTracks->ListOfTracks::begin(), iterEnd = mOutputTracks->ListOfTracks::end(); size_t cnt = mOMap.size(); size_t i = 0; for (; iterOut != iterEnd; ++i) { ListOfTracks::value_type o = *iterOut; // If tracks were removed from mOutputTracks, then there will be // tracks in the map that must be removed from mTracks. while (i < cnt && mOMap[i] != o.get()) { const auto t = mIMap[i]; if (t) { mTracks->Remove(t); } i++; } // This should never happen wxASSERT(i < cnt); // Remove the track from the output list...don't DELETE it iterOut = mOutputTracks->erase(iterOut); const auto t = mIMap[i]; if (t == NULL) { // This track is a NEW addition to output tracks; add it to mTracks mTracks->Add( o ); } else { // Replace mTracks entry with the NEW track mTracks->Replace(t, o); // If the track is a wave track, // Swap the wavecache track the ondemand task uses, since now the NEW // one will be kept in the project if (ODManager::IsInstanceCreated()) { ODManager::Instance()->ReplaceWaveTrack( t, o ); } } } // If tracks were removed from mOutputTracks, then there may be tracks // left at the end of the map that must be removed from mTracks. while (i < cnt) { const auto t = mIMap[i]; if (t) { mTracks->Remove(t); } i++; } // Reset map mIMap.clear(); mOMap.clear(); // Make sure we processed everything wxASSERT(mOutputTracks->empty()); // The output list is no longer needed mOutputTracks.reset(); nEffectsDone++; } const AudacityProject *Effect::FindProject() const { if (!inputTracks()) return nullptr; return inputTracks()->GetOwner(); } void Effect::CountWaveTracks() { mNumTracks = mTracks->Selected< const WaveTrack >().size(); mNumGroups = mTracks->SelectedLeaders< const WaveTrack >().size(); } double Effect::CalcPreviewInputLength(double previewLength) { return previewLength; } bool Effect::IsHidden() { return false; } void Effect::Preview(bool dryOnly) { if (mNumTracks == 0) { // nothing to preview return; } auto gAudioIO = AudioIO::Get(); if (gAudioIO->IsBusy()) { return; } wxWindow *FocusDialog = wxWindow::FindFocus(); double previewDuration; bool isNyquist = GetFamily() == NYQUISTEFFECTS_FAMILY; bool isGenerator = GetType() == EffectTypeGenerate; // Mix a few seconds of audio from all of the tracks double previewLen; gPrefs->Read(wxT("/AudioIO/EffectsPreviewLen"), &previewLen, 6.0); const double rate = mProjectRate; if (isNyquist && isGenerator) { previewDuration = CalcPreviewInputLength(previewLen); } else { previewDuration = wxMin(mDuration, CalcPreviewInputLength(previewLen)); } double t1 = mT0 + previewDuration; if ((t1 > mT1) && !isGenerator) { t1 = mT1; } if (t1 <= mT0) return; bool success = true; auto cleanup = finally( [&] { // Effect is already inited; we will call Process, End, and then Init // again, so the state is exactly the way it was before Preview // was called. if (!dryOnly) { End(); GuardedCall( [&]{ Init(); } ); } } ); auto vr0 = valueRestorer( mT0 ); auto vr1 = valueRestorer( mT1 ); // Most effects should stop at t1. if (!mPreviewFullSelection) mT1 = t1; // Save the original track list TrackList *saveTracks = mTracks; auto cleanup2 = finally( [&] { mTracks = saveTracks; if (FocusDialog) { FocusDialog->SetFocus(); } // In case of failed effect, be sure to free memory. ReplaceProcessedTracks( false ); } ); // Build NEW tracklist from rendering tracks // Set the same owning project, so FindProject() can see it within Process() const auto pProject = saveTracks->GetOwner(); auto uTracks = TrackList::Create( pProject ); mTracks = uTracks.get(); // Linear Effect preview optimised by pre-mixing to one track. // Generators need to generate per track. if (mIsLinearEffect && !isGenerator) { WaveTrack::Holder mixLeft, mixRight; MixAndRender(saveTracks, mFactory, rate, floatSample, mT0, t1, mixLeft, mixRight); if (!mixLeft) return; mixLeft->Offset(-mixLeft->GetStartTime()); mixLeft->SetSelected(true); WaveTrackView::Get( *mixLeft ) .SetDisplay(WaveTrackViewConstants::NoDisplay); auto pLeft = mTracks->Add( mixLeft ); Track *pRight{}; if (mixRight) { mixRight->Offset(-mixRight->GetStartTime()); mixRight->SetSelected(true); pRight = mTracks->Add( mixRight ); } mTracks->GroupChannels(*pLeft, pRight ? 2 : 1); } else { for (auto src : saveTracks->Any< const WaveTrack >()) { if (src->GetSelected() || mPreviewWithNotSelected) { auto dest = src->Copy(mT0, t1); dest->SetSelected(src->GetSelected()); WaveTrackView::Get( *static_cast<WaveTrack*>(dest.get()) ) .SetDisplay(WaveTrackViewConstants::NoDisplay); mTracks->Add( dest ); } } } // NEW tracks start at time zero. // Adjust mT0 and mT1 to be the times to process, and to // play back in these tracks mT1 -= mT0; mT0 = 0.0; // Update track/group counts CountWaveTracks(); // Apply effect if (!dryOnly) { ProgressDialog progress{ GetName(), XO("Preparing preview"), pdlgHideCancelButton }; // Have only "Stop" button. auto vr = valueRestorer( mProgress, &progress ); auto vr2 = valueRestorer( mIsPreview, true ); success = Process(); } if (success) { auto tracks = ProjectAudioManager::GetAllPlaybackTracks(*mTracks, true); // Some effects (Paulstretch) may need to generate more // than previewLen, so take the min. t1 = std::min(mT0 + previewLen, mT1); // Start audio playing AudioIOStartStreamOptions options { pProject, rate }; int token = gAudioIO->StartStream(tracks, mT0, t1, options); if (token) { auto previewing = ProgressResult::Success; // The progress dialog must be deleted before stopping the stream // to allow events to flow to the app during StopStream processing. // The progress dialog blocks these events. { ProgressDialog progress (GetName(), XO("Previewing"), pdlgHideCancelButton); while (gAudioIO->IsStreamActive(token) && previewing == ProgressResult::Success) { ::wxMilliSleep(100); previewing = progress.Update(gAudioIO->GetStreamTime() - mT0, t1 - mT0); } } gAudioIO->StopStream(); while (gAudioIO->IsBusy()) { ::wxMilliSleep(100); } } else { ShowErrorDialog(FocusDialog, XO("Error"), XO("Error opening sound device.\nTry changing the audio host, playback device and the project sample rate."), wxT("Error_opening_sound_device")); } } } int Effect::MessageBox( const TranslatableString& message, long style, const TranslatableString &titleStr) { auto title = titleStr.empty() ? GetName() : XO("%s: %s").Format( GetName(), titleStr ); return AudacityMessageBox( message, title, style, mUIParent ); }
/******************************************************************************** * This file is part of CinoLib * * Copyright(C) 2016: Marco Livesu * * * * The MIT License * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * * IN THE SOFTWARE. * * * * Author(s): * * * * Marco Livesu (marco.livesu@gmail.com) * * http://pers.ge.imati.cnr.it/livesu/ * * * * Italian National Research Council (CNR) * * Institute for Applied Mathematics and Information Technologies (IMATI) * * Via de Marini, 6 * * 16149 Genoa, * * Italy * *********************************************************************************/ #include <cinolib/meshes/hexmesh.h> #include <cinolib/cino_inline.h> #include <cinolib/quality.h> #include <cinolib/io/read_write.h> #include <cinolib/min_max_inf.h> #include <cinolib/standard_elements_tables.h> #include <cinolib/vector_serialization.h> #include <cinolib/io/io_utilities.h> #include <queue> #include <float.h> #include <map> #include <set> namespace cinolib { //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE Hexmesh<M,V,E,F,P>::Hexmesh(const std::vector<vec3d> & verts, const std::vector<uint> & polys) { this->init(verts, polys_from_serialized_vids(polys,8)); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE Hexmesh<M,V,E,F,P>::Hexmesh(const std::vector<double> & coords, const std::vector<uint> & polys) { this->init(vec3d_from_serialized_xyz(coords), polys_from_serialized_vids(polys,8)); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE Hexmesh<M,V,E,F,P>::Hexmesh(const std::vector<vec3d> & verts, const std::vector<std::vector<uint>> & polys) { this->init(verts, polys); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE Hexmesh<M,V,E,F,P>::Hexmesh(const char * filename) { load(filename); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE void Hexmesh<M,V,E,F,P>::load(const char * filename) { this->clear(); this->mesh_data().filename = std::string(filename); std::vector<vec3d> tmp_verts; std::vector<std::vector<uint>> tmp_polys; std::vector<int> vert_labels; std::vector<int> poly_labels; std::string str(filename); std::string filetype = "." + get_file_extension(str); if (filetype.compare(".mesh") == 0 || filetype.compare(".MESH") == 0) { read_MESH(filename, tmp_verts, tmp_polys, vert_labels, poly_labels); } else if (filetype.compare(".vtu") == 0 || filetype.compare(".VTU") == 0) { read_VTU(filename, tmp_verts, tmp_polys); } else if (filetype.compare(".vtk") == 0 || filetype.compare(".VTK") == 0) { read_VTK(filename, tmp_verts, tmp_polys); } else { std::cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : load() : file format not supported yet " << std::endl; } this->init(tmp_verts, tmp_polys, vert_labels, poly_labels); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE void Hexmesh<M,V,E,F,P>::save(const char * filename) const { std::string str(filename); std::string filetype = "." + get_file_extension(str); if (filetype.compare(".mesh") == 0 || filetype.compare(".MESH") == 0) { if(this->polys_are_labeled()) { write_MESH(filename, this->verts, this->p2v, std::vector<int>(this->num_verts(),0), this->vector_poly_labels()); } else write_MESH(filename, this->verts, this->p2v); } else if (filetype.compare(".vtu") == 0 || filetype.compare(".VTU") == 0) { write_VTU(filename, this->verts, this->p2v); } else if (filetype.compare(".vtk") == 0 || filetype.compare(".VTK") == 0) { write_VTK(filename, this->verts, this->p2v); } else if (filetype.compare(".hedra") == 0 || filetype.compare(".HEDRA") == 0) { write_HEDRA(filename, this->verts, this->faces, this->polys, this->polys_face_winding); } else { std::cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : write() : file format not supported yet " << std::endl; } } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE void Hexmesh<M,V,E,F,P>::update_f_normal(const uint fid) { // STEAL BETTER NORMAL ESTIMATION FROM QUADMESH! vec3d v0 = this->face_vert(fid,0); vec3d v1 = this->face_vert(fid,1); vec3d v2 = this->face_vert(fid,2); vec3d u = v1 - v0; if(!u.is_degenerate()) u.normalize(); vec3d v = v2 - v0; if(!v.is_degenerate()) v.normalize(); vec3d n = u.cross(v); if(!n.is_degenerate()) n.normalize(); this->face_data(fid).normal = n; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE void Hexmesh<M,V,E,F,P>::print_quality(const bool list_folded_elements) { if(list_folded_elements) std::cout << "Folded Hexa: "; double asj = 0.0; double msj = inf_double; uint inv = 0; for(uint pid=0; pid<this->num_polys(); ++pid) { double q = this->poly_data(pid).quality; asj += q; msj = std::min(msj, q); if (q <= 0.0) { ++inv; if (list_folded_elements) std::cout << pid << " - "; } } asj /= static_cast<double>(this->num_polys()); if (list_folded_elements) std::cout << std::endl << std::endl; std::cout << std::endl; std::cout << "MIN SJ : " << msj << std::endl; std::cout << "AVG SJ : " << asj << std::endl; std::cout << "INV EL : " << inv << " (out of " << this->num_polys() << ")" << std::endl; std::cout << std::endl; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE bool Hexmesh<M,V,E,F,P>::vert_is_singular(const uint vid) const { uint count = 0; for(uint eid : this->adj_v2e(vid)) { if(this->edge_is_singular(eid)) ++count; } if (count>0 && count!=2) return true; return false; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE bool Hexmesh<M,V,E,F,P>::vert_is_regular(const uint vid) const { return !this->vert_is_singular(vid); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE bool Hexmesh<M,V,E,F,P>::edge_is_singular(const uint eid) const { if (this->edge_is_on_srf(eid)) { if(this->edge_valence(eid)!=2) return true; return false; } if (this->edge_valence(eid)!=4) return true; return false; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE bool Hexmesh<M,V,E,F,P>::edge_is_regular(const uint eid) const { return !this->edge_is_singular(eid); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE std::vector<uint> Hexmesh<M,V,E,F,P>::face_sheet(const uint fid) const { std::vector<uint> sheet; std::queue<uint> q; q.push(fid); std::unordered_set<uint> visited; visited.insert(fid); while(!q.empty()) { uint fid = q.front(); q.pop(); sheet.push_back(fid); uint eid,nbr; for(eid : this->adj_f2e(fid)) { if (this->edge_is_singular(eid)) continue; for(nbr : this->adj_e2f(eid)) { if(!this->faces_share_poly(fid,nbr) && DOES_NOT_CONTAIN(visited,nbr)) { visited.insert(nbr); q.push(nbr); } } } } return sheet; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE vec3d Hexmesh<M,V,E,F,P>::verts_average(const std::vector<uint> & vids) const { vec3d res(0,0,0); for(uint vid: vids) res += this->vert(vid); res /= static_cast<double>(vids.size()); return res; } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE uint Hexmesh<M,V,E,F,P>::poly_face_opposite_to(const uint pid, const uint fid) const { assert(this->poly_contains_face(pid, fid)); for(uint f : this->adj_p2f(pid)) { if(this->faces_are_disjoint(fid,f)) return f; } assert(false); return 0; // warning killer } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE void Hexmesh<M,V,E,F,P>::poly_subdivide(const std::vector<std::vector<std::vector<uint>>> & poly_split_scheme) { std::vector<vec3d> new_verts; std::vector<uint> new_polys; std::map<std::vector<uint>,uint> v_map; std::vector<uint> vids; for(uint pid=0; pid<this->num_polys(); ++pid) { for(const auto & sub_poly: poly_split_scheme) { assert(sub_poly.size() == 8); for(short off=0; off<8; ++off) { vids.clear(); for(uint i : sub_poly.at(off)) vids.push_back(this->poly_vert_id(pid,i)); sort(vids.begin(), vids.end()); auto query = v_map.find(vids); if (query != v_map.end()) { new_polys.push_back(query->second); } else { uint fresh_id = new_verts.size(); new_verts.push_back(verts_average(vids)); v_map[vids] = fresh_id; new_polys.push_back(fresh_id); } } } } *this = Hexmesh<M,V,E,F,P>(new_verts,new_polys); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE double Hexmesh<M,V,E,F,P>::poly_volume(const uint pid) const { return hex_unsigned_volume(this->poly_vert(pid,0), this->poly_vert(pid,1), this->poly_vert(pid,2), this->poly_vert(pid,3), this->poly_vert(pid,4), this->poly_vert(pid,5), this->poly_vert(pid,6), this->poly_vert(pid,7)); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: template<class M, class V, class E, class F, class P> CINO_INLINE bool Hexmesh<M,V,E,F,P>::poly_fix_orientation() { if(AbstractPolyhedralMesh<M,V,E,F,P>::poly_fix_orientation()) { uint bad = 0; for(uint pid=0; pid<this->num_polys(); ++pid) { this->poly_reorder_p2v(pid); this->update_p_quality(pid); if(this->poly_data(pid).quality < 0.0) ++bad; } if(bad > 0.5*this->num_polys()) { for(uint pid=0; pid<this->num_polys(); ++pid) { this->poly_flip_winding(pid); this->poly_reorder_p2v(pid); } this->update_quality(); } return true; } return false; } }
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include "base58.h" #include "key.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_hostmasternode.h" #include <string> #include <vector> struct TestDerivation { std::string pub; std::string prv; unsigned int nChild; }; struct TestVector { std::string strHexMaster; std::vector<TestDerivation> vDerive; TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {} TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) { vDerive.push_back(TestDerivation()); TestDerivation &der = vDerive.back(); der.pub = pub; der.prv = prv; der.nChild = nChild; return *this; } }; TestVector test1 = TestVector("000102030405060708090a0b0c0d0e0f") ("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", 0x80000000) ("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw", "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", 1) ("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ", "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", 0x80000002) ("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5", "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", 2) ("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV", "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", 1000000000) ("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy", "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", 0); TestVector test2 = TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542") ("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", 0) ("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH", "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", 0xFFFFFFFF) ("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a", "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", 1) ("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon", "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", 0xFFFFFFFE) ("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL", "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", 2) ("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt", "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", 0); void RunTest(const TestVector &test) { std::vector<unsigned char> seed = ParseHex(test.strHexMaster); CExtKey key; CExtPubKey pubkey; key.SetMaster(&seed[0], seed.size()); pubkey = key.Neuter(); BOOST_FOREACH(const TestDerivation &derive, test.vDerive) { unsigned char data[74]; key.Encode(data); pubkey.Encode(data); // Test private key CBitcoinExtKey b58key; b58key.SetKey(key); BOOST_CHECK(b58key.ToString() == derive.prv); CBitcoinExtKey b58keyDecodeCheck(derive.prv); CExtKey checkKey = b58keyDecodeCheck.GetKey(); assert(checkKey == key); //ensure a base58 decoded key also matches // Test public key CBitcoinExtPubKey b58pubkey; b58pubkey.SetKey(pubkey); BOOST_CHECK(b58pubkey.ToString() == derive.pub); CBitcoinExtPubKey b58PubkeyDecodeCheck(derive.pub); CExtPubKey checkPubKey = b58PubkeyDecodeCheck.GetKey(); assert(checkPubKey == pubkey); //ensure a base58 decoded pubkey also matches // Derive new keys CExtKey keyNew; BOOST_CHECK(key.Derive(keyNew, derive.nChild)); CExtPubKey pubkeyNew = keyNew.Neuter(); if (!(derive.nChild & 0x80000000)) { // Compare with public derivation CExtPubKey pubkeyNew2; BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild)); BOOST_CHECK(pubkeyNew == pubkeyNew2); } key = keyNew; pubkey = pubkeyNew; CDataStream ssPub(SER_DISK, CLIENT_VERSION); ssPub << pubkeyNew; BOOST_CHECK(ssPub.size() == 75); CDataStream ssPriv(SER_DISK, CLIENT_VERSION); ssPriv << keyNew; BOOST_CHECK(ssPriv.size() == 75); CExtPubKey pubCheck; CExtKey privCheck; ssPub >> pubCheck; ssPriv >> privCheck; BOOST_CHECK(pubCheck == pubkeyNew); BOOST_CHECK(privCheck == keyNew); } } BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(bip32_test1) { RunTest(test1); } BOOST_AUTO_TEST_CASE(bip32_test2) { RunTest(test2); } BOOST_AUTO_TEST_SUITE_END()
#include "Scene/System/CollisionSystem/CollisionRenderObject.h" CollisionRenderObject::CollisionRenderObject(DAVA::Entity* entity, btCollisionWorld* word, DAVA::RenderObject* renderObject) : CollisionBaseObject(entity, word) { if ((renderObject == nullptr) || (word == nullptr)) return; DAVA::Matrix4 curEntityTransform = entity->GetWorldTransform(); int maxVertexCount = 0; int bestLodIndex = 0; int curSwitchIndex = renderObject->GetSwitchIndex(); // search for best lod index for (DAVA::uint32 i = 0; i < renderObject->GetRenderBatchCount(); ++i) { int batchLodIndex = 0; int batchSwitchIndex = 0; DAVA::RenderBatch* batch = renderObject->GetRenderBatch(i, batchLodIndex, batchSwitchIndex); int vertexCount = batch->GetPolygonGroup()->GetVertexCount(); if ((vertexCount > maxVertexCount) && (curSwitchIndex == batchSwitchIndex)) { bestLodIndex = batchLodIndex; maxVertexCount = vertexCount; } } bool anyPolygonAdded = false; for (DAVA::uint32 i = 0; i < renderObject->GetRenderBatchCount(); ++i) { int batchLodIndex = 0; int batchSwitchIndex = 0; DAVA::RenderBatch* batch = renderObject->GetRenderBatch(i, batchLodIndex, batchSwitchIndex); if ((batchLodIndex == bestLodIndex) && (batchSwitchIndex == curSwitchIndex)) { DAVA::PolygonGroup* pg = batch->GetPolygonGroup(); if (pg != nullptr) { // is this the first polygon in cycle if (!anyPolygonAdded) { anyPolygonAdded = true; btTriangles = new btTriangleMesh(); } for (DAVA::int32 i = 0; i < pg->GetPrimitiveCount(); ++i) { DAVA::int32 index0, index1, index2; pg->GetIndex(i * 3, index0); pg->GetIndex(i * 3 + 1, index1); pg->GetIndex(i * 3 + 2, index2); DAVA::Vector3 v0; DAVA::Vector3 v1; DAVA::Vector3 v2; pg->GetCoord(index0, v0); pg->GetCoord(index1, v1); pg->GetCoord(index2, v2); v0 = v0 * curEntityTransform; v1 = v1 * curEntityTransform; v2 = v2 * curEntityTransform; btTriangles->addTriangle(btVector3(v0.x, v0.y, v0.z), btVector3(v1.x, v1.y, v1.z), btVector3(v2.x, v2.y, v2.z), false); } } } } if (anyPolygonAdded) { btShape = new btBvhTriangleMeshShape(btTriangles, true, true); btObject = new btCollisionObject(); btObject->setCollisionShape(btShape); btWord->addCollisionObject(btObject); DAVA::AABBox3 boundingBox = renderObject->GetBoundingBox(); boundingBox.AddPoint(boundingBox.min - DAVA::Vector3(0.5f, 0.5f, 0.5f)); boundingBox.AddPoint(boundingBox.max + DAVA::Vector3(0.5f, 0.5f, 0.5f)); object.SetBoundingBox(boundingBox); } } CollisionRenderObject::~CollisionRenderObject() { if (btObject != nullptr) { btWord->removeCollisionObject(btObject); DAVA::SafeDelete(btObject); DAVA::SafeDelete(btShape); DAVA::SafeDelete(btTriangles); } } struct ClassifyTrianglesToSinglePlaneCallback : public btInternalTriangleIndexCallback { DAVA::Plane plane; CollisionBaseObject::ClassifyPlaneResult result = CollisionBaseObject::ClassifyPlaneResult::Behind; ClassifyTrianglesToSinglePlaneCallback(const DAVA::Plane& pl) : plane(pl) { } void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex) override { if (result == CollisionBaseObject::ClassifyPlaneResult::Behind) { float d0 = plane.DistanceToPoint(DAVA::Vector3(triangle[0].x(), triangle[0].y(), triangle[0].z())); float d1 = plane.DistanceToPoint(DAVA::Vector3(triangle[1].x(), triangle[1].y(), triangle[1].z())); float d2 = plane.DistanceToPoint(DAVA::Vector3(triangle[2].x(), triangle[2].y(), triangle[2].z())); DAVA::float32 minDistance = std::min(d0, std::min(d1, d2)); DAVA::float32 maxDistance = std::max(d0, std::max(d1, d2)); if ((minDistance >= 0.0f) && (maxDistance >= 0.0f)) { result = CollisionBaseObject::ClassifyPlaneResult::InFront; } else if (((minDistance < 0.0f) && (maxDistance >= 0.0f)) || ((minDistance >= 0.0f) && (maxDistance < 0.0f))) { result = CollisionBaseObject::ClassifyPlaneResult::Intersects; } } } }; inline int CROLocal_FloatsIsNegative(float& v1, float& v2) { return ((reinterpret_cast<uint32_t&>(v1) & 0x80000000) & (reinterpret_cast<uint32_t&>(v2) & 0x80000000)) >> 31; } inline const DAVA::Vector3& CROLocal_btVectorToDava(const btVector3* v) { return *(reinterpret_cast<const DAVA::Vector3*>(v)); } inline void CROLocal_Sort(float values[3]) { if (values[1] > values[0]) std::swap(values[1], values[0]); if (values[2] > values[1]) std::swap(values[2], values[1]); if (values[1] > values[0]) std::swap(values[1], values[0]); } struct ClassifyTrianglesToMultiplePlanesCallback : public btInternalTriangleIndexCallback { const DAVA::Vector<DAVA::Plane>& planes; int numTriangles = 0; int trianglesBehind = 0; ClassifyTrianglesToMultiplePlanesCallback(const DAVA::Vector<DAVA::Plane>& pl, int nt) : planes(pl) , numTriangles(nt) { } void internalProcessTriangleIndex(btVector3* triangle, int partId, int triangleIndex) override { for (const DAVA::Plane& plane : planes) { float distances[3] = { plane.DistanceToPoint(CROLocal_btVectorToDava(triangle)), plane.DistanceToPoint(CROLocal_btVectorToDava(triangle + 1)), plane.DistanceToPoint(CROLocal_btVectorToDava(triangle + 2)) }; CROLocal_Sort(distances); if (CROLocal_FloatsIsNegative(distances[0], distances[2])) { ++trianglesBehind; break; } } } }; CollisionBaseObject::ClassifyPlaneResult CollisionRenderObject::ClassifyToPlane(const DAVA::Plane& plane) { if ((btShape == nullptr) || (ClassifyBoundingBoxToPlane(object.GetBoundingBox(), plane) == ClassifyPlaneResult::Behind)) return ClassifyPlaneResult::Behind; btBvhTriangleMeshShape* shape = static_cast<btBvhTriangleMeshShape*>(btShape); ClassifyTrianglesToSinglePlaneCallback cb(plane); btTriangles->InternalProcessAllTriangles(&cb, shape->getLocalAabbMin(), shape->getLocalAabbMax()); return cb.result; } CollisionBaseObject::ClassifyPlanesResult CollisionRenderObject::ClassifyToPlanes(const DAVA::Vector<DAVA::Plane>& planes) { if (btShape == nullptr) return CollisionBaseObject::ClassifyPlanesResult::Outside; for (const DAVA::Plane& plane : planes) { if (ClassifyBoundingBoxToPlane(object.GetBoundingBox(), TransformPlaneToLocalSpace(plane)) == ClassifyPlaneResult::Behind) { return CollisionBaseObject::ClassifyPlanesResult::Outside; } } btBvhTriangleMeshShape* shape = static_cast<btBvhTriangleMeshShape*>(btShape); ClassifyTrianglesToMultiplePlanesCallback cb(planes, btTriangles->getNumTriangles()); btTriangles->InternalProcessAllTriangles(&cb, shape->getLocalAabbMin(), shape->getLocalAabbMax()); return (cb.trianglesBehind == btTriangles->getNumTriangles()) ? CollisionBaseObject::ClassifyPlanesResult::Outside : CollisionBaseObject::ClassifyPlanesResult::ContainsOrIntersects; }
#include "dynet/dynet.h" #include "dynet/training.h" #include "dynet/expr.h" #include "dynet/lstm.h" #include "dynet/mp.h" #include "rnnlm.h" #include <boost/algorithm/string.hpp> #include <iostream> #include <fstream> #include <vector> /* TODO: - The shadow params in the trainers need to be shared. */ using namespace std; using namespace dynet; using namespace dynet::mp; using namespace boost::interprocess; typedef vector<int> Datum; vector<Datum> ReadData(string filename) { vector<Datum> data; ifstream fs(filename); if (!fs.is_open()) { cerr << "ERROR: Unable to open " << filename << endl; exit(1); } string line; while (getline(fs, line)) { data.push_back(read_sentence(line, d)); } return data; } template<class T, class D> class Learner : public ILearner<D, dynet::real> { public: explicit Learner(RNNLanguageModel<T>& rnnlm, unsigned data_size) : rnnlm(rnnlm) {} ~Learner() {} dynet::real LearnFromDatum(const D& datum, bool learn) { ComputationGraph cg; Expression loss_expr = rnnlm.BuildLMGraph(datum, cg); dynet::real loss = as_scalar(cg.forward(loss_expr)); if (learn) { cg.backward(loss_expr); } return loss; } void SaveModel() {} private: RNNLanguageModel<T>& rnnlm; }; int main(int argc, char** argv) { if (argc < 4) { cerr << "Usage: " << argv[0] << " cores corpus.txt dev.txt [iterations]" << endl; return 1; } srand(time(NULL)); unsigned num_children = atoi(argv[1]); assert (num_children <= 64); vector<Datum> data = ReadData(argv[2]); vector<Datum> dev_data = ReadData(argv[3]); unsigned num_iterations = (argc >= 5) ? atoi(argv[4]) : UINT_MAX; unsigned dev_frequency = 5000; unsigned report_frequency = 10; dynet::initialize(argc, argv, true); ParameterCollection model; SimpleSGDTrainer sgd(model, 0.2); //AdagradTrainer sgd(model, 0.0); //AdamTrainer sgd(model, 0.0); RNNLanguageModel<LSTMBuilder> rnnlm(model); Learner<LSTMBuilder, Datum> learner(rnnlm, data.size()); run_multi_process<Datum>(num_children, &learner, &sgd, data, dev_data, num_iterations, dev_frequency, report_frequency); }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "TestFunctions.h" namespace facebook { namespace hermes { namespace synthtest { const char *hostFunctionCreatesObjectsTrace() { return R"###( { "globalObjID": 1, "env": { "mathRandomSeed": 0, "callsToDateNow": [], "callsToNewDate": [], "callsToDateAsFunction": [], "callsToHermesInternalGetInstrumentedStats": [], }, "trace": [ { "type": "CreateHostFunctionRecord", "time": 0, "objID": 10 }, { "type": "SetPropertyRecord", "time": 0, "objID": 1, "propName": "foo", "value": "object:10" }, { "type": "BeginExecJSRecord", "time": 0 }, { "type": "CallToNativeRecord", "time": 0, "functionID": 10, "thisArg": "undefined:", "args": [] }, { "type": "CreateObjectRecord", "time": 0, "objID": 11 }, { "type": "SetPropertyRecord", "time": 0, "objID": 11, "propName": "a", "value": "string:hello" }, { "type": "SetPropertyRecord", "time": 0, "objID": 11, "propName": "b", "value": "null:" }, { "type": "ReturnFromNativeRecord", "time": 0, "retval": "object:11" }, { "type": "CallToNativeRecord", "time": 0, "functionID": 10, "thisArg": "undefined:", "args": [] }, { "type": "CreateObjectRecord", "time": 0, "objID": 12 }, { "type": "SetPropertyRecord", "time": 0, "objID": 12, "propName": "a", "value": "null:" }, { "type": "SetPropertyRecord", "time": 0, "objID": 12, "propName": "b", "value": "string:hello" }, { "type": "ReturnFromNativeRecord", "time": 0, "retval": "object:12" }, { "type": "EndExecJSRecord", "retval": "undefined:", "time": 0 } ] } )###"; } const char *hostFunctionCreatesObjectsSource() { return R"###( 'use strict'; (function(global) { // Native code creates a function foo. // foo returns an object with two properties, a: "hello" and b: null. // The second time it is called, it should return an object with a: null, and // b: "hello". var o = global.foo(); if (o.a !== "hello") { throw new Error("o.a !== \"hello\""); } if (o.b !== null) { throw new Error("o.b !== null"); } // The second returned object should swap the properties. var p = global.foo(); if (o === p) { throw new Error("o and p should be different objects"); } if (p.a !== null) { throw new Error("o.a !== null"); } if (p.b !== "hello") { throw new Error("o.b !== \"hello\""); } })(this); )###"; } } // namespace synthtest } // namespace hermes } // namespace facebook
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/frame_host/render_frame_host_impl.h" #include "base/bind.h" #include "base/command_line.h" #include "base/containers/hash_tables.h" #include "base/lazy_instance.h" #include "base/metrics/histogram.h" #include "base/metrics/user_metrics_action.h" #include "base/time/time.h" #include "content/browser/accessibility/accessibility_mode_helper.h" #include "content/browser/accessibility/browser_accessibility_manager.h" #include "content/browser/accessibility/browser_accessibility_state_impl.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/frame_host/cross_process_frame_connector.h" #include "content/browser/frame_host/cross_site_transferring_request.h" #include "content/browser/frame_host/frame_accessibility.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/frame_host/render_frame_host_delegate.h" #include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/frame_host/render_widget_host_view_child_frame.h" #include "content/browser/geolocation/geolocation_service_context.h" #include "content/browser/permissions/permission_service_context.h" #include "content/browser/permissions/permission_service_impl.h" #include "content/browser/renderer_host/input/input_router.h" #include "content/browser/renderer_host/input/timeout_monitor.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/browser/renderer_host/render_view_host_delegate_view.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/browser/transition_request_manager.h" #include "content/common/accessibility_messages.h" #include "content/common/frame_messages.h" #include "content/common/input_messages.h" #include "content/common/inter_process_time_ticks_converter.h" #include "content/common/navigation_params.h" #include "content/common/render_frame_setup.mojom.h" #include "content/common/swapped_out_messages.h" #include "content/public/browser/ax_event_notification_details.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_plugin_guest_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/stream_handle.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/common/url_utils.h" #include "ui/accessibility/ax_tree.h" #include "url/gurl.h" #if defined(OS_MACOSX) #include "content/browser/frame_host/popup_menu_helper_mac.h" #endif using base::TimeDelta; namespace content { namespace { // The next value to use for the accessibility reset token. int g_next_accessibility_reset_token = 1; // The (process id, routing id) pair that identifies one RenderFrame. typedef std::pair<int32, int32> RenderFrameHostID; typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*> RoutingIDFrameMap; base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map = LAZY_INSTANCE_INITIALIZER; // Translate a WebKit text direction into a base::i18n one. base::i18n::TextDirection WebTextDirectionToChromeTextDirection( blink::WebTextDirection dir) { switch (dir) { case blink::WebTextDirectionLeftToRight: return base::i18n::LEFT_TO_RIGHT; case blink::WebTextDirectionRightToLeft: return base::i18n::RIGHT_TO_LEFT; default: NOTREACHED(); return base::i18n::UNKNOWN_DIRECTION; } } } // namespace // static bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) { return rfh_state == STATE_DEFAULT; } // static RenderFrameHost* RenderFrameHost::FromID(int render_process_id, int render_frame_id) { return RenderFrameHostImpl::FromID(render_process_id, render_frame_id); } // static RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id, int routing_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer(); RoutingIDFrameMap::iterator it = frames->find( RenderFrameHostID(process_id, routing_id)); return it == frames->end() ? NULL : it->second; } RenderFrameHostImpl::RenderFrameHostImpl(RenderViewHostImpl* render_view_host, RenderFrameHostDelegate* delegate, FrameTree* frame_tree, FrameTreeNode* frame_tree_node, int routing_id, int flags) : render_view_host_(render_view_host), delegate_(delegate), cross_process_frame_connector_(NULL), render_frame_proxy_host_(NULL), frame_tree_(frame_tree), frame_tree_node_(frame_tree_node), routing_id_(routing_id), render_frame_created_(false), navigations_suspended_(false), is_waiting_for_beforeunload_ack_(false), unload_ack_is_for_cross_site_transition_(false), accessibility_reset_token_(0), accessibility_reset_count_(0), no_create_browser_accessibility_manager_for_testing_(false), weak_ptr_factory_(this) { bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT); frame_tree_->RegisterRenderFrameHost(this); GetProcess()->AddRoute(routing_id_, this); g_routing_id_frame_map.Get().insert(std::make_pair( RenderFrameHostID(GetProcess()->GetID(), routing_id_), this)); if (is_swapped_out) { rfh_state_ = STATE_SWAPPED_OUT; } else { rfh_state_ = STATE_DEFAULT; GetSiteInstance()->increment_active_frame_count(); } SetUpMojoIfNeeded(); swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind( &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr()))); } RenderFrameHostImpl::~RenderFrameHostImpl() { GetProcess()->RemoveRoute(routing_id_); g_routing_id_frame_map.Get().erase( RenderFrameHostID(GetProcess()->GetID(), routing_id_)); if (delegate_) delegate_->RenderFrameDeleted(this); FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this); // If this was swapped out, it already decremented the active frame count of // the SiteInstance it belongs to. if (IsRFHStateActive(rfh_state_)) GetSiteInstance()->decrement_active_frame_count(); // Notify the FrameTree that this RFH is going away, allowing it to shut down // the corresponding RenderViewHost if it is no longer needed. frame_tree_->UnregisterRenderFrameHost(this); // NULL out the swapout timer; in crash dumps this member will be null only if // the dtor has run. swapout_event_monitor_timeout_.reset(); } int RenderFrameHostImpl::GetRoutingID() { return routing_id_; } SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() { return render_view_host_->GetSiteInstance(); } RenderProcessHost* RenderFrameHostImpl::GetProcess() { // TODO(nasko): This should return its own process, once we have working // cross-process navigation for subframes. return render_view_host_->GetProcess(); } RenderFrameHost* RenderFrameHostImpl::GetParent() { FrameTreeNode* parent_node = frame_tree_node_->parent(); if (!parent_node) return NULL; return parent_node->current_frame_host(); } const std::string& RenderFrameHostImpl::GetFrameName() { return frame_tree_node_->frame_name(); } bool RenderFrameHostImpl::IsCrossProcessSubframe() { FrameTreeNode* parent_node = frame_tree_node_->parent(); if (!parent_node) return false; return GetSiteInstance() != parent_node->current_frame_host()->GetSiteInstance(); } GURL RenderFrameHostImpl::GetLastCommittedURL() { return frame_tree_node_->current_url(); } gfx::NativeView RenderFrameHostImpl::GetNativeView() { RenderWidgetHostView* view = render_view_host_->GetView(); if (!view) return NULL; return view->GetNativeView(); } void RenderFrameHostImpl::ExecuteJavaScript( const base::string16& javascript) { Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_, javascript, 0, false)); } void RenderFrameHostImpl::ExecuteJavaScript( const base::string16& javascript, const JavaScriptResultCallback& callback) { static int next_id = 1; int key = next_id++; Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_, javascript, key, true)); javascript_callbacks_.insert(std::make_pair(key, callback)); } void RenderFrameHostImpl::ExecuteJavaScriptForTests( const base::string16& javascript) { Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript, 0, false)); } RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() { return render_view_host_; } ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() { return service_registry_.get(); } bool RenderFrameHostImpl::Send(IPC::Message* message) { if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) { return render_view_host_->input_router()->SendInput( make_scoped_ptr(message)); } return GetProcess()->Send(message); } bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { // Filter out most IPC messages if this frame is swapped out. // We still want to handle certain ACKs to keep our state consistent. if (is_swapped_out()) { if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) { // If this is a synchronous message and we decided not to handle it, // we must send an error reply, or else the renderer will be stuck // and won't respond to future requests. if (msg.is_sync()) { IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg); reply->set_reply_error(); Send(reply); } // Don't continue looking for someone to handle it. return true; } } if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame, OnDidStartProvisionalLoadForFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad, OnDidCommitProvisionalLoad(msg)) IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted, OnDocumentOnLoadCompleted) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse, OnJavaScriptExecuteResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage, OnRunJavaScriptMessage) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding) IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation, OnBeginNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) #if defined(OS_MACOSX) || defined(OS_ANDROID) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_END_MESSAGE_MAP() // No further actions here, since we may have been deleted. return handled; } void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) { Send(new AccessibilityMsg_SetFocus(routing_id_, object_id)); } void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) { Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id)); } void RenderFrameHostImpl::AccessibilityShowMenu( const gfx::Point& global_point) { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view) view->AccessibilityShowMenu(global_point); } void RenderFrameHostImpl::AccessibilityScrollToMakeVisible( int acc_obj_id, const gfx::Rect& subfocus) { Send(new AccessibilityMsg_ScrollToMakeVisible( routing_id_, acc_obj_id, subfocus)); } void RenderFrameHostImpl::AccessibilityScrollToPoint( int acc_obj_id, const gfx::Point& point) { Send(new AccessibilityMsg_ScrollToPoint( routing_id_, acc_obj_id, point)); } void RenderFrameHostImpl::AccessibilitySetTextSelection( int object_id, int start_offset, int end_offset) { Send(new AccessibilityMsg_SetTextSelection( routing_id_, object_id, start_offset, end_offset)); } void RenderFrameHostImpl::AccessibilitySetValue( int object_id, const base::string16& value) { Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value)); } bool RenderFrameHostImpl::AccessibilityViewHasFocus() const { RenderWidgetHostView* view = render_view_host_->GetView(); if (view) return view->HasFocus(); return false; } gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const { RenderWidgetHostView* view = render_view_host_->GetView(); if (view) return view->GetViewBounds(); return gfx::Rect(); } gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen( const gfx::Rect& bounds) const { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view) return view->AccessibilityOriginInScreen(bounds); return gfx::Point(); } void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) { Send(new AccessibilityMsg_HitTest(routing_id_, point)); } void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) { Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id)); } void RenderFrameHostImpl::AccessibilityFatalError() { browser_accessibility_manager_.reset(NULL); if (accessibility_reset_token_) return; accessibility_reset_count_++; if (accessibility_reset_count_ >= kMaxAccessibilityResets) { Send(new AccessibilityMsg_FatalError(routing_id_)); } else { accessibility_reset_token_ = g_next_accessibility_reset_token++; UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1); Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_)); } } gfx::AcceleratedWidget RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view) return view->AccessibilityGetAcceleratedWidget(); return gfx::kNullAcceleratedWidget; } gfx::NativeViewAccessible RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view) return view->AccessibilityGetNativeViewAccessible(); return NULL; } BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame( int accessibility_node_id) { RenderFrameHostImpl* child_frame = FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id); if (!child_frame) return NULL; // Return NULL if this isn't an out-of-process iframe. Same-process iframes // are already part of the accessibility tree. if (child_frame->GetProcess()->GetID() == GetProcess()->GetID()) return NULL; // As a sanity check, make sure the frame we're going to return belongs // to the same BrowserContext. if (GetSiteInstance()->GetBrowserContext() != child_frame->GetSiteInstance()->GetBrowserContext()) { NOTREACHED(); return NULL; } return child_frame->GetOrCreateBrowserAccessibilityManager(); } BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() { RenderFrameHostImpl* parent_frame = NULL; int parent_node_id = 0; if (!FrameAccessibility::GetInstance()->GetParent( this, &parent_frame, &parent_node_id)) { return NULL; } // As a sanity check, make sure the frame we're going to return belongs // to the same BrowserContext. if (GetSiteInstance()->GetBrowserContext() != parent_frame->GetSiteInstance()->GetBrowserContext()) { NOTREACHED(); return NULL; } BrowserAccessibilityManager* manager = parent_frame->browser_accessibility_manager(); if (!manager) return NULL; return manager->GetFromID(parent_node_id); } bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id, int proxy_routing_id) { TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame"); DCHECK(!IsRenderFrameLive()) << "Creating frame twice"; // The process may (if we're sharing a process with another host that already // initialized it) or may not (we have our own process or the old process // crashed) have been initialized. Calling Init multiple times will be // ignored, so this is safe. if (!GetProcess()->Init()) return false; DCHECK(GetProcess()->HasConnection()); Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id, proxy_routing_id)); // The renderer now has a RenderFrame for this RenderFrameHost. Note that // this path is only used for out-of-process iframes. Main frame RenderFrames // are created with their RenderView, and same-site iframes are created at the // time of OnCreateChildFrame. set_render_frame_created(true); return true; } bool RenderFrameHostImpl::IsRenderFrameLive() { // RenderFrames are created for main frames at the same time as RenderViews, // so we rely on IsRenderViewLive. For subframes, we keep track of each // RenderFrame individually with render_frame_created_. bool is_live = !GetParent() ? render_view_host_->IsRenderViewLive() : GetProcess()->HasConnection() && render_frame_created_; // Sanity check: the RenderView should always be live if the RenderFrame is. DCHECK(!is_live || render_view_host_->IsRenderViewLive()); return is_live; } void RenderFrameHostImpl::Init() { GetProcess()->ResumeRequestsForView(routing_id_); } void RenderFrameHostImpl::OnAddMessageToConsole( int32 level, const base::string16& message, int32 line_no, const base::string16& source_id) { if (delegate_->AddMessageToConsole(level, message, line_no, source_id)) return; // Pass through log level only on WebUI pages to limit console spew. int32 resolved_level = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) ? level : 0; // LogMessages can be persisted so this shouldn't be logged in incognito mode. if (resolved_level >= ::logging::GetMinLogLevel() && !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord()) { logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" << message << "\", source: " << source_id << " (" << line_no << ")"; } } void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id, const std::string& frame_name) { // It is possible that while a new RenderFrameHost was committed, the // RenderFrame corresponding to this host sent an IPC message to create a // frame and it is delivered after this host is swapped out. // Ignore such messages, as we know this RenderFrameHost is going away. if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) return; RenderFrameHostImpl* new_frame = frame_tree_->AddFrame( frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name); if (!new_frame) return; // We know that the RenderFrame has been created in this case, immediately // after the CreateChildFrame IPC was sent. new_frame->set_render_frame_created(true); if (delegate_) delegate_->RenderFrameCreated(new_frame); } void RenderFrameHostImpl::OnDetach() { frame_tree_->RemoveFrame(frame_tree_node_); } void RenderFrameHostImpl::OnFrameFocused() { frame_tree_->SetFocusedFrame(frame_tree_node_); } void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) { OpenURL(params, GetSiteInstance()); } void RenderFrameHostImpl::OnDocumentOnLoadCompleted( FrameMsg_UILoadMetricsReportType::Value report_type, base::TimeTicks ui_timestamp) { if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) { UMA_HISTOGRAM_TIMES("Navigation.UI_OnLoadComplete.Link", base::TimeTicks::Now() - ui_timestamp); } // This message is only sent for top-level frames. TODO(avi): when frame tree // mirroring works correctly, add a check here to enforce it. delegate_->DocumentOnLoadCompleted(this); } void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame( const GURL& url, bool is_transition_navigation) { frame_tree_node_->navigator()->DidStartProvisionalLoad( this, url, is_transition_navigation); } void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError( const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params); } void RenderFrameHostImpl::OnDidFailLoadWithError( const GURL& url, int error_code, const base::string16& error_description) { GURL validated_url(url); GetProcess()->FilterURL(false, &validated_url); frame_tree_node_->navigator()->DidFailLoadWithError( this, validated_url, error_code, error_description); } // Called when the renderer navigates. For every frame loaded, we'll get this // notification containing parameters identifying the navigation. // // Subframes are identified by the page transition type. For subframes loaded // as part of a wider page load, the page_id will be the same as for the top // level frame. If the user explicitly requests a subframe navigation, we will // get a new page_id because we need to create a new navigation entry for that // action. void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) { // Read the parameters out of the IPC message directly to avoid making another // copy when we filter the URLs. PickleIterator iter(msg); FrameHostMsg_DidCommitProvisionalLoad_Params validated_params; if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>:: Read(&msg, &iter, &validated_params)) return; TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad", "url", validated_params.url.possibly_invalid_spec()); // If we're waiting for a cross-site beforeunload ack from this renderer and // we receive a Navigate message from the main frame, then the renderer was // navigating already and sent it before hearing the FrameMsg_Stop message. // We do not want to cancel the pending navigation in this case, since the // old page will soon be stopped. Instead, treat this as a beforeunload ack // to allow the pending navigation to continue. if (is_waiting_for_beforeunload_ack_ && unload_ack_is_for_cross_site_transition_ && ui::PageTransitionIsMainFrame(validated_params.transition)) { base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_; OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now()); return; } // If we're waiting for an unload ack from this renderer and we receive a // Navigate message, then the renderer was navigating before it received the // unload request. It will either respond to the unload request soon or our // timer will expire. Either way, we should ignore this message, because we // have already committed to closing this renderer. if (IsWaitingForUnloadACK()) return; if (validated_params.report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) { UMA_HISTOGRAM_TIMES("Navigation.UI_OnCommitProvisionalLoad.Link", base::TimeTicks::Now() - validated_params.ui_timestamp); } RenderProcessHost* process = GetProcess(); // Attempts to commit certain off-limits URL should be caught more strictly // than our FilterURL checks below. If a renderer violates this policy, it // should be killed. if (!CanCommitURL(validated_params.url)) { VLOG(1) << "Blocked URL " << validated_params.url.spec(); validated_params.url = GURL(url::kAboutBlankURL); RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled")); // Kills the process. process->ReceivedBadMessage(); } // Without this check, an evil renderer can trick the browser into creating // a navigation entry for a banned URL. If the user clicks the back button // followed by the forward button (or clicks reload, or round-trips through // session restore, etc), we'll think that the browser commanded the // renderer to load the URL and grant the renderer the privileges to request // the URL. To prevent this attack, we block the renderer from inserting // banned URLs into the navigation controller in the first place. process->FilterURL(false, &validated_params.url); process->FilterURL(true, &validated_params.referrer.url); for (std::vector<GURL>::iterator it(validated_params.redirects.begin()); it != validated_params.redirects.end(); ++it) { process->FilterURL(false, &(*it)); } process->FilterURL(true, &validated_params.searchable_form_url); // Without this check, the renderer can trick the browser into using // filenames it can't access in a future session restore. if (!render_view_host_->CanAccessFilesOfPageState( validated_params.page_state)) { GetProcess()->ReceivedBadMessage(); return; } accessibility_reset_count_ = 0; frame_tree_node()->navigator()->DidNavigate(this, validated_params); } void RenderFrameHostImpl::OnDidDropNavigation() { // At the end of Navigate(), the delegate's DidStartLoading is called to force // the spinner to start, even if the renderer didn't yet begin the load. If it // turns out that the renderer dropped the navigation, we need to turn off the // spinner. delegate_->DidStopLoading(this); } RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() { return static_cast<RenderWidgetHostImpl*>(render_view_host_); } int RenderFrameHostImpl::GetEnabledBindings() { return render_view_host_->GetEnabledBindings(); } void RenderFrameHostImpl::OnCrossSiteResponse( const GlobalRequestID& global_request_id, scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request, const std::vector<GURL>& transfer_url_chain, const Referrer& referrer, ui::PageTransition page_transition, bool should_replace_current_entry) { frame_tree_node_->render_manager()->OnCrossSiteResponse( this, global_request_id, cross_site_transferring_request.Pass(), transfer_url_chain, referrer, page_transition, should_replace_current_entry); } void RenderFrameHostImpl::OnDeferredAfterResponseStarted( const GlobalRequestID& global_request_id, const TransitionLayerData& transition_data) { frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted( global_request_id, this); if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted()) frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart(); else delegate_->DidDeferAfterResponseStarted(transition_data); } void RenderFrameHostImpl::SwapOut( RenderFrameProxyHost* proxy, bool is_loading) { // The end of this event is in OnSwapOutACK when the RenderFrame has completed // the operation and sends back an IPC message. // The trace event may not end properly if the ACK times out. We expect this // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost. TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this); // If this RenderFrameHost is not in the default state, it must have already // gone through this, therefore just return. if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) { NOTREACHED() << "RFH should be in default state when calling SwapOut."; return; } SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT); swapout_event_monitor_timeout_->Start( base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)); // There may be no proxy if there are no active views in the process. int proxy_routing_id = MSG_ROUTING_NONE; FrameReplicationState replication_state; if (proxy) { set_render_frame_proxy_host(proxy); proxy_routing_id = proxy->GetRoutingID(); replication_state = proxy->frame_tree_node()->current_replication_state(); } if (IsRenderFrameLive()) { Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading, replication_state)); } if (!GetParent()) delegate_->SwappedOut(this); } void RenderFrameHostImpl::OnBeforeUnloadACK( bool proceed, const base::TimeTicks& renderer_before_unload_start_time, const base::TimeTicks& renderer_before_unload_end_time) { TRACE_EVENT_ASYNC_END0( "navigation", "RenderFrameHostImpl::BeforeUnload", this); DCHECK(!GetParent()); // If this renderer navigated while the beforeunload request was in flight, we // may have cleared this state in OnDidCommitProvisionalLoad, in which case we // can ignore this message. // However renderer might also be swapped out but we still want to proceed // with navigation, otherwise it would block future navigations. This can // happen when pending cross-site navigation is canceled by a second one just // before OnDidCommitProvisionalLoad while current RVH is waiting for commit // but second navigation is started from the beginning. if (!is_waiting_for_beforeunload_ack_) { return; } DCHECK(!send_before_unload_start_time_.is_null()); // Sets a default value for before_unload_end_time so that the browser // survives a hacked renderer. base::TimeTicks before_unload_end_time = renderer_before_unload_end_time; if (!renderer_before_unload_start_time.is_null() && !renderer_before_unload_end_time.is_null()) { // When passing TimeTicks across process boundaries, we need to compensate // for any skew between the processes. Here we are converting the // renderer's notion of before_unload_end_time to TimeTicks in the browser // process. See comments in inter_process_time_ticks_converter.h for more. base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now(); InterProcessTimeTicksConverter converter( LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_), LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time), RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time), RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time)); LocalTimeTicks browser_before_unload_end_time = converter.ToLocalTimeTicks( RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time)); before_unload_end_time = browser_before_unload_end_time.ToTimeTicks(); // Collect UMA on the inter-process skew. bool is_skew_additive = false; if (converter.IsSkewAdditiveForMetrics()) { is_skew_additive = true; base::TimeDelta skew = converter.GetSkewForMetrics(); if (skew >= base::TimeDelta()) { UMA_HISTOGRAM_TIMES( "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew); } else { UMA_HISTOGRAM_TIMES( "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew); } } UMA_HISTOGRAM_BOOLEAN( "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser", is_skew_additive); base::TimeDelta on_before_unload_overhead_time = (receive_before_unload_ack_time - send_before_unload_start_time_) - (renderer_before_unload_end_time - renderer_before_unload_start_time); UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime", on_before_unload_overhead_time); frame_tree_node_->navigator()->LogBeforeUnloadTime( renderer_before_unload_start_time, renderer_before_unload_end_time); } // Resets beforeunload waiting state. is_waiting_for_beforeunload_ack_ = false; render_view_host_->decrement_in_flight_event_count(); render_view_host_->StopHangMonitorTimeout(); send_before_unload_start_time_ = base::TimeTicks(); frame_tree_node_->render_manager()->OnBeforeUnloadACK( unload_ack_is_for_cross_site_transition_, proceed, before_unload_end_time); // If canceled, notify the delegate to cancel its pending navigation entry. if (!proceed) render_view_host_->GetDelegate()->DidCancelLoading(); } bool RenderFrameHostImpl::IsWaitingForUnloadACK() const { return render_view_host_->is_waiting_for_close_ack_ || rfh_state_ == STATE_PENDING_SWAP_OUT; } void RenderFrameHostImpl::OnSwapOutACK() { OnSwappedOut(); } void RenderFrameHostImpl::OnSwappedOut() { // Ignore spurious swap out ack. if (rfh_state_ != STATE_PENDING_SWAP_OUT) return; TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this); swapout_event_monitor_timeout_->Stop(); if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) { // We are now deleted. return; } // If this RFH wasn't pending deletion, then it is now swapped out. SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT); } void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) { // Validate the URLs in |params|. If the renderer can't request the URLs // directly, don't show them in the context menu. ContextMenuParams validated_params(params); RenderProcessHost* process = GetProcess(); // We don't validate |unfiltered_link_url| so that this field can be used // when users want to copy the original link URL. process->FilterURL(true, &validated_params.link_url); process->FilterURL(true, &validated_params.src_url); process->FilterURL(false, &validated_params.page_url); process->FilterURL(true, &validated_params.frame_url); delegate_->ShowContextMenu(this, validated_params); } void RenderFrameHostImpl::OnJavaScriptExecuteResponse( int id, const base::ListValue& result) { const base::Value* result_value; if (!result.Get(0, &result_value)) { // Programming error or rogue renderer. NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse"; return; } std::map<int, JavaScriptResultCallback>::iterator it = javascript_callbacks_.find(id); if (it != javascript_callbacks_.end()) { it->second.Run(result_value); javascript_callbacks_.erase(it); } else { NOTREACHED() << "Received script response for unknown request"; } } void RenderFrameHostImpl::OnRunJavaScriptMessage( const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptMessageType type, IPC::Message* reply_msg) { // While a JS message dialog is showing, tabs in the same process shouldn't // process input events. GetProcess()->SetIgnoreInputEvents(true); render_view_host_->StopHangMonitorTimeout(); delegate_->RunJavaScriptMessage(this, message, default_prompt, frame_url, type, reply_msg); } void RenderFrameHostImpl::OnRunBeforeUnloadConfirm( const GURL& frame_url, const base::string16& message, bool is_reload, IPC::Message* reply_msg) { // While a JS beforeunload dialog is showing, tabs in the same process // shouldn't process input events. GetProcess()->SetIgnoreInputEvents(true); render_view_host_->StopHangMonitorTimeout(); delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg); } void RenderFrameHostImpl::OnTextSurroundingSelectionResponse( const base::string16& content, size_t start_offset, size_t end_offset) { render_view_host_->OnTextSurroundingSelectionResponse( content, start_offset, end_offset); } void RenderFrameHostImpl::OnDidAccessInitialDocument() { delegate_->DidAccessInitialDocument(); } void RenderFrameHostImpl::OnDidDisownOpener() { // This message is only sent for top-level frames. TODO(avi): when frame tree // mirroring works correctly, add a check here to enforce it. delegate_->DidDisownOpener(this); } void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) { // Update the RVH's current page ID so that future IPCs from the renderer // correspond to the new page. render_view_host_->page_id_ = page_id; } void RenderFrameHostImpl::OnUpdateTitle( const base::string16& title, blink::WebTextDirection title_direction) { // This message is only sent for top-level frames. TODO(avi): when frame tree // mirroring works correctly, add a check here to enforce it. if (title.length() > kMaxTitleChars) { NOTREACHED() << "Renderer sent too many characters in title."; return; } delegate_->UpdateTitle(this, render_view_host_->page_id_, title, WebTextDirectionToChromeTextDirection( title_direction)); } void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) { // This message is only sent for top-level frames. TODO(avi): when frame tree // mirroring works correctly, add a check here to enforce it. delegate_->UpdateEncoding(this, encoding_name); } void RenderFrameHostImpl::OnBeginNavigation( const FrameHostMsg_BeginNavigation_Params& params, const CommonNavigationParams& common_params) { CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableBrowserSideNavigation)); frame_tree_node()->navigator()->OnBeginNavigation( frame_tree_node(), params, common_params); } void RenderFrameHostImpl::OnAccessibilityEvents( const std::vector<AccessibilityHostMsg_EventParams>& params, int reset_token) { // Don't process this IPC if either we're waiting on a reset and this // IPC doesn't have the matching token ID, or if we're not waiting on a // reset but this message includes a reset token. if (accessibility_reset_token_ != reset_token) { Send(new AccessibilityMsg_Events_ACK(routing_id_)); return; } accessibility_reset_token_ = 0; RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if ((accessibility_mode != AccessibilityModeOff) && view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) { if (accessibility_mode & AccessibilityModeFlagPlatform) { GetOrCreateBrowserAccessibilityManager(); if (browser_accessibility_manager_) browser_accessibility_manager_->OnAccessibilityEvents(params); } if (browser_accessibility_manager_) { // Get the frame routing ids from out-of-process iframes and // browser plugin instance ids from guests and update the mappings in // FrameAccessibility. for (size_t i = 0; i < params.size(); ++i) { const AccessibilityHostMsg_EventParams& param = params[i]; UpdateCrossProcessIframeAccessibility( param.node_to_frame_routing_id_map); UpdateGuestFrameAccessibility( param.node_to_browser_plugin_instance_id_map); } } // Send the updates to the automation extension API. std::vector<AXEventNotificationDetails> details; details.reserve(params.size()); for (size_t i = 0; i < params.size(); ++i) { const AccessibilityHostMsg_EventParams& param = params[i]; AXEventNotificationDetails detail(param.update.node_id_to_clear, param.update.nodes, param.event_type, param.id, GetProcess()->GetID(), routing_id_); details.push_back(detail); } delegate_->AccessibilityEventReceived(details); } // Always send an ACK or the renderer can be in a bad state. Send(new AccessibilityMsg_Events_ACK(routing_id_)); // The rest of this code is just for testing; bail out if we're not // in that mode. if (accessibility_testing_callback_.is_null()) return; for (size_t i = 0; i < params.size(); i++) { const AccessibilityHostMsg_EventParams& param = params[i]; if (static_cast<int>(param.event_type) < 0) continue; if (!ax_tree_for_testing_) { if (browser_accessibility_manager_) { ax_tree_for_testing_.reset(new ui::AXTree( browser_accessibility_manager_->SnapshotAXTreeForTesting())); } else { ax_tree_for_testing_.reset(new ui::AXTree()); CHECK(ax_tree_for_testing_->Unserialize(param.update)) << ax_tree_for_testing_->error(); } } else { CHECK(ax_tree_for_testing_->Unserialize(param.update)) << ax_tree_for_testing_->error(); } accessibility_testing_callback_.Run(param.event_type, param.id); } } void RenderFrameHostImpl::OnAccessibilityLocationChanges( const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) { if (accessibility_reset_token_) return; RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) { AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode & AccessibilityModeFlagPlatform) { BrowserAccessibilityManager* manager = GetOrCreateBrowserAccessibilityManager(); if (manager) manager->OnLocationChanges(params); } // TODO(aboxhall): send location change events to web contents observers too } } void RenderFrameHostImpl::OnAccessibilityFindInPageResult( const AccessibilityHostMsg_FindInPageResultParams& params) { AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode & AccessibilityModeFlagPlatform) { BrowserAccessibilityManager* manager = GetOrCreateBrowserAccessibilityManager(); if (manager) { manager->OnFindInPageResult( params.request_id, params.match_index, params.start_id, params.start_offset, params.end_id, params.end_offset); } } } #if defined(OS_MACOSX) || defined(OS_ANDROID) void RenderFrameHostImpl::OnShowPopup( const FrameHostMsg_ShowPopup_Params& params) { RenderViewHostDelegateView* view = render_view_host_->delegate_->GetDelegateView(); if (view) { view->ShowPopupMenu(this, params.bounds, params.item_height, params.item_font_size, params.selected_item, params.popup_items, params.right_aligned, params.allow_multiple_selection); } } void RenderFrameHostImpl::OnHidePopup() { RenderViewHostDelegateView* view = render_view_host_->delegate_->GetDelegateView(); if (view) view->HidePopupMenu(); } #endif void RenderFrameHostImpl::RegisterMojoServices() { GeolocationServiceContext* geolocation_service_context = delegate_ ? delegate_->GetGeolocationServiceContext() : NULL; if (geolocation_service_context) { // TODO(creis): Bind process ID here so that GeolocationServiceImpl // can perform permissions checks once site isolation is complete. // crbug.com/426384 GetServiceRegistry()->AddService<GeolocationService>( base::Bind(&GeolocationServiceContext::CreateService, base::Unretained(geolocation_service_context), base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission, base::Unretained(this)))); } if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); GetServiceRegistry()->AddService<PermissionService>( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); } void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) { // Only main frames should be swapped out and retained inside a proxy host. if (rfh_state == STATE_SWAPPED_OUT) CHECK(!GetParent()); // We update the number of RenderFrameHosts in a SiteInstance when the swapped // out status of a RenderFrameHost gets flipped to/from active. if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state)) GetSiteInstance()->increment_active_frame_count(); else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state)) GetSiteInstance()->decrement_active_frame_count(); // The active and swapped out state of the RVH is determined by its main // frame, since subframes should have their own widgets. if (frame_tree_node_->IsMainFrame()) { render_view_host_->set_is_active(IsRFHStateActive(rfh_state)); render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT); } // Whenever we change the RFH state to and from active or swapped out state, // we should not be waiting for beforeunload or close acks. We clear them // here to be safe, since they can cause navigations to be ignored in // OnDidCommitProvisionalLoad. // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine. if (rfh_state == STATE_DEFAULT || rfh_state == STATE_SWAPPED_OUT || rfh_state_ == STATE_DEFAULT || rfh_state_ == STATE_SWAPPED_OUT) { if (is_waiting_for_beforeunload_ack_) { is_waiting_for_beforeunload_ack_ = false; render_view_host_->decrement_in_flight_event_count(); render_view_host_->StopHangMonitorTimeout(); } send_before_unload_start_time_ = base::TimeTicks(); render_view_host_->is_waiting_for_close_ack_ = false; } rfh_state_ = rfh_state; } bool RenderFrameHostImpl::CanCommitURL(const GURL& url) { // TODO(creis): We should also check for WebUI pages here. Also, when the // out-of-process iframes implementation is ready, we should check for // cross-site URLs that are not allowed to commit in this process. // Give the client a chance to disallow URLs from committing. return GetContentClient()->browser()->CanCommitURL(GetProcess(), url); } void RenderFrameHostImpl::Navigate(const FrameMsg_Navigate_Params& params) { TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate"); // Browser plugin guests are not allowed to navigate outside web-safe schemes, // so do not grant them the ability to request additional URLs. if (!GetProcess()->IsIsolatedGuest()) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL( GetProcess()->GetID(), params.common_params.url); if (params.common_params.url.SchemeIs(url::kDataScheme) && params.base_url_for_data_url.SchemeIs(url::kFileScheme)) { // If 'data:' is used, and we have a 'file:' base url, grant access to // local files. ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL( GetProcess()->GetID(), params.base_url_for_data_url); } } // We may be returning to an existing NavigationEntry that had been granted // file access. If this is a different process, we will need to grant the // access again. The files listed in the page state are validated when they // are received from the renderer to prevent abuse. if (params.commit_params.page_state.IsValid()) { render_view_host_->GrantFileAccessFromPageState( params.commit_params.page_state); } // Only send the message if we aren't suspended at the start of a cross-site // request. if (navigations_suspended_) { // Shouldn't be possible to have a second navigation while suspended, since // navigations will only be suspended during a cross-site request. If a // second navigation occurs, RenderFrameHostManager will cancel this pending // RFH and create a new pending RFH. DCHECK(!suspended_nav_params_.get()); suspended_nav_params_.reset(new FrameMsg_Navigate_Params(params)); } else { // Get back to a clean state, in case we start a new navigation without // completing a RFH swap or unload handler. SetState(RenderFrameHostImpl::STATE_DEFAULT); Send(new FrameMsg_Navigate(routing_id_, params)); } // Force the throbber to start. We do this because Blink's "started // loading" message will be received asynchronously from the UI of the // browser. But we want to keep the throbber in sync with what's happening // in the UI. For example, we want to start throbbing immediately when the // user navigates even if the renderer is delayed. There is also an issue // with the throbber starting because the WebUI (which controls whether the // favicon is displayed) happens synchronously. If the start loading // messages was asynchronous, then the default favicon would flash in. // // Blink doesn't send throb notifications for JavaScript URLs, so we // don't want to either. if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme)) delegate_->DidStartLoading(this, true); } void RenderFrameHostImpl::NavigateToURL(const GURL& url) { FrameMsg_Navigate_Params params; params.common_params.url = url; params.common_params.transition = ui::PAGE_TRANSITION_LINK; params.common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL; params.commit_params.browser_navigation_start = base::TimeTicks::Now(); params.page_id = -1; params.pending_history_list_offset = -1; params.current_history_list_offset = -1; params.current_history_list_length = 0; Navigate(params); } void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params, SiteInstance* source_site_instance) { GURL validated_url(params.url); GetProcess()->FilterURL(false, &validated_url); TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url", validated_url.possibly_invalid_spec()); frame_tree_node_->navigator()->RequestOpenURL( this, validated_url, source_site_instance, params.referrer, params.disposition, params.should_replace_current_entry, params.user_gesture); } void RenderFrameHostImpl::Stop() { Send(new FrameMsg_Stop(routing_id_)); } void RenderFrameHostImpl::DispatchBeforeUnload(bool for_cross_site_transition) { // TODO(creis): Support beforeunload on subframes. For now just pretend that // the handler ran and allowed the navigation to proceed. if (GetParent() || !IsRenderFrameLive()) { // We don't have a live renderer, so just skip running beforeunload. frame_tree_node_->render_manager()->OnBeforeUnloadACK( for_cross_site_transition, true, base::TimeTicks::Now()); return; } TRACE_EVENT_ASYNC_BEGIN0( "navigation", "RenderFrameHostImpl::BeforeUnload", this); // This may be called more than once (if the user clicks the tab close button // several times, or if she clicks the tab close button then the browser close // button), and we only send the message once. if (is_waiting_for_beforeunload_ack_) { // Some of our close messages could be for the tab, others for cross-site // transitions. We always want to think it's for closing the tab if any // of the messages were, since otherwise it might be impossible to close // (if there was a cross-site "close" request pending when the user clicked // the close button). We want to keep the "for cross site" flag only if // both the old and the new ones are also for cross site. unload_ack_is_for_cross_site_transition_ = unload_ack_is_for_cross_site_transition_ && for_cross_site_transition; } else { // Start the hang monitor in case the renderer hangs in the beforeunload // handler. is_waiting_for_beforeunload_ack_ = true; unload_ack_is_for_cross_site_transition_ = for_cross_site_transition; // Increment the in-flight event count, to ensure that input events won't // cancel the timeout timer. render_view_host_->increment_in_flight_event_count(); render_view_host_->StartHangMonitorTimeout( TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)); send_before_unload_start_time_ = base::TimeTicks::Now(); Send(new FrameMsg_BeforeUnload(routing_id_)); } } void RenderFrameHostImpl::DisownOpener() { Send(new FrameMsg_DisownOpener(GetRoutingID())); } void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before, size_t after) { Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after)); } void RenderFrameHostImpl::JavaScriptDialogClosed( IPC::Message* reply_msg, bool success, const base::string16& user_input, bool dialog_was_suppressed) { GetProcess()->SetIgnoreInputEvents(false); bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK(); // If we are executing as part of (before)unload event handling, we don't // want to use the regular hung_renderer_delay_ms_ if the user has agreed to // leave the current page. In this case, use the regular timeout value used // during the (before)unload handling. if (is_waiting) { render_view_host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds( success ? RenderViewHostImpl::kUnloadTimeoutMS : render_view_host_->hung_renderer_delay_ms_)); } FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg, success, user_input); Send(reply_msg); // If we are waiting for an unload or beforeunload ack and the user has // suppressed messages, kill the tab immediately; a page that's spamming // alerts in onbeforeunload is presumably malicious, so there's no point in // continuing to run its script and dragging out the process. // This must be done after sending the reply since RenderView can't close // correctly while waiting for a response. if (is_waiting && dialog_was_suppressed) render_view_host_->delegate_->RendererUnresponsive(render_view_host_); } // PlzNavigate void RenderFrameHostImpl::CommitNavigation( ResourceResponse* response, scoped_ptr<StreamHandle> body, const CommonNavigationParams& common_params, const CommitNavigationParams& commit_params) { // TODO(clamy): Check if we have to add security checks for the browser plugin // guests. Send(new FrameMsg_CommitNavigation( routing_id_, response->head, body->GetURL(), common_params, commit_params)); // TODO(clamy): Check if we should start the throbber for non javascript urls // here. // TODO(clamy): Release the stream handle once the renderer has finished // reading it. stream_handle_ = body.Pass(); } void RenderFrameHostImpl::SetUpMojoIfNeeded() { if (service_registry_.get()) return; service_registry_.reset(new ServiceRegistryImpl()); if (!GetProcess()->GetServiceRegistry()) return; RegisterMojoServices(); RenderFrameSetupPtr setup; GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup); mojo::ServiceProviderPtr service_provider; setup->GetServiceProviderForFrame(routing_id_, mojo::GetProxy(&service_provider)); service_registry_->BindRemoteServiceProvider( service_provider.PassMessagePipe()); #if defined(OS_ANDROID) service_registry_android_.reset( new ServiceRegistryAndroid(service_registry_.get())); #endif } void RenderFrameHostImpl::InvalidateMojoConnection() { #if defined(OS_ANDROID) // The Android-specific service registry has a reference to // |service_registry_| and thus must be torn down first. service_registry_android_.reset(); #endif service_registry_.reset(); } void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility( const std::map<int32, int>& node_to_frame_routing_id_map) { for (const auto& iter : node_to_frame_routing_id_map) { // This is the id of the accessibility node that has a child frame. int32 node_id = iter.first; // The routing id from either a RenderFrame or a RenderFrameProxy. int frame_routing_id = iter.second; FrameTree* frame_tree = frame_tree_node()->frame_tree(); FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID( GetProcess()->GetID(), frame_routing_id); if (child_frame_tree_node) { FrameAccessibility::GetInstance()->AddChildFrame( this, node_id, child_frame_tree_node->frame_tree_node_id()); } } } void RenderFrameHostImpl::UpdateGuestFrameAccessibility( const std::map<int32, int>& node_to_browser_plugin_instance_id_map) { for (const auto& iter : node_to_browser_plugin_instance_id_map) { // This is the id of the accessibility node that hosts a plugin. int32 node_id = iter.first; // The id of the browser plugin. int browser_plugin_instance_id = iter.second; FrameAccessibility::GetInstance()->AddGuestWebContents( this, node_id, browser_plugin_instance_id); } } void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) { Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode)); } void RenderFrameHostImpl::SetAccessibilityCallbackForTesting( const base::Callback<void(ui::AXEvent, int)>& callback) { accessibility_testing_callback_ = callback; } const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() { return ax_tree_for_testing_.get(); } BrowserAccessibilityManager* RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view && !browser_accessibility_manager_ && !no_create_browser_accessibility_manager_for_testing_) { browser_accessibility_manager_.reset( view->CreateBrowserAccessibilityManager(this)); if (browser_accessibility_manager_) UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1); else UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1); } return browser_accessibility_manager_.get(); } void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility( int request_id) { AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode & AccessibilityModeFlagPlatform) { BrowserAccessibilityManager* manager = GetOrCreateBrowserAccessibilityManager(); if (manager) manager->ActivateFindInPageResult(request_id); } } #if defined(OS_WIN) void RenderFrameHostImpl::SetParentNativeViewAccessible( gfx::NativeViewAccessible accessible_parent) { RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetView()); if (view) view->SetParentNativeViewAccessible(accessible_parent); } gfx::NativeViewAccessible RenderFrameHostImpl::GetParentNativeViewAccessible() const { return delegate_->GetParentNativeViewAccessible(); } #elif defined(OS_MACOSX) void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) { Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index)); } void RenderFrameHostImpl::DidCancelPopupMenu() { Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1)); } #elif defined(OS_ANDROID) void RenderFrameHostImpl::DidSelectPopupMenuItems( const std::vector<int>& selected_indices) { Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices)); } void RenderFrameHostImpl::DidCancelPopupMenu() { Send(new FrameMsg_SelectPopupMenuItems( routing_id_, true, std::vector<int>())); } #endif void RenderFrameHostImpl::ClearPendingTransitionRequestData() { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &TransitionRequestManager::ClearPendingTransitionRequestData, base::Unretained(TransitionRequestManager::GetInstance()), GetProcess()->GetID(), routing_id_)); } void RenderFrameHostImpl::SetNavigationsSuspended( bool suspend, const base::TimeTicks& proceed_time) { // This should only be called to toggle the state. DCHECK(navigations_suspended_ != suspend); navigations_suspended_ = suspend; if (navigations_suspended_) { TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl navigation suspended", this); } else { TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl navigation suspended", this); } if (!suspend && suspended_nav_params_) { // There's navigation message params waiting to be sent. Now that we're not // suspended anymore, resume navigation by sending them. If we were swapped // out, we should also stop filtering out the IPC messages now. SetState(RenderFrameHostImpl::STATE_DEFAULT); DCHECK(!proceed_time.is_null()); suspended_nav_params_->commit_params.browser_navigation_start = proceed_time; Send(new FrameMsg_Navigate(routing_id_, *suspended_nav_params_)); suspended_nav_params_.reset(); } } void RenderFrameHostImpl::CancelSuspendedNavigations() { // Clear any state if a pending navigation is canceled or preempted. if (suspended_nav_params_) suspended_nav_params_.reset(); TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl navigation suspended", this); navigations_suspended_ = false; } void RenderFrameHostImpl::DidUseGeolocationPermission() { RenderFrameHost* top_frame = frame_tree_node()->frame_tree()->GetMainFrame(); GetContentClient()->browser()->RegisterPermissionUsage( PERMISSION_GEOLOCATION, delegate_->GetAsWebContents(), GetLastCommittedURL().GetOrigin(), top_frame->GetLastCommittedURL().GetOrigin()); } } // namespace content
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #define QT_NO_URL_CAST_FROM_STRING 1 #define _WIN32_WINNT 0x0600 #include "qwindowsdialoghelpers.h" #include "qwindowscontext.h" #include "qwindowswindow.h" #include "qwindowsintegration.h" #include "qwindowstheme.h" // Color conversion helpers #include <QtGui/QGuiApplication> #include <QtGui/QColor> #include <QtCore/QDebug> #include <QtCore/QRegExp> #include <QtCore/QTimer> #include <QtCore/QDir> #include <QtCore/QScopedArrayPointer> #include <QtCore/QSharedPointer> #include <QtCore/QObject> #include <QtCore/QThread> #include <QtCore/QSysInfo> #include <QtCore/QSharedData> #include <QtCore/QExplicitlySharedDataPointer> #include <QtCore/QMutex> #include <QtCore/QMutexLocker> #include <QtCore/private/qsystemlibrary_p.h> #include <algorithm> #include "qtwindows_additional.h" #define STRICT_TYPED_ITEMIDS #include <shlobj.h> #include <shlwapi.h> // #define USE_NATIVE_COLOR_DIALOG /* Testing purposes only */ #ifdef Q_CC_MINGW /* Add missing declarations for MinGW */ #ifndef __IShellLibrary_FWD_DEFINED__ /* Constants obtained by running the below stream operator for * CLSID, IID on the constants in the Windows SDK libraries. */ static const IID IID_IFileOpenDialog = {0xd57c7288, 0xd4ad, 0x4768, {0xbe, 0x02, 0x9d, 0x96, 0x95, 0x32, 0xd9, 0x60}}; static const IID IID_IFileSaveDialog = {0x84bccd23, 0x5fde, 0x4cdb,{0xae, 0xa4, 0xaf, 0x64, 0xb8, 0x3d, 0x78, 0xab}}; #ifdef __MINGW64_VERSION_MAJOR static const IID q_IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe}}; #define IID_IShellItem q_IID_IShellItem #else static const IID IID_IShellItem = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe}}; static const IID IID_IShellItemArray = {0xb63ea76d, 0x1f85, 0x456f, {0xa1, 0x9c, 0x48, 0x15, 0x9e, 0xfa, 0x85, 0x8b}}; # define LFF_FORCEFILESYSTEM 1 #endif static const IID IID_IFileDialogEvents = {0x973510db, 0x7d7f, 0x452b,{0x89, 0x75, 0x74, 0xa8, 0x58, 0x28, 0xd3, 0x54}}; static const CLSID CLSID_FileOpenDialog = {0xdc1c5a9c, 0xe88a, 0x4dde, {0xa5, 0xa1, 0x60, 0xf8, 0x2a, 0x20, 0xae, 0xf7}}; static const CLSID CLSID_FileSaveDialog = {0xc0b4e2f3, 0xba21, 0x4773,{0x8d, 0xba, 0x33, 0x5e, 0xc9, 0x46, 0xeb, 0x8b}}; typedef struct _COMDLG_FILTERSPEC { LPCWSTR pszName; LPCWSTR pszSpec; } COMDLG_FILTERSPEC; #define FOS_OVERWRITEPROMPT 0x2 #define FOS_STRICTFILETYPES 0x4 #define FOS_NOCHANGEDIR 0x8 #define FOS_PICKFOLDERS 0x20 #define FOS_FORCEFILESYSTEM 0x40 #define FOS_ALLNONSTORAGEITEMS 0x80 #define FOS_NOVALIDATE 0x100 #define FOS_ALLOWMULTISELECT 0x200 #define FOS_PATHMUSTEXIST 0x800 #define FOS_FILEMUSTEXIST 0x1000 #define FOS_CREATEPROMPT 0x2000 #define FOS_SHAREAWARE 0x4000 #define FOS_NOREADONLYRETURN 0x8000 #define FOS_NOTESTFILECREATE 0x10000 #define FOS_HIDEMRUPLACES 0x20000 #define FOS_HIDEPINNEDPLACES 0x40000 #define FOS_NODEREFERENCELINKS 0x100000 #define FOS_DONTADDTORECENT 0x2000000 #define FOS_FORCESHOWHIDDEN 0x10000000 #define FOS_DEFAULTNOMINIMODE 0x20000000 #define FOS_FORCEPREVIEWPANEON 0x40000000 #if __MINGW64_VERSION_MAJOR < 2 typedef int GETPROPERTYSTOREFLAGS; #define GPS_DEFAULT 0x00000000 #define GPS_HANDLERPROPERTIESONLY 0x00000001 #define GPS_READWRITE 0x00000002 #define GPS_TEMPORARY 0x00000004 #define GPS_FASTPROPERTIESONLY 0x00000008 #define GPS_OPENSLOWITEM 0x00000010 #define GPS_DELAYCREATION 0x00000020 #define GPS_BESTEFFORT 0x00000040 #define GPS_MASK_VALID 0x0000007F #endif typedef int (QT_WIN_CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData); // message from browser #define BFFM_INITIALIZED 1 #define BFFM_SELCHANGED 2 #define BFFM_ENABLEOK (WM_USER + 101) // Browsing for directory. #define BIF_NONEWFOLDERBUTTON 0x0200 #define BIF_NOTRANSLATETARGETS 0x0400 #define BIF_BROWSEFORCOMPUTER 0x1000 #define BIF_BROWSEFORPRINTER 0x2000 #define BIF_BROWSEINCLUDEFILES 0x4000 #define BIF_SHAREABLE 0x8000 //the enums typedef enum { SIATTRIBFLAGS_AND = 0x1, SIATTRIBFLAGS_OR = 0x2, SIATTRIBFLAGS_APPCOMPAT = 0x3, SIATTRIBFLAGS_MASK = 0x3 } SIATTRIBFLAGS; #ifndef __MINGW64_VERSION_MAJOR typedef enum { SIGDN_NORMALDISPLAY = 0x00000000, SIGDN_PARENTRELATIVEPARSING = 0x80018001, SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8001c001, SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, SIGDN_PARENTRELATIVEEDITING = 0x80031001, SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, SIGDN_FILESYSPATH = 0x80058000, SIGDN_URL = 0x80068000 } SIGDN; #endif typedef enum { FDAP_BOTTOM = 0x00000000, FDAP_TOP = 0x00000001 } FDAP; typedef enum { FDESVR_DEFAULT = 0x00000000, FDESVR_ACCEPT = 0x00000001, FDESVR_REFUSE = 0x00000002 } FDE_SHAREVIOLATION_RESPONSE; typedef FDE_SHAREVIOLATION_RESPONSE FDE_OVERWRITE_RESPONSE; //the structs typedef struct { LPCWSTR pszName; LPCWSTR pszSpec; } qt_COMDLG_FILTERSPEC; typedef struct { GUID fmtid; DWORD pid; } qt_PROPERTYKEY; typedef struct { USHORT cb; BYTE abID[1]; } qt_SHITEMID, *qt_LPSHITEMID; typedef struct { qt_SHITEMID mkid; } qt_ITEMIDLIST, *qt_LPITEMIDLIST; typedef const qt_ITEMIDLIST *qt_LPCITEMIDLIST; typedef struct { HWND hwndOwner; qt_LPCITEMIDLIST pidlRoot; LPWSTR pszDisplayName; LPCWSTR lpszTitle; UINT ulFlags; BFFCALLBACK lpfn; LPARAM lParam; int iImage; } qt_BROWSEINFO; #endif // __IShellLibrary_FWD_DEFINED__ #ifndef __IFileDialogEvents_FWD_DEFINED__ DECLARE_INTERFACE(IFileDialogEvents); #endif #ifndef __IShellItem_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IShellItem, IUnknown) { STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID bhid, REFIID riid, void **ppv) PURE; STDMETHOD(GetParent)(THIS_ IShellItem **ppsi) PURE; STDMETHOD(GetDisplayName)(THIS_ SIGDN sigdnName, LPWSTR *ppszName) PURE; STDMETHOD(GetAttributes)(THIS_ ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE; STDMETHOD(Compare)(THIS_ IShellItem *psi, DWORD hint, int *piOrder) PURE; }; #endif #ifndef __IShellItemFilter_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IShellItemFilter, IUnknown) { STDMETHOD(IncludeItem)(THIS_ IShellItem *psi) PURE; STDMETHOD(GetEnumFlagsForItem)(THIS_ IShellItem *psi, DWORD *pgrfFlags) PURE; }; #endif #ifndef __IEnumShellItems_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IEnumShellItems, IUnknown) { STDMETHOD(Next)(THIS_ ULONG celt, IShellItem **rgelt, ULONG *pceltFetched) PURE; STDMETHOD(Skip)(THIS_ ULONG celt) PURE; STDMETHOD(Reset)(THIS_) PURE; STDMETHOD(Clone)(THIS_ IEnumShellItems **ppenum) PURE; }; #endif #ifndef __IShellItemArray_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IShellItemArray, IUnknown) { STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID rbhid, REFIID riid, void **ppvOut) PURE; STDMETHOD(GetPropertyStore)(THIS_ GETPROPERTYSTOREFLAGS flags, REFIID riid, void **ppv) PURE; STDMETHOD(GetPropertyDescriptionList)(THIS_ const qt_PROPERTYKEY *keyType, REFIID riid, void **ppv) PURE; STDMETHOD(GetAttributes)(THIS_ SIATTRIBFLAGS dwAttribFlags, ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE; STDMETHOD(GetCount)(THIS_ DWORD *pdwNumItems) PURE; STDMETHOD(GetItemAt)(THIS_ DWORD dwIndex, IShellItem **ppsi) PURE; STDMETHOD(EnumItems)(THIS_ IEnumShellItems **ppenumShellItems) PURE; }; #endif #ifndef __IShellLibrary_INTERFACE_DEFINED__ enum LIBRARYOPTIONFLAGS {}; enum DEFAULTSAVEFOLDERTYPE { DSFT_DETECT = 1 }; enum LIBRARYSAVEFLAGS {}; DECLARE_INTERFACE_(IShellLibrary, IUnknown) { STDMETHOD(LoadLibraryFromItem)(THIS_ IShellItem *psiLibrary, DWORD grfMode) PURE; STDMETHOD(LoadLibraryFromKnownFolder)(THIS_ const GUID &kfidLibrary, DWORD grfMode) PURE; STDMETHOD(AddFolder)(THIS_ IShellItem *psiLocation) PURE; STDMETHOD(RemoveFolder)(THIS_ IShellItem *psiLocation) PURE; STDMETHOD(GetFolders)(THIS_ int lff, REFIID riid, void **ppv) PURE; STDMETHOD(ResolveFolder)(THIS_ IShellItem *psiFolderToResolve, DWORD dwTimeout, REFIID riid, void **ppv) PURE; STDMETHOD(GetDefaultSaveFolder)(THIS_ DEFAULTSAVEFOLDERTYPE dsft, REFIID riid, void **ppv) PURE; STDMETHOD(SetDefaultSaveFolder)(THIS_ DEFAULTSAVEFOLDERTYPE dsft, IShellItem *psi) PURE; STDMETHOD(GetOptions)(THIS_ LIBRARYOPTIONFLAGS *plofOptions) PURE; STDMETHOD(SetOptions)(THIS_ LIBRARYOPTIONFLAGS lofMask, LIBRARYOPTIONFLAGS lofOptions) PURE; STDMETHOD(GetFolderType)(THIS_ GUID *pftid) PURE; STDMETHOD(SetFolderType)(THIS_ const GUID &ftid) PURE; STDMETHOD(GetIcon)(THIS_ LPWSTR *ppszIcon) PURE; STDMETHOD(SetIcon)(THIS_ LPCWSTR pszIcon) PURE; STDMETHOD(Commit)(THIS_) PURE; STDMETHOD(Save)(THIS_ IShellItem *psiFolderToSaveIn, LPCWSTR pszLibraryName, LIBRARYSAVEFLAGS lsf, IShellItem **ppsiSavedTo) PURE; STDMETHOD(SaveInKnownFolder)(THIS_ const GUID &kfidToSaveIn, LPCWSTR pszLibraryName, LIBRARYSAVEFLAGS lsf,IShellItem **ppsiSavedTo) PURE; }; #endif #ifndef __IModalWindow_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IModalWindow, IUnknown) { STDMETHOD(Show)(THIS_ HWND hwndParent) PURE; }; #endif #ifndef __IFileDialog_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IFileDialog, IModalWindow) { STDMETHOD(SetFileTypes)(THIS_ UINT cFileTypes, const COMDLG_FILTERSPEC *rgFilterSpec) PURE; STDMETHOD(SetFileTypeIndex)(THIS_ UINT iFileType) PURE; STDMETHOD(GetFileTypeIndex)(THIS_ UINT *piFileType) PURE; STDMETHOD(Advise)(THIS_ IFileDialogEvents *pfde, DWORD *pdwCookie) PURE; STDMETHOD(Unadvise)(THIS_ DWORD dwCookie) PURE; STDMETHOD(SetOptions)(THIS_ DWORD fos) PURE; STDMETHOD(GetOptions)(THIS_ DWORD *pfos) PURE; STDMETHOD(SetDefaultFolder)(THIS_ IShellItem *psi) PURE; STDMETHOD(SetFolder)(THIS_ IShellItem *psi) PURE; STDMETHOD(GetFolder)(THIS_ IShellItem **ppsi) PURE; STDMETHOD(GetCurrentSelection)(THIS_ IShellItem **ppsi) PURE; STDMETHOD(SetFileName)(THIS_ LPCWSTR pszName) PURE; STDMETHOD(GetFileName)(THIS_ LPWSTR *pszName) PURE; STDMETHOD(SetTitle)(THIS_ LPCWSTR pszTitle) PURE; STDMETHOD(SetOkButtonLabel)(THIS_ LPCWSTR pszText) PURE; STDMETHOD(SetFileNameLabel)(THIS_ LPCWSTR pszLabel) PURE; STDMETHOD(GetResult)(THIS_ IShellItem **ppsi) PURE; STDMETHOD(AddPlace)(THIS_ IShellItem *psi, FDAP fdap) PURE; STDMETHOD(SetDefaultExtension)(THIS_ LPCWSTR pszDefaultExtension) PURE; STDMETHOD(Close)(THIS_ HRESULT hr) PURE; STDMETHOD(SetClientGuid)(THIS_ REFGUID guid) PURE; STDMETHOD(ClearClientData)(THIS_) PURE; STDMETHOD(SetFilter)(THIS_ IShellItemFilter *pFilter) PURE; }; #endif #ifndef __IFileDialogEvents_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IFileDialogEvents, IUnknown) { STDMETHOD(OnFileOk)(THIS_ IFileDialog *pfd) PURE; STDMETHOD(OnFolderChanging)(THIS_ IFileDialog *pfd, IShellItem *psiFolder) PURE; STDMETHOD(OnFolderChange)(THIS_ IFileDialog *pfd) PURE; STDMETHOD(OnSelectionChange)(THIS_ IFileDialog *pfd) PURE; STDMETHOD(OnShareViolation)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_SHAREVIOLATION_RESPONSE *pResponse) PURE; STDMETHOD(OnTypeChange)(THIS_ IFileDialog *pfd) PURE; STDMETHOD(OnOverwrite)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_OVERWRITE_RESPONSE *pResponse) PURE; }; #endif #ifndef __IFileOpenDialog_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IFileOpenDialog, IFileDialog) { STDMETHOD(GetResults)(THIS_ IShellItemArray **ppenum) PURE; STDMETHOD(GetSelectedItems)(THIS_ IShellItemArray **ppsai) PURE; }; #endif #ifndef __IPropertyStore_FWD_DEFINED__ typedef IUnknown IPropertyStore; #endif #ifndef __IFileOperationProgressSink_FWD_DEFINED__ typedef IUnknown IFileOperationProgressSink; #endif #ifndef __IFileSaveDialog_INTERFACE_DEFINED__ DECLARE_INTERFACE_(IFileSaveDialog, IFileDialog) { public: STDMETHOD(SetSaveAsItem)(THIS_ IShellItem *psi) PURE; STDMETHOD(SetProperties)(THIS_ IPropertyStore *pStore) PURE; STDMETHOD(SetCollectedProperties)(THIS_ IPropertyStore *pStore) PURE; STDMETHOD(GetProperties)(THIS_ IPropertyStore **ppStore) PURE; STDMETHOD(ApplyProperties)(THIS_ IShellItem *psi, IPropertyStore *pStore, HWND hwnd, IFileOperationProgressSink *pSink) PURE; }; #endif #endif // Q_CC_MINGW QT_BEGIN_NAMESPACE /* Output UID (IID, CLSID) as C++ constants. * The constants are contained in the Windows SDK libs, but not for MinGW. */ static inline QString guidToString(const GUID &g) { QString rc; QTextStream str(&rc); str.setIntegerBase(16); str.setNumberFlags(str.numberFlags() | QTextStream::ShowBase); str << '{' << g.Data1 << ", " << g.Data2 << ", " << g.Data3; str.setFieldWidth(2); str.setFieldAlignment(QTextStream::AlignRight); str.setPadChar(QLatin1Char('0')); str << ",{" << g.Data4[0] << ", " << g.Data4[1] << ", " << g.Data4[2] << ", " << g.Data4[3] << ", " << g.Data4[4] << ", " << g.Data4[5] << ", " << g.Data4[6] << ", " << g.Data4[7] << "}};"; return rc; } inline QDebug operator<<(QDebug d, const GUID &g) { d.nospace() << guidToString(g); return d; } // Return an allocated wchar_t array from a QString, reserve more memory if desired. static wchar_t *qStringToWCharArray(const QString &s, size_t reserveSize = 0) { const size_t stringSize = s.size(); wchar_t *result = new wchar_t[qMax(stringSize + 1, reserveSize)]; s.toWCharArray(result); result[stringSize] = 0; return result; } namespace QWindowsDialogs { /*! \fn eatMouseMove() After closing a windows dialog with a double click (i.e. open a file) the message queue still contains a dubious WM_MOUSEMOVE message where the left button is reported to be down (wParam != 0). remove all those messages (usually 1) and post the last one with a reset button state. \ingroup qt-lighthouse-win */ void eatMouseMove() { MSG msg = {0, 0, 0, 0, 0, {0, 0} }; while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE)) ; if (msg.message == WM_MOUSEMOVE) PostMessage(msg.hwnd, msg.message, 0, msg.lParam); qCDebug(lcQpaDialogs) << __FUNCTION__ << "triggered=" << (msg.message == WM_MOUSEMOVE); } } // namespace QWindowsDialogs /*! \class QWindowsNativeDialogBase \brief Base class for Windows native dialogs. Base classes for native dialogs (using the CLSID-based dialog interfaces "IFileDialog", etc. available from Windows Vista on) that mimick the behaviour of their QDialog counterparts as close as possible. Instances of derived classes are controlled by QWindowsDialogHelperBase-derived classes. A major difference is that there is only an exec(), which is a modal, blocking call; there is no non-blocking show(). There 2 types of native dialogs: \list \li Dialogs provided by the Comdlg32 library (ChooseColor, ChooseFont). They only provide a modal, blocking function call (with idle processing). \li File dialogs are classes derived from IFileDialog. They inherit IModalWindow and their exec() method (calling IModalWindow::Show()) is similarly blocking, but methods like close() can be called on them from event handlers. \endlist \sa QWindowsDialogHelperBase \internal \ingroup qt-lighthouse-win */ class QWindowsNativeDialogBase : public QObject { Q_OBJECT public: virtual void setWindowTitle(const QString &title) = 0; bool executed() const { return m_executed; } void exec(HWND owner = 0) { doExec(owner); m_executed = true; } signals: void accepted(); void rejected(); public slots: virtual void close() = 0; protected: QWindowsNativeDialogBase() : m_executed(false) {} private: virtual void doExec(HWND owner = 0) = 0; bool m_executed; }; /*! \class QWindowsDialogHelperBase \brief Helper for native Windows dialogs. Provides basic functionality and introduces new virtuals. The native dialog is created in setVisible_sys() since then modality and the state of DontUseNativeDialog is known. Modal dialogs are then run by exec(). Non-modal dialogs are shown using a separate thread started in show() should they support it. \sa QWindowsDialogThread, QWindowsNativeDialogBase \internal \ingroup qt-lighthouse-win */ template <class BaseClass> QWindowsDialogHelperBase<BaseClass>::QWindowsDialogHelperBase() : m_nativeDialog(0), m_ownerWindow(0), m_timerId(0), m_thread(0) { } template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::cleanupThread() { if (m_thread) { // Thread may be running if the dialog failed to close. if (m_thread->isRunning()) m_thread->wait(500); if (m_thread->isRunning()) { m_thread->terminate(); m_thread->wait(300); if (m_thread->isRunning()) qCCritical(lcQpaDialogs) <<__FUNCTION__ << "Failed to terminate thread."; else qCWarning(lcQpaDialogs) << __FUNCTION__ << "Thread terminated."; } delete m_thread; m_thread = 0; } } template <class BaseClass> QWindowsNativeDialogBase *QWindowsDialogHelperBase<BaseClass>::nativeDialog() const { if (m_nativeDialog.isNull()) { qWarning("%s invoked with no native dialog present.", __FUNCTION__); return 0; } return m_nativeDialog.data(); } template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::timerEvent(QTimerEvent *) { startDialogThread(); } template <class BaseClass> QWindowsNativeDialogBase *QWindowsDialogHelperBase<BaseClass>::ensureNativeDialog() { // Create dialog and apply common settings. Check "executed" flag as well // since for example IFileDialog::Show() works only once. if (m_nativeDialog.isNull() || m_nativeDialog->executed()) m_nativeDialog = QWindowsNativeDialogBasePtr(createNativeDialog()); return m_nativeDialog.data(); } /*! \class QWindowsDialogThread \brief Run a non-modal native dialog in a separate thread. \sa QWindowsDialogHelperBase \internal \ingroup qt-lighthouse-win */ class QWindowsDialogThread : public QThread { public: typedef QSharedPointer<QWindowsNativeDialogBase> QWindowsNativeDialogBasePtr; explicit QWindowsDialogThread(const QWindowsNativeDialogBasePtr &d, HWND owner) : m_dialog(d), m_owner(owner) {} void run(); private: const QWindowsNativeDialogBasePtr m_dialog; const HWND m_owner; }; void QWindowsDialogThread::run() { qCDebug(lcQpaDialogs) << '>' << __FUNCTION__; m_dialog->exec(m_owner); qCDebug(lcQpaDialogs) << '<' << __FUNCTION__; } template <class BaseClass> bool QWindowsDialogHelperBase<BaseClass>::show(Qt::WindowFlags, Qt::WindowModality windowModality, QWindow *parent) { const bool modal = (windowModality != Qt::NonModal); if (!parent) parent = QGuiApplication::focusWindow(); // Need a parent window, else the application loses activation when closed. if (parent) { m_ownerWindow = QWindowsWindow::handleOf(parent); } else { m_ownerWindow = 0; } qCDebug(lcQpaDialogs) << __FUNCTION__ << "modal=" << modal << " modal supported? " << supportsNonModalDialog(parent) << "native=" << m_nativeDialog.data() << "owner" << m_ownerWindow; if (!modal && !supportsNonModalDialog(parent)) return false; // Was it changed in-between? if (!ensureNativeDialog()) return false; // Start a background thread to show the dialog. For modal dialogs, // a subsequent call to exec() may follow. So, start an idle timer // which will start the dialog thread. If exec() is then called, the // timer is stopped and dialog->exec() is called directly. cleanupThread(); if (modal) { m_timerId = this->startTimer(0); } else { startDialogThread(); } return true; } template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::startDialogThread() { Q_ASSERT(!m_nativeDialog.isNull()); Q_ASSERT(!m_thread); m_thread = new QWindowsDialogThread(m_nativeDialog, m_ownerWindow); m_thread->start(); stopTimer(); } template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::stopTimer() { if (m_timerId) { this->killTimer(m_timerId); m_timerId = 0; } } #ifndef Q_OS_WINCE // Find a file dialog window created by IFileDialog by process id, window // title and class, which starts with a hash '#'. struct FindDialogContext { explicit FindDialogContext(const QString &titleIn) : title(qStringToWCharArray(titleIn)), processId(GetCurrentProcessId()), hwnd(0) {} const QScopedArrayPointer<wchar_t> title; const DWORD processId; HWND hwnd; // contains the HWND of the window found. }; static BOOL QT_WIN_CALLBACK findDialogEnumWindowsProc(HWND hwnd, LPARAM lParam) { FindDialogContext *context = reinterpret_cast<FindDialogContext *>(lParam); DWORD winPid = 0; GetWindowThreadProcessId(hwnd, &winPid); if (winPid != context->processId) return TRUE; wchar_t buf[256]; if (!RealGetWindowClass(hwnd, buf, sizeof(buf)/sizeof(wchar_t)) || buf[0] != L'#') return TRUE; if (!GetWindowTextW(hwnd, buf, sizeof(buf)/sizeof(wchar_t)) || wcscmp(buf, context->title.data())) return TRUE; context->hwnd = hwnd; return FALSE; } static inline HWND findDialogWindow(const QString &title) { FindDialogContext context(title); EnumWindows(findDialogEnumWindowsProc, reinterpret_cast<LPARAM>(&context)); return context.hwnd; } #endif // !Q_OS_WINCE template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::hide() { if (m_nativeDialog) m_nativeDialog->close(); m_ownerWindow = 0; } template <class BaseClass> void QWindowsDialogHelperBase<BaseClass>::exec() { qCDebug(lcQpaDialogs) << __FUNCTION__; stopTimer(); if (QWindowsNativeDialogBase *nd = nativeDialog()) { nd->exec(m_ownerWindow); m_nativeDialog.clear(); } } /*! \class QWindowsFileDialogSharedData \brief Explicitly shared file dialog parameters that are not in QFileDialogOptions. Contain Parameters that need to be cached while the native dialog does not exist yet. In addition, the data are updated by the change notifications of the IFileDialogEvent, as querying them after the dialog has closed does not reliably work. Provides thread-safe setters (for the non-modal case). \internal \ingroup qt-lighthouse-win \sa QFileDialogOptions */ class QWindowsFileDialogSharedData { public: QWindowsFileDialogSharedData() : m_data(new Data) {} void fromOptions(const QSharedPointer<QFileDialogOptions> &o); QUrl directory() const; void setDirectory(const QUrl &); QString selectedNameFilter() const; void setSelectedNameFilter(const QString &); QList<QUrl> selectedFiles() const; void setSelectedFiles(const QList<QUrl> &); QString selectedFile() const; private: class Data : public QSharedData { public: QUrl directory; QString selectedNameFilter; QList<QUrl> selectedFiles; QMutex mutex; }; QExplicitlySharedDataPointer<Data> m_data; }; inline QUrl QWindowsFileDialogSharedData::directory() const { m_data->mutex.lock(); const QUrl result = m_data->directory; m_data->mutex.unlock(); return result; } inline void QWindowsFileDialogSharedData::setDirectory(const QUrl &d) { QMutexLocker (&m_data->mutex); m_data->directory = d; } inline QString QWindowsFileDialogSharedData::selectedNameFilter() const { m_data->mutex.lock(); const QString result = m_data->selectedNameFilter; m_data->mutex.unlock(); return result; } inline void QWindowsFileDialogSharedData::setSelectedNameFilter(const QString &f) { QMutexLocker (&m_data->mutex); m_data->selectedNameFilter = f; } inline QList<QUrl> QWindowsFileDialogSharedData::selectedFiles() const { m_data->mutex.lock(); const QList<QUrl> result = m_data->selectedFiles; m_data->mutex.unlock(); return result; } inline QString QWindowsFileDialogSharedData::selectedFile() const { const QList<QUrl> files = selectedFiles(); return files.isEmpty() ? QString() : files.front().toLocalFile(); } inline void QWindowsFileDialogSharedData::setSelectedFiles(const QList<QUrl> &urls) { QMutexLocker (&m_data->mutex); m_data->selectedFiles = urls; } inline void QWindowsFileDialogSharedData::fromOptions(const QSharedPointer<QFileDialogOptions> &o) { QMutexLocker (&m_data->mutex); m_data->directory = o->initialDirectory(); m_data->selectedFiles = o->initiallySelectedFiles(); m_data->selectedNameFilter = o->initiallySelectedNameFilter(); } /*! \class QWindowsNativeFileDialogEventHandler \brief Listens to IFileDialog events and forwards them to QWindowsNativeFileDialogBase Events like 'folder change' that have an equivalent signal in QFileDialog are forwarded. \sa QWindowsNativeFileDialogBase, QWindowsFileDialogHelper \internal \ingroup qt-lighthouse-win */ class QWindowsNativeFileDialogBase; class QWindowsNativeFileDialogEventHandler : public IFileDialogEvents { public: static IFileDialogEvents *create(QWindowsNativeFileDialogBase *nativeFileDialog); // IUnknown methods IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv) { if (riid != IID_IUnknown && riid != IID_IFileDialogEvents) { *ppv = NULL; return ResultFromScode(E_NOINTERFACE); } *ppv = this; AddRef(); return NOERROR; } IFACEMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_ref); } IFACEMETHODIMP_(ULONG) Release() { const long ref = InterlockedDecrement(&m_ref); if (!ref) delete this; return ref; } // IFileDialogEvents methods IFACEMETHODIMP OnFileOk(IFileDialog *); IFACEMETHODIMP OnFolderChange(IFileDialog *) { return S_OK; } IFACEMETHODIMP OnFolderChanging(IFileDialog *, IShellItem *); IFACEMETHODIMP OnHelp(IFileDialog *) { return S_OK; } IFACEMETHODIMP OnSelectionChange(IFileDialog *); IFACEMETHODIMP OnShareViolation(IFileDialog *, IShellItem *, FDE_SHAREVIOLATION_RESPONSE *) { return S_OK; } IFACEMETHODIMP OnTypeChange(IFileDialog *); IFACEMETHODIMP OnOverwrite(IFileDialog *, IShellItem *, FDE_OVERWRITE_RESPONSE *) { return S_OK; } QWindowsNativeFileDialogEventHandler(QWindowsNativeFileDialogBase *nativeFileDialog) : m_ref(1), m_nativeFileDialog(nativeFileDialog) {} virtual ~QWindowsNativeFileDialogEventHandler() {} private: long m_ref; QWindowsNativeFileDialogBase *m_nativeFileDialog; }; IFileDialogEvents *QWindowsNativeFileDialogEventHandler::create(QWindowsNativeFileDialogBase *nativeFileDialog) { IFileDialogEvents *result; QWindowsNativeFileDialogEventHandler *eventHandler = new QWindowsNativeFileDialogEventHandler(nativeFileDialog); if (FAILED(eventHandler->QueryInterface(IID_IFileDialogEvents, reinterpret_cast<void **>(&result)))) { qErrnoWarning("Unable to obtain IFileDialogEvents"); return 0; } eventHandler->Release(); return result; } /*! \class QWindowsNativeFileDialogBase \brief Windows native file dialog wrapper around IFileOpenDialog, IFileSaveDialog. Provides convenience methods. Note that only IFileOpenDialog has multi-file functionality. \sa QWindowsNativeFileDialogEventHandler, QWindowsFileDialogHelper \internal \ingroup qt-lighthouse-win */ class QWindowsNativeFileDialogBase : public QWindowsNativeDialogBase { Q_OBJECT Q_PROPERTY(bool hideFiltersDetails READ hideFiltersDetails WRITE setHideFiltersDetails) public: ~QWindowsNativeFileDialogBase(); inline static QWindowsNativeFileDialogBase *create(QFileDialogOptions::AcceptMode am, const QWindowsFileDialogSharedData &data); virtual void setWindowTitle(const QString &title); inline void setMode(QFileDialogOptions::FileMode mode, QFileDialogOptions::AcceptMode acceptMode, QFileDialogOptions::FileDialogOptions options); inline void setDirectory(const QString &directory); inline void updateDirectory() { setDirectory(m_data.directory().toLocalFile()); } inline QString directory() const; virtual void doExec(HWND owner = 0); virtual void setNameFilters(const QStringList &f); inline void selectNameFilter(const QString &filter); inline void updateSelectedNameFilter() { selectNameFilter(m_data.selectedNameFilter()); } inline QString selectedNameFilter() const; void selectFile(const QString &fileName) const; bool hideFiltersDetails() const { return m_hideFiltersDetails; } void setHideFiltersDetails(bool h) { m_hideFiltersDetails = h; } void setDefaultSuffix(const QString &s); inline bool hasDefaultSuffix() const { return m_hasDefaultSuffix; } inline void setLabelText(QFileDialogOptions::DialogLabel l, const QString &text); // Return the selected files for tracking in OnSelectionChanged(). virtual QList<QUrl> selectedFiles() const = 0; // Return the result for tracking in OnFileOk(). Differs from selection for // example by appended default suffixes, etc. virtual QList<QUrl> dialogResult() const = 0; inline void onFolderChange(IShellItem *); inline void onSelectionChange(); inline void onTypeChange(); inline bool onFileOk(); signals: void directoryEntered(const QUrl &directory); void currentChanged(const QUrl &file); void filterSelected(const QString & filter); public slots: virtual void close(); protected: explicit QWindowsNativeFileDialogBase(const QWindowsFileDialogSharedData &data); bool init(const CLSID &clsId, const IID &iid); void setDefaultSuffixSys(const QString &s); inline IFileDialog * fileDialog() const { return m_fileDialog; } static QString itemPath(IShellItem *item); static QList<QUrl> libraryItemFolders(IShellItem *item); static QString libraryItemDefaultSaveFolder(IShellItem *item); static int itemPaths(IShellItemArray *items, QList<QUrl> *fileResult = 0); static IShellItem *shellItem(const QString &path); const QWindowsFileDialogSharedData &data() const { return m_data; } QWindowsFileDialogSharedData &data() { return m_data; } private: IFileDialog *m_fileDialog; IFileDialogEvents *m_dialogEvents; DWORD m_cookie; QStringList m_nameFilters; bool m_hideFiltersDetails; bool m_hasDefaultSuffix; QWindowsFileDialogSharedData m_data; QString m_title; }; QWindowsNativeFileDialogBase::QWindowsNativeFileDialogBase(const QWindowsFileDialogSharedData &data) : m_fileDialog(0), m_dialogEvents(0), m_cookie(0), m_hideFiltersDetails(false), m_hasDefaultSuffix(false), m_data(data) { } QWindowsNativeFileDialogBase::~QWindowsNativeFileDialogBase() { if (m_dialogEvents && m_fileDialog) m_fileDialog->Unadvise(m_cookie); if (m_dialogEvents) m_dialogEvents->Release(); if (m_fileDialog) m_fileDialog->Release(); } bool QWindowsNativeFileDialogBase::init(const CLSID &clsId, const IID &iid) { HRESULT hr = CoCreateInstance(clsId, NULL, CLSCTX_INPROC_SERVER, iid, reinterpret_cast<void **>(&m_fileDialog)); if (FAILED(hr)) { qErrnoWarning("CoCreateInstance failed"); return false; } m_dialogEvents = QWindowsNativeFileDialogEventHandler::create(this); if (!m_dialogEvents) return false; // Register event handler hr = m_fileDialog->Advise(m_dialogEvents, &m_cookie); if (FAILED(hr)) { qErrnoWarning("IFileDialog::Advise failed"); return false; } qCDebug(lcQpaDialogs) << __FUNCTION__ << m_fileDialog << m_dialogEvents << m_cookie; return true; } void QWindowsNativeFileDialogBase::setWindowTitle(const QString &title) { m_title = title; m_fileDialog->SetTitle(reinterpret_cast<const wchar_t *>(title.utf16())); } IShellItem *QWindowsNativeFileDialogBase::shellItem(const QString &path) { #ifndef Q_OS_WINCE if (QWindowsContext::shell32dll.sHCreateItemFromParsingName) { IShellItem *result = 0; const QString native = QDir::toNativeSeparators(path); const HRESULT hr = QWindowsContext::shell32dll.sHCreateItemFromParsingName(reinterpret_cast<const wchar_t *>(native.utf16()), NULL, IID_IShellItem, reinterpret_cast<void **>(&result)); if (SUCCEEDED(hr)) return result; } #endif qErrnoWarning("%s: SHCreateItemFromParsingName(%s)) failed", __FUNCTION__, qPrintable(path)); return 0; } void QWindowsNativeFileDialogBase::setDirectory(const QString &directory) { if (!directory.isEmpty()) { if (IShellItem *psi = QWindowsNativeFileDialogBase::shellItem(directory)) { m_fileDialog->SetFolder(psi); psi->Release(); } } } QString QWindowsNativeFileDialogBase::directory() const { #ifndef Q_OS_WINCE IShellItem *item = 0; if (m_fileDialog && SUCCEEDED(m_fileDialog->GetFolder(&item)) && item) return QWindowsNativeFileDialogBase::itemPath(item); #endif return QString(); } void QWindowsNativeFileDialogBase::doExec(HWND owner) { qCDebug(lcQpaDialogs) << '>' << __FUNCTION__; // Show() blocks until the user closes the dialog, the dialog window // gets a WM_CLOSE or the parent window is destroyed. const HRESULT hr = m_fileDialog->Show(owner); QWindowsDialogs::eatMouseMove(); qCDebug(lcQpaDialogs) << '<' << __FUNCTION__ << " returns " << hex << hr; if (hr == S_OK) { emit accepted(); } else { emit rejected(); } } void QWindowsNativeFileDialogBase::setMode(QFileDialogOptions::FileMode mode, QFileDialogOptions::AcceptMode acceptMode, QFileDialogOptions::FileDialogOptions options) { DWORD flags = FOS_PATHMUSTEXIST | FOS_FORCESHOWHIDDEN; if (options & QFileDialogOptions::DontResolveSymlinks) flags |= FOS_NODEREFERENCELINKS; switch (mode) { case QFileDialogOptions::AnyFile: if (acceptMode == QFileDialogOptions::AcceptSave) flags |= FOS_NOREADONLYRETURN; if (!(options & QFileDialogOptions::DontConfirmOverwrite)) flags |= FOS_OVERWRITEPROMPT; break; case QFileDialogOptions::ExistingFile: flags |= FOS_FILEMUSTEXIST; break; case QFileDialogOptions::Directory: case QFileDialogOptions::DirectoryOnly: flags |= FOS_PICKFOLDERS | FOS_FILEMUSTEXIST; break; case QFileDialogOptions::ExistingFiles: flags |= FOS_FILEMUSTEXIST | FOS_ALLOWMULTISELECT; break; } qCDebug(lcQpaDialogs) << __FUNCTION__ << "mode=" << mode << "acceptMode=" << acceptMode << "options=" << options << "results in" << showbase << hex << flags; if (FAILED(m_fileDialog->SetOptions(flags))) qErrnoWarning("%s: SetOptions() failed", __FUNCTION__); } #if !defined(Q_OS_WINCE) && defined(__IShellLibrary_INTERFACE_DEFINED__) // Windows SDK 7 // Helper for "Libraries": collections of folders appearing from Windows 7 // on, visible in the file dialogs. // Load a library from a IShellItem (sanitized copy of the inline function // SHLoadLibraryFromItem from ShObjIdl.h, which does not exist for MinGW). static IShellLibrary *sHLoadLibraryFromItem(IShellItem *libraryItem, DWORD mode) { // ID symbols present from Windows 7 on: static const CLSID classId_ShellLibrary = {0xd9b3211d, 0xe57f, 0x4426, {0xaa, 0xef, 0x30, 0xa8, 0x6, 0xad, 0xd3, 0x97}}; static const IID iId_IShellLibrary = {0x11a66efa, 0x382e, 0x451a, {0x92, 0x34, 0x1e, 0xe, 0x12, 0xef, 0x30, 0x85}}; IShellLibrary *helper = 0; IShellLibrary *result = 0; if (SUCCEEDED(CoCreateInstance(classId_ShellLibrary, NULL, CLSCTX_INPROC_SERVER, iId_IShellLibrary, reinterpret_cast<void **>(&helper)))) if (SUCCEEDED(helper->LoadLibraryFromItem(libraryItem, mode))) helper->QueryInterface(iId_IShellLibrary, reinterpret_cast<void **>(&result)); if (helper) helper->Release(); return result; } // Return all folders of a library-type item. QList<QUrl> QWindowsNativeFileDialogBase::libraryItemFolders(IShellItem *item) { QList<QUrl> result; if (IShellLibrary *library = sHLoadLibraryFromItem(item, STGM_READ | STGM_SHARE_DENY_WRITE)) { IShellItemArray *itemArray = 0; if (SUCCEEDED(library->GetFolders(LFF_FORCEFILESYSTEM, IID_IShellItemArray, reinterpret_cast<void **>(&itemArray)))) { QWindowsNativeFileDialogBase::itemPaths(itemArray, &result); itemArray->Release(); } library->Release(); } return result; } // Return default save folders of a library-type item. QString QWindowsNativeFileDialogBase::libraryItemDefaultSaveFolder(IShellItem *item) { QString result; if (IShellLibrary *library = sHLoadLibraryFromItem(item, STGM_READ | STGM_SHARE_DENY_WRITE)) { IShellItem *item = 0; if (SUCCEEDED(library->GetDefaultSaveFolder(DSFT_DETECT, IID_IShellItem, reinterpret_cast<void **>(&item)))) { result = QWindowsNativeFileDialogBase::itemPath(item); item->Release(); } library->Release(); } return result; } #else // !Q_OS_WINCE && __IShellLibrary_INTERFACE_DEFINED__ QList<QUrl> QWindowsNativeFileDialogBase::libraryItemFolders(IShellItem *) { return QList<QUrl>(); } QString QWindowsNativeFileDialogBase::libraryItemDefaultSaveFolder(IShellItem *) { return QString(); } #endif // Q_OS_WINCE || !__IShellLibrary_INTERFACE_DEFINED__ QString QWindowsNativeFileDialogBase::itemPath(IShellItem *item) { SFGAOF attributes = 0; // Check whether it has a file system representation? if (FAILED(item->GetAttributes(SFGAO_FILESYSTEM, &attributes))) return QString(); if (attributes & SFGAO_FILESYSTEM) { LPWSTR name = 0; QString result; if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &name))) { result = QDir::cleanPath(QString::fromWCharArray(name)); CoTaskMemFree(name); } return result; } // Check for a "Library" item if ((QSysInfo::windowsVersion() & QSysInfo::WV_NT_based) && QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) return QWindowsNativeFileDialogBase::libraryItemDefaultSaveFolder(item); return QString(); } int QWindowsNativeFileDialogBase::itemPaths(IShellItemArray *items, QList<QUrl> *result /* = 0 */) { DWORD itemCount = 0; if (result) result->clear(); if (FAILED(items->GetCount(&itemCount))) return 0; if (result && itemCount) { result->reserve(itemCount); for (DWORD i = 0; i < itemCount; ++i) { IShellItem *item = 0; if (SUCCEEDED(items->GetItemAt(i, &item))) result->push_back(QUrl::fromLocalFile(QWindowsNativeFileDialogBase::itemPath(item))); } } return itemCount; } // Split a list of name filters into description and actual filters struct FilterSpec { QString description; QString filter; }; static QList<FilterSpec> filterSpecs(const QStringList &filters, bool hideFilterDetails, int *totalStringLength) { QList<FilterSpec> result; result.reserve(filters.size()); *totalStringLength = 0; const QRegExp filterSeparatorRE(QStringLiteral("[;\\s]+")); const QString separator = QStringLiteral(";"); Q_ASSERT(filterSeparatorRE.isValid()); // Split filter specification as 'Texts (*.txt[;] *.doc)', '*.txt[;] *.doc' // into description and filters specification as '*.txt;*.doc' foreach (const QString &filterString, filters) { const int openingParenPos = filterString.lastIndexOf(QLatin1Char('(')); const int closingParenPos = openingParenPos != -1 ? filterString.indexOf(QLatin1Char(')'), openingParenPos + 1) : -1; FilterSpec filterSpec; filterSpec.filter = closingParenPos == -1 ? filterString : filterString.mid(openingParenPos + 1, closingParenPos - openingParenPos - 1).trimmed(); if (filterSpec.filter.isEmpty()) filterSpec.filter += QLatin1Char('*'); filterSpec.filter.replace(filterSeparatorRE, separator); filterSpec.description = filterString; if (hideFilterDetails && openingParenPos != -1) { // Do not show pattern in description filterSpec.description.truncate(openingParenPos); while (filterSpec.description.endsWith(QLatin1Char(' '))) filterSpec.description.truncate(filterSpec.description.size() - 1); } *totalStringLength += filterSpec.filter.size() + filterSpec.description.size(); result.push_back(filterSpec); } return result; } void QWindowsNativeFileDialogBase::setNameFilters(const QStringList &filters) { /* Populates an array of COMDLG_FILTERSPEC from list of filters, * store the strings in a flat, contiguous buffer. */ m_nameFilters = filters; int totalStringLength = 0; const QList<FilterSpec> specs = filterSpecs(filters, m_hideFiltersDetails, &totalStringLength); const int size = specs.size(); QScopedArrayPointer<WCHAR> buffer(new WCHAR[totalStringLength + 2 * size]); QScopedArrayPointer<COMDLG_FILTERSPEC> comFilterSpec(new COMDLG_FILTERSPEC[size]); const QString matchesAll = QStringLiteral(" (*)"); WCHAR *ptr = buffer.data(); // Split filter specification as 'Texts (*.txt[;] *.doc)' // into description and filters specification as '*.txt;*.doc' for (int i = 0; i < size; ++i) { // Display glitch (CLSID only): 'All files (*)' shows up as 'All files (*) (*)' QString description = specs[i].description; if (!m_hideFiltersDetails && description.endsWith(matchesAll)) description.truncate(description.size() - matchesAll.size()); // Add to buffer. comFilterSpec[i].pszName = ptr; ptr += description.toWCharArray(ptr); *ptr++ = 0; comFilterSpec[i].pszSpec = ptr; ptr += specs[i].filter.toWCharArray(ptr); *ptr++ = 0; } m_fileDialog->SetFileTypes(size, comFilterSpec.data()); } void QWindowsNativeFileDialogBase::setDefaultSuffix(const QString &s) { setDefaultSuffixSys(s); m_hasDefaultSuffix = !s.isEmpty(); } void QWindowsNativeFileDialogBase::setDefaultSuffixSys(const QString &s) { // If this parameter is non-empty, it will be appended by the dialog for the 'Any files' // filter ('*'). If this parameter is non-empty and the current filter has a suffix, // the dialog will append the filter's suffix. wchar_t *wSuffix = const_cast<wchar_t *>(reinterpret_cast<const wchar_t *>(s.utf16())); m_fileDialog->SetDefaultExtension(wSuffix); } void QWindowsNativeFileDialogBase::setLabelText(QFileDialogOptions::DialogLabel l, const QString &text) { wchar_t *wText = const_cast<wchar_t *>(reinterpret_cast<const wchar_t *>(text.utf16())); switch (l) { break; case QFileDialogOptions::FileName: m_fileDialog->SetFileNameLabel(wText); break; case QFileDialogOptions::Accept: m_fileDialog->SetOkButtonLabel(wText); break; case QFileDialogOptions::LookIn: case QFileDialogOptions::Reject: case QFileDialogOptions::FileType: case QFileDialogOptions::DialogLabelCount: break; } } void QWindowsNativeFileDialogBase::selectFile(const QString &fileName) const { m_fileDialog->SetFileName((wchar_t*)fileName.utf16()); } // Return the index of the selected filter, accounting for QFileDialog // sometimes stripping the filter specification depending on the // hideFilterDetails setting. static int indexOfNameFilter(const QStringList &filters, const QString &needle) { const int index = filters.indexOf(needle); if (index >= 0) return index; for (int i = 0; i < filters.size(); ++i) if (filters.at(i).startsWith(needle)) return i; return -1; } void QWindowsNativeFileDialogBase::selectNameFilter(const QString &filter) { if (filter.isEmpty()) return; const int index = indexOfNameFilter(m_nameFilters, filter); if (index < 0) { qWarning("%s: Invalid parameter '%s' not found in '%s'.", __FUNCTION__, qPrintable(filter), qPrintable(m_nameFilters.join(QStringLiteral(", ")))); return; } m_fileDialog->SetFileTypeIndex(index + 1); // one-based. } QString QWindowsNativeFileDialogBase::selectedNameFilter() const { UINT uIndex = 0; if (SUCCEEDED(m_fileDialog->GetFileTypeIndex(&uIndex))) { const int index = uIndex - 1; // one-based if (index < m_nameFilters.size()) return m_nameFilters.at(index); } return QString(); } void QWindowsNativeFileDialogBase::onFolderChange(IShellItem *item) { if (item) { const QUrl directory = QUrl::fromLocalFile(QWindowsNativeFileDialogBase::itemPath(item)); m_data.setDirectory(directory); emit directoryEntered(directory); } } void QWindowsNativeFileDialogBase::onSelectionChange() { const QList<QUrl> current = selectedFiles(); m_data.setSelectedFiles(current); if (current.size() == 1) emit currentChanged(current.front()); } void QWindowsNativeFileDialogBase::onTypeChange() { const QString filter = selectedNameFilter(); m_data.setSelectedNameFilter(filter); emit filterSelected(filter); } bool QWindowsNativeFileDialogBase::onFileOk() { // Store selected files as GetResults() returns invalid data after the dialog closes. m_data.setSelectedFiles(dialogResult()); return true; } void QWindowsNativeFileDialogBase::close() { m_fileDialog->Close(S_OK); #ifndef Q_OS_WINCE // IFileDialog::Close() does not work unless invoked from a callback. // Try to find the window and send it a WM_CLOSE in addition. const HWND hwnd = findDialogWindow(m_title); qCDebug(lcQpaDialogs) << __FUNCTION__ << "closing" << hwnd; if (hwnd && IsWindowVisible(hwnd)) PostMessageW(hwnd, WM_CLOSE, 0, 0); #endif // !Q_OS_WINCE } HRESULT QWindowsNativeFileDialogEventHandler::OnFolderChanging(IFileDialog *, IShellItem *item) { m_nativeFileDialog->onFolderChange(item); return S_OK; } HRESULT QWindowsNativeFileDialogEventHandler::OnSelectionChange(IFileDialog *) { m_nativeFileDialog->onSelectionChange(); return S_OK; } HRESULT QWindowsNativeFileDialogEventHandler::OnTypeChange(IFileDialog *) { m_nativeFileDialog->onTypeChange(); return S_OK; } HRESULT QWindowsNativeFileDialogEventHandler::OnFileOk(IFileDialog *) { return m_nativeFileDialog->onFileOk() ? S_OK : S_FALSE; } /*! \class QWindowsNativeSaveFileDialog \brief Windows native file save dialog wrapper around IFileSaveDialog. Implements single-selection methods. \internal \ingroup qt-lighthouse-win */ class QWindowsNativeSaveFileDialog : public QWindowsNativeFileDialogBase { Q_OBJECT public: explicit QWindowsNativeSaveFileDialog(const QWindowsFileDialogSharedData &data) : QWindowsNativeFileDialogBase(data) {} virtual void setNameFilters(const QStringList &f); virtual QList<QUrl> selectedFiles() const; virtual QList<QUrl> dialogResult() const; }; // Return the first suffix from the name filter "Foo files (*.foo;*.bar)" -> "foo". static inline QString suffixFromFilter(const QString &filter) { int suffixPos = filter.indexOf(QLatin1String("(*.")); if (suffixPos < 0) return QString(); suffixPos += 3; int endPos = filter.indexOf(QLatin1Char(' '), suffixPos + 1); if (endPos < 0) endPos = filter.indexOf(QLatin1Char(';'), suffixPos + 1); if (endPos < 0) endPos = filter.indexOf(QLatin1Char(')'), suffixPos + 1); return endPos >= 0 ? filter.mid(suffixPos, endPos - suffixPos) : QString(); } void QWindowsNativeSaveFileDialog::setNameFilters(const QStringList &f) { QWindowsNativeFileDialogBase::setNameFilters(f); // QTBUG-31381, QTBUG-30748: IFileDialog will update the suffix of the selected name // filter only if a default suffix is set (see docs). Set the first available // suffix unless we have a defaultSuffix. if (!hasDefaultSuffix()) { foreach (const QString &filter, f) { const QString suffix = suffixFromFilter(filter); if (!suffix.isEmpty()) { setDefaultSuffixSys(suffix); break; } } } // m_hasDefaultSuffix } QList<QUrl> QWindowsNativeSaveFileDialog::dialogResult() const { QList<QUrl> result; IShellItem *item = 0; if (SUCCEEDED(fileDialog()->GetResult(&item)) && item) result.push_back(QUrl::fromLocalFile(QWindowsNativeFileDialogBase::itemPath(item))); return result; } QList<QUrl> QWindowsNativeSaveFileDialog::selectedFiles() const { QList<QUrl> result; IShellItem *item = 0; const HRESULT hr = fileDialog()->GetCurrentSelection(&item); if (SUCCEEDED(hr) && item) result.push_back(QUrl::fromLocalFile(QWindowsNativeSaveFileDialog::itemPath(item))); return result; } /*! \class QWindowsNativeOpenFileDialog \brief Windows native file save dialog wrapper around IFileOpenDialog. Implements multi-selection methods. \internal \ingroup qt-lighthouse-win */ class QWindowsNativeOpenFileDialog : public QWindowsNativeFileDialogBase { public: explicit QWindowsNativeOpenFileDialog(const QWindowsFileDialogSharedData &data) : QWindowsNativeFileDialogBase(data) {} virtual QList<QUrl> selectedFiles() const; virtual QList<QUrl> dialogResult() const; private: inline IFileOpenDialog *openFileDialog() const { return static_cast<IFileOpenDialog *>(fileDialog()); } }; QList<QUrl> QWindowsNativeOpenFileDialog::dialogResult() const { QList<QUrl> result; IShellItemArray *items = 0; if (SUCCEEDED(openFileDialog()->GetResults(&items)) && items) QWindowsNativeFileDialogBase::itemPaths(items, &result); return result; } QList<QUrl> QWindowsNativeOpenFileDialog::selectedFiles() const { QList<QUrl> result; IShellItemArray *items = 0; const HRESULT hr = openFileDialog()->GetSelectedItems(&items); if (SUCCEEDED(hr) && items) QWindowsNativeFileDialogBase::itemPaths(items, &result); return result; } /*! \brief Factory method for QWindowsNativeFileDialogBase returning QWindowsNativeOpenFileDialog or QWindowsNativeSaveFileDialog depending on QFileDialog::AcceptMode. */ QWindowsNativeFileDialogBase *QWindowsNativeFileDialogBase::create(QFileDialogOptions::AcceptMode am, const QWindowsFileDialogSharedData &data) { QWindowsNativeFileDialogBase *result = 0; if (am == QFileDialogOptions::AcceptOpen) { result = new QWindowsNativeOpenFileDialog(data); if (!result->init(CLSID_FileOpenDialog, IID_IFileOpenDialog)) { delete result; return 0; } } else { result = new QWindowsNativeSaveFileDialog(data); if (!result->init(CLSID_FileSaveDialog, IID_IFileSaveDialog)) { delete result; return 0; } } return result; } static inline bool isQQuickWindow(const QWindow *w = 0) { return w && w->inherits("QQuickWindow"); } /*! \class QWindowsFileDialogHelper \brief Helper for native Windows file dialogs For Qt 4 compatibility, do not create native non-modal dialogs on widgets, but only on QQuickWindows, which do not have a fallback. \internal \ingroup qt-lighthouse-win */ class QWindowsFileDialogHelper : public QWindowsDialogHelperBase<QPlatformFileDialogHelper> { public: QWindowsFileDialogHelper() {} virtual bool supportsNonModalDialog(const QWindow * /* parent */ = 0) const { return false; } virtual bool defaultNameFilterDisables() const { return false; } virtual void setDirectory(const QUrl &directory) Q_DECL_OVERRIDE; virtual QUrl directory() const Q_DECL_OVERRIDE; virtual void selectFile(const QUrl &filename) Q_DECL_OVERRIDE; virtual QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE; virtual void setFilter() Q_DECL_OVERRIDE; virtual void selectNameFilter(const QString &filter) Q_DECL_OVERRIDE; virtual QString selectedNameFilter() const Q_DECL_OVERRIDE; private: virtual QWindowsNativeDialogBase *createNativeDialog(); inline QWindowsNativeFileDialogBase *nativeFileDialog() const { return static_cast<QWindowsNativeFileDialogBase *>(nativeDialog()); } // Cache for the case no native dialog is created. QWindowsFileDialogSharedData m_data; }; QWindowsNativeDialogBase *QWindowsFileDialogHelper::createNativeDialog() { QWindowsNativeFileDialogBase *result = QWindowsNativeFileDialogBase::create(options()->acceptMode(), m_data); if (!result) return 0; QObject::connect(result, SIGNAL(accepted()), this, SIGNAL(accept())); QObject::connect(result, SIGNAL(rejected()), this, SIGNAL(reject())); QObject::connect(result, SIGNAL(directoryEntered(QUrl)), this, SIGNAL(directoryEntered(QUrl))); QObject::connect(result, SIGNAL(currentChanged(QUrl)), this, SIGNAL(currentChanged(QUrl))); QObject::connect(result, SIGNAL(filterSelected(QString)), this, SIGNAL(filterSelected(QString))); // Apply settings. const QSharedPointer<QFileDialogOptions> &opts = options(); m_data.fromOptions(opts); const QFileDialogOptions::FileMode mode = opts->fileMode(); result->setWindowTitle(opts->windowTitle()); result->setMode(mode, opts->acceptMode(), opts->options()); result->setHideFiltersDetails(opts->testOption(QFileDialogOptions::HideNameFilterDetails)); const QStringList nameFilters = opts->nameFilters(); if (!nameFilters.isEmpty()) result->setNameFilters(nameFilters); if (opts->isLabelExplicitlySet(QFileDialogOptions::FileName)) result->setLabelText(QFileDialogOptions::FileName, opts->labelText(QFileDialogOptions::FileName)); if (opts->isLabelExplicitlySet(QFileDialogOptions::Accept)) result->setLabelText(QFileDialogOptions::Accept, opts->labelText(QFileDialogOptions::Accept)); result->updateDirectory(); result->updateSelectedNameFilter(); const QList<QUrl> initialSelection = opts->initiallySelectedFiles(); if (initialSelection.size() > 0) { const QUrl url = initialSelection.front(); if (url.isLocalFile()) { QFileInfo info(url.toLocalFile()); if (!info.isDir()) result->selectFile(info.fileName()); } else { result->selectFile(url.path()); // TODO url.fileName() once it exists } } // No need to select initialNameFilter if mode is Dir if (mode != QFileDialogOptions::Directory && mode != QFileDialogOptions::DirectoryOnly) { const QString initialNameFilter = opts->initiallySelectedNameFilter(); if (!initialNameFilter.isEmpty()) result->selectNameFilter(initialNameFilter); } const QString defaultSuffix = opts->defaultSuffix(); if (!defaultSuffix.isEmpty()) result->setDefaultSuffix(defaultSuffix); return result; } void QWindowsFileDialogHelper::setDirectory(const QUrl &directory) { qCDebug(lcQpaDialogs) << __FUNCTION__ << directory.toString(); m_data.setDirectory(directory); if (hasNativeDialog()) nativeFileDialog()->updateDirectory(); } QUrl QWindowsFileDialogHelper::directory() const { return m_data.directory(); } void QWindowsFileDialogHelper::selectFile(const QUrl &fileName) { qCDebug(lcQpaDialogs) << __FUNCTION__ << fileName.toString(); if (hasNativeDialog()) // Might be invoked from the QFileDialog constructor. nativeFileDialog()->selectFile(fileName.toLocalFile()); // ## should use QUrl::fileName() once it exists } QList<QUrl> QWindowsFileDialogHelper::selectedFiles() const { return m_data.selectedFiles(); } void QWindowsFileDialogHelper::setFilter() { qCDebug(lcQpaDialogs) << __FUNCTION__; } void QWindowsFileDialogHelper::selectNameFilter(const QString &filter) { m_data.setSelectedNameFilter(filter); if (hasNativeDialog()) nativeFileDialog()->updateSelectedNameFilter(); } QString QWindowsFileDialogHelper::selectedNameFilter() const { return m_data.selectedNameFilter(); } #ifndef Q_OS_WINCE /*! \class QWindowsXpNativeFileDialog \brief Native Windows directory dialog for Windows XP using SHlib-functions. Uses the synchronous GetOpenFileNameW(), GetSaveFileNameW() from ComDlg32 or SHBrowseForFolder() for directories. \internal \sa QWindowsXpFileDialogHelper \ingroup qt-lighthouse-win */ class QWindowsXpNativeFileDialog : public QWindowsNativeDialogBase { Q_OBJECT public: typedef QSharedPointer<QFileDialogOptions> OptionsPtr; static QWindowsXpNativeFileDialog *create(const OptionsPtr &options, const QWindowsFileDialogSharedData &data); virtual void setWindowTitle(const QString &t) { m_title = t; } virtual void doExec(HWND owner = 0); virtual QPlatformDialogHelper::DialogCode result() const { return m_result; } int existingDirCallback(HWND hwnd, UINT uMsg, LPARAM lParam); public slots: virtual void close() {} private: typedef BOOL (APIENTRY *PtrGetOpenFileNameW)(LPOPENFILENAMEW); typedef BOOL (APIENTRY *PtrGetSaveFileNameW)(LPOPENFILENAMEW); explicit QWindowsXpNativeFileDialog(const OptionsPtr &options, const QWindowsFileDialogSharedData &data); void populateOpenFileName(OPENFILENAME *ofn, HWND owner) const; QList<QUrl> execExistingDir(HWND owner); QList<QUrl> execFileNames(HWND owner, int *selectedFilterIndex) const; const OptionsPtr m_options; QString m_title; QPlatformDialogHelper::DialogCode m_result; QWindowsFileDialogSharedData m_data; static PtrGetOpenFileNameW m_getOpenFileNameW; static PtrGetSaveFileNameW m_getSaveFileNameW; }; QWindowsXpNativeFileDialog::PtrGetOpenFileNameW QWindowsXpNativeFileDialog::m_getOpenFileNameW = 0; QWindowsXpNativeFileDialog::PtrGetSaveFileNameW QWindowsXpNativeFileDialog::m_getSaveFileNameW = 0; QWindowsXpNativeFileDialog *QWindowsXpNativeFileDialog::create(const OptionsPtr &options, const QWindowsFileDialogSharedData &data) { // GetOpenFileNameW() GetSaveFileName() are resolved // dynamically as not to create a dependency on Comdlg32, which // is used on XP only. if (!m_getOpenFileNameW) { QSystemLibrary library(QStringLiteral("Comdlg32")); m_getOpenFileNameW = (PtrGetOpenFileNameW)(library.resolve("GetOpenFileNameW")); m_getSaveFileNameW = (PtrGetSaveFileNameW)(library.resolve("GetSaveFileNameW")); } if (m_getOpenFileNameW && m_getSaveFileNameW) return new QWindowsXpNativeFileDialog(options, data); return 0; } QWindowsXpNativeFileDialog::QWindowsXpNativeFileDialog(const OptionsPtr &options, const QWindowsFileDialogSharedData &data) : m_options(options), m_result(QPlatformDialogHelper::Rejected), m_data(data) { setWindowTitle(m_options->windowTitle()); } void QWindowsXpNativeFileDialog::doExec(HWND owner) { int selectedFilterIndex = -1; const QList<QUrl> selectedFiles = m_options->fileMode() == QFileDialogOptions::DirectoryOnly ? execExistingDir(owner) : execFileNames(owner, &selectedFilterIndex); m_data.setSelectedFiles(selectedFiles); QWindowsDialogs::eatMouseMove(); if (selectedFiles.isEmpty()) { m_result = QPlatformDialogHelper::Rejected; emit rejected(); } else { const QStringList nameFilters = m_options->nameFilters(); if (selectedFilterIndex >= 0 && selectedFilterIndex < nameFilters.size()) m_data.setSelectedNameFilter(nameFilters.at(selectedFilterIndex)); QUrl firstFile = selectedFiles.front(); m_data.setDirectory(firstFile.adjusted(QUrl::RemoveFilename)); m_result = QPlatformDialogHelper::Accepted; emit accepted(); } } // Callback for QWindowsNativeXpFileDialog directory dialog. // MFC Directory Dialog. Contrib: Steve Williams (minor parts from Scott Powers) static int QT_WIN_CALLBACK xpFileDialogGetExistingDirCallbackProc(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData) { QWindowsXpNativeFileDialog *dialog = reinterpret_cast<QWindowsXpNativeFileDialog *>(lpData); return dialog->existingDirCallback(hwnd, uMsg, lParam); } /* The correct declaration of the SHGetPathFromIDList symbol is * being used in mingw-w64 as of r6215, which is a v3 snapshot. */ #if defined(Q_CC_MINGW) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 3) typedef ITEMIDLIST *qt_LpItemIdList; #else typedef PIDLIST_ABSOLUTE qt_LpItemIdList; #endif int QWindowsXpNativeFileDialog::existingDirCallback(HWND hwnd, UINT uMsg, LPARAM lParam) { switch (uMsg) { case BFFM_INITIALIZED: { if (!m_title.isEmpty()) SetWindowText(hwnd, (wchar_t *)m_title.utf16()); const QString initialFile = QDir::toNativeSeparators(m_data.directory().toLocalFile()); if (!initialFile.isEmpty()) SendMessage(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initialFile.utf16())); } break; case BFFM_SELCHANGED: { wchar_t path[MAX_PATH]; const bool ok = SHGetPathFromIDList(reinterpret_cast<qt_LpItemIdList>(lParam), path) && path[0]; SendMessage(hwnd, BFFM_ENABLEOK, ok ? 1 : 0, 1); } break; } return 0; } QList<QUrl> QWindowsXpNativeFileDialog::execExistingDir(HWND owner) { BROWSEINFO bi; wchar_t initPath[MAX_PATH]; initPath[0] = 0; bi.hwndOwner = owner; bi.pidlRoot = NULL; bi.lpszTitle = 0; bi.pszDisplayName = initPath; bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE; bi.lpfn = xpFileDialogGetExistingDirCallbackProc; bi.lParam = LPARAM(this); QList<QUrl> selectedFiles; if (qt_LpItemIdList pItemIDList = SHBrowseForFolder(&bi)) { wchar_t path[MAX_PATH]; path[0] = 0; if (SHGetPathFromIDList(pItemIDList, path) && path[0]) selectedFiles.push_back(QUrl::fromLocalFile(QDir::cleanPath(QString::fromWCharArray(path)))); IMalloc *pMalloc; if (SHGetMalloc(&pMalloc) == NOERROR) { pMalloc->Free(pItemIDList); pMalloc->Release(); } } return selectedFiles; } // Open/Save files void QWindowsXpNativeFileDialog::populateOpenFileName(OPENFILENAME *ofn, HWND owner) const { ZeroMemory(ofn, sizeof(OPENFILENAME)); ofn->lStructSize = sizeof(OPENFILENAME); ofn->hwndOwner = owner; // Create a buffer with the filter strings. int totalStringLength = 0; QList<FilterSpec> specs = filterSpecs(m_options->nameFilters(), m_options->options() & QFileDialogOptions::HideNameFilterDetails, &totalStringLength); const int size = specs.size(); wchar_t *ptr = new wchar_t[totalStringLength + 2 * size + 1]; ofn->lpstrFilter = ptr; foreach (const FilterSpec &spec, specs) { ptr += spec.description.toWCharArray(ptr); *ptr++ = 0; ptr += spec.filter.toWCharArray(ptr); *ptr++ = 0; } *ptr = 0; const int nameFilterIndex = indexOfNameFilter(m_options->nameFilters(), m_data.selectedNameFilter()); if (nameFilterIndex >= 0) ofn->nFilterIndex = nameFilterIndex + 1; // 1..n based. // lpstrFile receives the initial selection and is the buffer // for the target. If it contains any invalid character, the dialog // will not show. ofn->nMaxFile = 65535; const QString initiallySelectedFile = QDir::toNativeSeparators(m_data.selectedFile()).remove(QLatin1Char('<')). remove(QLatin1Char('>')).remove(QLatin1Char('"')).remove(QLatin1Char('|')); ofn->lpstrFile = qStringToWCharArray(initiallySelectedFile, ofn->nMaxFile); ofn->lpstrInitialDir = qStringToWCharArray(QDir::toNativeSeparators(m_data.directory().toLocalFile())); ofn->lpstrTitle = (wchar_t*)m_title.utf16(); // Determine lpstrDefExt. Note that the current MSDN docs document this // member wrong. It should rather be documented as "the default extension // if no extension was given and if the current filter does not have an // extension (e.g (*)). If the current filter has an extension, use // the extension of the current filter". if (m_options->acceptMode() == QFileDialogOptions::AcceptSave) { QString defaultSuffix = m_options->defaultSuffix(); if (defaultSuffix.startsWith(QLatin1Char('.'))) defaultSuffix.remove(0, 1); // QTBUG-33156, also create empty strings to trigger the appending mechanism. ofn->lpstrDefExt = qStringToWCharArray(defaultSuffix); } // Flags. ofn->Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_PATHMUSTEXIST); if (m_options->fileMode() == QFileDialogOptions::ExistingFile || m_options->fileMode() == QFileDialogOptions::ExistingFiles) ofn->Flags |= (OFN_FILEMUSTEXIST); if (m_options->fileMode() == QFileDialogOptions::ExistingFiles) ofn->Flags |= (OFN_ALLOWMULTISELECT); if (!(m_options->options() & QFileDialogOptions::DontConfirmOverwrite)) ofn->Flags |= OFN_OVERWRITEPROMPT; } QList<QUrl> QWindowsXpNativeFileDialog::execFileNames(HWND owner, int *selectedFilterIndex) const { *selectedFilterIndex = -1; OPENFILENAME ofn; populateOpenFileName(&ofn, owner); QList<QUrl> result; const bool isSave = m_options->acceptMode() == QFileDialogOptions::AcceptSave; if (isSave ? m_getSaveFileNameW(&ofn) : m_getOpenFileNameW(&ofn)) { *selectedFilterIndex = ofn.nFilterIndex - 1; const QString dir = QDir::cleanPath(QString::fromWCharArray(ofn.lpstrFile)); result.push_back(QUrl::fromLocalFile(dir)); // For multiselection, the first item is the path followed // by "\0<file1>\0<file2>\0\0". if (ofn.Flags & (OFN_ALLOWMULTISELECT)) { wchar_t *ptr = ofn.lpstrFile + dir.size() + 1; if (*ptr) { result.pop_front(); const QString path = dir + QLatin1Char('/'); while (*ptr) { const QString fileName = QString::fromWCharArray(ptr); result.push_back(QUrl::fromLocalFile(path + fileName)); ptr += fileName.size() + 1; } // extract multiple files } // has multiple files } // multiple flag set } delete [] ofn.lpstrFile; delete [] ofn.lpstrInitialDir; delete [] ofn.lpstrFilter; delete [] ofn.lpstrDefExt; return result; } /*! \class QWindowsXpFileDialogHelper \brief Dialog helper using QWindowsXpNativeFileDialog \sa QWindowsXpNativeFileDialog \internal \ingroup qt-lighthouse-win */ class QWindowsXpFileDialogHelper : public QWindowsDialogHelperBase<QPlatformFileDialogHelper> { public: QWindowsXpFileDialogHelper() {} virtual bool supportsNonModalDialog(const QWindow * /* parent */ = 0) const { return false; } virtual bool defaultNameFilterDisables() const { return true; } virtual void setDirectory(const QUrl &directory) Q_DECL_OVERRIDE; virtual QUrl directory() const Q_DECL_OVERRIDE; virtual void selectFile(const QUrl &url) Q_DECL_OVERRIDE; virtual QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE; virtual void setFilter() Q_DECL_OVERRIDE {} virtual void selectNameFilter(const QString &) Q_DECL_OVERRIDE; virtual QString selectedNameFilter() const Q_DECL_OVERRIDE; private: virtual QWindowsNativeDialogBase *createNativeDialog(); inline QWindowsXpNativeFileDialog *nativeFileDialog() const { return static_cast<QWindowsXpNativeFileDialog *>(nativeDialog()); } QWindowsFileDialogSharedData m_data; }; QWindowsNativeDialogBase *QWindowsXpFileDialogHelper::createNativeDialog() { m_data.fromOptions(options()); if (QWindowsXpNativeFileDialog *result = QWindowsXpNativeFileDialog::create(options(), m_data)) { QObject::connect(result, SIGNAL(accepted()), this, SIGNAL(accept())); QObject::connect(result, SIGNAL(rejected()), this, SIGNAL(reject())); return result; } return 0; } void QWindowsXpFileDialogHelper::setDirectory(const QUrl &directory) { m_data.setDirectory(directory); // Dialog cannot be updated at run-time. } QUrl QWindowsXpFileDialogHelper::directory() const { return m_data.directory(); } void QWindowsXpFileDialogHelper::selectFile(const QUrl &url) { m_data.setSelectedFiles(QList<QUrl>() << url); // Dialog cannot be updated at run-time. } QList<QUrl> QWindowsXpFileDialogHelper::selectedFiles() const { return m_data.selectedFiles(); } void QWindowsXpFileDialogHelper::selectNameFilter(const QString &f) { m_data.setSelectedNameFilter(f); // Dialog cannot be updated at run-time. } QString QWindowsXpFileDialogHelper::selectedNameFilter() const { return m_data.selectedNameFilter(); } #endif // Q_OS_WINCE /*! \class QWindowsNativeColorDialog \brief Native Windows color dialog. Wrapper around Comdlg32's ChooseColor() function. Not currently in use as QColorDialog is equivalent. \sa QWindowsColorDialogHelper \sa #define USE_NATIVE_COLOR_DIALOG \internal \ingroup qt-lighthouse-win */ typedef QSharedPointer<QColor> SharedPointerColor; #ifdef USE_NATIVE_COLOR_DIALOG class QWindowsNativeColorDialog : public QWindowsNativeDialogBase { Q_OBJECT public: enum { CustomColorCount = 16 }; explicit QWindowsNativeColorDialog(const SharedPointerColor &color); virtual void setWindowTitle(const QString &) {} virtual QPlatformDialogHelper::DialogCode result() const { return m_code; } public slots: virtual void close() {} private: virtual void doExec(HWND owner = 0); COLORREF m_customColors[CustomColorCount]; QPlatformDialogHelper::DialogCode m_code; SharedPointerColor m_color; }; QWindowsNativeColorDialog::QWindowsNativeColorDialog(const SharedPointerColor &color) : m_code(QPlatformDialogHelper::Rejected), m_color(color) { std::fill(m_customColors, m_customColors + 16, COLORREF(0)); } void QWindowsNativeColorDialog::doExec(HWND owner) { typedef BOOL (WINAPI *ChooseColorWType)(LPCHOOSECOLORW); CHOOSECOLOR chooseColor; ZeroMemory(&chooseColor, sizeof(chooseColor)); chooseColor.lStructSize = sizeof(chooseColor); chooseColor.hwndOwner = owner; chooseColor.lpCustColors = m_customColors; QRgb *qCustomColors = QColorDialogOptions::customColors(); const int customColorCount = qMin(QColorDialogOptions::customColorCount(), int(CustomColorCount)); for (int c= 0; c < customColorCount; ++c) m_customColors[c] = qColorToCOLORREF(QColor(qCustomColors[c])); chooseColor.rgbResult = qColorToCOLORREF(*m_color); chooseColor.Flags = CC_FULLOPEN | CC_RGBINIT; static ChooseColorWType chooseColorW = 0; if (!chooseColorW) { QSystemLibrary library(QStringLiteral("Comdlg32")); chooseColorW = (ChooseColorWType)library.resolve("ChooseColorW"); } if (chooseColorW) { m_code = chooseColorW(&chooseColor) ? QPlatformDialogHelper::Accepted : QPlatformDialogHelper::Rejected; QWindowsDialogs::eatMouseMove(); } else { m_code = QPlatformDialogHelper::Rejected; } if (m_code == QPlatformDialogHelper::Accepted) { *m_color = COLORREFToQColor(chooseColor.rgbResult); for (int c= 0; c < customColorCount; ++c) qCustomColors[c] = COLORREFToQColor(m_customColors[c]).rgb(); emit accepted(); } else { emit rejected(); } } /*! \class QWindowsColorDialogHelper \brief Helper for native Windows color dialogs Not currently in use as QColorDialog is equivalent. \sa #define USE_NATIVE_COLOR_DIALOG \sa QWindowsNativeColorDialog \internal \ingroup qt-lighthouse-win */ class QWindowsColorDialogHelper : public QWindowsDialogHelperBase<QPlatformColorDialogHelper> { public: QWindowsColorDialogHelper() : m_currentColor(new QColor) {} virtual bool supportsNonModalDialog() { return false; } virtual QColor currentColor() const { return *m_currentColor; } virtual void setCurrentColor(const QColor &c) { *m_currentColor = c; } private: inline QWindowsNativeColorDialog *nativeFileDialog() const { return static_cast<QWindowsNativeColorDialog *>(nativeDialog()); } virtual QWindowsNativeDialogBase *createNativeDialog(); SharedPointerColor m_currentColor; }; QWindowsNativeDialogBase *QWindowsColorDialogHelper::createNativeDialog() { QWindowsNativeColorDialog *nativeDialog = new QWindowsNativeColorDialog(m_currentColor); nativeDialog->setWindowTitle(options()->windowTitle()); connect(nativeDialog, SIGNAL(accepted()), this, SIGNAL(accept())); connect(nativeDialog, SIGNAL(rejected()), this, SIGNAL(reject())); return nativeDialog; } #endif // USE_NATIVE_COLOR_DIALOG namespace QWindowsDialogs { // QWindowsDialogHelperBase creation functions bool useHelper(QPlatformTheme::DialogType type) { if (QWindowsIntegration::instance()->options() & QWindowsIntegration::NoNativeDialogs) return false; switch (type) { case QPlatformTheme::FileDialog: return QSysInfo::windowsVersion() >= QSysInfo::WV_XP; case QPlatformTheme::ColorDialog: #ifdef USE_NATIVE_COLOR_DIALOG return true; #else break; #endif case QPlatformTheme::FontDialog: case QPlatformTheme::MessageDialog: break; default: break; } return false; } QPlatformDialogHelper *createHelper(QPlatformTheme::DialogType type) { if (QWindowsIntegration::instance()->options() & QWindowsIntegration::NoNativeDialogs) return 0; switch (type) { case QPlatformTheme::FileDialog: #ifndef Q_OS_WINCE // Note: "Windows XP Professional x64 Edition has version number WV_5_2 (WV_2003). if (QWindowsIntegration::instance()->options() & QWindowsIntegration::XpNativeDialogs || QSysInfo::windowsVersion() <= QSysInfo::WV_2003) { return new QWindowsXpFileDialogHelper(); } if (QSysInfo::windowsVersion() > QSysInfo::WV_2003) return new QWindowsFileDialogHelper(); #else return new QWindowsFileDialogHelper(); #endif // Q_OS_WINCE case QPlatformTheme::ColorDialog: #ifdef USE_NATIVE_COLOR_DIALOG return new QWindowsColorDialogHelper(); #else break; #endif case QPlatformTheme::FontDialog: case QPlatformTheme::MessageDialog: break; default: break; } return 0; } } // namespace QWindowsDialogs QT_END_NAMESPACE #include "qwindowsdialoghelpers.moc"
#include <jni.h> #include "context.h" #include "NativeLog.h" using namespace std; std::shared_ptr<context> g_ctx; //查看类的方法签名: javap -s com.lxl.someiplib.SomeIPClient void on_message(const std::shared_ptr<vsomeip::message> &_message) { int status; JNIEnv* env = NULL; status = g_ctx->vm->GetEnv((void **)&env, JNI_VERSION_1_6); if(status < 0) { status = g_ctx->vm->AttachCurrentThread(&env, NULL); if(status < 0) { env = NULL; return; } } jclass clz = env->GetObjectClass(g_ctx->app_object); if (clz == nullptr) { return; } //获取要回调的方法 jmethodID jMethodId = env->GetMethodID(clz, "onMessage", "(III[B)V"); if (jMethodId == nullptr) { return; } // 获取消息信息 int serviceId = _message->get_service(); int instanceId = _message->get_instance(); int methodId = _message->get_method(); std::shared_ptr<vsomeip::payload> its_payload = _message->get_payload(); // 转jbyteArray jbyte *by = (jbyte*)its_payload->get_data(); int dataSize = its_payload->get_length(); jbyteArray jarray = env->NewByteArray(its_payload->get_length()); env->SetByteArrayRegion(jarray, 0, dataSize, by); env->CallVoidMethod(g_ctx->app_object, jMethodId, serviceId, instanceId, methodId, jarray); env->DeleteLocalRef(clz); g_ctx->vm->DetachCurrentThread(); } void on_availability(int serviceId, int instanceId, bool is_available) { int status; JNIEnv* env = NULL; status = g_ctx->vm->GetEnv((void **)&env, JNI_VERSION_1_6); if(status < 0) { status = g_ctx->vm->AttachCurrentThread(&env, NULL); if(status < 0) { env = NULL; return; } } jclass clz = env->GetObjectClass(g_ctx->app_object); if (clz == nullptr) { return; } //获取要回调的方法 jmethodID jMethodId = env->GetMethodID(clz, "onAvailability", "(IIZ)V"); if (jMethodId == nullptr) { return; } if(is_available) { env->CallVoidMethod(g_ctx->app_object, jMethodId, serviceId, instanceId, JNI_TRUE); } else { env->CallVoidMethod(g_ctx->app_object, jMethodId, serviceId, instanceId, JNI_FALSE); } env->DeleteLocalRef(clz); g_ctx->vm->DetachCurrentThread(); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_create(JNIEnv *env, jclass clazz, jstring app_name, jobject client) { // 初始化context g_ctx = std::make_shared<context>(); env->GetJavaVM(&g_ctx->vm); const char* appNameConverted = env->GetStringUTFChars(app_name, 0); char* appNameCopied = (char*) malloc(sizeof(char)*(strlen(appNameConverted)+1)); strcpy(appNameCopied, appNameConverted); g_ctx->app = vsomeip::runtime::get()->create_application(appNameConverted); g_ctx->app_name = appNameCopied; //生成一个全局引用,回调的时候findclass才不会为null jobject callback = env->NewGlobalRef(client); g_ctx->app_object = callback; // 释放资源 env->ReleaseStringUTFChars(app_name, appNameConverted); } extern "C" JNIEXPORT jboolean JNICALL Java_com_lxl_someiplib_SomeIPClient_init(JNIEnv *env, jclass clazz) { bool ret = g_ctx->app->init(); return ret; } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_request_1service(JNIEnv *env, jclass clazz, jint service_id, jint instance_id) { g_ctx->app->request_service(service_id, instance_id); g_ctx->app->register_availability_handler(service_id, instance_id, on_availability); g_ctx->app->register_message_handler(service_id, instance_id, vsomeip::ANY_METHOD, on_message); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_start(JNIEnv *env, jclass clazz) { g_ctx->app->start(); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_stop(JNIEnv *env, jclass clazz) { g_ctx->app->stop(); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_close(JNIEnv *env, jclass clazz) { // 释放资源 env->DeleteGlobalRef(g_ctx->app_object); free(g_ctx->app_name); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_send_1request(JNIEnv *env, jclass clazz, jint service_id, jint instance_id, jint method_id, jbyteArray payload) { // 构建请求消息 std::shared_ptr< vsomeip::message > request = vsomeip::runtime::get()->create_request(); request->set_service(service_id); request->set_instance(instance_id); request->set_method(method_id); // 填充Payload std::shared_ptr< vsomeip::payload > its_payload = vsomeip::runtime::get()->create_payload(); jbyte* bBuffer = env->GetByteArrayElements(payload, 0); int payloadLen = env->GetArrayLength(payload); std::unique_ptr< vsomeip::byte_t[] > its_data (new vsomeip::byte_t[payloadLen]()); memcpy(its_data.get(), bBuffer, payloadLen); its_payload->set_data(its_data.get(), payloadLen); request->set_payload(its_payload); // 发送请求 g_ctx->app->send(request); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_request_1event(JNIEnv *env, jclass clazz, jint service_id, jint instance_id, jint event_id, jint event_group_id) { std::set<vsomeip::eventgroup_t> its_groups; its_groups.insert(event_group_id); g_ctx->app->request_event(service_id, instance_id, event_id, its_groups, vsomeip_v3::event_type_e::ET_EVENT, vsomeip_v3::reliability_type_e::RT_BOTH); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_subscribe_1eventgroup(JNIEnv *env, jclass clazz, jint service_id, jint instance_id, jint event_group_id) { g_ctx->app->subscribe(service_id, instance_id, event_group_id); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_unsubscribe_1eventgroup(JNIEnv *env, jclass clazz, jint service_id, jint instance_id, jint event_group_id) { g_ctx->app->unsubscribe(service_id, instance_id, event_group_id); } extern "C" JNIEXPORT void JNICALL Java_com_lxl_someiplib_SomeIPClient_subscribe_1event(JNIEnv *env, jclass clazz, jint service_id, jint instance_id, jint event_group_id, jint event_id) { g_ctx->app->subscribe(service_id, instance_id, event_group_id, vsomeip_v3::ANY_MAJOR, event_id); }
#pragma once #if ! defined(yyFlexLexerOnce) #undef yyFlexLexer #define yyFlexLexer Json_FlexLexer #include <FlexLexer.h> #endif #include "json_parser.hpp" #include "location.hh" namespace json { class scanner : public Json_FlexLexer { public: scanner(std::istream &in, std::ostream &out) : Json_FlexLexer(in, out) { } ~scanner() { } //get rid of override virtual function warning using Json_FlexLexer::yylex; virtual int yylex(json::parser::semantic_type *const lval, json::parser::location_type *location); private: json::parser::semantic_type *yylval = nullptr; }; }
/***** Vca::VCohort Implementation *****/ /************************ ************************ ***** Interfaces ***** ************************ ************************/ /******************** ***** System ***** ********************/ #include "Vk.h" #include "VpSocket.h" // Needed for waitpid. #include "VConfig.h" /****************** ***** Self ***** ******************/ #include "Vca_VCohort.h" /************************ ***** Supporting ***** ************************/ #include "Vca.h" #include "Vca_CompilerHappyPill.h" #include "Vca_VBSConsumer.h" #include "Vca_VRolePlayer.h" #include "Vca_VTimer.h" #include "Vca_VcaThreadState.h" /********************* ***** Logging ***** *********************/ /*************************************************/ namespace { typedef V::VString VString; char const *LogFileName () { static char const *pLogFileName = getenv ("VcaDeviceLog"); static bool bNotInitialized = true; if (!pLogFileName && bNotInitialized) { bNotInitialized = false; if (V::GetEnvironmentBoolean ("TracingDevices")) { static VString iLogFileName (VString () << "p_" << getpid () << "_device.log"); pLogFileName = iLogFileName; } } return pLogFileName; } V::VLogger g_iDeviceLogger (LogFileName ()); } V::VLogger &Vca::VCohort::defaultLogger () const { return g_iDeviceLogger; } V::VLogger &Vca::VCohort::DefaultLogger () { return g_iDeviceLogger; } /*************************************************/ namespace Vca { bool s_bDeviceManagerPollEnabled = V::GetEnvironmentInteger ("VcaDeviceManagerPollEnabled", 1) != 0; bool TracingCohortWaitStates () { static bool const bTracingCohortWaitStates = V::GetEnvironmentInteger ("VcaTracingCohortWaitStates", 0) != 0; return bTracingCohortWaitStates; } } /*************************************************/ /**************************************** **************************************** ***** ***** ***** Vca::VCohort::Cache::Index ***** ***** ***** **************************************** ****************************************/ /***************************** ***************************** ***** Index Generator ***** ***************************** *****************************/ namespace { Vca::counter_t g_xNextIndex; bool g_bHalted = false; } Vca::count_t Vca::VCohort::Cache::Index::NextIndex () { return g_xNextIndex++; } /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VCohort::Cache::Index::Index () : m_xIndex (NextIndex ()) { } /********************************* ********************************* ***** ***** ***** Vca::VCohort::Cache ***** ***** ***** ********************************* *********************************/ /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VCohort::Cache::Cache () : m_xArrayLB (UINT_MAX), m_xArrayUB (0) { } /************************* ************************* ***** Destruction ***** ************************* *************************/ Vca::VCohort::Cache::~Cache () { } /******************** ******************** ***** Access ***** ******************** ********************/ bool Vca::VCohort::Cache::getElementIndex (Index const &rIndex, unsigned int &rxElement) const { rxElement = rIndex - m_xArrayLB; return m_xArrayLB <= rIndex && rIndex <= m_xArrayUB; } void *Vca::VCohort::Cache::value (Index const &rIndex) const { unsigned int xElement; return getElementIndex (rIndex, xElement) ? const_cast<char*>(m_iArray[xElement].referent ()) : 0; } /******************** ******************** ***** Update ***** ******************** ********************/ bool Vca::VCohort::Cache::attach (Index const &rIndex, void const *pValue) { unsigned int xElement; if (getElementIndex (rIndex, xElement)) { if (m_iArray[xElement].isntNil ()) return false; m_iArray[xElement].setTo ((char const*)pValue); return true; } if (m_iArray.elementCount () == 0) { m_iArray.Guarantee (1); m_xArrayLB = m_xArrayUB = rIndex; m_iArray[0].setTo ((char const*)pValue); return true; } if (m_xArrayLB > rIndex) { m_iArray.Prepend (m_xArrayLB - rIndex); m_xArrayLB = rIndex; m_iArray[0].setTo ((char const*)pValue); return true; } m_iArray.Append (rIndex - m_xArrayUB); m_xArrayUB = rIndex; m_iArray[m_xArrayUB - m_xArrayLB].setTo ((char const*)pValue); return true; } bool Vca::VCohort::Cache::detach (Index const &rIndex, void const *pValue) { unsigned int xElement; if (getElementIndex (rIndex, xElement) && m_iArray[xElement].referent () == (char const*)pValue) { m_iArray[xElement] = 0; return true; } return false; } /********************************* ********************************* ***** ***** ***** Vca::VCohort::Claim ***** ***** ***** ********************************* *********************************/ /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VCohort::Claim::Claim ( VRolePlayer *pObject, bool bWait ) : m_pThread (Thread::Here ()), m_pThreadLink (m_pThread->cohortClaims ()), m_pCohort (pObject->cohort ()), m_bHeld (false), m_bRelinquished (false) { m_pThread->attach (this, bWait); } Vca::VCohort::Claim::Claim ( VCohort *pCohort, bool bWait ) : m_pThread (Thread::Here ()), m_pThreadLink (m_pThread->cohortClaims ()), m_pCohort (pCohort), m_bHeld (false), m_bRelinquished (false) { m_pThread->attach (this, bWait); } Vca::VCohort::Claim::Claim ( bool bClaimingThreadCohort // true for event processors, false for factories ) : m_pThread (Thread::Here ()), m_pThreadLink (m_pThread->cohortClaims ()), m_pCohort ( bClaimingThreadCohort ? m_pThread->cohort () : 0 ), m_bHeld (false), m_bRelinquished (false) { m_pThread->attach (this, bClaimingThreadCohort); } Vca::VCohort::Claim::Claim (Thread *pThread) : m_pThread (pThread), m_bHeld (false), m_bRelinquished (false) { m_pThread->attach (this); } /************************* ************************* ***** Destruction ***** ************************* *************************/ Vca::VCohort::Claim::~Claim () { m_pThread->detach (this); } /******************** ******************** ***** Access ***** ******************** ********************/ Vca::VCohort *Vca::VCohort::Claim::cohort () { if (m_pCohort.isNil ()) { m_bHeld = false; m_pCohort.setTo (new VCohort ()); acquire (); // will never block. } return m_pCohort; } /******************** ******************** ***** Update ***** ******************** ********************/ void Vca::VCohort::Claim::clear () { if (m_pCohort) { release (); m_pCohort.clear (); m_bHeld = true; } } bool Vca::VCohort::Claim::setTo (VCohort *pCohort, bool bWait) { if (pCohort != m_pCohort) { release (); m_pCohort.setTo (pCohort); } return acquire (bWait); } bool Vca::VCohort::Claim::setTo (VRolePlayer *pObject, bool bWait) { return setTo (pObject->cohort (), bWait); } /************************ ************************ ***** Management ***** ************************ ************************/ bool Vca::VCohort::Claim::acquire (bool bWait) { if (!acquireTry () && bWait) { do { if (TracingCohortWaitStates ()) printf ( "+++ Thread %p waiting for cohort %p%s.\n", m_pThread.referent (), m_pCohort.referent (), m_pCohort->isVca () ? " (Vca)" : "" ); // release all claims and block m_pThread->releaseCohorts (); m_pCohort->onReleaseSignal (this); m_pThread->waitForSignal (); if (TracingCohortWaitStates ()) printf ("+++ Thread %p resumed.\n", m_pThread.referent ()); } while (!acquireTry () || !m_pThread->acquireCohorts ()); } return m_bHeld; } bool Vca::VCohort::Claim::acquireTry () { if (m_pCohort.isNil ()) m_bHeld = true; #ifdef VMS_LINUX_EXPLICIT_COMPAT // ... Some builds allow a thread to lock its default cohort: else if (!m_bHeld) m_pCohort->attemptClaim (m_bHeld, m_pThread); return m_bHeld; #else // ... Most builds explicitly disallow it: else if (m_pThreadLink.isNil ()) // ... claims with no thread link successor provide a thread's default cohort which they will NEVER lock: m_bHeld = false; else if (!m_bHeld) m_pCohort->attemptClaim (m_bHeld, m_pThread); return m_bHeld || m_pThreadLink.isNil (); #endif } void Vca::VCohort::Claim::release () { if (m_pCohort.isNil ()) m_bHeld = false; else if (m_bHeld) m_pCohort->releaseClaim (m_bHeld, m_pThread); } void Vca::VCohort::Claim::relinquish (Pointer &rpSuccessor) { if (m_bHeld) { m_bRelinquished = true; release (); } rpSuccessor.setTo (m_pThreadLink); } bool Vca::VCohort::Claim::unlinquish (Pointer &rpSuccessor) { if (m_bRelinquished && !acquireTry ()) return false; m_bRelinquished = false; rpSuccessor.setTo (m_pThreadLink); return true; } /*********************************** *********************************** ***** ***** ***** Vca::VCohort::Manager ***** ***** ***** *********************************** ***********************************/ /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VCohort::Manager::Manager (VCohort *pCohort) : m_pCohort (pCohort) { } Vca::VCohort::Manager::Manager () : m_pCohort (Vca ()) { } /************************* ************************* ***** Destruction ***** ************************* *************************/ Vca::VCohort::Manager::~Manager () { m_pCohort->detach (this); } /***************************** ***************************** ***** Cohort Creation ***** ***************************** *****************************/ Vca::VCohort *Vca::VCohort::Manager::cohort () { return m_pCohort; } /*********************** *********************** ***** Callbacks ***** *********************** ***********************/ bool Vca::VCohort::Manager::onCohortEvent_() { return m_pCohort->postInterrupt (); } bool Vca::VCohort::Manager::onEmptyCohort_() { return true; } /****************************** ****************************** ***** Event Processing ***** ****************************** ******************************/ /****************************************************************************** * This is the main Vca event loop. ******************************************************************************/ void Vca::VCohort::Manager::doEvents () { while (doEvents (m_pCohort->needsTending () ? Vca_InfiniteWait : 1000)); } /****************************************************************************** * Routine: doEvents * This method is used to wait on the global event set for the specified * period of time. Since there could be global active timers * ...this method takes them into consideration on deciding on the time to wait * i.e. if there is a timer with expiry time lesser than the argument of this * function then the wait is done on the timer's expiry time (lesser time).... * After waiting on the minimum time it triggers the timers that are active * and if there was an event that was fired ..handles it and tries to drain the * event set. * Return Value: * Boolean indicating whether there is some more events or timers waiting * to be handled. ******************************************************************************/ bool Vca::VCohort::Manager::doEvents (size_t sTimeout) { bool bEventsHandled = false; return doEvents (sTimeout, bEventsHandled); } bool Vca::VCohort::Manager::doEvents (size_t sTimeout, bool &rbEventsHandled) { return m_pCohort->processEvents (this, sTimeout, rbEventsHandled); } /******************************************** ******************************************** ***** ***** ***** Vca::VCohort::ProcessorRequest ***** ***** ***** ******************************************** ********************************************/ template class Vca_API V::VThreadedProcessor_<Vca::VCohort::ProcessorRequest>; Vca::VCohort::Processor::Reference Vca::VCohort::g_pProcessor; static Vca::VCohort::Processor *g_pProcessorToo = 0; /*********************** *********************** ***** Execution ***** *********************** ***********************/ void Vca::VCohort::ProcessorRequest::process () { Claim iClaim (m_pCohort, false); decrementProcessorRequestCount (); // ... remove the processor claim if (iClaim.isHeld ()) { Manager iManager (m_pCohort); if (iManager.attachCohortEvents ()) { do { iManager.doEvents (Vca_InfiniteWait); } while (m_pCohort->needsTending () && !g_bHalted && (!isAtExit () || m_pCohort->isntVca ())); // If the process is exiting and this loop is processing the Vca cohort, we exit the loop, so that the exit handler can pick up the Vca cohort and process the exit events within. } } } /************************** ************************** ***** ***** ***** Vca::VCohort ***** ***** ***** ************************** **************************/ /************************** ************************** ***** Construction ***** ************************** **************************/ Vca::VCohort::VCohort () : MessageStarter (this) { } /************************* ************************* ***** Destruction ***** ************************* *************************/ Vca::VCohort::~VCohort () { } /********************* ********************* ***** Globals ***** ********************* *********************/ Vca::VCohort *Vca::VCohort::Here () { return VcaThreadState::Cohort (); } Vca::VCohort::Reference Vca::VCohort::g_pVcaCohort; extern "C" { static void AtExitHandler () { if (Vca::isAtExit ()) // ... only do this once. return; Vca::setAtExit (); if (Vca::ExitCalled ()) { g_bHalted = true; return; } // initiate a shutdown... Vca::Shutdown (); // ... wait for it to happen, ... Vca::VCohort::Reference pVca (Vca::VCohort::Vca ()); pVca->postInterrupt (); Vca::VCohort::Claim iShutdownClaim (pVca); // ... and run the event loop just to be sure. Vca::VCohort::Manager iShutdownManager (pVca); if (iShutdownManager.attachCohortEvents ()) { Vca::VCohort::DefaultLogger().printf ("At Exit Handler Running\n"); V::VTime iNow; V::VTime iLimit (iNow); iLimit += 1000000 * static_cast<unsigned __int64>( V::GetEnvironmentValue ("VcaAtExitTimeout", static_cast<double>(3.0)) // default == 3 seconds ); bool bNotDone = true; bool bUninformed = true; while (bNotDone && iLimit > iNow) { bNotDone = iShutdownManager.doEvents ((size_t)((iLimit - iNow)/ 1000)); iNow.setToNow (); } } g_bHalted = true; if (g_pProcessorToo) g_pProcessorToo->stop (); Vca::VCohort::DefaultLogger().printf ("At Exit Handler Exiting\n"); } } void Vca::VCohort::CallExitHandler () { #if defined (sun) AtExitHandler (); #endif } Vca::VCohort *Vca::VCohort::Vca () { if (g_pVcaCohort.isNil ()) { Claim iFactoryClaim (false); if (g_pVcaCohort.interlockedSetIfNil (iFactoryClaim.cohort ())) { #ifdef _WIN32 /************************************************************************************************* *>>>> There's no point in using an atexit handler in a Windows DLL because the threads <<<<* *>>>> this handler needs to gracefully stop have been unceremoniously blown away before <<<<* *>>>> the handler is called. In the world of Windows, the only atexit handlers that see <<<<* *>>>> the process' threads are those established by the main (.exe) program. After these <<<<* *>>>> handlers are run, the main calls ExitProcess which terminates all threads but the <<<<* *>>>> main thread and aborts all outstanding I/O's on those threads before calling the <<<<* *>>>> termination code for any DLLs. Not much point in trying to exit gracefully in that <<<<* *>>>> world, is there? <<<<* *************************************************************************************************/ #else atexit (&AtExitHandler); #endif } } return g_pVcaCohort; } /****************************** ****************************** ***** Claim Management ***** ****************************** ******************************/ void Vca::VCohort::attemptClaim (bool &rbHeld, Thread *pThread) { if (pThread == m_pClaimHolder || m_pClaimHolder.interlockedSetIfNil (pThread)) { rbHeld = true; if (0 == m_sHolderClaim++) { drainMessageQueue (); } } } //------ // This routine is always called by the thread holding the claim. //------ void Vca::VCohort::releaseClaim (bool &rbHeld, Thread *pThread) { // Make sure we're in the thread that holds the claim. if (pThread == m_pClaimHolder) { rbHeld = false; // Decrement the claim. if (m_sHolderClaim.decrementIsZero ()) { // Claim was last remaining claim for this cohort. Claim::Pointer pBlockedClaim; if (m_pBlockedClaims.interlockedPop (pBlockedClaim, &Claim::m_pCohortLink)) { // There's another thread waiting for this cohort. // Hand this cohort to said thread and wake it up. m_pClaimHolder.setTo (pBlockedClaim->thread ()); // Hand-off m_pClaimHolder->signal (); // Wake-up } else { // There's no other thread waiting for this cohort. m_pClaimHolder.clear (); // Clear claim. startEventMonitor (); // Start event monitor for the newly released cohort. } } } } void Vca::VCohort::onReleaseSignal (Claim *pClaim) { m_pBlockedClaims.interlockedPush (pClaim, &Claim::m_pCohortLink); } /****************************** ****************************** ***** Event Management ***** ****************************** ******************************/ void Vca::VCohort::schedule (Message *pMessage) { if (m_iMessageQueue.enqueue (pMessage)) startEventMonitor (); else postInterrupt (); } #ifdef __VMS #define Workaround #endif bool Vca::VCohort::attach (Manager *pManager) { #ifdef Workaround bool bThis = this != 0; bool bAttached = bThis && m_pManager.interlockedSetIfNil (pManager); if (bAttached) { #else if (m_pManager.interlockedSetIfNil (pManager)) { #endif m_pManager->onCohortEvent (); return true; } return false; } bool Vca::VCohort::detach (Manager *pManager) { return m_pManager.interlockedClearIf (pManager); } bool Vca::VCohort::attach (VDeviceManager *pDeviceManager) { return pDeviceManager && pDeviceManager->memberOf (this) && m_pDeviceManager.setIfNil (pDeviceManager); } bool Vca::VCohort::detach (VDeviceManager *pDeviceManager) { return m_pDeviceManager.clearIf (pDeviceManager); } bool Vca::VCohort::attach (VTimer *pTimer) { if (!pTimer || !pTimer->memberOf (this) || !pTimer->attach (m_pPendingTimers)) return false; if (0 == m_cPendingTimers++) startEventMonitor (); else postInterrupt (); return true; } bool Vca::VCohort::detach (VTimer *pTimer) { if (!pTimer || !pTimer->memberOf (this) || !pTimer->detach (m_pPendingTimers)) return false; m_cPendingTimers.decrement (); postInterrupt (); return true; } bool Vca::VCohort::needsTending () const { return m_iMessageQueue.isntEmpty () || hasPrimaryTimers () || ( m_pDeviceManager && m_pDeviceManager->hasUses () ); } void Vca::VCohort::onEmptyCohort () { if (m_pManager) m_pManager->onEmptyCohort (); } void Vca::VCohort::start_(VMessage *pMessage) { schedule (pMessage); } void Vca::VCohort::startEventMonitor () { if (m_pManager) // We have a cohort manager. Let it know that we have an event to process. m_pManager->onCohortEvent (); else if (m_sHolderClaim.isntZero () || m_cProcessorRequests.isntZero () || doesntNeedTending ()) // We _don't_ have a cohort manager and we can't start a new thread. Let's fire an interrupt on our device manager to make sure that we have everything we should from it. This is necessary when two startEventMonitor() invocations have started in separate threads simultaneously, and one has gotten to processing events first. postInterrupt (); // race avoidance else if (!g_bHalted) { // We're not claimed, we haven't tried to start a new thread, there's work to be done and we're not halted. We can start a new thread. ProcessorRequest iRequest (this); if (g_pProcessor.isNil ()) { Processor::Reference pProcessor (new Processor ()); if (g_pProcessor.interlockedSetIfNil (pProcessor)) g_pProcessorToo = pProcessor; } g_pProcessor->process (iRequest); } } /****************************** ****************************** ***** Event Processing ***** ****************************** ******************************/ void Vca::VCohort::decrementProcessorRequestCount () { if (m_cProcessorRequests.decrementIsZero ()) { startEventMonitor (); } } bool Vca::VCohort::postInterrupt () { return m_pDeviceManager && m_pDeviceManager->postInterrupt (); } bool Vca::VCohort::processEvents (Manager *pEM, size_t sTimeout, bool &rbEventsProcessed) { if (!pEM) defaultLogger().printf ("+++ Vca::VCohort[%p]::processEvents: NO EVENT MANAGER\n", this); rbEventsProcessed = false; // Clean up zombies, ... #if !defined(_WIN32) && !defined(__VMS) int childStatus; while (waitpid (0, &childStatus, WNOHANG) > 0); #endif // ... drain the message and output queues, ... count_t const cMessages = m_iMessageQueue.enqueueCount () - m_iMessageQueue.dequeueCount (); drainQueues (); // ... adjust the initial timeout for timers and event manager information, ... sTimeout = m_pPendingTimers ? m_pPendingTimers->adjustedTimeout (sTimeout) : sTimeout; sTimeout = pEM ? pEM->adjustedTimeout (sTimeout) : sTimeout; // ... and process any external events that come our way: bool bExternalSources = false; if (ShutdownCalled ()) { defaultLogger().printf ( "+++ VCohort[%p]::processEvents: Shutting down with %s device manager, I/O count: %u, timer count: %u, message count: %u, %ums timeout%s.\n", this, m_pDeviceManager ? "a" : "no", m_pDeviceManager ? m_pDeviceManager->useCount () : 0, m_cPendingTimers.value (), cMessages, sTimeout, isVca () ? " (Vca)" : "" ); for (VTimer::Reference pTimer (m_pPendingTimers); pTimer; pTimer.setTo (pTimer->m_pSuccessor)) { defaultLogger().printf ( " Timer[%p]: TTE: %7.3g seconds, Purpose: %s\n", pTimer.referent (), static_cast<double>(pTimer->timeToExpire ()) / 1e6, pTimer->purpose ().content () ); } } if (EventsDisabled (sTimeout, m_tLastEvent)) { defaultLogger().printf ( "+++ VCohort[%p]::processEvents: Events disabled with %s device manager, I/O count: %u, timer count: %u, message count: %u, %ums timeout%s.\n", this, m_pDeviceManager ? "a" : "no", m_pDeviceManager ? m_pDeviceManager->useCount () : 0, m_cPendingTimers.value (), cMessages, sTimeout, isVca () ? " (Vca)" : "" ); for (VTimer::Reference pTimer (m_pPendingTimers); pTimer; pTimer.setTo (pTimer->m_pSuccessor)) { defaultLogger().printf ( " Timer[%p]: TTE: %7.3g seconds, Purpose: %s\n", pTimer.referent (), static_cast<double>(pTimer->timeToExpire ()) / 1e6, pTimer->purpose ().content () ); } } else if (sTimeout > 0 || (s_bDeviceManagerPollEnabled && m_pDeviceManager.isntNil () && m_pDeviceManager->hasUses ())) { VDeviceManager::Reference pDM (m_pDeviceManager); if (pDM.isNil ()) { // If there are no primary timers (no timers or we're shutting down), ... if (pEM && !hasPrimaryTimers ()) // ... let the event manager trim the timeout: sTimeout = pEM ? pEM->adjustedTimeoutNDM (sTimeout) : 0; // The context for ignoring the event manager when there are // timers is that the timers have already set the timeout // to the time the next timer is due to fire. Absent other // sources of events, trimming the timeout further (which is // what the default implementation of 'adjustedTimeoutNDM' // does) will just put us into CPU looping land. If there // are no timers or other sources of events, however, the // value of 'sTimeout' is going to be the value passed to // this routine. That is almost certainly going to be // 'no timeout'. In that case, trimming the timeout is // mandatory. // If we still have a timeout, ... if (sTimeout > 0) { // ... create a device manager to process it, ... VDeviceManager::Supply (pDM, this); // ... drain our queues, ... drainQueues (); // ... and re-adjust the timeout for whatever timers and events where introduced by the drain: sTimeout = m_pPendingTimers ? m_pPendingTimers->adjustedTimeout (sTimeout) : sTimeout; sTimeout = pEM ? pEM->adjustedTimeout (sTimeout) : sTimeout; } } bExternalSources = ( pDM && pDM->processEvents (sTimeout, rbEventsProcessed) ) || hasPrimaryTimers (); if (triggerTimers ()) rbEventsProcessed = true; bool bEventsProcessed = false; do { if (bEventsProcessed) rbEventsProcessed = true; drainQueues (); } while (pDM && pDM->processEvents (0, bEventsProcessed) && bEventsProcessed); if (rbEventsProcessed) { bExternalSources = true; m_tLastEvent.setToNow (); } } else if (hasTimers ()) { bExternalSources = timersArePrimary (); rbEventsProcessed = triggerTimers (); } return bExternalSources; } /**************************************** **************************************** ***** Event Processing Utilities ***** **************************************** ****************************************/ void Vca::VCohort::drainMessageQueue () { if (m_iMessageQueue.isntEmpty ()) do { MessageReference pMessage (m_iMessageQueue.head ()); pMessage->run (); } while (m_iMessageQueue.dequeueAndTest ()); } void Vca::VCohort::drainOutputQueue () { VBSConsumer::PutBufferedData (); } void Vca::VCohort::drainQueues () { do { drainMessageQueue (); drainOutputQueue (); } while (m_iMessageQueue.isntEmpty ()); } bool Vca::VCohort::triggerTimers () { bool bAtLeastOneThatFired = false; while (m_pPendingTimers && m_pPendingTimers->triggerIfExpired ()) { bAtLeastOneThatFired = true; } return bAtLeastOneThatFired; }
#include "Base.h" #include "Effect.h" #include "FileSystem.h" #include "Game.h" #define OPENGL_ES_DEFINE "OPENGL_ES" namespace gameplay { // Cache of unique effects. static std::map<std::string, Effect*> __effectCache; static Effect* __currentEffect = NULL; Effect::Effect() : _program(0) { } Effect::~Effect() { // Remove this effect from the cache. __effectCache.erase(_id); // Free uniforms. for (std::map<std::string, Uniform*>::iterator itr = _uniforms.begin(); itr != _uniforms.end(); ++itr) { SAFE_DELETE(itr->second); } if (_program) { // If our program object is currently bound, unbind it before we're destroyed. if (__currentEffect == this) { GPRHI_ASSERT( GPRHI_UseProgram(0) ); __currentEffect = NULL; } GPRHI_ASSERT( GPRHI_DeleteProgram(_program) ); _program = 0; } } Effect* Effect::createFromFile(const char* vshPath, const char* fshPath, const char* defines) { GP_ASSERT(vshPath); GP_ASSERT(fshPath); // Search the effect cache for an identical effect that is already loaded. std::string uniqueId = vshPath; uniqueId += ';'; uniqueId += fshPath; uniqueId += ';'; if (defines) { uniqueId += defines; } std::map<std::string, Effect*>::const_iterator itr = __effectCache.find(uniqueId); if (itr != __effectCache.end()) { // Found an exiting effect with this id, so increase its ref count and return it. GP_ASSERT(itr->second); itr->second->addRef(); return itr->second; } // Read source from file. char* vshSource = FileSystem::readAll(vshPath); if (vshSource == NULL) { GP_ERROR("Failed to read vertex shader from file '%s'.", vshPath); return NULL; } char* fshSource = FileSystem::readAll(fshPath); if (fshSource == NULL) { GP_ERROR("Failed to read fragment shader from file '%s'.", fshPath); SAFE_DELETE_ARRAY(vshSource); return NULL; } Effect* effect = createFromSource(vshPath, vshSource, fshPath, fshSource, defines); SAFE_DELETE_ARRAY(vshSource); SAFE_DELETE_ARRAY(fshSource); if (effect == NULL) { GP_ERROR("Failed to create effect from shaders '%s', '%s'.", vshPath, fshPath); } else { // Store this effect in the cache. effect->_id = uniqueId; __effectCache[uniqueId] = effect; } return effect; } Effect* Effect::createFromSource(const char* vshSource, const char* fshSource, const char* defines) { return createFromSource(NULL, vshSource, NULL, fshSource, defines); } static void replaceDefines(const char* defines, std::string& out) { Properties* graphicsConfig = Game::getInstance()->getConfig()->getNamespace("graphics", true); const char* GPRHI_obalDefines = graphicsConfig ? graphicsConfig->getString("shaderDefines") : NULL; // Build full semicolon delimited list of defines #ifdef OPENGL_ES out = OPENGL_ES_DEFINE; #else out = ""; #endif if (GPRHI_obalDefines && strlen(GPRHI_obalDefines) > 0) { if (out.length() > 0) out += ';'; out += GPRHI_obalDefines; } if (defines && strlen(defines) > 0) { if (out.length() > 0) out += ';'; out += defines; } // Replace semicolons if (out.length() > 0) { size_t pos; out.insert(0, "#define "); while ((pos = out.find(';')) != std::string::npos) { out.replace(pos, 1, "\n#define "); } out += "\n"; } } static void replaceIncludes(const char* filepath, const char* source, std::string& out) { // Replace the #include "xxxx.xxx" with the sourced file contents of "filepath/xxxx.xxx" std::string str = source; size_t lastPos = 0; size_t headPos = 0; size_t fileLen = str.length(); size_t tailPos = fileLen; while (headPos < fileLen) { lastPos = headPos; if (headPos == 0) { // find the first "#include" headPos = str.find("#include"); } else { // find the next "#include" headPos = str.find("#include", headPos + 1); } // If "#include" is found if (headPos != std::string::npos) { // append from our last position for the legth (head - last position) out.append(str.substr(lastPos, headPos - lastPos)); // find the start quote " size_t startQuote = str.find("\"", headPos) + 1; if (startQuote == std::string::npos) { // We have started an "#include" but missing the leading quote " GP_ERROR("Compile failed for shader '%s' missing leading \".", filepath); return; } // find the end quote " size_t endQuote = str.find("\"", startQuote); if (endQuote == std::string::npos) { // We have a start quote but missing the trailing quote " GP_ERROR("Compile failed for shader '%s' missing trailing \".", filepath); return; } // jump the head position past the end quote headPos = endQuote + 1; // File path to include and 'stitch' in the value in the quotes to the file path and source it. std::string filepathStr = filepath; std::string directoryPath = filepathStr.substr(0, filepathStr.rfind('/') + 1); size_t len = endQuote - (startQuote); std::string includeStr = str.substr(startQuote, len); directoryPath.append(includeStr); const char* includedSource = FileSystem::readAll(directoryPath.c_str()); if (includedSource == NULL) { GP_ERROR("Compile failed for shader '%s' invalid filepath.", filepathStr.c_str()); return; } else { // Valid file so lets attempt to see if we need to append anything to it too (recurse...) replaceIncludes(directoryPath.c_str(), includedSource, out); SAFE_DELETE_ARRAY(includedSource); } } else { // Append the remaining out.append(str.c_str(), lastPos, tailPos); } } } static void writeShaderToErrorFile(const char* filePath, const char* source) { std::string path = filePath; path += ".err"; std::unique_ptr<Stream> stream(FileSystem::open(path.c_str(), FileSystem::WRITE)); if (stream.get() != NULL && stream->canWrite()) { stream->write(source, 1, strlen(source)); } } Effect* Effect::createFromSource(const char* vshPath, const char* vshSource, const char* fshPath, const char* fshSource, const char* defines) { GP_ASSERT(vshSource); GP_ASSERT(fshSource); const unsigned int SHADER_SOURCE_LENGTH = 3; const gp_char* shaderSource[SHADER_SOURCE_LENGTH]; char* infoLog = NULL; gp_uint vertexShader; gp_uint fragmentShader; gp_uint program; gp_int length; gp_int success; // Replace all comma separated definitions with #define prefix and \n suffix std::string definesStr = ""; replaceDefines(defines, definesStr); shaderSource[0] = definesStr.c_str(); shaderSource[1] = "\n"; std::string vshSourceStr = ""; if (vshPath) { // Replace the #include "xxxxx.xxx" with the sources that come from file paths replaceIncludes(vshPath, vshSource, vshSourceStr); if (vshSource && strlen(vshSource) != 0) vshSourceStr += "\n"; } shaderSource[2] = vshPath ? vshSourceStr.c_str() : vshSource; GPRHI_ASSERT( vertexShader = GPRHI_CreateShader(GP_RHI_VERTEX_SHADER) ); GPRHI_ASSERT( GPRHI_ShaderSource(vertexShader, SHADER_SOURCE_LENGTH, shaderSource, NULL) ); GPRHI_ASSERT( GPRHI_CompileShader(vertexShader) ); GPRHI_ASSERT( GPRHI_GetShaderiv(vertexShader, GP_RHI_SHADER_GET_COMPILE_STATUS, &success) ); if (success != GP_TRUE) { GPRHI_ASSERT( GPRHI_GetShaderiv(vertexShader, GP_RHI_SHADER_GET_INFO_LOG_LENGTH, &length) ); if (length == 0) { length = 4096; } if (length > 0) { infoLog = new char[length]; GPRHI_ASSERT( GPRHI_GetShaderInfoLog(vertexShader, length, NULL, infoLog) ); infoLog[length-1] = '\0'; } // Write out the expanded shader file. if (vshPath) writeShaderToErrorFile(vshPath, shaderSource[2]); GP_ERROR("Compile failed for vertex shader '%s' with error '%s'.", vshPath == NULL ? vshSource : vshPath, infoLog == NULL ? "" : infoLog); SAFE_DELETE_ARRAY(infoLog); // Clean up. GPRHI_ASSERT( GPRHI_DeleteShader(vertexShader) ); return NULL; } // Compile the fragment shader. std::string fshSourceStr; if (fshPath) { // Replace the #include "xxxxx.xxx" with the sources that come from file paths replaceIncludes(fshPath, fshSource, fshSourceStr); if (fshSource && strlen(fshSource) != 0) fshSourceStr += "\n"; } shaderSource[2] = fshPath ? fshSourceStr.c_str() : fshSource; GPRHI_ASSERT( fragmentShader = GPRHI_CreateShader(GP_RHI_PIXEL_SHADER) ); GPRHI_ASSERT( GPRHI_ShaderSource(fragmentShader, SHADER_SOURCE_LENGTH, shaderSource, NULL) ); GPRHI_ASSERT( GPRHI_CompileShader(fragmentShader) ); GPRHI_ASSERT( GPRHI_GetShaderiv(fragmentShader, GP_RHI_SHADER_GET_COMPILE_STATUS, &success) ); if (success != GP_TRUE) { GPRHI_ASSERT( GPRHI_GetShaderiv(fragmentShader, GP_RHI_SHADER_GET_INFO_LOG_LENGTH, &length) ); if (length == 0) { length = 4096; } if (length > 0) { infoLog = new char[length]; GPRHI_ASSERT( GPRHI_GetShaderInfoLog(fragmentShader, length, NULL, infoLog) ); infoLog[length-1] = '\0'; } // Write out the expanded shader file. if (fshPath) writeShaderToErrorFile(fshPath, shaderSource[2]); GP_ERROR("Compile failed for fragment shader (%s): %s", fshPath == NULL ? fshSource : fshPath, infoLog == NULL ? "" : infoLog); SAFE_DELETE_ARRAY(infoLog); // Clean up. GPRHI_ASSERT( GPRHI_DeleteShader(vertexShader) ); GPRHI_ASSERT( GPRHI_DeleteShader(fragmentShader) ); return NULL; } // Link program. GPRHI_ASSERT( program = GPRHI_CreateProgram() ); GPRHI_ASSERT( GPRHI_AttachShader(program, vertexShader) ); GPRHI_ASSERT( GPRHI_AttachShader(program, fragmentShader) ); GPRHI_ASSERT( GPRHI_LinkProgram(program) ); GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_LINK_STATUS, &success) ); // Delete shaders after linking. GPRHI_ASSERT( GPRHI_DeleteShader(vertexShader) ); GPRHI_ASSERT( GPRHI_DeleteShader(fragmentShader) ); // Check link status. if (success != GP_TRUE) { GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_INFO_LOG_LENGTH, &length) ); if (length == 0) { length = 4096; } if (length > 0) { infoLog = new char[length]; GPRHI_ASSERT( GPRHI_GetProgramInfoLog(program, length, NULL, infoLog) ); infoLog[length-1] = '\0'; } GP_ERROR("Linking program failed (%s,%s): %s", vshPath == NULL ? "NULL" : vshPath, fshPath == NULL ? "NULL" : fshPath, infoLog == NULL ? "" : infoLog); SAFE_DELETE_ARRAY(infoLog); // Clean up. GPRHI_ASSERT( GPRHI_DeleteProgram(program) ); return NULL; } // Create and return the new Effect. Effect* effect = new Effect(); effect->_program = program; // Query and store vertex attribute meta-data from the program. // NOTE: Rather than using GPRHI_BindAttribLocation to explicitly specify our own // preferred attribute locations, we're going to query the locations that were // automatically bound by the GPU. While it can sometimes be convenient to use // GPRHI_BindAttribLocation, some vendors actually reserve certain attribute indices // and therefore using this function can create compatibility issues between // different hardware vendors. gp_int activeAttributes; GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_ACTIVE_ATTRIBUTES, &activeAttributes) ); if (activeAttributes > 0) { GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_ACTIVE_ATTRIBUTE_MAX_LENGTH, &length) ); if (length > 0) { gp_char* attribName = new gp_char[length + 1]; gp_int attribSize; gp_enum attribType; gp_int attribLocation; for (int i = 0; i < activeAttributes; ++i) { // Query attribute info. GPRHI_ASSERT( GPRHI_GetActiveAttrib(program, i, length, NULL, &attribSize, &attribType, attribName) ); attribName[length] = '\0'; // Query the pre-assigned attribute location. GPRHI_ASSERT( attribLocation = GPRHI_GetAttribLocation(program, attribName) ); // Assign the vertex attribute mapping for the effect. effect->_vertexAttributes[attribName] = attribLocation; } SAFE_DELETE_ARRAY(attribName); } } // Query and store uniforms from the program. gp_int activeUniforms; GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_ACTIVE_UNIFORMS, &activeUniforms) ); if (activeUniforms > 0) { GPRHI_ASSERT( GPRHI_GetProgramiv(program, GP_RHI_SHADER_GET_ACTIVE_UNIFORM_MAX_LENGTH, &length) ); if (length > 0) { gp_char* uniformName = new gp_char[length + 1]; gp_int uniformSize; gp_enum uniformType; gp_int uniformLocation; unsigned int samplerIndex = 0; for (int i = 0; i < activeUniforms; ++i) { // Query uniform info. GPRHI_ASSERT( GPRHI_GetActiveUniform(program, i, length, NULL, &uniformSize, &uniformType, uniformName) ); uniformName[length] = '\0'; // null terminate if (length > 3) { // If this is an array uniform, strip array indexers off it since GL does not // seem to be consistent across different drivers/implementations in how it returns // array uniforms. On some systems it will return "u_matrixArray", while on others // it will return "u_matrixArray[0]". char* c = strrchr(uniformName, '['); if (c) { *c = '\0'; } } // Query the pre-assigned uniform location. GPRHI_ASSERT( uniformLocation = GPRHI_GetUniformLocation(program, uniformName) ); Uniform* uniform = new Uniform(); uniform->_effect = effect; uniform->_name = uniformName; uniform->_location = uniformLocation; uniform->_type = uniformType; if (uniformType == GP_RHI_UNIFORM_SAMPLER_2D || uniformType == GP_RHI_UNIFORM_SAMPLER_CUBE) { uniform->_index = samplerIndex; samplerIndex += uniformSize; } else { uniform->_index = 0; } effect->_uniforms[uniformName] = uniform; } SAFE_DELETE_ARRAY(uniformName); } } return effect; } const char* Effect::getId() const { return _id.c_str(); } VertexAttribute Effect::getVertexAttribute(const char* name) const { std::map<std::string, VertexAttribute>::const_iterator itr = _vertexAttributes.find(name); return (itr == _vertexAttributes.end() ? -1 : itr->second); } Uniform* Effect::getUniform(const char* name) const { std::map<std::string, Uniform*>::const_iterator itr = _uniforms.find(name); if (itr != _uniforms.end()) { // Return cached uniform variable return itr->second; } gp_int uniformLocation; GPRHI_ASSERT( uniformLocation = GPRHI_GetUniformLocation(_program, name) ); if (uniformLocation > -1) { // Check for array uniforms ("u_directionalLightColor[0]" -> "u_directionalLightColor") char* parentname = new char[strlen(name)+1]; strcpy(parentname, name); if (strtok(parentname, "[") != NULL) { std::map<std::string, Uniform*>::const_iterator itr = _uniforms.find(parentname); if (itr != _uniforms.end()) { Uniform* puniform = itr->second; Uniform* uniform = new Uniform(); uniform->_effect = const_cast<Effect*>(this); uniform->_name = name; uniform->_location = uniformLocation; uniform->_index = 0; uniform->_type = puniform->getType(); _uniforms[name] = uniform; SAFE_DELETE_ARRAY(parentname); return uniform; } } SAFE_DELETE_ARRAY(parentname); } // No uniform variable found - return NULL return NULL; } Uniform* Effect::getUniform(unsigned int index) const { unsigned int i = 0; for (std::map<std::string, Uniform*>::const_iterator itr = _uniforms.begin(); itr != _uniforms.end(); ++itr, ++i) { if (i == index) { return itr->second; } } return NULL; } unsigned int Effect::getUniformCount() const { return (unsigned int)_uniforms.size(); } void Effect::setValue(Uniform* uniform, float value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_Uniform1f(uniform->_location, value) ); } void Effect::setValue(Uniform* uniform, const float* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_Uniform1fv(uniform->_location, count, values) ); } void Effect::setValue(Uniform* uniform, int value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_Uniform1i(uniform->_location, value) ); } void Effect::setValue(Uniform* uniform, const int* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_Uniform1iv(uniform->_location, count, values) ); } void Effect::setValue(Uniform* uniform, const Matrix& value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_UniformMatrix4fv(uniform->_location, 1, GP_FALSE, value.m) ); } void Effect::setValue(Uniform* uniform, const Matrix* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_UniformMatrix4fv(uniform->_location, count, GP_FALSE, (gp_float*)values) ); } void Effect::setValue(Uniform* uniform, const Vector2& value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_Uniform2f(uniform->_location, value.x, value.y) ); } void Effect::setValue(Uniform* uniform, const Vector2* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_Uniform2fv(uniform->_location, count, (gp_float*)values) ); } void Effect::setValue(Uniform* uniform, const Vector3& value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_Uniform3f(uniform->_location, value.x, value.y, value.z) ); } void Effect::setValue(Uniform* uniform, const Vector3* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_Uniform3fv(uniform->_location, count, (gp_float*)values) ); } void Effect::setValue(Uniform* uniform, const Vector4& value) { GP_ASSERT(uniform); GPRHI_ASSERT( GPRHI_Uniform4f(uniform->_location, value.x, value.y, value.z, value.w) ); } void Effect::setValue(Uniform* uniform, const Vector4* values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(values); GPRHI_ASSERT( GPRHI_Uniform4fv(uniform->_location, count, (gp_float*)values) ); } void Effect::setValue(Uniform* uniform, const Texture::Sampler* sampler) { GP_ASSERT(uniform); GP_ASSERT(uniform->_type == GP_RHI_UNIFORM_SAMPLER_2D || uniform->_type == GP_RHI_UNIFORM_SAMPLER_CUBE); GP_ASSERT(sampler); GP_ASSERT((sampler->getTexture()->getType() == Texture::TEXTURE_2D && uniform->_type == GP_RHI_UNIFORM_SAMPLER_2D) || (sampler->getTexture()->getType() == Texture::TEXTURE_CUBE && uniform->_type == GP_RHI_UNIFORM_SAMPLER_CUBE)); GPRHI_ASSERT( GPRHI_ActiveTexture(GP_RHI_TEXTURE_SLOT_0 + uniform->_index) ); // Bind the sampler - this binds the texture and applies sampler state const_cast<Texture::Sampler*>(sampler)->bind(); GPRHI_ASSERT( GPRHI_Uniform1i(uniform->_location, uniform->_index) ); } void Effect::setValue(Uniform* uniform, const Texture::Sampler** values, unsigned int count) { GP_ASSERT(uniform); GP_ASSERT(uniform->_type == GP_RHI_UNIFORM_SAMPLER_2D || uniform->_type == GP_RHI_UNIFORM_SAMPLER_CUBE); GP_ASSERT(values); // Set samplers as active and load texture unit array gp_int units[32]; for (unsigned int i = 0; i < count; ++i) { GP_ASSERT((const_cast<Texture::Sampler*>(values[i])->getTexture()->getType() == Texture::TEXTURE_2D && uniform->_type == GP_RHI_UNIFORM_SAMPLER_2D) || (const_cast<Texture::Sampler*>(values[i])->getTexture()->getType() == Texture::TEXTURE_CUBE && uniform->_type == GP_RHI_UNIFORM_SAMPLER_CUBE)); GPRHI_ASSERT( GPRHI_ActiveTexture(GP_RHI_TEXTURE_SLOT_0 + uniform->_index + i) ); // Bind the sampler - this binds the texture and applies sampler state const_cast<Texture::Sampler*>(values[i])->bind(); units[i] = uniform->_index + i; } // Pass texture unit array to GL GPRHI_ASSERT( GPRHI_Uniform1iv(uniform->_location, count, units) ); } void Effect::bind() { GPRHI_ASSERT( GPRHI_UseProgram(_program) ); __currentEffect = this; } Effect* Effect::getCurrentEffect() { return __currentEffect; } Uniform::Uniform() : _location(-1), _type(0), _index(0), _effect(NULL) { } Uniform::~Uniform() { // hidden } Effect* Uniform::getEffect() const { return _effect; } const char* Uniform::getName() const { return _name.c_str(); } const gp_enum Uniform::getType() const { return _type; } }
/* * @file eeprom.cpp * @author Mikhail Ezhov <ezhov93@gmail.com> * @brief EEPROM source file. */ #include "eeprom.h" #include "MDR32F9Qx_eeprom.h" #include "MDR32F9Qx_rst_clk.h" void Eeprom::begin(Bank blank) { _bank = blank; uint32_t cpu = SystemCoreClock / 1e6; RST_CLK_PCLKcmd(RST_CLK_PCLK_EEPROM, ENABLE); if (cpu < 25) EEPROM_SetLatency(EEPROM_Latency_0); else if (cpu < 50) EEPROM_SetLatency(EEPROM_Latency_1); else if (cpu < 75) EEPROM_SetLatency(EEPROM_Latency_2); else if (cpu < 100) EEPROM_SetLatency(EEPROM_Latency_3); else if (cpu < 125) EEPROM_SetLatency(EEPROM_Latency_4); else if (cpu < 150) EEPROM_SetLatency(EEPROM_Latency_5); else EEPROM_SetLatency(EEPROM_Latency_6); } void Eeprom::begin() { begin(_bank); } __RAMFUNC void Eeprom::format(void) { __disable_irq(); EEPROM_EraseAllPages(_bank); __enable_irq(); } __RAMFUNC void Eeprom::erase(Page page) { const uint32_t address = pageToAddress(page); __disable_irq(); EEPROM_ErasePage(address, _bank); __enable_irq(); } bool Eeprom::isEmpty() const { uint32_t size; switch (_bank) { case MainBank: case AllBanks: size = NumberPagesOfMainBank; break; case InfoBank: size = NumberPagesOfInfoBank; break; } for (uint32_t page = Page0; page < size; ++page) if (!isEmpty((Page)page)) return false; return true; } bool Eeprom::isEmpty(Page page) const { const uint32_t beginPageAddress = pageToAddress(page); const uint32_t endPageAddress = beginPageAddress + PageSize; for (uint32_t cnt = beginPageAddress; cnt < endPageAddress; cnt += sizeof(uint32_t)) if (read(cnt) != PageEmpty) return false; return true; } __RAMFUNC uint32_t Eeprom::read(uint32_t address) const { __disable_irq(); uint32_t data = EEPROM_ReadWord(address, _bank); __enable_irq(); return data; } __RAMFUNC void Eeprom::read(uint32_t address, void *data, int size) { uint32_t *data_ptr = (uint32_t *)data; for (uint32_t cnt = 0; cnt < size; cnt += 4) if (cnt < NumberDWordOfPages) *data_ptr++ = read(address + cnt); } __RAMFUNC void Eeprom::write(uint32_t address, uint32_t data) { __disable_irq(); erase(addressToPage(address)); EEPROM_ProgramWord(address, _bank, data); __enable_irq(); } __RAMFUNC void Eeprom::write(uint32_t address, void *data, int size) { uint32_t *data_ptr = (uint32_t *)data; __disable_irq(); erase(addressToPage(address)); for (uint32_t cnt = 0; cnt < size; cnt += 4) if (cnt < NumberDWordOfPages) EEPROM_ProgramWord(address + cnt, _bank, *data_ptr++); __enable_irq(); } uint32_t Eeprom::pageToAddress(Page page) { return page << 12; } Eeprom::Page Eeprom::addressToPage(uint32_t address) { return (Page)((address & PageMask) >> 12); } /* void Eeprom::update(uint32 address, uint32 data) { const uint32 beginPageAddr = address&PAGE_MASK; const uint32 page = ADDRESS_TO_PAGE(address); uint32 array[NUMBER_DWORD_OF_PAGE]; read(address, array, PAGE_SIZE); array[address&(~PAGE_MASK)] = data; erase((Page)page); write(beginPageAddr, array, PAGE_SIZE); } void Eeprom::update(uint32 address, void* data, int size) { const uint32 beginPageAddr = address&PAGE_MASK; const uint32 endPageAddr = (address+size)&PAGE_MASK; const uint32 beginPage = ADDRESS_TO_PAGE(beginPageAddr); const uint32 endPage = ADDRESS_TO_PAGE(endPageAddr) const int numberOfPages = endPage-beginPage; uint32 array[NUMBER_DWORD_OF_PAGE]; for (uint32 page = beginPage; page<endPage; ++page) { const uint32 beginUpdateAddr = add read(address, array, PAGE_SIZE); erase((Page)page); format() write(); } } */
#ifndef TCLOBJECT_HH #define TCLOBJECT_HH #include "string_view.hh" #include "openmsx.hh" #include "xxhash.hh" #include <tcl.h> #include <iterator> #include <cassert> struct Tcl_Obj; namespace openmsx { class Interpreter; class TclObject { // For STL interface, see below struct iterator { iterator(const TclObject& obj_, unsigned i_) : obj(&obj_), i(i_) {} bool operator==(const iterator& other) const { assert(obj == other.obj); return i == other.i; } bool operator!=(const iterator& other) const { return !(*this == other); } string_view operator*() const { return obj->getListIndexUnchecked(i).getString(); } iterator& operator++() { ++i; return *this; } iterator operator++(int) { iterator result = *this; ++result; return result; } iterator& operator--() { --i; return *this; } iterator operator--(int) { iterator result = *this; --result; return result; } private: const TclObject* obj; unsigned i; }; public: TclObject() { init(Tcl_NewObj()); } explicit TclObject(Tcl_Obj* o) { init(o); } explicit TclObject(string_view v) { init(Tcl_NewStringObj(v.data(), int(v.size()))); } explicit TclObject(int v) { init(Tcl_NewIntObj(v)); } explicit TclObject(double v) { init(Tcl_NewDoubleObj(v)); } TclObject(const TclObject& o) { init(o.obj); } TclObject( TclObject&& o) noexcept { init(o.obj); } ~TclObject() { Tcl_DecrRefCount(obj); } // assignment operator so we can use vector<TclObject> TclObject& operator=(const TclObject& other) { if (&other != this) { Tcl_DecrRefCount(obj); init(other.obj); } return *this; } TclObject& operator=(TclObject&& other) noexcept { std::swap(obj, other.obj); return *this; } // get underlying Tcl_Obj Tcl_Obj* getTclObject() { return obj; } Tcl_Obj* getTclObjectNonConst() const { return const_cast<Tcl_Obj*>(obj); } // value setters void setString(string_view value); void setInt(int value); void setBoolean(bool value); void setDouble(double value); void setBinary(byte* buf, unsigned length); void addListElement(string_view element); void addListElement(int value); void addListElement(double value); void addListElement(const TclObject& element); template<typename ITER> void addListElements(ITER first, ITER last); template<typename Range> void addListElements(Range&& range); // value getters string_view getString() const; int getInt (Interpreter& interp) const; bool getBoolean (Interpreter& interp) const; double getDouble(Interpreter& interp) const; const byte* getBinary(unsigned& length) const; unsigned getListLength(Interpreter& interp) const; TclObject getListIndex(Interpreter& interp, unsigned index) const; TclObject getDictValue(Interpreter& interp, const TclObject& key) const; // STL-like interface when interpreting this TclObject as a list of // strings. Invalid Tcl lists are silently interpreted as empty lists. unsigned size() const { return getListLengthUnchecked(); } bool empty() const { return size() == 0; } auto begin() const { return iterator(*this, 0); } auto end() const { return iterator(*this, size()); } // expressions bool evalBool(Interpreter& interp) const; /** Interpret this TclObject as a command and execute it. * @param interp The Tcl interpreter * @param compile Should the command be compiled to bytecode? The * bytecode is stored inside the TclObject can speed up * future invocations of the same command. Only set this * flag when the command will be executed more than once. */ TclObject executeCommand(Interpreter& interp, bool compile = false); friend bool operator==(const TclObject& x, const TclObject& y) { return x.getString() == y.getString(); } friend bool operator==(const TclObject& x, string_view y) { return x.getString() == y; } friend bool operator==(string_view x, const TclObject& y) { return x == y.getString(); } friend bool operator!=(const TclObject& x, const TclObject& y) { return !(x == y); } friend bool operator!=(const TclObject& x, string_view y) { return !(x == y); } friend bool operator!=(string_view x, const TclObject& y) { return !(x == y); } private: void init(Tcl_Obj* obj_) noexcept { obj = obj_; Tcl_IncrRefCount(obj); } void addListElement(Tcl_Obj* element); unsigned getListLengthUnchecked() const; TclObject getListIndexUnchecked(unsigned index) const; Tcl_Obj* obj; }; template <typename ITER> void TclObject::addListElements(ITER first, ITER last) { for (ITER it = first; it != last; ++it) { addListElement(*it); } } template <typename Range> void TclObject::addListElements(Range&& range) { addListElements(std::begin(range), std::end(range)); } // We want to be able to reinterpret_cast a Tcl_Obj* as a TclObject. static_assert(sizeof(TclObject) == sizeof(Tcl_Obj*), ""); struct XXTclHasher { uint32_t operator()(string_view str) const { return xxhash(str); } uint32_t operator()(const TclObject& obj) const { return xxhash(obj.getString()); } }; } // namespace openmsx #endif
/** * Purpose: text file CSV input example, C++ style * Author: Emanuele Rizzolo * Class: 3XIN * Date: 2020/04/26 * Note: CSV stands for Comma Separated Values */ // directive for standard io functions #include <iostream> // directive for io manipulation #include <iomanip> // directive for file io functions #include <fstream> // directive for string io functions #include <sstream> // directive for string limits functions #include <limits> // directive for C-style string functions #include <cstring> using namespace std; #include "planet.h" #define DEBUG 1 const bool header = true; // whether to use an header line const char delim = '"'; // string delimiter (usually ") const char escape = '\\'; // escape character #define BUFFER_SIZE 100 bool readCSV(const char line[], planet &p) { static auto ignoreable = numeric_limits<streamsize>::max(); istringstream in(line); string name; in >> quoted(name, delim, escape); strcpy(p.name, name.c_str()); in.ignore(ignoreable, ',') >> p.mass; // ignore , and read in.ignore(ignoreable, ',') >> p.distance; // ignore , and read in.ignore(ignoreable, ',') >> p.inhabited; // ignore , and read in.ignore(ignoreable, ',') >> p.numSatellites; // ignore , and read return !(in.bad() || in.fail()); } // main function int main(int argc, char *argv[]) { char filename[] = "planets++.csv"; // open it for input // ifstream infile; // declaration // infile.open(filename); // open ifstream infile(filename); // automatic open with default open mode in // ifstream infile(filename, ios::in); // automatic open with explicit open mode in // check failure if (infile.is_open()) // or simply if(infile) { char line[BUFFER_SIZE]; if (header) { infile.ignore(numeric_limits<streamsize>::max(), '\n'); // skip header line } while (infile.getline(line, BUFFER_SIZE)) { if (DEBUG) { cout << line << endl; } planet p; if (readCSV(line, p)) { cout << p << endl; } } } else { cout << "failed to open file " << filename << endl; } // successful termination return 0; }
// Copyright 2021 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gmock/gmock.h" #include "src/writer/glsl/test_helper.h" namespace tint { namespace writer { namespace glsl { namespace { using ::testing::HasSubstr; using GlslGeneratorImplTest_Constructor = TestHelper; TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Bool) { WrapInFunction(Expr(false)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("false")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Int) { WrapInFunction(Expr(-12345)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("-12345")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_UInt) { WrapInFunction(Expr(56779u)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("56779u")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Float) { // Use a number close to 1<<30 but whose decimal representation ends in 0. WrapInFunction(Expr(static_cast<float>((1 << 30) - 4))); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("1073741824.0f")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Float) { WrapInFunction(Construct<f32>(-1.2e-5f)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("float(-0.000012f)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Bool) { WrapInFunction(Construct<bool>(true)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("bool(true)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Int) { WrapInFunction(Construct<i32>(-12345)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("int(-12345)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Uint) { WrapInFunction(Construct<u32>(12345u)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("uint(12345u)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec) { WrapInFunction(vec3<f32>(1.f, 2.f, 3.f)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("vec3(1.0f, 2.0f, 3.0f)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec_Empty) { WrapInFunction(vec3<f32>()); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("vec3(0.0f, 0.0f, 0.0f)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec_SingleScalar_Float) { WrapInFunction(vec3<f32>(2.0f)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("vec3((2.0f).xxx)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec_SingleScalar_Bool) { WrapInFunction(vec3<bool>(true)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("bvec3((true).xxx)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec_SingleScalar_Int) { WrapInFunction(vec3<i32>(2)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("ivec3((2).xxx)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Vec_SingleScalar_UInt) { WrapInFunction(vec3<u32>(2u)); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("uvec3((2u).xxx)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Mat) { WrapInFunction( mat2x3<f32>(vec3<f32>(1.f, 2.f, 3.f), vec3<f32>(3.f, 4.f, 5.f))); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT( gen.result(), HasSubstr("mat2x3(vec3(1.0f, 2.0f, 3.0f), vec3(3.0f, 4.0f, 5.0f))")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Mat_Empty) { WrapInFunction(mat2x3<f32>()); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("mat2x3(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f)")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Array) { WrapInFunction(Construct(ty.array(ty.vec3<f32>(), 3), vec3<f32>(1.f, 2.f, 3.f), vec3<f32>(4.f, 5.f, 6.f), vec3<f32>(7.f, 8.f, 9.f))); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("vec3[3](vec3(1.0f, 2.0f, 3.0f), " "vec3(4.0f, 5.0f, 6.0f), " "vec3(7.0f, 8.0f, 9.0f))")); } // TODO(bclayton): Zero-init arrays TEST_F(GlslGeneratorImplTest_Constructor, DISABLED_EmitConstructor_Type_Array_Empty) { WrapInFunction(Construct(ty.array(ty.vec3<f32>(), 3))); GeneratorImpl& gen = Build(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("{vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.0f)," " vec3(0.0f, 0.0f, 0.0f)}")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Struct) { auto* str = Structure("S", { Member("a", ty.i32()), Member("b", ty.f32()), Member("c", ty.vec3<i32>()), }); WrapInFunction(Construct(ty.Of(str), 1, 2.0f, vec3<i32>(3, 4, 5))); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("S(1, 2.0f, ivec3(3, 4, 5))")); } TEST_F(GlslGeneratorImplTest_Constructor, EmitConstructor_Type_Struct_Empty) { auto* str = Structure("S", { Member("a", ty.i32()), Member("b", ty.f32()), Member("c", ty.vec3<i32>()), }); WrapInFunction(Construct(ty.Of(str))); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); EXPECT_THAT(gen.result(), HasSubstr("S(0")); } } // namespace } // namespace glsl } // namespace writer } // namespace tint
// // Created by Robert David Hernandez on 3/29/20. // #include "State.h" State::State(int x, int y, double reward) : x(x), y(y), reward(reward) {} State::~State() { } int State::getX() const { return x; } void State::setX(int x) { State::x = x; } int State::getY() const { return y; } void State::setY(int y) { State::y = y; } double State::getReward() const { return reward; } void State::setReward(double reward) { State::reward = reward; } bool State::operator==(const State &rhs) const { return x == rhs.x && y == rhs.y; } bool State::operator!=(const State &rhs) const { return !(rhs == *this); } bool State::operator<(const State &rhs) const { if (x < rhs.x) return true; if (rhs.x < x) return false; return y < rhs.y; } bool State::operator>(const State &rhs) const { return rhs < *this; } bool State::operator<=(const State &rhs) const { return !(rhs < *this); } bool State::operator>=(const State &rhs) const { return !(*this < rhs); }
#pragma once #include <GLFW/glfw3.h> #include "hazel/renderer/graphics_context.hpp" #include "hazel/core/window.hpp" namespace hazel { class WindowsWindow : public Window { public: WindowsWindow(const WindowProps& props); virtual ~WindowsWindow(); void on_update() override; unsigned int width() const override { return data_.width; } unsigned int height() const override { return data_.height; } float content_scale_x() const override { return data_.content_scale_x; } float content_scale_y() const override { return data_.content_scale_y; } // Window attributes void set_event_callback(const EventCallbackFn& callback) override { data_.event_callback = callback; }; void set_vsync(bool enabled) override; bool is_vsync() const override; void* native_window() const override { return window_; } private: virtual void init(const WindowProps& props); virtual void shutdown(); GLFWwindow* window_; Scope<GraphicsContext> context_; struct WindowData { std::string title; unsigned int width, height; float content_scale_x, content_scale_y; bool vsync; EventCallbackFn event_callback; }; WindowData data_; }; } // namespace hazel
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: GameObject class GameObject; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: InstantiatePrefab class InstantiatePrefab : public UnityEngine::MonoBehaviour { public: // public UnityEngine.GameObject _prefab // Offset: 0x18 UnityEngine::GameObject* prefab; // protected System.Void Awake() // Offset: 0xCB7A48 void Awake(); // public System.Void .ctor() // Offset: 0xCB7B48 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static InstantiatePrefab* New_ctor(); }; // InstantiatePrefab } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::InstantiatePrefab*, "", "InstantiatePrefab"); #pragma pack(pop)
/* * Copyright (C) 2017 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #ifdef _MSC_VER #pragma warning(push, 0) #endif #include <ignition/msgs/stringmsg.pb.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <ignition/transport/Node.hh> #include <ignition/utilities/ExtraTestMacros.hh> #include "test_config.h" // NOLINT(build/include) #include "ignition/gui/Application.hh" #include "ignition/gui/Plugin.hh" #include "ignition/gui/MainWindow.hh" #include "Publisher.hh" int g_argc = 1; char **g_argv = new char *[g_argc]; using namespace ignition; using namespace gui; ///////////////////////////////////////////////// // See https://github.com/ignitionrobotics/ign-gui/issues/75 TEST(PublisherTest, IGN_UTILS_TEST_ENABLED_ONLY_ON_LINUX(Load)) { common::Console::SetVerbosity(4); Application app(g_argc, g_argv); app.AddPluginPath(std::string(PROJECT_BINARY_PATH) + "/lib"); EXPECT_TRUE(app.LoadPlugin("Publisher")); // Get main window auto win = app.findChild<MainWindow *>(); ASSERT_NE(nullptr, win); // Get plugin auto plugins = win->findChildren<Plugin *>(); EXPECT_EQ(plugins.size(), 1); auto plugin = plugins[0]; EXPECT_EQ(plugin->Title(), "Publisher"); // Cleanup plugins.clear(); } ///////////////////////////////////////////////// TEST(PublisherTest, IGN_UTILS_TEST_ENABLED_ONLY_ON_LINUX(Publish)) { common::Console::SetVerbosity(4); Application app(g_argc, g_argv); app.AddPluginPath(std::string(PROJECT_BINARY_PATH) + "/lib"); // Load plugin const char *pluginStr = "<plugin filename=\"Publisher\">" "<ignition-gui>" "<title>Publisher!</title>" "</ignition-gui>" "</plugin>"; tinyxml2::XMLDocument pluginDoc; EXPECT_EQ(tinyxml2::XML_SUCCESS, pluginDoc.Parse(pluginStr)); EXPECT_TRUE(app.LoadPlugin("Publisher", pluginDoc.FirstChildElement("plugin"))); // Get main window auto win = app.findChild<MainWindow *>(); ASSERT_NE(nullptr, win); // Show, but don't exec, so we don't block win->QuickWindow()->show(); // Get plugin auto plugins = win->findChildren<plugins::Publisher *>(); EXPECT_EQ(plugins.size(), 1); auto plugin = plugins[0]; EXPECT_EQ(plugin->Title(), "Publisher!"); // Message type EXPECT_EQ(plugin->MsgType(), "ignition.msgs.StringMsg"); // Message EXPECT_EQ(plugin->MsgData(), "data: \"Hello\""); // Topic EXPECT_EQ(plugin->Topic(), "/echo"); // Frequency EXPECT_DOUBLE_EQ(plugin->Frequency(), 1.0); // Subscribe bool received = false; std::function<void(const msgs::StringMsg &)> cb = [&](const msgs::StringMsg &_msg) { EXPECT_EQ(_msg.data(), "Hello"); received = true; }; transport::Node node; node.Subscribe("/echo", cb); EXPECT_FALSE(received); // Publish plugin->OnPublish(true); int sleep = 0; int maxSleep = 30; while (!received && sleep < maxSleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); QCoreApplication::processEvents(); sleep++; } EXPECT_TRUE(received); received = false; // Stop publishing plugin->OnPublish(false); sleep = 0; // cppcheck-suppress knownConditionTrueFalse while (!received && sleep < maxSleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); QCoreApplication::processEvents(); sleep++; } EXPECT_FALSE(received); // Publish once plugin->SetFrequency(0.0); plugin->OnPublish(true); sleep = 0; while (!received && sleep < maxSleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); QCoreApplication::processEvents(); sleep++; } EXPECT_TRUE(received); plugin->OnPublish(false); received = false; // Bad message type plugin->SetFrequency(1.0); plugin->SetMsgType("banana.message"); plugin->OnPublish(true); sleep = 0; // cppcheck-suppress knownConditionTrueFalse while (!received && sleep < maxSleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); QCoreApplication::processEvents(); sleep++; } EXPECT_FALSE(received); plugin->OnPublish(false); // Bad message type - msg combination plugin->SetMsgType("ignition.msgs.StringMsg"); plugin->SetMsgData("banana: apple"); plugin->OnPublish(true); sleep = 0; while (!received && sleep < maxSleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); QCoreApplication::processEvents(); sleep++; } EXPECT_FALSE(received); plugin->OnPublish(false); // Cleanup plugins.clear(); } ////////////////////////////////////////////////// TEST(PublisherTest, IGN_UTILS_TEST_ENABLED_ONLY_ON_LINUX(ParamsFromSDF)) { common::Console::SetVerbosity(4); Application app(g_argc, g_argv); app.AddPluginPath(std::string(PROJECT_BINARY_PATH) + "/lib"); // Load plugin const char *pluginStr = "<plugin filename=\"Publisher\">" "<topic>/fruit</topic>" "<message>number: 1 fruit {name:\"banana\"}</message>" "<message_type>ignition.msgs.Fruits</message_type>" "<frequency>0.1</frequency>" "</plugin>"; tinyxml2::XMLDocument pluginDoc; EXPECT_EQ(tinyxml2::XML_SUCCESS, pluginDoc.Parse(pluginStr)); EXPECT_TRUE(app.LoadPlugin("Publisher", pluginDoc.FirstChildElement("plugin"))); // Get main window auto win = app.findChild<MainWindow *>(); ASSERT_NE(nullptr, win); // Show, but don't exec, so we don't block win->QuickWindow()->show(); // Get plugin auto plugins = win->findChildren<plugins::Publisher *>(); EXPECT_EQ(plugins.size(), 1); auto plugin = plugins[0]; EXPECT_EQ(plugin->Title(), "Publisher"); // Message type EXPECT_EQ(plugin->MsgType(), "ignition.msgs.Fruits"); // Message EXPECT_EQ(plugin->MsgData(), "number: 1 fruit {name:\"banana\"}"); // Topic EXPECT_EQ(plugin->Topic(), "/fruit"); // Frequency EXPECT_DOUBLE_EQ(plugin->Frequency(), 0.1); }
#ifndef TEST_PLUGIN_LOADER_HPP #define TEST_PLUGIN_LOADER_HPP #include "core_unit_test/test_global_context.hpp" #include <string> #include <vector> namespace wgt { /** * Plugin loader to be used by unit tests. */ class TestPluginLoader { public: typedef std::vector<std::wstring> PluginList; TestPluginLoader(); virtual ~TestPluginLoader(); private: InterfacePtr interface_ = nullptr; GenericPluginManager& pluginManager_; PluginList plugins_; }; } // end namespace wgt #endif // TEST_PLUGIN_LOADER_HPP
// Copyright (c) 2019 The DailyCrypto developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/dailycrypto/receivedialog.h" #include "qt/dailycrypto/forms/ui_receivedialog.h" #include "qt/dailycrypto/qtutils.h" #include "walletmodel.h" #include <QFile> ReceiveDialog::ReceiveDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveDialog) { ui->setupUi(this); // Stylesheet this->setStyleSheet(parent->styleSheet()); ui->frameContainer->setProperty("cssClass", "container-dialog"); ui->frameContainer->setContentsMargins(10,10,10,10); // Title ui->labelTitle->setText("My Address"); ui->labelTitle->setProperty("cssClass", "text-title-dialog"); // Address ui->labelAddress->setText("D7VFR83SQbiezrW72hjcWJtcfip5krte2Z"); ui->labelAddress->setProperty("cssClass", "label-address-box"); // QR image QPixmap pixmap(":/res/img/img-qr-test-big.png"); ui->labelQrImg->setPixmap(pixmap.scaled( ui->labelQrImg->width(), ui->labelQrImg->height(), Qt::KeepAspectRatio) ); // Buttons ui->btnEsc->setText(""); ui->btnEsc->setProperty("cssClass", "ic-close"); ui->btnCancel->setProperty("cssClass", "btn-dialog-cancel"); ui->btnSave->setText("COPY"); ui->btnSave->setProperty("cssClass", "btn-primary"); ui->btnCancel->setVisible(false); connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(close())); connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(onCopy())); } void ReceiveDialog::updateQr(QString address){ if(!info) info = new SendCoinsRecipient(); info->address = address; QString uri = GUIUtil::formatBitcoinURI(*info); ui->labelQrImg->setText(""); ui->labelAddress->setText(address); QString error; QPixmap pixmap = encodeToQr(uri, error); if(!pixmap.isNull()){ qrImage = &pixmap; ui->labelQrImg->setPixmap(qrImage->scaled(ui->labelQrImg->width(), ui->labelQrImg->height())); }else{ ui->labelQrImg->setText(!error.isEmpty() ? error : "Error encoding address"); } } void ReceiveDialog::onCopy(){ GUIUtil::setClipboard(info->address); accept(); } ReceiveDialog::~ReceiveDialog() { delete ui; }
#include "renderer_ui_app.h" bool MyApp::OnInit() { MyFrame *frame = new MyFrame( "Hello World", wxPoint(50, 50), wxSize(450, 340) ); frame->Show( true ); return true; }
// Copyright (c) 2014-2017 The VillageCoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "base58.h" #include "clientversion.h" #include "init.h" #include "netbase.h" #include "validation.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeconfig.h" #include "masternodeman.h" #ifdef ENABLE_WALLET #include "privatesend-client.h" #endif // ENABLE_WALLET #include "privatesend-server.h" #include "rpc/server.h" #include "util.h" #include "utilmoneystr.h" #include <fstream> #include <iomanip> #include <univalue.h> UniValue masternodelist(const JSONRPCRequest& request); bool EnsureWalletIsAvailable(bool avoidException); #ifdef ENABLE_WALLET void EnsureWalletIsUnlocked(); UniValue privatesend(const JSONRPCRequest& request) { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "privatesend \"command\"\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" " start - Start mixing\n" " stop - Stop mixing\n" " reset - Reset mixing\n" ); if(fMasternodeMode) throw JSONRPCError(RPC_INTERNAL_ERROR, "Client-side mixing is not supported on masternodes"); if(request.params[0].get_str() == "start") { { LOCK(pwalletMain->cs_wallet); if (pwalletMain->IsLocked(true)) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please unlock wallet for mixing with walletpassphrase first."); } privateSendClient.fEnablePrivateSend = true; bool result = privateSendClient.DoAutomaticDenominating(*g_connman); return "Mixing " + (result ? "started successfully" : ("start failed: " + privateSendClient.GetStatus() + ", will retry")); } if(request.params[0].get_str() == "stop") { privateSendClient.fEnablePrivateSend = false; return "Mixing was stopped"; } if(request.params[0].get_str() == "reset") { privateSendClient.ResetPool(); return "Mixing was reset"; } return "Unknown command, please see \"help privatesend\""; } #endif // ENABLE_WALLET UniValue getpoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getpoolinfo\n" "Returns an object containing mixing pool related information.\n"); #ifdef ENABLE_WALLET CPrivateSendBase* pprivateSendBase = fMasternodeMode ? (CPrivateSendBase*)&privateSendServer : (CPrivateSendBase*)&privateSendClient; UniValue obj(UniValue::VOBJ); obj.push_back(Pair("state", pprivateSendBase->GetStateString())); obj.push_back(Pair("mixing_mode", (!fMasternodeMode && privateSendClient.fPrivateSendMultiSession) ? "multi-session" : "normal")); obj.push_back(Pair("queue", pprivateSendBase->GetQueueSize())); obj.push_back(Pair("entries", pprivateSendBase->GetEntriesCount())); obj.push_back(Pair("status", privateSendClient.GetStatus())); masternode_info_t mnInfo; if (privateSendClient.GetMixingMasternodeInfo(mnInfo)) { obj.push_back(Pair("outpoint", mnInfo.outpoint.ToStringShort())); obj.push_back(Pair("addr", mnInfo.addr.ToString())); } if (pwalletMain) { obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup)); obj.push_back(Pair("warnings", pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING ? "WARNING: keypool is almost depleted!" : "")); } #else // ENABLE_WALLET UniValue obj(UniValue::VOBJ); obj.push_back(Pair("state", privateSendServer.GetStateString())); obj.push_back(Pair("queue", privateSendServer.GetQueueSize())); obj.push_back(Pair("entries", privateSendServer.GetEntriesCount())); #endif // ENABLE_WALLET return obj; } UniValue masternode(const JSONRPCRequest& request) { std::string strCommand; if (request.params.size() >= 1) { strCommand = request.params[0].get_str(); } #ifdef ENABLE_WALLET if (strCommand == "start-many") throw JSONRPCError(RPC_INVALID_PARAMETER, "DEPRECATED, please use start-all instead"); #endif // ENABLE_WALLET if (request.fHelp || ( #ifdef ENABLE_WALLET strCommand != "start-alias" && strCommand != "start-all" && strCommand != "start-missing" && strCommand != "start-disabled" && strCommand != "outputs" && #endif // ENABLE_WALLET strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "debug" && strCommand != "current" && strCommand != "winner" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" && strCommand != "status")) throw std::runtime_error( "masternode \"command\"...\n" "Set of commands to execute masternode related actions\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" " count - Get information about number of masternodes (DEPRECATED options: 'total', 'ps', 'enabled', 'qualify', 'all')\n" " current - Print info on current masternode winner to be paid the next block (calculated locally)\n" " genkey - Generate new masternodeprivkey\n" #ifdef ENABLE_WALLET " outputs - Print masternode compatible outputs\n" " start-alias - Start single remote masternode by assigned alias configured in masternode.conf\n" " start-<mode> - Start remote masternodes configured in masternode.conf (<mode>: 'all', 'missing', 'disabled')\n" #endif // ENABLE_WALLET " status - Print masternode status information\n" " list - Print list of all known masternodes (see masternodelist for more info)\n" " list-conf - Print masternode.conf in JSON format\n" " winner - Print info on next masternode winner to vote for\n" " winners - Print list of masternode winners\n" ); if (strCommand == "list") { JSONRPCRequest newRequest = request; newRequest.params.setArray(); // forward params but skip "list" for (unsigned int i = 1; i < request.params.size(); i++) { newRequest.params.push_back(request.params[i]); } return masternodelist(newRequest); } if(strCommand == "connect") { if (request.params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Masternode address required"); std::string strAddress = request.params[1].get_str(); CService addr; if (!Lookup(strAddress.c_str(), addr, 0, false)) throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Incorrect masternode address %s", strAddress)); // TODO: Pass CConnman instance somehow and don't use global variable. g_connman->OpenMasternodeConnection(CAddress(addr, NODE_NETWORK)); if (!g_connman->IsConnected(CAddress(addr, NODE_NETWORK), CConnman::AllNodes)) throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Couldn't connect to masternode %s", strAddress)); return "successfully connected"; } if (strCommand == "count") { if (request.params.size() > 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Too many parameters"); int nCount; masternode_info_t mnInfo; mnodeman.GetNextMasternodeInQueueForPayment(true, nCount, mnInfo); int total = mnodeman.size(); int ps = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); int enabled = mnodeman.CountEnabled(); if (request.params.size() == 1) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("total", total)); obj.push_back(Pair("ps_compatible", ps)); obj.push_back(Pair("enabled", enabled)); obj.push_back(Pair("qualify", nCount)); return obj; } std::string strMode = request.params[1].get_str(); if (strMode == "total") return total; if (strMode == "ps") return ps; if (strMode == "enabled") return enabled; if (strMode == "qualify") return nCount; if (strMode == "all") return strprintf("Total: %d (PS Compatible: %d / Enabled: %d / Qualify: %d)", total, ps, enabled, nCount); } if (strCommand == "current" || strCommand == "winner") { int nCount; int nHeight; masternode_info_t mnInfo; CBlockIndex* pindex = NULL; { LOCK(cs_main); pindex = chainActive.Tip(); } nHeight = pindex->nHeight + (strCommand == "current" ? 1 : 10); mnodeman.UpdateLastPaid(pindex); if(!mnodeman.GetNextMasternodeInQueueForPayment(nHeight, true, nCount, mnInfo)) return "unknown"; UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", nHeight)); obj.push_back(Pair("IP:port", mnInfo.addr.ToString())); obj.push_back(Pair("protocol", mnInfo.nProtocolVersion)); obj.push_back(Pair("outpoint", mnInfo.outpoint.ToStringShort())); obj.push_back(Pair("payee", CBitcoinAddress(mnInfo.pubKeyCollateralAddress.GetID()).ToString())); obj.push_back(Pair("lastseen", mnInfo.nTimeLastPing)); obj.push_back(Pair("activeseconds", mnInfo.nTimeLastPing - mnInfo.sigTime)); return obj; } #ifdef ENABLE_WALLET if (strCommand == "start-alias") { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; if (request.params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Please specify an alias"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } std::string strAlias = request.params[1].get_str(); bool fFound = false; UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", strAlias)); for (const auto& mne : masternodeConfig.getEntries()) { if(mne.getAlias() == strAlias) { fFound = true; std::string strError; CMasternodeBroadcast mnb; bool fResult = CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb); int nDoS; if (fResult && !mnodeman.CheckMnbAndUpdateMasternodeList(NULL, mnb, nDoS, *g_connman)) { strError = "Failed to verify MNB"; fResult = false; } statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(!fResult) { statusObj.push_back(Pair("errorMessage", strError)); } mnodeman.NotifyMasternodeUpdates(*g_connman); break; } } if(!fFound) { statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Could not find alias in config. Verify with list-conf.")); } return statusObj; } if (strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } if((strCommand == "start-missing" || strCommand == "start-disabled") && !masternodeSync.IsMasternodeListSynced()) { throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "You can't use this command until masternode list is synced"); } int nSuccessful = 0; int nFailed = 0; UniValue resultsObj(UniValue::VOBJ); for (const auto& mne : masternodeConfig.getEntries()) { std::string strError; COutPoint outpoint = COutPoint(uint256S(mne.getTxHash()), (uint32_t)atoi(mne.getOutputIndex())); CMasternode mn; bool fFound = mnodeman.Get(outpoint, mn); CMasternodeBroadcast mnb; if(strCommand == "start-missing" && fFound) continue; if(strCommand == "start-disabled" && fFound && mn.IsEnabled()) continue; bool fResult = CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb); int nDoS; if (fResult && !mnodeman.CheckMnbAndUpdateMasternodeList(NULL, mnb, nDoS, *g_connman)) { strError = "Failed to verify MNB"; fResult = false; } UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if (fResult) { nSuccessful++; } else { nFailed++; statusObj.push_back(Pair("errorMessage", strError)); } resultsObj.push_back(Pair("status", statusObj)); } mnodeman.NotifyMasternodeUpdates(*g_connman); UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully started %d masternodes, failed to start %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } #endif // ENABLE_WALLET if (strCommand == "genkey") { CKey secret; secret.MakeNewKey(false); return CBitcoinSecret(secret).ToString(); } if (strCommand == "list-conf") { UniValue resultObj(UniValue::VOBJ); for (const auto& mne : masternodeConfig.getEntries()) { COutPoint outpoint = COutPoint(uint256S(mne.getTxHash()), (uint32_t)atoi(mne.getOutputIndex())); CMasternode mn; bool fFound = mnodeman.Get(outpoint, mn); std::string strStatus = fFound ? mn.GetStatus() : "MISSING"; UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("alias", mne.getAlias())); mnObj.push_back(Pair("address", mne.getIp())); mnObj.push_back(Pair("privateKey", mne.getPrivKey())); mnObj.push_back(Pair("txHash", mne.getTxHash())); mnObj.push_back(Pair("outputIndex", mne.getOutputIndex())); mnObj.push_back(Pair("status", strStatus)); resultObj.push_back(Pair("masternode", mnObj)); } return resultObj; } #ifdef ENABLE_WALLET if (strCommand == "outputs") { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; // Find possible candidates std::vector<COutput> vPossibleCoins; pwalletMain->AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_1000); UniValue obj(UniValue::VOBJ); for (const auto& out : vPossibleCoins) { obj.push_back(Pair(out.tx->GetHash().ToString(), strprintf("%d", out.i))); } return obj; } #endif // ENABLE_WALLET if (strCommand == "status") { if (!fMasternodeMode) throw JSONRPCError(RPC_INTERNAL_ERROR, "This is not a masternode"); UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("outpoint", activeMasternode.outpoint.ToStringShort())); mnObj.push_back(Pair("service", activeMasternode.service.ToString())); CMasternode mn; if(mnodeman.Get(activeMasternode.outpoint, mn)) { mnObj.push_back(Pair("payee", CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); } mnObj.push_back(Pair("status", activeMasternode.GetStatus())); return mnObj; } if (strCommand == "winners") { int nHeight; { LOCK(cs_main); CBlockIndex* pindex = chainActive.Tip(); if(!pindex) return NullUniValue; nHeight = pindex->nHeight; } int nLast = 10; std::string strFilter = ""; if (request.params.size() >= 2) { nLast = atoi(request.params[1].get_str()); } if (request.params.size() == 3) { strFilter = request.params[2].get_str(); } if (request.params.size() > 3) throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'masternode winners ( \"count\" \"filter\" )'"); UniValue obj(UniValue::VOBJ); for(int i = nHeight - nLast; i < nHeight + 20; i++) { std::string strPayment = GetRequiredPaymentsString(i); if (strFilter !="" && strPayment.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strprintf("%d", i), strPayment)); } return obj; } return NullUniValue; } UniValue masternodelist(const JSONRPCRequest& request) { std::string strMode = "json"; std::string strFilter = ""; if (request.params.size() >= 1) strMode = request.params[0].get_str(); if (request.params.size() == 2) strFilter = request.params[1].get_str(); if (request.fHelp || ( strMode != "activeseconds" && strMode != "addr" && strMode != "daemon" && strMode != "full" && strMode != "info" && strMode != "json" && strMode != "lastseen" && strMode != "lastpaidtime" && strMode != "lastpaidblock" && strMode != "protocol" && strMode != "payee" && strMode != "pubkey" && strMode != "rank" && strMode != "sentinel" && strMode != "status")) { throw std::runtime_error( "masternodelist ( \"mode\" \"filter\" )\n" "Get a list of masternodes in different modes\n" "\nArguments:\n" "1. \"mode\" (string, optional/required to use filter, defaults = json) The mode to run list in\n" "2. \"filter\" (string, optional) Filter results. Partial match by outpoint by default in all modes,\n" " additional matches in some modes are also available\n" "\nAvailable modes:\n" " activeseconds - Print number of seconds masternode recognized by the network as enabled\n" " (since latest issued \"masternode start/start-many/start-alias\")\n" " addr - Print ip address associated with a masternode (can be additionally filtered, partial match)\n" " daemon - Print daemon version of a masternode (can be additionally filtered, exact match)\n" " full - Print info in format 'status protocol payee lastseen activeseconds lastpaidtime lastpaidblock IP'\n" " (can be additionally filtered, partial match)\n" " info - Print info in format 'status protocol payee lastseen activeseconds sentinelversion sentinelstate IP'\n" " (can be additionally filtered, partial match)\n" " json - Print info in JSON format (can be additionally filtered, partial match)\n" " lastpaidblock - Print the last block height a node was paid on the network\n" " lastpaidtime - Print the last time a node was paid on the network\n" " lastseen - Print timestamp of when a masternode was last seen on the network\n" " payee - Print VillageCoin address associated with a masternode (can be additionally filtered,\n" " partial match)\n" " protocol - Print protocol of a masternode (can be additionally filtered, exact match)\n" " pubkey - Print the masternode (not collateral) public key\n" " rank - Print rank of a masternode based on current block\n" " sentinel - Print sentinel version of a masternode (can be additionally filtered, exact match)\n" " status - Print masternode status: PRE_ENABLED / ENABLED / EXPIRED / SENTINEL_PING_EXPIRED / NEW_START_REQUIRED /\n" " UPDATE_REQUIRED / POSE_BAN / OUTPOINT_SPENT (can be additionally filtered, partial match)\n" ); } if (strMode == "full" || strMode == "json" || strMode == "lastpaidtime" || strMode == "lastpaidblock") { CBlockIndex* pindex = NULL; { LOCK(cs_main); pindex = chainActive.Tip(); } mnodeman.UpdateLastPaid(pindex); } UniValue obj(UniValue::VOBJ); if (strMode == "rank") { CMasternodeMan::rank_pair_vec_t vMasternodeRanks; mnodeman.GetMasternodeRanks(vMasternodeRanks); for (const auto& rankpair : vMasternodeRanks) { std::string strOutpoint = rankpair.second.outpoint.ToStringShort(); if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, rankpair.first)); } } else { std::map<COutPoint, CMasternode> mapMasternodes = mnodeman.GetFullMasternodeMap(); for (const auto& mnpair : mapMasternodes) { CMasternode mn = mnpair.second; std::string strOutpoint = mnpair.first.ToStringShort(); if (strMode == "activeseconds") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)(mn.lastPing.sigTime - mn.sigTime))); } else if (strMode == "addr") { std::string strAddress = mn.addr.ToString(); if (strFilter !="" && strAddress.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strAddress)); } else if (strMode == "daemon") { std::string strDaemon = mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? FormatVersion(mn.lastPing.nDaemonVersion) : "Unknown"; if (strFilter !="" && strDaemon.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strDaemon)); } else if (strMode == "sentinel") { std::string strSentinel = mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? SafeIntVersionToString(mn.lastPing.nSentinelVersion) : "Unknown"; if (strFilter !="" && strSentinel.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strSentinel)); } else if (strMode == "full") { std::ostringstream streamFull; streamFull << std::setw(18) << mn.GetStatus() << " " << mn.nProtocolVersion << " " << CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << std::setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << std::setw(10) << mn.GetLastPaidTime() << " " << std::setw(6) << mn.GetLastPaidBlock() << " " << mn.addr.ToString(); std::string strFull = streamFull.str(); if (strFilter !="" && strFull.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strFull)); } else if (strMode == "info") { std::ostringstream streamInfo; streamInfo << std::setw(18) << mn.GetStatus() << " " << mn.nProtocolVersion << " " << CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << (int64_t)mn.lastPing.sigTime << " " << std::setw(8) << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << SafeIntVersionToString(mn.lastPing.nSentinelVersion) << " " << (mn.lastPing.fSentinelIsCurrent ? "current" : "expired") << " " << mn.addr.ToString(); std::string strInfo = streamInfo.str(); if (strFilter !="" && strInfo.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strInfo)); } else if (strMode == "json") { std::ostringstream streamInfo; streamInfo << mn.addr.ToString() << " " << CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString() << " " << mn.GetStatus() << " " << mn.nProtocolVersion << " " << mn.lastPing.nDaemonVersion << " " << SafeIntVersionToString(mn.lastPing.nSentinelVersion) << " " << (mn.lastPing.fSentinelIsCurrent ? "current" : "expired") << " " << (int64_t)mn.lastPing.sigTime << " " << (int64_t)(mn.lastPing.sigTime - mn.sigTime) << " " << mn.GetLastPaidTime() << " " << mn.GetLastPaidBlock(); std::string strInfo = streamInfo.str(); if (strFilter !="" && strInfo.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; UniValue objMN(UniValue::VOBJ); objMN.push_back(Pair("address", mn.addr.ToString())); objMN.push_back(Pair("payee", CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); objMN.push_back(Pair("status", mn.GetStatus())); objMN.push_back(Pair("protocol", mn.nProtocolVersion)); objMN.push_back(Pair("daemonversion", mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? FormatVersion(mn.lastPing.nDaemonVersion) : "Unknown")); objMN.push_back(Pair("sentinelversion", mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? SafeIntVersionToString(mn.lastPing.nSentinelVersion) : "Unknown")); objMN.push_back(Pair("sentinelstate", (mn.lastPing.fSentinelIsCurrent ? "current" : "expired"))); objMN.push_back(Pair("lastseen", (int64_t)mn.lastPing.sigTime)); objMN.push_back(Pair("activeseconds", (int64_t)(mn.lastPing.sigTime - mn.sigTime))); objMN.push_back(Pair("lastpaidtime", mn.GetLastPaidTime())); objMN.push_back(Pair("lastpaidblock", mn.GetLastPaidBlock())); obj.push_back(Pair(strOutpoint, objMN)); } else if (strMode == "lastpaidblock") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, mn.GetLastPaidBlock())); } else if (strMode == "lastpaidtime") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, mn.GetLastPaidTime())); } else if (strMode == "lastseen") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)mn.lastPing.sigTime)); } else if (strMode == "payee") { CBitcoinAddress address(mn.pubKeyCollateralAddress.GetID()); std::string strPayee = address.ToString(); if (strFilter !="" && strPayee.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strPayee)); } else if (strMode == "protocol") { if (strFilter !="" && strFilter != strprintf("%d", mn.nProtocolVersion) && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, mn.nProtocolVersion)); } else if (strMode == "pubkey") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, HexStr(mn.pubKeyMasternode))); } else if (strMode == "status") { std::string strStatus = mn.GetStatus(); if (strFilter !="" && strStatus.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strStatus)); } } } return obj; } bool DecodeHexVecMnb(std::vector<CMasternodeBroadcast>& vecMnb, std::string strHexMnb) { if (!IsHex(strHexMnb)) return false; std::vector<unsigned char> mnbData(ParseHex(strHexMnb)); CDataStream ssData(mnbData, SER_NETWORK, PROTOCOL_VERSION); try { ssData >> vecMnb; } catch (const std::exception&) { return false; } return true; } UniValue masternodebroadcast(const JSONRPCRequest& request) { std::string strCommand; if (request.params.size() >= 1) strCommand = request.params[0].get_str(); if (request.fHelp || ( #ifdef ENABLE_WALLET strCommand != "create-alias" && strCommand != "create-all" && #endif // ENABLE_WALLET strCommand != "decode" && strCommand != "relay")) throw std::runtime_error( "masternodebroadcast \"command\"...\n" "Set of commands to create and relay masternode broadcast messages\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" #ifdef ENABLE_WALLET " create-alias - Create single remote masternode broadcast message by assigned alias configured in masternode.conf\n" " create-all - Create remote masternode broadcast messages for all masternodes configured in masternode.conf\n" #endif // ENABLE_WALLET " decode - Decode masternode broadcast message\n" " relay - Relay masternode broadcast message to the network\n" ); #ifdef ENABLE_WALLET if (strCommand == "create-alias") { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; // wait for reindex and/or import to finish if (fImporting || fReindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Wait for reindex and/or import to finish"); if (request.params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Please specify an alias"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } bool fFound = false; std::string strAlias = request.params[1].get_str(); UniValue statusObj(UniValue::VOBJ); std::vector<CMasternodeBroadcast> vecMnb; statusObj.push_back(Pair("alias", strAlias)); for (const auto& mne : masternodeConfig.getEntries()) { if(mne.getAlias() == strAlias) { fFound = true; std::string strError; CMasternodeBroadcast mnb; bool fResult = CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb, true); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(fResult) { vecMnb.push_back(mnb); CDataStream ssVecMnb(SER_NETWORK, PROTOCOL_VERSION); ssVecMnb << vecMnb; statusObj.push_back(Pair("hex", HexStr(ssVecMnb))); } else { statusObj.push_back(Pair("errorMessage", strError)); } break; } } if(!fFound) { statusObj.push_back(Pair("result", "not found")); statusObj.push_back(Pair("errorMessage", "Could not find alias in config. Verify with list-conf.")); } return statusObj; } if (strCommand == "create-all") { if (!EnsureWalletIsAvailable(request.fHelp)) return NullUniValue; // wait for reindex and/or import to finish if (fImporting || fReindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Wait for reindex and/or import to finish"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } int nSuccessful = 0; int nFailed = 0; UniValue resultsObj(UniValue::VOBJ); std::vector<CMasternodeBroadcast> vecMnb; for (const auto& mne : masternodeConfig.getEntries()) { std::string strError; CMasternodeBroadcast mnb; bool fResult = CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb, true); UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(fResult) { nSuccessful++; vecMnb.push_back(mnb); } else { nFailed++; statusObj.push_back(Pair("errorMessage", strError)); } resultsObj.push_back(Pair("status", statusObj)); } CDataStream ssVecMnb(SER_NETWORK, PROTOCOL_VERSION); ssVecMnb << vecMnb; UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully created broadcast messages for %d masternodes, failed to create %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); returnObj.push_back(Pair("detail", resultsObj)); returnObj.push_back(Pair("hex", HexStr(ssVecMnb.begin(), ssVecMnb.end()))); return returnObj; } #endif // ENABLE_WALLET if (strCommand == "decode") { if (request.params.size() != 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'masternodebroadcast decode \"hexstring\"'"); std::vector<CMasternodeBroadcast> vecMnb; if (!DecodeHexVecMnb(vecMnb, request.params[1].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Masternode broadcast message decode failed"); int nSuccessful = 0; int nFailed = 0; int nDos = 0; UniValue returnObj(UniValue::VOBJ); for (const auto& mnb : vecMnb) { UniValue resultObj(UniValue::VOBJ); if(mnb.CheckSignature(nDos)) { nSuccessful++; resultObj.push_back(Pair("outpoint", mnb.outpoint.ToStringShort())); resultObj.push_back(Pair("addr", mnb.addr.ToString())); resultObj.push_back(Pair("pubKeyCollateralAddress", CBitcoinAddress(mnb.pubKeyCollateralAddress.GetID()).ToString())); resultObj.push_back(Pair("pubKeyMasternode", CBitcoinAddress(mnb.pubKeyMasternode.GetID()).ToString())); resultObj.push_back(Pair("vchSig", EncodeBase64(&mnb.vchSig[0], mnb.vchSig.size()))); resultObj.push_back(Pair("sigTime", mnb.sigTime)); resultObj.push_back(Pair("protocolVersion", mnb.nProtocolVersion)); resultObj.push_back(Pair("nLastDsq", mnb.nLastDsq)); UniValue lastPingObj(UniValue::VOBJ); lastPingObj.push_back(Pair("outpoint", mnb.lastPing.masternodeOutpoint.ToStringShort())); lastPingObj.push_back(Pair("blockHash", mnb.lastPing.blockHash.ToString())); lastPingObj.push_back(Pair("sigTime", mnb.lastPing.sigTime)); lastPingObj.push_back(Pair("vchSig", EncodeBase64(&mnb.lastPing.vchSig[0], mnb.lastPing.vchSig.size()))); resultObj.push_back(Pair("lastPing", lastPingObj)); } else { nFailed++; resultObj.push_back(Pair("errorMessage", "Masternode broadcast signature verification failed")); } returnObj.push_back(Pair(mnb.GetHash().ToString(), resultObj)); } returnObj.push_back(Pair("overall", strprintf("Successfully decoded broadcast messages for %d masternodes, failed to decode %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); return returnObj; } if (strCommand == "relay") { if (request.params.size() < 2 || request.params.size() > 3) throw JSONRPCError(RPC_INVALID_PARAMETER, "masternodebroadcast relay \"hexstring\"\n" "\nArguments:\n" "1. \"hex\" (string, required) Broadcast messages hex string\n"); std::vector<CMasternodeBroadcast> vecMnb; if (!DecodeHexVecMnb(vecMnb, request.params[1].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Masternode broadcast message decode failed"); int nSuccessful = 0; int nFailed = 0; UniValue returnObj(UniValue::VOBJ); // verify all signatures first, bailout if any of them broken for (const auto& mnb : vecMnb) { UniValue resultObj(UniValue::VOBJ); resultObj.push_back(Pair("outpoint", mnb.outpoint.ToStringShort())); resultObj.push_back(Pair("addr", mnb.addr.ToString())); int nDos = 0; bool fResult; if (mnb.CheckSignature(nDos)) { fResult = mnodeman.CheckMnbAndUpdateMasternodeList(NULL, mnb, nDos, *g_connman); mnodeman.NotifyMasternodeUpdates(*g_connman); } else fResult = false; if(fResult) { nSuccessful++; resultObj.push_back(Pair(mnb.GetHash().ToString(), "successful")); } else { nFailed++; resultObj.push_back(Pair("errorMessage", "Masternode broadcast signature verification failed")); } returnObj.push_back(Pair(mnb.GetHash().ToString(), resultObj)); } returnObj.push_back(Pair("overall", strprintf("Successfully relayed broadcast messages for %d masternodes, failed to relay %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); return returnObj; } return NullUniValue; } UniValue sentinelping(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw std::runtime_error( "sentinelping version\n" "\nSentinel ping.\n" "\nArguments:\n" "1. version (string, required) Sentinel version in the form \"x.x.x\"\n" "\nResult:\n" "state (boolean) Ping result\n" "\nExamples:\n" + HelpExampleCli("sentinelping", "1.0.2") + HelpExampleRpc("sentinelping", "1.0.2") ); } activeMasternode.UpdateSentinelPing(StringVersionToInt(request.params[0].get_str())); return true; } static const CRPCCommand commands[] = { // category name actor (function) okSafe argNames // --------------------- ------------------------ ----------------------- ------ ---------- { "village", "masternode", &masternode, true, {} }, { "village", "masternodelist", &masternodelist, true, {} }, { "village", "masternodebroadcast", &masternodebroadcast, true, {} }, { "village", "getpoolinfo", &getpoolinfo, true, {} }, { "village", "sentinelping", &sentinelping, true, {} }, #ifdef ENABLE_WALLET { "village", "privatesend", &privatesend, false, {} }, #endif // ENABLE_WALLET }; void RegisterMasternodeRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTwoPointRadialGradient.h" /* Two-point radial gradients are specified by two circles, each with a center point and radius. The gradient can be considered to be a series of concentric circles, with the color interpolated from the start circle (at t=0) to the end circle (at t=1). For each point (x, y) in the span, we want to find the interpolated circle that intersects that point. The center of the desired circle (Cx, Cy) falls at some distance t along the line segment between the start point (Sx, Sy) and end point (Ex, Ey): Cx = (1 - t) * Sx + t * Ex (0 <= t <= 1) Cy = (1 - t) * Sy + t * Ey The radius of the desired circle (r) is also a linear interpolation t between the start and end radii (Sr and Er): r = (1 - t) * Sr + t * Er But (x - Cx)^2 + (y - Cy)^2 = r^2 so (x - ((1 - t) * Sx + t * Ex))^2 + (y - ((1 - t) * Sy + t * Ey))^2 = ((1 - t) * Sr + t * Er)^2 Solving for t yields [(Sx - Ex)^2 + (Sy - Ey)^2 - (Er - Sr)^2)] * t^2 + [2 * (Sx - Ex)(x - Sx) + 2 * (Sy - Ey)(y - Sy) - 2 * (Er - Sr) * Sr] * t + [(x - Sx)^2 + (y - Sy)^2 - Sr^2] = 0 To simplify, let Dx = Sx - Ex, Dy = Sy - Ey, Dr = Er - Sr, dx = x - Sx, dy = y - Sy [Dx^2 + Dy^2 - Dr^2)] * t^2 + 2 * [Dx * dx + Dy * dy - Dr * Sr] * t + [dx^2 + dy^2 - Sr^2] = 0 A quadratic in t. The two roots of the quadratic reflect the two possible circles on which the point may fall. Solving for t yields the gradient value to use. If a<0, the start circle is entirely contained in the end circle, and one of the roots will be <0 or >1 (off the line segment). If a>0, the start circle falls at least partially outside the end circle (or vice versa), and the gradient defines a "tube" where a point may be on one circle (on the inside of the tube) or the other (outside of the tube). We choose one arbitrarily. In order to keep the math to within the limits of fixed point, we divide the entire quadratic by Dr^2, and replace (x - Sx)/Dr with x' and (y - Sy)/Dr with y', giving [Dx^2 / Dr^2 + Dy^2 / Dr^2 - 1)] * t^2 + 2 * [x' * Dx / Dr + y' * Dy / Dr - Sr / Dr] * t + [x'^2 + y'^2 - Sr^2/Dr^2] = 0 (x' and y' are computed by appending the subtract and scale to the fDstToIndex matrix in the constructor). Since the 'A' component of the quadratic is independent of x' and y', it is precomputed in the constructor. Since the 'B' component is linear in x' and y', if x and y are linear in the span, 'B' can be computed incrementally with a simple delta (db below). If it is not (e.g., a perspective projection), it must be computed in the loop. */ namespace { inline SkFixed two_point_radial(SkScalar b, SkScalar fx, SkScalar fy, SkScalar sr2d2, SkScalar foura, SkScalar oneOverTwoA, bool posRoot) { SkScalar c = SkScalarSquare(fx) + SkScalarSquare(fy) - sr2d2; if (0 == foura) { return SkScalarToFixed(SkScalarDiv(-c, b)); } SkScalar discrim = SkScalarSquare(b) - SkScalarMul(foura, c); if (discrim < 0) { discrim = -discrim; } SkScalar rootDiscrim = SkScalarSqrt(discrim); SkScalar result; if (posRoot) { result = SkScalarMul(-b + rootDiscrim, oneOverTwoA); } else { result = SkScalarMul(-b - rootDiscrim, oneOverTwoA); } return SkScalarToFixed(result); } typedef void (* TwoPointRadialShadeProc)(SkScalar fx, SkScalar dx, SkScalar fy, SkScalar dy, SkScalar b, SkScalar db, SkScalar fSr2D2, SkScalar foura, SkScalar fOneOverTwoA, bool posRoot, SkPMColor* SK_RESTRICT dstC, const SkPMColor* SK_RESTRICT cache, int count); void shadeSpan_twopoint_clamp(SkScalar fx, SkScalar dx, SkScalar fy, SkScalar dy, SkScalar b, SkScalar db, SkScalar fSr2D2, SkScalar foura, SkScalar fOneOverTwoA, bool posRoot, SkPMColor* SK_RESTRICT dstC, const SkPMColor* SK_RESTRICT cache, int count) { for (; count > 0; --count) { SkFixed t = two_point_radial(b, fx, fy, fSr2D2, foura, fOneOverTwoA, posRoot); SkFixed index = SkClampMax(t, 0xFFFF); SkASSERT(index <= 0xFFFF); *dstC++ = cache[index >> SkGradientShaderBase::kCache32Shift]; fx += dx; fy += dy; b += db; } } void shadeSpan_twopoint_mirror(SkScalar fx, SkScalar dx, SkScalar fy, SkScalar dy, SkScalar b, SkScalar db, SkScalar fSr2D2, SkScalar foura, SkScalar fOneOverTwoA, bool posRoot, SkPMColor* SK_RESTRICT dstC, const SkPMColor* SK_RESTRICT cache, int count) { for (; count > 0; --count) { SkFixed t = two_point_radial(b, fx, fy, fSr2D2, foura, fOneOverTwoA, posRoot); SkFixed index = mirror_tileproc(t); SkASSERT(index <= 0xFFFF); *dstC++ = cache[index >> SkGradientShaderBase::kCache32Shift]; fx += dx; fy += dy; b += db; } } void shadeSpan_twopoint_repeat(SkScalar fx, SkScalar dx, SkScalar fy, SkScalar dy, SkScalar b, SkScalar db, SkScalar fSr2D2, SkScalar foura, SkScalar fOneOverTwoA, bool posRoot, SkPMColor* SK_RESTRICT dstC, const SkPMColor* SK_RESTRICT cache, int count) { for (; count > 0; --count) { SkFixed t = two_point_radial(b, fx, fy, fSr2D2, foura, fOneOverTwoA, posRoot); SkFixed index = repeat_tileproc(t); SkASSERT(index <= 0xFFFF); *dstC++ = cache[index >> SkGradientShaderBase::kCache32Shift]; fx += dx; fy += dy; b += db; } } } ///////////////////////////////////////////////////////////////////// SkTwoPointRadialGradient::SkTwoPointRadialGradient( const SkPoint& start, SkScalar startRadius, const SkPoint& end, SkScalar endRadius, const SkColor colors[], const SkScalar pos[], int colorCount, SkShader::TileMode mode, SkUnitMapper* mapper) : SkGradientShaderBase(colors, pos, colorCount, mode, mapper), fCenter1(start), fCenter2(end), fRadius1(startRadius), fRadius2(endRadius) { init(); } SkShader::BitmapType SkTwoPointRadialGradient::asABitmap( SkBitmap* bitmap, SkMatrix* matrix, SkShader::TileMode* xy) const { if (bitmap) { this->getGradientTableBitmap(bitmap); } SkScalar diffL = 0; // just to avoid gcc warning if (matrix) { diffL = SkScalarSqrt(SkScalarSquare(fDiff.fX) + SkScalarSquare(fDiff.fY)); } if (matrix) { if (diffL) { SkScalar invDiffL = SkScalarInvert(diffL); matrix->setSinCos(-SkScalarMul(invDiffL, fDiff.fY), SkScalarMul(invDiffL, fDiff.fX)); } else { matrix->reset(); } matrix->preConcat(fPtsToUnit); } if (xy) { xy[0] = fTileMode; xy[1] = kClamp_TileMode; } return kTwoPointRadial_BitmapType; } SkShader::GradientType SkTwoPointRadialGradient::asAGradient( SkShader::GradientInfo* info) const { if (info) { commonAsAGradient(info); info->fPoint[0] = fCenter1; info->fPoint[1] = fCenter2; info->fRadius[0] = fRadius1; info->fRadius[1] = fRadius2; } return kRadial2_GradientType; } void SkTwoPointRadialGradient::shadeSpan(int x, int y, SkPMColor* dstCParam, int count) { SkASSERT(count > 0); SkPMColor* SK_RESTRICT dstC = dstCParam; // Zero difference between radii: fill with transparent black. if (fDiffRadius == 0) { sk_bzero(dstC, count * sizeof(*dstC)); return; } SkMatrix::MapXYProc dstProc = fDstToIndexProc; TileProc proc = fTileProc; const SkPMColor* SK_RESTRICT cache = this->getCache32(); SkScalar foura = fA * 4; bool posRoot = fDiffRadius < 0; if (fDstToIndexClass != kPerspective_MatrixClass) { SkPoint srcPt; dstProc(fDstToIndex, SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf, &srcPt); SkScalar dx, fx = srcPt.fX; SkScalar dy, fy = srcPt.fY; if (fDstToIndexClass == kFixedStepInX_MatrixClass) { SkFixed fixedX, fixedY; (void)fDstToIndex.fixedStepInX(SkIntToScalar(y), &fixedX, &fixedY); dx = SkFixedToScalar(fixedX); dy = SkFixedToScalar(fixedY); } else { SkASSERT(fDstToIndexClass == kLinear_MatrixClass); dx = fDstToIndex.getScaleX(); dy = fDstToIndex.getSkewY(); } SkScalar b = (SkScalarMul(fDiff.fX, fx) + SkScalarMul(fDiff.fY, fy) - fStartRadius) * 2; SkScalar db = (SkScalarMul(fDiff.fX, dx) + SkScalarMul(fDiff.fY, dy)) * 2; TwoPointRadialShadeProc shadeProc = shadeSpan_twopoint_repeat; if (SkShader::kClamp_TileMode == fTileMode) { shadeProc = shadeSpan_twopoint_clamp; } else if (SkShader::kMirror_TileMode == fTileMode) { shadeProc = shadeSpan_twopoint_mirror; } else { SkASSERT(SkShader::kRepeat_TileMode == fTileMode); } (*shadeProc)(fx, dx, fy, dy, b, db, fSr2D2, foura, fOneOverTwoA, posRoot, dstC, cache, count); } else { // perspective case SkScalar dstX = SkIntToScalar(x); SkScalar dstY = SkIntToScalar(y); for (; count > 0; --count) { SkPoint srcPt; dstProc(fDstToIndex, dstX, dstY, &srcPt); SkScalar fx = srcPt.fX; SkScalar fy = srcPt.fY; SkScalar b = (SkScalarMul(fDiff.fX, fx) + SkScalarMul(fDiff.fY, fy) - fStartRadius) * 2; SkFixed t = two_point_radial(b, fx, fy, fSr2D2, foura, fOneOverTwoA, posRoot); SkFixed index = proc(t); SkASSERT(index <= 0xFFFF); *dstC++ = cache[index >> SkGradientShaderBase::kCache32Shift]; dstX += SK_Scalar1; } } } bool SkTwoPointRadialGradient::setContext( const SkBitmap& device, const SkPaint& paint, const SkMatrix& matrix){ // For now, we might have divided by zero, so detect that if (0 == fDiffRadius) { return false; } if (!this->INHERITED::setContext(device, paint, matrix)) { return false; } // we don't have a span16 proc fFlags &= ~kHasSpan16_Flag; return true; } #ifdef SK_DEVELOPER void SkTwoPointRadialGradient::toString(SkString* str) const { str->append("SkTwoPointRadialGradient: ("); str->append("center1: ("); str->appendScalar(fCenter1.fX); str->append(", "); str->appendScalar(fCenter1.fY); str->append(") radius1: "); str->appendScalar(fRadius1); str->append(" "); str->append("center2: ("); str->appendScalar(fCenter2.fX); str->append(", "); str->appendScalar(fCenter2.fY); str->append(") radius2: "); str->appendScalar(fRadius2); str->append(" "); this->INHERITED::toString(str); str->append(")"); } #endif SkTwoPointRadialGradient::SkTwoPointRadialGradient( SkFlattenableReadBuffer& buffer) : INHERITED(buffer), fCenter1(buffer.readPoint()), fCenter2(buffer.readPoint()), fRadius1(buffer.readScalar()), fRadius2(buffer.readScalar()) { init(); }; void SkTwoPointRadialGradient::flatten( SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writePoint(fCenter1); buffer.writePoint(fCenter2); buffer.writeScalar(fRadius1); buffer.writeScalar(fRadius2); } void SkTwoPointRadialGradient::init() { fDiff = fCenter1 - fCenter2; fDiffRadius = fRadius2 - fRadius1; // hack to avoid zero-divide for now SkScalar inv = fDiffRadius ? SkScalarInvert(fDiffRadius) : 0; fDiff.fX = SkScalarMul(fDiff.fX, inv); fDiff.fY = SkScalarMul(fDiff.fY, inv); fStartRadius = SkScalarMul(fRadius1, inv); fSr2D2 = SkScalarSquare(fStartRadius); fA = SkScalarSquare(fDiff.fX) + SkScalarSquare(fDiff.fY) - SK_Scalar1; fOneOverTwoA = fA ? SkScalarInvert(fA * 2) : 0; fPtsToUnit.setTranslate(-fCenter1.fX, -fCenter1.fY); fPtsToUnit.postScale(inv, inv); } ///////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU #include "GrTBackendEffectFactory.h" // For brevity typedef GrGLUniformManager::UniformHandle UniformHandle; static const UniformHandle kInvalidUniformHandle = GrGLUniformManager::kInvalidUniformHandle; class GrGLRadial2Gradient : public GrGLGradientEffect { public: GrGLRadial2Gradient(const GrBackendEffectFactory& factory, const GrDrawEffect&); virtual ~GrGLRadial2Gradient() { } virtual void emitCode(GrGLShaderBuilder*, const GrDrawEffect&, EffectKey, const char* outputColor, const char* inputColor, const TextureSamplerArray&) SK_OVERRIDE; virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; static EffectKey GenKey(const GrDrawEffect&, const GrGLCaps& caps); protected: UniformHandle fVSParamUni; UniformHandle fFSParamUni; const char* fVSVaryingName; const char* fFSVaryingName; bool fIsDegenerate; // @{ /// Values last uploaded as uniforms SkScalar fCachedCenter; SkScalar fCachedRadius; bool fCachedPosRoot; // @} private: typedef GrGLGradientEffect INHERITED; }; ///////////////////////////////////////////////////////////////////// class GrRadial2Gradient : public GrGradientEffect { public: static GrEffectRef* Create(GrContext* ctx, const SkTwoPointRadialGradient& shader, const SkMatrix& matrix, SkShader::TileMode tm) { AutoEffectUnref effect(SkNEW_ARGS(GrRadial2Gradient, (ctx, shader, matrix, tm))); return CreateEffectRef(effect); } virtual ~GrRadial2Gradient() { } static const char* Name() { return "Two-Point Radial Gradient"; } virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE { return GrTBackendEffectFactory<GrRadial2Gradient>::getInstance(); } // The radial gradient parameters can collapse to a linear (instead of quadratic) equation. bool isDegenerate() const { return SK_Scalar1 == fCenterX1; } SkScalar center() const { return fCenterX1; } SkScalar radius() const { return fRadius0; } bool isPosRoot() const { return SkToBool(fPosRoot); } typedef GrGLRadial2Gradient GLEffect; private: virtual bool onIsEqual(const GrEffect& sBase) const SK_OVERRIDE { const GrRadial2Gradient& s = CastEffect<GrRadial2Gradient>(sBase); return (INHERITED::onIsEqual(sBase) && this->fCenterX1 == s.fCenterX1 && this->fRadius0 == s.fRadius0 && this->fPosRoot == s.fPosRoot); } GrRadial2Gradient(GrContext* ctx, const SkTwoPointRadialGradient& shader, const SkMatrix& matrix, SkShader::TileMode tm) : INHERITED(ctx, shader, matrix, tm) , fCenterX1(shader.getCenterX1()) , fRadius0(shader.getStartRadius()) , fPosRoot(shader.getDiffRadius() < 0) { } GR_DECLARE_EFFECT_TEST; // @{ // Cache of values - these can change arbitrarily, EXCEPT // we shouldn't change between degenerate and non-degenerate?! SkScalar fCenterX1; SkScalar fRadius0; SkBool8 fPosRoot; // @} typedef GrGradientEffect INHERITED; }; ///////////////////////////////////////////////////////////////////// GR_DEFINE_EFFECT_TEST(GrRadial2Gradient); GrEffectRef* GrRadial2Gradient::TestCreate(SkMWCRandom* random, GrContext* context, const GrDrawTargetCaps&, GrTexture**) { SkPoint center1 = {random->nextUScalar1(), random->nextUScalar1()}; SkScalar radius1 = random->nextUScalar1(); SkPoint center2; SkScalar radius2; do { center2.set(random->nextUScalar1(), random->nextUScalar1()); radius2 = random->nextUScalar1 (); // There is a bug in two point radial gradients with identical radii } while (radius1 == radius2); SkColor colors[kMaxRandomGradientColors]; SkScalar stopsArray[kMaxRandomGradientColors]; SkScalar* stops = stopsArray; SkShader::TileMode tm; int colorCount = RandomGradientParams(random, colors, &stops, &tm); SkAutoTUnref<SkShader> shader(SkGradientShader::CreateTwoPointRadial(center1, radius1, center2, radius2, colors, stops, colorCount, tm)); SkPaint paint; return shader->asNewEffect(context, paint); } ///////////////////////////////////////////////////////////////////// GrGLRadial2Gradient::GrGLRadial2Gradient(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect) : INHERITED(factory) , fVSParamUni(kInvalidUniformHandle) , fFSParamUni(kInvalidUniformHandle) , fVSVaryingName(NULL) , fFSVaryingName(NULL) , fCachedCenter(SK_ScalarMax) , fCachedRadius(-SK_ScalarMax) , fCachedPosRoot(0) { const GrRadial2Gradient& data = drawEffect.castEffect<GrRadial2Gradient>(); fIsDegenerate = data.isDegenerate(); } void GrGLRadial2Gradient::emitCode(GrGLShaderBuilder* builder, const GrDrawEffect& drawEffect, EffectKey key, const char* outputColor, const char* inputColor, const TextureSamplerArray& samplers) { this->emitYCoordUniform(builder); const char* fsCoords; const char* vsCoordsVarying; GrSLType coordsVaryingType; this->setupMatrix(builder, key, &fsCoords, &vsCoordsVarying, &coordsVaryingType); // 2 copies of uniform array, 1 for each of vertex & fragment shader, // to work around Xoom bug. Doesn't seem to cause performance decrease // in test apps, but need to keep an eye on it. fVSParamUni = builder->addUniformArray(GrGLShaderBuilder::kVertex_ShaderType, kFloat_GrSLType, "Radial2VSParams", 6); fFSParamUni = builder->addUniformArray(GrGLShaderBuilder::kFragment_ShaderType, kFloat_GrSLType, "Radial2FSParams", 6); // For radial gradients without perspective we can pass the linear // part of the quadratic as a varying. if (kVec2f_GrSLType == coordsVaryingType) { builder->addVarying(kFloat_GrSLType, "Radial2BCoeff", &fVSVaryingName, &fFSVaryingName); } // VS { SkString p2; SkString p3; builder->getUniformVariable(fVSParamUni).appendArrayAccess(2, &p2); builder->getUniformVariable(fVSParamUni).appendArrayAccess(3, &p3); // For radial gradients without perspective we can pass the linear // part of the quadratic as a varying. if (kVec2f_GrSLType == coordsVaryingType) { // r2Var = 2 * (r2Parm[2] * varCoord.x - r2Param[3]) builder->vsCodeAppendf("\t%s = 2.0 *(%s * %s.x - %s);\n", fVSVaryingName, p2.c_str(), vsCoordsVarying, p3.c_str()); } } // FS { SkString cName("c"); SkString ac4Name("ac4"); SkString rootName("root"); SkString t; SkString p0; SkString p1; SkString p2; SkString p3; SkString p4; SkString p5; builder->getUniformVariable(fFSParamUni).appendArrayAccess(0, &p0); builder->getUniformVariable(fFSParamUni).appendArrayAccess(1, &p1); builder->getUniformVariable(fFSParamUni).appendArrayAccess(2, &p2); builder->getUniformVariable(fFSParamUni).appendArrayAccess(3, &p3); builder->getUniformVariable(fFSParamUni).appendArrayAccess(4, &p4); builder->getUniformVariable(fFSParamUni).appendArrayAccess(5, &p5); // If we we're able to interpolate the linear component, // bVar is the varying; otherwise compute it SkString bVar; if (kVec2f_GrSLType == coordsVaryingType) { bVar = fFSVaryingName; } else { bVar = "b"; builder->fsCodeAppendf("\tfloat %s = 2.0 * (%s * %s.x - %s);\n", bVar.c_str(), p2.c_str(), fsCoords, p3.c_str()); } // c = (x^2)+(y^2) - params[4] builder->fsCodeAppendf("\tfloat %s = dot(%s, %s) - %s;\n", cName.c_str(), fsCoords, fsCoords, p4.c_str()); // If we aren't degenerate, emit some extra code, and accept a slightly // more complex coord. if (!fIsDegenerate) { // ac4 = 4.0 * params[0] * c builder->fsCodeAppendf("\tfloat %s = %s * 4.0 * %s;\n", ac4Name.c_str(), p0.c_str(), cName.c_str()); // root = sqrt(b^2-4ac) // (abs to avoid exception due to fp precision) builder->fsCodeAppendf("\tfloat %s = sqrt(abs(%s*%s - %s));\n", rootName.c_str(), bVar.c_str(), bVar.c_str(), ac4Name.c_str()); // t is: (-b + params[5] * sqrt(b^2-4ac)) * params[1] t.printf("(-%s + %s * %s) * %s", bVar.c_str(), p5.c_str(), rootName.c_str(), p1.c_str()); } else { // t is: -c/b t.printf("-%s / %s", cName.c_str(), bVar.c_str()); } this->emitColorLookup(builder, t.c_str(), outputColor, inputColor, samplers[0]); } } void GrGLRadial2Gradient::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { INHERITED::setData(uman, drawEffect); const GrRadial2Gradient& data = drawEffect.castEffect<GrRadial2Gradient>(); GrAssert(data.isDegenerate() == fIsDegenerate); SkScalar centerX1 = data.center(); SkScalar radius0 = data.radius(); if (fCachedCenter != centerX1 || fCachedRadius != radius0 || fCachedPosRoot != data.isPosRoot()) { SkScalar a = SkScalarMul(centerX1, centerX1) - SK_Scalar1; // When we're in the degenerate (linear) case, the second // value will be INF but the program doesn't read it. (We // use the same 6 uniforms even though we don't need them // all in the linear case just to keep the code complexity // down). float values[6] = { SkScalarToFloat(a), 1 / (2.f * SkScalarToFloat(a)), SkScalarToFloat(centerX1), SkScalarToFloat(radius0), SkScalarToFloat(SkScalarMul(radius0, radius0)), data.isPosRoot() ? 1.f : -1.f }; uman.set1fv(fVSParamUni, 0, 6, values); uman.set1fv(fFSParamUni, 0, 6, values); fCachedCenter = centerX1; fCachedRadius = radius0; fCachedPosRoot = data.isPosRoot(); } } GrGLEffect::EffectKey GrGLRadial2Gradient::GenKey(const GrDrawEffect& drawEffect, const GrGLCaps&) { enum { kIsDegenerate = 1 << kMatrixKeyBitCnt, }; EffectKey key = GenMatrixKey(drawEffect); if (drawEffect.castEffect<GrRadial2Gradient>().isDegenerate()) { key |= kIsDegenerate; } return key; } ///////////////////////////////////////////////////////////////////// GrEffectRef* SkTwoPointRadialGradient::asNewEffect(GrContext* context, const SkPaint&) const { SkASSERT(NULL != context); // invert the localM, translate to center1 (fPtsToUni), rotate so center2 is on x axis. SkMatrix matrix; if (!this->getLocalMatrix().invert(&matrix)) { return NULL; } matrix.postConcat(fPtsToUnit); SkScalar diffLen = fDiff.length(); if (0 != diffLen) { SkScalar invDiffLen = SkScalarInvert(diffLen); SkMatrix rot; rot.setSinCos(-SkScalarMul(invDiffLen, fDiff.fY), SkScalarMul(invDiffLen, fDiff.fX)); matrix.postConcat(rot); } return GrRadial2Gradient::Create(context, *this, matrix, fTileMode); } #else GrEffectRef* SkTwoPointRadialGradient::asNewEffect(GrContext*, const SkPaint&) const { SkDEBUGFAIL("Should not call in GPU-less build"); return NULL; } #endif