int GGI_lin8_crossblit(ggi_visual *src, int sx, int sy, int w, int h, ggi_visual *dst, int dx, int dy) { LIBGGICLIP_COPYBOX(dst,sx,sy,w,h,dx,dy); PREPARE_FB(dst); /* Check if the src-read and dst-write buffers are in the same layout and that the destination pixelformat is sane. */ if (src->r_frame && src->r_frame->layout == dst->w_frame->layout && dst->w_frame->buffer.plb.pixelformat->stdformat != 0) { uint32_t srcformat = src->r_frame->buffer.plb.pixelformat->stdformat; uint32_t dstformat = dst->w_frame->buffer.plb.pixelformat->stdformat; int pixels = w*h; PREPARE_FB(src); /* These are the accelerated cases. If neither suits then * fall back to the default. */ if (srcformat == dstformat && pixels > 512) { if ((dst->palette->clut.size == src->palette->clut.size) && !memcmp(dst->palette->clut.data, src->palette->clut.data, sizeof(ggi_color)*dst->palette->clut.size)) { crossblit_same(src, sx, sy, w, h, dst, dx, dy); } else { crossblit_8_to_8(src, sx, sy, w, h, dst, dx, dy); } return 0; } } fallback(src, sx, sy, w, h, dst, dx, dy); return 0; }
Application::Application(int& argc, char** argv) : QtSingleApplication("org.gottcode.FocusWriter", argc, argv), m_window(0) { setApplicationName("FocusWriter"); setApplicationVersion(VERSIONSTR); setOrganizationDomain("gottcode.org"); setOrganizationName("GottCode"); { QIcon fallback(":/hicolor/256x256/apps/focuswriter.png"); fallback.addFile(":/hicolor/128x128/apps/focuswriter.png"); fallback.addFile(":/hicolor/64x64/apps/focuswriter.png"); fallback.addFile(":/hicolor/48x48/apps/focuswriter.png"); fallback.addFile(":/hicolor/32x32/apps/focuswriter.png"); fallback.addFile(":/hicolor/24x24/apps/focuswriter.png"); fallback.addFile(":/hicolor/22x22/apps/focuswriter.png"); fallback.addFile(":/hicolor/16x16/apps/focuswriter.png"); if (!QIcon::themeName().isEmpty() && (QIcon::themeName() != "hicolor")) { setWindowIcon(QIcon::fromTheme("focuswriter", fallback)); } else { setWindowIcon(fallback); } } #ifndef Q_OS_MAC setAttribute(Qt::AA_DontUseNativeMenuBar); #else setAttribute(Qt::AA_DontShowIconsInMenus, true); #endif # if defined(Q_OS_MAC) || defined(Q_OS_WIN32) new RTF::Clipboard; #endif qputenv("UNICODEMAP_JP", "cp932"); m_files = arguments().mid(1); processEvents(); }
void setInternalUserAuthParams(const BSONObj& authParamsIn) { if (!isInternalAuthSet()) { authParamsSet = true; } boost::mutex::scoped_lock lk(authParamMutex); if (authParamsIn["mechanism"].String() != "SCRAM-SHA-1") { authParams = authParamsIn.copy(); return; } // Create authParams for legacy MONGODB-CR authentication for 2.6/2.8 mixed // mode if applicable. mmb::Document fallback(authParamsIn); fallback.root().findFirstChildNamed("mechanism").setValueString("MONGODB-CR"); mmb::Document doc(authParamsIn); mmb::Element fallbackEl = doc.makeElementObject("fallbackParams"); fallbackEl.setValueObject(fallback.getObject()); doc.root().pushBack(fallbackEl); authParams = doc.getObject().copy(); }
bool peek(struct parser *parser, struct lexer *lex, enum token_type type) { /* {{{ peek_body */ struct token tok = fetch_token(parser, lex); fallback(lex); if (tok.type == type){ #if DEBUG /* {{{ */ if (NM_DEBUG_GET_FLAG(NM_DEBUG_LEXER)){ fprintf(stderr, "%s:%05u:%03u peek ", lex->name, lex->line, lex->col); debug_print_token(tok); fprintf(stderr, "\n"); } /* }}} */ #endif lex->curr_tok = tok; return true; } else { return false; } /* }}} */ }
Boolean transform1(xgobidata *xg, int *cols, int ncols, float *incr, float (*domain_adj)(float), float (*inv_domain_adj)(float), int tfnum, double param) { int i, j, k, n; float min, max, diff, t1, tincr; float mean, stddev; float fmedian, ref; Boolean allequal, tform_ok = true; double dtmp; switch (domain_ind) { case DOMAIN_OK: *incr = 0; domain_adj = no_change; inv_domain_adj = no_change; break; case RAISE_MIN_TO_0: tincr = fabs(xg->lim_raw[ tform_cols[0] ].min); for (j=0; j<ncols; j++) if ( (t1=fabs(xg->lim_raw[ tform_cols[j] ].min)) > tincr ) tincr = t1; *incr = tincr; domain_adj = raise_min_to_0; inv_domain_adj = inv_raise_min_to_0; break; case RAISE_MIN_TO_1: tincr = fabs(xg->lim_raw[ tform_cols[0] ].min); for (j=0; j<ncols; j++) if ( (t1=fabs(xg->lim_raw[ tform_cols[j] ].min)) > tincr ) tincr = t1; *incr = tincr; domain_adj = raise_min_to_1; inv_domain_adj = inv_raise_min_to_1; break; case NEGATE: *incr = 0.0; domain_adj = negate; inv_domain_adj = negate; break; default: *incr = 0; domain_adj = no_change; inv_domain_adj = no_change; } switch(tfnum) { case RESTORE: /* Restore original values -- set domain adj to null */ /* * If the transformation panel has been initialized, perform * the restore functions. * * Retore all, without regard to rows_in_plot */ if (domain_menu_btn != NULL && domain_menu_btn[DOMAIN_OK] != NULL) { XtCallCallbacks(domain_menu_btn[DOMAIN_OK], XtNcallback, (XtPointer) xg); for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows; i++) { xg->tform1[i][j] = xg->raw_data[i][j]; } (void) strcpy(xg->collab_tform1[j], xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } } break; case APPLY_ADJ: /* Apply domain adj */ for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = (*domain_adj)(xg->raw_data[k][j]); } (void) strcpy(xg->collab_tform1[j], xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case POWER: /* Box-Cox power transform family */ if (fabs(param-0) < .001) { /* Natural log */ for (n=0; n<ncols; n++) { if (!tform_ok) break; j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ((*domain_adj)(xg->raw_data[k][j]) <= 0) { fprintf(stderr, "%f %f\n", xg->raw_data[k][j], (*domain_adj)(xg->raw_data[k][j])); DOMAIN_ERROR; show_message(message, xg); tform_ok = false; break; } } } for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = (float) log((double) ((*domain_adj)(xg->raw_data[k][j]))); } (void) sprintf(xg->collab_tform1[j], "ln(%s)", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } } else { for (n=0; n<ncols; n++) { if (!tform_ok) break; j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; dtmp = pow((double) (*domain_adj)(xg->raw_data[k][j]), param); dtmp = (dtmp - 1.0) / param; /* If dtmp no good, restore and return */ if (!finite(dtmp)) { fprintf(stderr, "%f %f %f\n", xg->raw_data[k][j], (*domain_adj)(xg->raw_data[k][j]), dtmp); DOMAIN_ERROR; show_message(message, xg); fallback(xg); tform_ok = false; break; } xg->tform1[k][j] = (float) dtmp; } (void) sprintf(xg->collab_tform1[j], "B-C(%s,%.2f)", xg->collab[j], param); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } } break; case ABSVALUE: for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ((xg->raw_data[k][j] + domain_incr) < 0) xg->tform1[k][j] = (float) fabs((double)(*domain_adj)(xg->raw_data[k][j])) ; else xg->tform1[k][j] = (*domain_adj)(xg->raw_data[k][j]); } (void) sprintf(xg->collab_tform1[j], "Abs(%s)", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case INVERSE: /* 1/x */ for (n=0; n<ncols; n++) { if (!tform_ok) break; j = cols[n]; for (i=0; i<xg->nrows; i++) { k = xg->rows_in_plot[i]; if ((*domain_adj)(xg->raw_data[k][j]) == 0) { DOMAIN_ERROR; show_message(message, xg); tform_ok = false; break; } } } for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = (float) pow((double) (*domain_adj)(xg->raw_data[k][j]), (double) (-1.0)); } (void) sprintf(xg->collab_tform1[j], "1/%s", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case LOG10: /* Base 10 log */ for (n=0; n<ncols; n++) { if (!tform_ok) break; j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ( (*domain_adj)(xg->raw_data[k][j]) <= 0) { DOMAIN_ERROR; show_message(message, xg); tform_ok = false; break; } } } for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = (float) log10((double) (*domain_adj)(xg->raw_data[k][j])); } (void) sprintf(xg->collab_tform1[j], "log10(%s)", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case SCALE: /* Map onto [0,1] */ /* First find min and max; they get updated after transformations */ /* min = max = (*domain_adj)(xg->raw_data[0][cols[0]]); for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ( (ref = (*domain_adj)(xg->raw_data[k][j])) < min) min = ref; else if (ref > max) max = ref; } } adjust_limits(&min, &max); diff = max - min;*/ for (n=0; n<ncols; n++) { j = cols[n]; min = max = (*domain_adj)(xg->raw_data[0][j]); for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ( (ref = (*domain_adj)(xg->raw_data[k][j])) < min) min = ref; else if (ref > max) max = ref; } adjust_limits(&min, &max); diff = max - min; printf("%f, %f, %f\n",min,max,diff); for (i=0; i<xg->nrows; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = ((*domain_adj)(xg->raw_data[k][j]) - min)/diff; } (void) sprintf(xg->collab_tform1[j], "%s [0,1]", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case STANDARDIZE: /* (x-mean)/sigma */ /* DOMAIN_ERROR if stddev == 0 */ for (n=0; n<ncols; n++) { j = cols[n]; mean_stddev(xg, j, domain_adj, &mean, &stddev); for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = ((*domain_adj)(xg->raw_data[k][j]) - mean)/stddev; } (void) sprintf(xg->collab_tform1[j], "(%s-m)/s", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case DISCRETE2: /* x>median */ /* refuse to discretize if all values are the same */ for (n=0; n<ncols; n++) { j = cols[n]; allequal = True; ref = xg->raw_data[0][cols[j]]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if (xg->raw_data[k][j] != ref) { allequal = False; break; } } if (allequal) { DOMAIN_ERROR; show_message(message, xg); tform_ok = false; break; } } /* First find median */ /* Then find the true min and max */ for (n=0; n<ncols; n++) { j = cols[n]; min = max = (*domain_adj)(xg->raw_data[0][j]); fmedian = median (xg, xg->raw_data, j); fmedian = (*domain_adj)(fmedian); for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if ( (ref = (*domain_adj)(xg->raw_data[k][j])) < min) min = ref; else if (ref > max) max = ref; } /* }*/ /* This prevents the collapse of the data in a special case */ if (max == fmedian) fmedian = (min + max)/2.0; printf("%f %f %f \n",min,max,fmedian); /* for (n=0; n<ncols; n++) { j = cols[n];*/ for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = ( (*domain_adj)(xg->raw_data[k][j]) > fmedian ) ? 1.0 : 0.0; } (void) sprintf(xg->collab_tform1[j], "%s:0,1", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } break; case ZSCORE: { float *z_score_data; float ftmp; /* Allocate array for z scores */ z_score_data = (float *) XtMalloc((Cardinal) xg->nrows_in_plot * sizeof(float)); for (n=0; n<ncols; n++) { float zmean=0, zvar=0; j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; ftmp = (*domain_adj)(xg->raw_data[k][j]); z_score_data[k] = ftmp; zmean += ftmp; zvar += (ftmp * ftmp); } zmean /= xg->nrows_in_plot; zvar = (float)sqrt((float)(zvar/xg->nrows_in_plot - zmean*zmean)); for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; z_score_data[k] = (z_score_data[k]-zmean)/zvar; } for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; if (z_score_data[k]>0) z_score_data[k] = erf(z_score_data[k]/sqrt(2.))/ 2.8284271+0.5; else if (z_score_data[k]<0) z_score_data[k] = 0.5 - erf((float) fabs((double) z_score_data[k])/sqrt(2.))/2.8284271; else z_score_data[k]=0.5; } for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[k][j] = z_score_data[k]; } (void) sprintf(xg->collab_tform1[j], "zsc(%s)", xg->collab[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform1[j], NULL); } XtFree((XtPointer) z_score_data);/* mallika */ } break; case NORMSCORE: case RANK: { paird *pairs = (paird *) XtMalloc ((Cardinal) xg->nrows_in_plot * sizeof (paird)); for (n=0; n<ncols; n++) { j = cols[n]; for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; pairs[k].f = xg->raw_data[i][j]; pairs[k].indx = k; } qsort ((char *) pairs, xg->nrows_in_plot, sizeof (paird), pcompare); for (i=0; i<xg->nrows_in_plot; i++) { k = xg->rows_in_plot[i]; xg->tform1[pairs[k].indx][j] = (tfnum == RANK) ? (float) k : qnorm ((float) (k+1) / (float) (xg->nrows_in_plot+1)); } if (tfnum == NORMSCORE) (void) sprintf(xg->collab_tform2[j], "normsc(%s)", xg->collab_tform1[j]); else (void) sprintf(xg->collab_tform2[j], "rank(%s)", xg->collab_tform1[j]); XtVaSetValues(varlabel[j], XtNlabel, xg->collab_tform2[j], NULL); } XtFree ((XtPointer) pairs); } break; } if (tform_ok) { /* Set tform_tp[] for transformed columns */ for (n=0; n<ncols; n++) { tform_tp[cols[n]].tform1 = tfnum; tform_tp[cols[n]].domain_incr = *incr; tform_tp[cols[n]].param = param; tform_tp[cols[n]].domain_adj = domain_adj; tform_tp[cols[n]].inv_domain_adj = inv_domain_adj; } } for (n=0; n<ncols; n++) { j = cols[n]; (void) strcpy(xg->collab_tform2[j], xg->collab_tform1[j]); for (i=0; i<xg->nrows; i++) { xg->tform2[i][j] = xg->tform1[i][j]; } } return(tform_ok); }
static bool __icu_hasBinaryProperty(wint_t wc, UProperty property, int (*fallback)(int)) { typedef UBool (*FnT)(UChar32, UProperty); static auto u_hasBinaryProperty = reinterpret_cast<FnT>(__find_icu_symbol("u_hasBinaryProperty")); return u_hasBinaryProperty ? u_hasBinaryProperty(wc, property) : fallback(wc); }
enum nss_status _nss_resolve_gethostbyname3_r( const char *name, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp, char **canonp) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL, *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; char *r_name, *r_aliases, *r_addr, *r_addr_list; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; size_t l, idx, ms, alen; const char *canonical; int c, r, i = 0; assert(name); assert(result); assert(buffer); assert(errnop); assert(h_errnop); if (af == AF_UNSPEC) af = AF_INET; if (af != AF_INET && af != AF_INET6) { r = -EAFNOSUPPORT; goto fail; } r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_message_new_method_call( bus, &req, "org.freedesktop.resolve1", "/org/freedesktop/resolve1", "org.freedesktop.resolve1.Manager", "ResolveHostname"); if (r < 0) goto fail; r = sd_bus_message_set_auto_start(req, false); if (r < 0) goto fail; r = sd_bus_message_append(req, "isit", 0, name, af, (uint64_t) 0); if (r < 0) goto fail; r = sd_bus_call(bus, req, DNS_CALL_TIMEOUT_USEC, &error, &reply); if (r < 0) { if (sd_bus_error_has_name(&error, _BUS_ERROR_DNS "NXDOMAIN")) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } if (bus_error_shall_fallback(&error)) { enum nss_status (*fallback)( const char *name, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp, char **canonp); fallback = (enum nss_status (*)(const char *name, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp, char **canonp)) find_fallback("libnss_dns.so.2", "_nss_dns_gethostbyname3_r"); if (fallback) return fallback(name, af, result, buffer, buflen, errnop, h_errnop, ttlp, canonp); } *errnop = -r; *h_errnop = NO_RECOVERY; return NSS_STATUS_UNAVAIL; } c = count_addresses(reply, af, &canonical); if (c < 0) { r = c; goto fail; } if (c == 0) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } if (isempty(canonical)) canonical = name; alen = FAMILY_ADDRESS_SIZE(af); l = strlen(canonical); ms = ALIGN(l+1) + c * ALIGN(alen) + (c+2) * sizeof(char*); if (buflen < ms) { *errnop = ENOMEM; *h_errnop = TRY_AGAIN; return NSS_STATUS_TRYAGAIN; } /* First, append name */ r_name = buffer; memcpy(r_name, canonical, l+1); idx = ALIGN(l+1); /* Second, create empty aliases array */ r_aliases = buffer + idx; ((char**) r_aliases)[0] = NULL; idx += sizeof(char*); /* Third, append addresses */ r_addr = buffer + idx; r = sd_bus_message_enter_container(reply, 'a', "(iiay)"); if (r < 0) goto fail; while ((r = sd_bus_message_enter_container(reply, 'r', "iiay")) > 0) { int ifindex, family; const void *a; size_t sz; r = sd_bus_message_read(reply, "ii", &ifindex, &family); if (r < 0) goto fail; if (ifindex < 0) { r = -EINVAL; goto fail; } r = sd_bus_message_read_array(reply, 'y', &a, &sz); if (r < 0) goto fail; r = sd_bus_message_exit_container(reply); if (r < 0) goto fail; if (family != af) continue; if (sz != alen) { r = -EINVAL; goto fail; } memcpy(r_addr + i*ALIGN(alen), a, alen); i++; } if (r < 0) goto fail; assert(i == c); idx += c * ALIGN(alen); /* Fourth, append address pointer array */ r_addr_list = buffer + idx; for (i = 0; i < c; i++) ((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen); ((char**) r_addr_list)[i] = NULL; idx += (c+1) * sizeof(char*); assert(idx == ms); result->h_name = r_name; result->h_aliases = (char**) r_aliases; result->h_addrtype = af; result->h_length = alen; result->h_addr_list = (char**) r_addr_list; /* Explicitly reset all error variables */ *errnop = 0; *h_errnop = NETDB_SUCCESS; h_errno = 0; if (ttlp) *ttlp = 0; if (canonp) *canonp = r_name; return NSS_STATUS_SUCCESS; fail: *errnop = -r; *h_errnop = NO_DATA; return NSS_STATUS_UNAVAIL; }
// ---------------------------------------------------------------------------- void FontWithFace::render(const core::stringw& text, const core::rect<s32>& position, const video::SColor& color, bool hcenter, bool vcenter, const core::rect<s32>* clip, FontSettings* font_settings, FontCharCollector* char_collector) { const bool is_bold_face = dynamic_cast<BoldFace*>(this); const bool black_border = font_settings ? font_settings->useBlackBorder() : false; const bool rtl = font_settings ? font_settings->isRTL() : false; const float scale = font_settings ? font_settings->getScale() : 1.0f; const float shadow = font_settings ? font_settings->useShadow() : false; if (shadow) { assert(font_settings); // Avoid infinite recursion font_settings->setShadow(false); core::rect<s32> shadowpos = position; shadowpos.LowerRightCorner.X += 2; shadowpos.LowerRightCorner.Y += 2; render(text, shadowpos, font_settings->getShadowColor(), hcenter, vcenter, clip, font_settings); // Set back font_settings->setShadow(true); } core::position2d<float> offset(float(position.UpperLeftCorner.X), float(position.UpperLeftCorner.Y)); core::dimension2d<s32> text_dimension; if (rtl || hcenter || vcenter || clip) { text_dimension = getDimension(text.c_str(), font_settings); if (hcenter) offset.X += (position.getWidth() - text_dimension.Width) / 2; else if (rtl) offset.X += (position.getWidth() - text_dimension.Width); if (vcenter) offset.Y += (position.getHeight() - text_dimension.Height) / 2; if (clip) { core::rect<s32> clippedRect(core::position2d<s32> (s32(offset.X), s32(offset.Y)), text_dimension); clippedRect.clipAgainst(*clip); if (!clippedRect.isValid()) return; } } // Collect character locations const unsigned int text_size = text.size(); core::array<s32> indices(text_size); core::array<core::position2d<float>> offsets(text_size); std::vector<bool> fallback(text_size); // Test again if lazy load char is needed, // as some text isn't drawn with getDimension insertCharacters(text.c_str()); updateCharactersList(); for (u32 i = 0; i < text_size; i++) { wchar_t c = text[i]; if (c == L'\r' || // Windows breaks c == L'\n' ) // Unix breaks { if (c==L'\r' && text[i+1]==L'\n') c = text[++i]; offset.Y += m_font_max_height * scale; offset.X = position.UpperLeftCorner.X; if (hcenter) offset.X += (position.getWidth() - text_dimension.Width) >> 1; continue; } // if lineBreak bool use_fallback_font = false; const FontArea &area = getAreaFromCharacter(c, &use_fallback_font); fallback[i] = use_fallback_font; if (char_collector == NULL) { float glyph_offset_x = area.bearing_x * (fallback[i] ? m_fallback_font_scale : scale); float glyph_offset_y = area.offset_y * (fallback[i] ? m_fallback_font_scale : scale); offset.X += glyph_offset_x; offset.Y += glyph_offset_y; offsets.push_back(offset); offset.X -= glyph_offset_x; offset.Y -= glyph_offset_y; } else { // Prevent overwriting texture used by billboard text when // using lazy loading characters if (supportLazyLoadChar() && fallback[i]) { const int cur_texno = m_fallback_font->getSpriteBank() ->getSprites()[area.spriteno].Frames[0].textureNumber; if (cur_texno == int(m_fallback_font->getSpriteBank() ->getTextureCount() - 1)) { m_fallback_font->createNewGlyphPage(); } } else if (supportLazyLoadChar()) { const int cur_texno = m_spritebank ->getSprites()[area.spriteno].Frames[0].textureNumber; if (cur_texno == int(m_spritebank->getTextureCount() - 1)) { createNewGlyphPage(); } } // Billboard text specific, use offset_y_bt instead float glyph_offset_x = area.bearing_x * (fallback[i] ? m_fallback_font_scale : scale); float glyph_offset_y = area.offset_y_bt * (fallback[i] ? m_fallback_font_scale : scale); offset.X += glyph_offset_x; offset.Y += glyph_offset_y; offsets.push_back(offset); offset.X -= glyph_offset_x; offset.Y -= glyph_offset_y; } indices.push_back(area.spriteno); offset.X += getCharWidth(area, fallback[i], scale); } // for i < text_size // Do the actual rendering const int indice_amount = indices.size(); core::array<gui::SGUISprite>& sprites = m_spritebank->getSprites(); core::array<core::rect<s32>>& positions = m_spritebank->getPositions(); core::array<gui::SGUISprite>* fallback_sprites; core::array<core::rect<s32>>* fallback_positions; if (m_fallback_font != NULL) { fallback_sprites = &m_fallback_font->m_spritebank->getSprites(); fallback_positions = &m_fallback_font->m_spritebank->getPositions(); } else { fallback_sprites = NULL; fallback_positions = NULL; } const int sprite_amount = sprites.size(); if ((black_border || is_bold_face) && char_collector == NULL) { // Draw black border first, to make it behind the real character // which make script language display better video::SColor black(color.getAlpha(),0,0,0); for (int n = 0; n < indice_amount; n++) { const int sprite_id = indices[n]; if (!fallback[n] && (sprite_id < 0 || sprite_id >= sprite_amount)) continue; if (indices[n] == -1) continue; const int tex_id = (fallback[n] ? (*fallback_sprites)[sprite_id].Frames[0].textureNumber : sprites[sprite_id].Frames[0].textureNumber); core::rect<s32> source = (fallback[n] ? (*fallback_positions) [(*fallback_sprites)[sprite_id].Frames[0].rectNumber] : positions[sprites[sprite_id].Frames[0].rectNumber]); core::dimension2d<float> size(0.0f, 0.0f); float cur_scale = (fallback[n] ? m_fallback_font_scale : scale); size.Width = source.getSize().Width * cur_scale; size.Height = source.getSize().Height * cur_scale; core::rect<float> dest(offsets[n], size); video::ITexture* texture = (fallback[n] ? m_fallback_font->m_spritebank->getTexture(tex_id) : m_spritebank->getTexture(tex_id)); for (int x_delta = -2; x_delta <= 2; x_delta++) { for (int y_delta = -2; y_delta <= 2; y_delta++) { if (x_delta == 0 || y_delta == 0) continue; draw2DImage(texture, dest + core::position2d<float> (float(x_delta), float(y_delta)), source, clip, black, true); } } } } for (int n = 0; n < indice_amount; n++) { const int sprite_id = indices[n]; if (!fallback[n] && (sprite_id < 0 || sprite_id >= sprite_amount)) continue; if (indices[n] == -1) continue; const int tex_id = (fallback[n] ? (*fallback_sprites)[sprite_id].Frames[0].textureNumber : sprites[sprite_id].Frames[0].textureNumber); core::rect<s32> source = (fallback[n] ? (*fallback_positions)[(*fallback_sprites)[sprite_id].Frames[0] .rectNumber] : positions[sprites[sprite_id].Frames[0].rectNumber]); core::dimension2d<float> size(0.0f, 0.0f); float cur_scale = (fallback[n] ? m_fallback_font_scale : scale); size.Width = source.getSize().Width * cur_scale; size.Height = source.getSize().Height * cur_scale; core::rect<float> dest(offsets[n], size); video::ITexture* texture = (fallback[n] ? m_fallback_font->m_spritebank->getTexture(tex_id) : m_spritebank->getTexture(tex_id)); if (fallback[n] || is_bold_face) { video::SColor top = GUIEngine::getSkin()->getColor("font::top"); video::SColor bottom = GUIEngine::getSkin() ->getColor("font::bottom"); top.setAlpha(color.getAlpha()); bottom.setAlpha(color.getAlpha()); video::SColor title_colors[] = {top, bottom, top, bottom}; if (char_collector != NULL) { char_collector->collectChar(texture, dest, source, title_colors); } else { draw2DImage(texture, dest, source, clip, title_colors, true); } } else { if (char_collector != NULL) { video::SColor colors[] = {color, color, color, color}; char_collector->collectChar(texture, dest, source, colors); } else { draw2DImage(texture, dest, source, clip, color, true); } } } } // render
void Page::parse() { m_source = m_reply->readAll(); // Check redirection QUrl redir = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { m_url = m_site->fixUrl(redir.toString(), m_url); load(); return; } // Reading reply and resetting vars qDeleteAll(m_images); m_images.clear(); m_tags.clear(); /*m_imagesCount = -1; m_pagesCount = -1;*/ if (m_source.isEmpty()) { if (m_reply->error() != QNetworkReply::OperationCanceledError) { log("Loading error: "+m_reply->errorString()); fallback(); } return; } int first = m_smart ? ((m_page - 1) * m_imagesPerPage) % m_blim : 0; // XML if (m_format == "xml") { // Initializations QDomDocument doc; QString errorMsg; int errorLine, errorColumn; if (!doc.setContent(m_source, false, &errorMsg, &errorLine, &errorColumn)) { log(tr("Erreur lors de l'analyse du fichier XML : %1 (%2 - %3).").arg(errorMsg, QString::number(errorLine), QString::number(errorColumn))); fallback(); return; } QDomElement docElem = doc.documentElement(); // Getting last page int count = docElem.attributes().namedItem("count").nodeValue().toFloat(); QString database = docElem.attributes().namedItem("type").nodeValue(); if (count == 0 && database == "array") { count = docElem.elementsByTagName("total-count").at(0).toElement().text().toInt(); } if (count > 0) { m_imagesCount = count; } // Reading posts QDomNodeList nodeList = docElem.elementsByTagName("post"); if (nodeList.count() > 0) { for (int id = 0; id < nodeList.count(); id++) { QMap<QString,QString> d; if (database == "array") { QStringList infos, assoc; infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general" << "ext"; assoc << "created-at" << "status" << "source" << "has_comments" << "file-url" << "large-file-url" << "change" << "sample_width" << "has-children" << "preview-file-url" << "image-width" << "md5" << "preview_width" << "sample_height" << "parent-id" << "image-height" << "has_notes" << "uploader-id" << "file_size" << "id" << "preview_height" << "rating" << "tag-string" << "uploader-name" << "score" << "tag-string-artist" << "tag-string-character" << "tag-string-copyright" << "tag-string-general" << "file-ext"; for (int i = 0; i < infos.count(); i++) { d[infos.at(i)] = nodeList.at(id + first).namedItem(assoc.at(i)).toElement().text(); } } else { QStringList infos; infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score"; for (int i = 0; i < infos.count(); i++) { d[infos.at(i)] = nodeList.at(id + first).attributes().namedItem(infos.at(i)).nodeValue().trimmed(); } } this->parseImage(d, id + first); } } } // RSS else if (m_format == "rss") { // Initializations QDomDocument doc; QString errorMsg; int errorLine, errorColumn; if (!doc.setContent(m_source, false, &errorMsg, &errorLine, &errorColumn)) { log(tr("Erreur lors de l'analyse du fichier RSS : %1 (%2 - %3).").arg(errorMsg, QString::number(errorLine), QString::number(errorColumn))); fallback(); return; } QDomElement docElem = doc.documentElement(); // Reading posts QDomNodeList nodeList = docElem.elementsByTagName("item"); if (nodeList.count() > 0) { for (int id = 0; id < nodeList.count(); id++) { QDomNodeList children = nodeList.at(id + first).childNodes(); QMap<QString,QString> d, dat; for (int i = 0; i < children.size(); i++) { QString content = children.at(i).childNodes().at(0).nodeValue(); if (!content.isEmpty()) { dat.insert(children.at(i).nodeName(), content.trimmed()); } else { dat.insert(children.at(i).nodeName(), children.at(i).attributes().namedItem("url").nodeValue().trimmed()); } } // QDateTime::fromString(date, "ddd, dd MMM yyyy hh:mm:ss +0000"); // shimmie date format d.insert("page_url", dat["link"]); d.insert("tags", dat["media:keywords"]); d.insert("preview_url", dat["media:thumbnail"]); d.insert("sample_url", dat["media:content"]); d.insert("file_url", dat["media:content"]); if (!d.contains("id")) { QRegExp rx("/(\\d+)"); rx.indexIn(d["page_url"]); d.insert("id", rx.cap(1)); } this->parseImage(d, id + first); } } } // Regexes else if (m_format == "regex") { // Getting tags if (m_site->contains("Regex/Tags")) { QRegExp rxtags(m_site->value("Regex/Tags")); rxtags.setMinimal(true); QStringList tags = QStringList(); int p = 0; while (((p = rxtags.indexIn(m_source, p)) != -1)) { if (!tags.contains(rxtags.cap(2))) { m_tags.append(Tag(rxtags.cap(2), rxtags.cap(1), rxtags.cap(3).toInt())); tags.append(rxtags.cap(2)); } p += rxtags.matchedLength(); } } // Getting images QRegExp rx(m_site->value("Regex/Image")); QStringList order = m_site->value("Regex/Order").split('|'); rx.setMinimal(true); int pos = 0, id = 0; while ((pos = rx.indexIn(m_source, pos)) != -1) { pos += rx.matchedLength(); QMap<QString,QString> d; for (int i = 0; i < order.size(); i++) { d[order.at(i)] = rx.cap(i+1); } // JSON elements if (order.contains("json") && !d["json"].isEmpty()) { QVariant src = Json::parse(d["json"]); if (!src.isNull()) { QMap<QString,QVariant> map = src.toMap(); for (int i = 0; i < map.size(); i++) { d[map.keys().at(i)] = map.values().at(i).toString(); } } } this->parseImage(d, id + first); id++; } } // JSON else if (m_format == "json") { QVariant src = Json::parse(m_source); if (!src.isNull()) { QMap<QString, QVariant> sc; QList<QVariant> sourc = src.toList(); if (sourc.isEmpty()) { sourc = src.toMap().value("images").toList(); } for (int id = 0; id < sourc.count(); id++) { sc = sourc.at(id + first).toMap(); QMap<QString,QString> d; if (sc.contains("tag_string")) { QStringList infos, assoc; infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score" << "tags_artist" << "tags_character" << "tags_copyright" << "tags_general"; assoc << "created_at" << "status" << "source" << "has_comments" << "file_url" << "large_file_url" << "change" << "sample_width" << "has_children" << "preview_file_url" << "image_width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "image_height" << "has_notes" << "uploader_id" << "file_size" << "id" << "preview_height" << "rating" << "tag_string" << "uploader_name" << "score" << "tag_string_artist" << "tag_string_character" << "tag_string_copyright" << "tag_string_general"; for (int i = 0; i < infos.count(); i++) { d[infos.at(i)] = sc.value(assoc.at(i)).toString().trimmed(); } } else if (sc.contains("tag_ids")) { QStringList infos, assoc; infos << "created_at" << "source" << "file_url" << "preview_url" << "width" << "md5" << "height" << "id" << "tags" << "author" << "score"; assoc << "created_at" << "source_url" << "image" << "image" << "width" << "id" << "height" << "id_number" << "tags" << "uploader" << "score"; for (int i = 0; i < infos.count(); i++) { d[infos.at(i)] = sc.value(assoc.at(i)).toString().trimmed(); } } else { QStringList infos; infos << "created_at" << "status" << "source" << "has_comments" << "file_url" << "sample_url" << "change" << "sample_width" << "has_children" << "preview_url" << "width" << "md5" << "preview_width" << "sample_height" << "parent_id" << "height" << "has_notes" << "creator_id" << "file_size" << "id" << "preview_height" << "rating" << "tags" << "author" << "score"; for (int i = 0; i < infos.count(); i++) { d[infos.at(i)] = sc.value(infos.at(i)).toString().trimmed(); } } this->parseImage(d, id + first); } } else { fallback(); return; } } // If tags have not been retrieved yet if (m_tags.isEmpty()) { QStringList tagsGot; for (int i = 0; i < m_images.count(); i++) { QList<Tag> tags = m_images.at(i)->tags(); for (int t = 0; t < tags.count(); t++) { if (tagsGot.contains(tags[t].text())) { m_tags[tagsGot.indexOf(tags[t].text())].setCount(m_tags[tagsGot.indexOf(tags[t].text())].count()+1); } else { m_tags.append(tags[t]); tagsGot.append(tags[t].text()); } } } } // Getting last page if (m_site->contains("LastPage") && m_pagesCount < 1) { m_pagesCount = m_site->value("LastPage").toInt(); } if (m_site->contains("Regex/Count") && m_imagesCount < 1) { QRegExp rxlast(m_site->value("Regex/Count")); rxlast.indexIn(m_source, 0); m_imagesCount = rxlast.cap(1).remove(",").toInt(); } if (m_site->contains("Regex/LastPage") && m_pagesCount < 1) { QRegExp rxlast(m_site->value("Regex/LastPage")); rxlast.indexIn(m_source, 0); m_pagesCount = rxlast.cap(1).remove(",").toInt(); } // Guess images count if (m_site->contains("Urls/"+QString::number(m_currentSource)+"/Limit") && m_pagesCount > 0) { m_imagesCount = m_pagesCount * m_site->value("Urls/"+QString::number(m_currentSource)+"/Limit").toInt(); } // Remove first n images (according to site settings) int skip = m_site->setting("ignore/always", 0).toInt(); if (m_page == m_site->value("FirstPage").toInt()) skip = m_site->setting("ignore/1", 0).toInt(); if (m_images.size() > m_imagesPerPage && m_images.size() > skip) for (int i = 0; i < skip; ++i) m_images.removeFirst(); // Virtual paging int firstImage = 0; int lastImage = m_smart ? m_imagesPerPage : m_images.size(); if (!m_originalUrl.contains("{page}")) { firstImage = m_imagesPerPage * (m_page - 1); lastImage = m_imagesPerPage; } while (firstImage > 0) { m_images.removeFirst(); firstImage--; } while (m_images.size() > lastImage) { m_images.removeLast(); } m_reply->deleteLater(); m_replyExists = false; QString t = m_search.join(" "); if (m_site->contains("DefaultTag") && t.isEmpty()) { t = m_site->value("DefaultTag"); } if (!m_search.isEmpty() && !m_site->value("Urls/"+QString::number(m_currentSource)+"/"+(t.isEmpty() && !m_site->contains("Urls/"+QString::number(m_currentSource)+"/Home") ? "Home" : "Tags")).contains("{tags}")) { m_errors.append(tr("La recherche par tags est impossible avec la source choisie (%1).").arg(m_format)); } emit finishedLoading(this); }
//TODO: virtual void operator()( Sprite& o ) { fallback(o); } virtual void operator()( Mesh& o ) { fallback(o); }
virtual void operator()( Particle& o ) { fallback(o); }
//TODO: virtual void operator()( Bone& o ) { fallback(o); } virtual void operator()( Camera& o ) { fallback(o); }
//! draws some text and clips it to the specified rectangle if wanted void ScalableFont::doDraw(const core::stringw& text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip, FontCharCollector* charCollector) { if (!Driver) return; if (m_shadow) { m_shadow = false; // avoid infinite recursion core::rect<s32> shadowpos = position; shadowpos.LowerRightCorner.X += 2; shadowpos.LowerRightCorner.Y += 2; draw(text, shadowpos, m_shadow_color, hcenter, vcenter, clip); m_shadow = true; // set back } core::position2d<s32> offset = position.UpperLeftCorner; core::dimension2d<s32> text_dimension; if (m_rtl || hcenter || vcenter || clip) { text_dimension = getDimension(text.c_str()); if (hcenter) offset.X += (position.getWidth() - text_dimension.Width) / 2; else if (m_rtl) offset.X += (position.getWidth() - text_dimension.Width); if (vcenter) offset.Y += (position.getHeight() - text_dimension.Height) / 2; if (clip) { core::rect<s32> clippedRect(offset, text_dimension); clippedRect.clipAgainst(*clip); if (!clippedRect.isValid()) return; } } // ---- collect character locations const unsigned int text_size = text.size(); core::array<s32> indices(text_size); core::array<core::position2di> offsets(text_size); std::vector<bool> fallback(text_size); for (u32 i = 0; i<text_size; i++) { wchar_t c = text[i]; if (c == L'\r' || // Windows breaks c == L'\n' ) // Unix breaks { if(c==L'\r' && text[i+1]==L'\n') c = text[++i]; offset.Y += (int)(MaxHeight*m_scale); offset.X = position.UpperLeftCorner.X; if (hcenter) offset.X += (position.getWidth() - text_dimension.Width) >> 1; continue; } // if lineBreak bool use_fallback_font = false; const SFontArea &area = getAreaFromCharacter(c, &use_fallback_font); fallback[i] = use_fallback_font; offset.X += area.underhang; offsets.push_back(offset); // Invisible character. add something to the array anyway so that // indices from the various arrays remain in sync indices.push_back( Invisible.findFirst(c) < 0 ? area.spriteno : -1 ); offset.X += getCharWidth(area, fallback[i]); } // for i<text_size // ---- do the actual rendering const int indiceAmount = indices.size(); core::array< SGUISprite >& sprites = SpriteBank->getSprites(); core::array< core::rect<s32> >& positions = SpriteBank->getPositions(); core::array< SGUISprite >* fallback_sprites; core::array< core::rect<s32> >* fallback_positions; if(m_fallback_font!=NULL) { fallback_sprites = &m_fallback_font->SpriteBank->getSprites(); fallback_positions = &m_fallback_font->SpriteBank->getPositions(); } else { fallback_sprites = NULL; fallback_positions = NULL; } const int spriteAmount = sprites.size(); for (int n=0; n<indiceAmount; n++) { const int spriteID = indices[n]; if (!fallback[n] && (spriteID < 0 || spriteID >= spriteAmount)) continue; if (indices[n] == -1) continue; //assert(sprites[spriteID].Frames.size() > 0); const int texID = (fallback[n] ? (*fallback_sprites)[spriteID].Frames[0].textureNumber : sprites[spriteID].Frames[0].textureNumber); core::rect<s32> source = (fallback[n] ? (*fallback_positions)[(*fallback_sprites)[spriteID].Frames[0].rectNumber] : positions[sprites[spriteID].Frames[0].rectNumber]); const TextureInfo& info = (fallback[n] ? (*(m_fallback_font->m_texture_files.find(texID))).second : (*(m_texture_files.find(texID))).second ); float char_scale = info.m_scale; core::dimension2d<s32> size = source.getSize(); float scale = (fallback[n] ? m_scale*m_fallback_font_scale : m_scale); size.Width = (int)(size.Width * scale * char_scale); size.Height = (int)(size.Height * scale * char_scale); // align vertically if character is smaller int y_shift = (size.Height < MaxHeight*m_scale ? (int)((MaxHeight*m_scale - size.Height)/2.0f) : 0); core::rect<s32> dest(offsets[n] + core::position2di(0, y_shift), size); video::ITexture* texture = (fallback[n] ? m_fallback_font->SpriteBank->getTexture(texID) : SpriteBank->getTexture(texID) ); /* if (fallback[n]) { Log::info("ScalableFont", "Using fallback font %s; source area is %d, %d; size %d, %d; dest = %d, %d", core::stringc(texture->getName()).c_str(), source.UpperLeftCorner.X, source.UpperLeftCorner.Y, source.getWidth(), source.getHeight(), offsets[n].X, offsets[n].Y); } */ if (texture == NULL) { // perform lazy loading if (fallback[n]) { m_fallback_font->lazyLoadTexture(texID); texture = m_fallback_font->SpriteBank->getTexture(texID); } else { lazyLoadTexture(texID); texture = SpriteBank->getTexture(texID); } if (texture == NULL) { Log::warn("ScalableFont", "Character not found in current font"); continue; // no such character } } if (m_black_border && charCollector == NULL) { // draw black border video::SColor black(color.getAlpha(),0,0,0); for (int x_delta=-2; x_delta<=2; x_delta++) { for (int y_delta=-2; y_delta<=2; y_delta++) { if (x_delta == 0 || y_delta == 0) continue; draw2DImage(texture, dest + core::position2d<s32>(x_delta, y_delta), source, clip, black, true); } } } if (fallback[n]) { // TODO: don't hardcode colors? video::SColor orange(color.getAlpha(), 255, 100, 0); video::SColor yellow(color.getAlpha(), 255, 220, 15); video::SColor title_colors[] = {orange, yellow, orange, yellow}; if (charCollector != NULL) { charCollector->collectChar(texture, dest, source, title_colors); } else { draw2DImage(texture, dest, source, clip, title_colors, true); } } else { if (charCollector != NULL) { video::SColor colors[] = { color, color, color, color }; charCollector->collectChar(texture, dest, source, colors); } else { draw2DImage(texture, dest, source, clip, color, true); } #ifdef FONT_DEBUG video::IVideoDriver* driver = GUIEngine::getDriver(); driver->draw2DLine(core::position2d<s32>(dest.UpperLeftCorner.X, dest.UpperLeftCorner.Y), core::position2d<s32>(dest.UpperLeftCorner.X, dest.LowerRightCorner.Y), video::SColor(255, 255,0,0)); driver->draw2DLine(core::position2d<s32>(dest.LowerRightCorner.X, dest.LowerRightCorner.Y), core::position2d<s32>(dest.LowerRightCorner.X, dest.UpperLeftCorner.Y), video::SColor(255, 255,0,0)); driver->draw2DLine(core::position2d<s32>(dest.LowerRightCorner.X, dest.LowerRightCorner.Y), core::position2d<s32>(dest.UpperLeftCorner.X, dest.LowerRightCorner.Y), video::SColor(255, 255,0,0)); driver->draw2DLine(core::position2d<s32>(dest.UpperLeftCorner.X, dest.UpperLeftCorner.Y), core::position2d<s32>(dest.LowerRightCorner.X, dest.UpperLeftCorner.Y), video::SColor(255, 255,0,0)); #endif } } }
U_CAPI const UChar* U_EXPORT2 ucurr_getName(const UChar* currency, const char* locale, UCurrNameStyle nameStyle, UBool* isChoiceFormat, // fillin int32_t* len, // fillin UErrorCode* ec) { // Look up the Currencies resource for the given locale. The // Currencies locale data looks like this: //|en { //| Currencies { //| USD { "US$", "US Dollar" } //| CHF { "Sw F", "Swiss Franc" } //| INR { "=0#Rs|1#Re|1<Rs", "=0#Rupees|1#Rupee|1<Rupees" } //| //... //| } //|} if (ec == NULL || U_FAILURE(*ec)) { return 0; } int32_t choice = (int32_t) nameStyle; if (choice < 0 || choice > 1) { *ec = U_ILLEGAL_ARGUMENT_ERROR; return 0; } // In the future, resource bundles may implement multi-level // fallback. That is, if a currency is not found in the en_US // Currencies data, then the en Currencies data will be searched. // Currently, if a Currencies datum exists in en_US and en, the // en_US entry hides that in en. // We want multi-level fallback for this resource, so we implement // it manually. // Use a separate UErrorCode here that does not propagate out of // this function. UErrorCode ec2 = U_ZERO_ERROR; char loc[ULOC_FULLNAME_CAPACITY]; uloc_getName(locale, loc, sizeof(loc), &ec2); if (U_FAILURE(ec2) || ec2 == U_STRING_NOT_TERMINATED_WARNING) { *ec = U_ILLEGAL_ARGUMENT_ERROR; return 0; } char buf[ISO_COUNTRY_CODE_LENGTH+1]; myUCharsToChars(buf, currency); const UChar* s = NULL; // Multi-level resource inheritance fallback loop for (;;) { ec2 = U_ZERO_ERROR; UResourceBundle* rb = ures_open(NULL, loc, &ec2); UResourceBundle* curr = ures_getByKey(rb, CURRENCIES, NULL, &ec2); UResourceBundle* names = ures_getByKey(curr, buf, NULL, &ec2); s = ures_getStringByIndex(names, choice, len, &ec2); ures_close(names); ures_close(curr); ures_close(rb); // If we've succeeded we're done. Otherwise, try to fallback. // If that fails (because we are already at root) then exit. if (U_SUCCESS(ec2) || !fallback(loc)) { break; } } // Determine if this is a ChoiceFormat pattern. One leading mark // indicates a ChoiceFormat. Two indicates a static string that // starts with a mark. In either case, the first mark is ignored, // if present. Marks in the rest of the string have no special // meaning. *isChoiceFormat = FALSE; if (U_SUCCESS(ec2)) { U_ASSERT(s != NULL); int32_t i=0; while (i < *len && s[i] == CHOICE_FORMAT_MARK && i < 2) { ++i; } *isChoiceFormat = (i == 1); if (i != 0) ++s; // Skip over first mark return s; } // If we fail to find a match, use the ISO 4217 code *len = u_strlen(currency); // Should == ISO_COUNTRY_CODE_LENGTH, but maybe not...? return currency; }
void WrapperFactoryTest::testUnknown() { struct IntFactory { static int * timesOne(int * factor) { int * result = new int; *result = *factor * 1; return result; } static int * timesTwo(int * factor) { int * result = new int; *result = *factor * 2; return result; } static int * timesThree(int * factor) { int * result = new int; *result = *factor * 3; return result; } }; typedef std::function<int * (int *)> IntCreator; { Util::WrapperFactory<int *, int *, int, IntCreator, Util::FallbackPolicies::ExceptionFallback> factory; factory.registerType(1, IntFactory::timesOne); factory.registerType(2, IntFactory::timesTwo); factory.registerType(3, IntFactory::timesThree); int one = 1; int two = 2; int three = 3; int * productA = factory.create(3, &one); int * productB = factory.create(2, &two); int * productC = factory.create(1, &three); CPPUNIT_ASSERT(productA != nullptr); CPPUNIT_ASSERT(productB != nullptr); CPPUNIT_ASSERT(productC != nullptr); CPPUNIT_ASSERT_EQUAL(3, *productA); CPPUNIT_ASSERT_EQUAL(4, *productB); CPPUNIT_ASSERT_EQUAL(3, *productC); delete productC; delete productB; delete productA; typedef Util::FallbackPolicies::ExceptionFallback<int *, int>::Exception FactoryException; CPPUNIT_ASSERT_THROW(factory.create(0, &one), FactoryException); CPPUNIT_ASSERT_THROW(factory.create(4, &two), FactoryException); CPPUNIT_ASSERT_THROW(factory.create(17, &three), FactoryException); } { Util::WrapperFactory<int *, int *, int, IntCreator, Util::FallbackPolicies::NULLFallback> factory; factory.registerType(1, IntFactory::timesOne); factory.registerType(2, IntFactory::timesTwo); factory.registerType(3, IntFactory::timesThree); int one = 1; int two = 2; int three = 3; CPPUNIT_ASSERT_EQUAL(static_cast<int *>(nullptr), factory.create(0, &one)); CPPUNIT_ASSERT_EQUAL(static_cast<int *>(nullptr), factory.create(4, &two)); CPPUNIT_ASSERT_EQUAL(static_cast<int *>(nullptr), factory.create(17, &three)); CPPUNIT_ASSERT_NO_THROW(factory.create(0, &one)); CPPUNIT_ASSERT_NO_THROW(factory.create(4, &two)); CPPUNIT_ASSERT_NO_THROW(factory.create(17, &three)); } { std::ostringstream outputStream; Util::FallbackPolicies::DefaultCreatorFallback<int *, int> fallback(2, outputStream); Util::WrapperFactory<int *, int *, int, IntCreator, Util::FallbackPolicies::DefaultCreatorFallback> factory(fallback); factory.registerType(1, IntFactory::timesOne); factory.registerType(2, IntFactory::timesTwo); factory.registerType(3, IntFactory::timesThree); int one = 1; int two = 2; int three = 3; int * productA = factory.create(0, &one); int * productB = factory.create(4, &two); int * productC = factory.create(17, &three); CPPUNIT_ASSERT(outputStream.good()); CPPUNIT_ASSERT(!outputStream.str().empty()); CPPUNIT_ASSERT(productA != nullptr); CPPUNIT_ASSERT(productB != nullptr); CPPUNIT_ASSERT(productC != nullptr); CPPUNIT_ASSERT_EQUAL(2, *productA); CPPUNIT_ASSERT_EQUAL(4, *productB); CPPUNIT_ASSERT_EQUAL(6, *productC); delete productC; delete productB; delete productA; } }
int main(int argc, char *argv[]) { struct addrinfo hints, *res, *src=NULL; int r; int sock, output_fd; union { struct group_req gr; struct group_source_req gsr; } gr; int ifid, level; int ssm = 0; int on = 1; int first = 1; parseCmdLine(argc, argv); if (conf_output) { output_fd = open(conf_output, O_WRONLY | O_CREAT | O_TRUNC, 0755); free(conf_output); conf_output = NULL; } else { output_fd = fileno(stdout); if (isatty(output_fd)) { logger(LOG_ERROR, "Output should be redirected. Not writing any data.\n"); output_fd = open("/dev/null", O_WRONLY); } } if (output_fd < 0) { logger(LOG_FATAL, "Cannot open output file: %s\n", strerror(errno)); exit(EXIT_FAILURE); } memset(&hints, 0, sizeof(hints)); hints.ai_family = conf_family; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; r = getaddrinfo(conf_IP, conf_port, &hints, &res); free(conf_IP); conf_IP=NULL; free(conf_port); conf_port=NULL; if (r) { logger(LOG_FATAL, "Getaddrinfo failed: %s\n", gai_strerror(r)); exit(EXIT_FAILURE); } if (res->ai_next != NULL) { logger(LOG_ERROR, "The multicast address is ambiguous!\n"); } sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); r = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); if (r) { logger(LOG_ERROR, "SO_REUSEADDR " "failed: %s\n", strerror(errno)); } r = bind(sock,(struct sockaddr *) res->ai_addr, res->ai_addrlen); if (r) { logger(LOG_FATAL, "Cannot bind: %s\n", strerror(errno)); exit(EXIT_FAILURE); } /** SSM Case */ if (conf_source) { memset(&hints, 0, sizeof(hints)); hints.ai_family = conf_family; r = getaddrinfo(conf_source, NULL, &hints, &src); free(conf_source); conf_source=NULL; if (r) { logger(LOG_FATAL, "Source getaddrinfo failed: %s. Ignoring.\n", gai_strerror(r)); ssm = 0; } else { if (res->ai_next != NULL) { logger(LOG_ERROR, "The source address is ambiguous!\n"); } memcpy(&(gr.gsr.gsr_source), src->ai_addr, min(sizeof(gr.gsr.gsr_source), src->ai_addrlen)); ssm = 1; freeaddrinfo(src); src=NULL; } } /** Interface Case */ if (conf_interface) { ifid = if_nametoindex(conf_interface); if (ifid == 0) { logger(LOG_ERROR, "Interface %s not found. Ignoring\n", conf_interface); } free(conf_interface); conf_interface=NULL; } else { ifid = 0; } switch (res->ai_family) { case AF_INET: level = SOL_IP; break; case AF_INET6: level = SOL_IPV6; if ( ((const struct sockaddr_in6 *) (res->ai_addr))->sin6_scope_id != 0) { if (ifid != 0) { logger(LOG_ERROR, "Interface id overriden " "by scoped IPv6 address.\n"); } ifid = ((const struct sockaddr_in6 *) (res->ai_addr))->sin6_scope_id; } break; default: logger(LOG_ERROR, "Address family does not support mcast.\n"); exit(EXIT_FAILURE); } if (ssm) { memcpy(&(gr.gsr.gsr_group), res->ai_addr, min(sizeof(gr.gsr.gsr_group), res->ai_addrlen)); gr.gsr.gsr_interface = ifid; r = setsockopt(sock, level, MCAST_JOIN_SOURCE_GROUP, &(gr.gsr), sizeof(gr.gsr)); } else { memcpy(&(gr.gr.gr_group), res->ai_addr, min(sizeof(gr.gr.gr_group), res->ai_addrlen)); gr.gr.gr_interface = ifid; r = setsockopt(sock, level, MCAST_JOIN_GROUP, &(gr.gr), sizeof(gr.gr)); } if (r) { logger(LOG_ERROR, "Cannot join mcast group: %s\n", strerror(errno)); /*Fallback to protocol-specific API*/ if (fallback(sock, ssm, ssm? (void*)&(gr.gsr):(void*)&(gr.gr))){ logger(LOG_FATAL, "Fallback failed.\n"); exit(EXIT_FAILURE); } logger(LOG_ERROR, "Fallback succeded.\n"); } freeaddrinfo(res); res= NULL; /** Joined. Let's forward traffic. */ logger(LOG_DEBUG, "Joined. Waiting for data...\n"); while(1) { uint8_t buf[UDPBUFLEN]; int payloadstart, payloadlength; uint16_t seqn, oldseqn; r = recv(sock, buf, sizeof(buf), 0); if (r < 0){ logger(LOG_FATAL,"Recv() failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (first) { logger(LOG_INFO, "First packet received. Good.\n"); } if (first && !conf_udponly && (r < 12 || (buf[0]&0xC0) != 0x80)) { logger(LOG_ERROR, "First packet is not RTP, " "switching to UDP mode.\n"); conf_udponly = 1; } if (!conf_udponly) { if (r < 12 || (buf[0]&0xC0) != 0x80) { /*malformed RTP/UDP/IP packet*/ logger(LOG_INFO,"Malformed RTP packet received\n"); continue; } payloadstart = 12; /* basic RTP header length */ if (buf[0]&0x0F) { payloadstart += (buf[0]&0x0F) * 4; /*CRSC headers*/ logger(LOG_DEBUG, "CRSC header found\n"); } if (buf[0]&0x10) { /*Extension header*/ payloadstart += 4 + 4*ntohs(*((uint16_t *)(buf+payloadstart+2))); logger(LOG_DEBUG, "Extension header found\n"); } payloadlength = r - payloadstart; if (buf[0]&0x20) { /*Padding*/ payloadlength -= buf[r]; logger(LOG_DEBUG, "Padding found\n"); /*last octet indicate padding length*/ } if(payloadlength<0) { logger(LOG_INFO,"Malformed RTP packet received\n"); continue; } seqn = ntohs(*((uint16_t *)(buf+2))); if (!first && seqn==oldseqn) { logger(LOG_INFO,"Duplicated RTP packet " "received (seqn %d)\n", seqn); continue; } if (!first && (seqn != ((oldseqn+1)&0xFFFF))) { logger(LOG_INFO,"Congestion - expected %d, " "received %d\n", (oldseqn+1)&0xFFFF, seqn); } oldseqn=seqn; } else { payloadstart = 0; payloadlength = r; } first=0; while (payloadlength>0) { r = write(output_fd, buf+payloadstart, payloadlength); if (r<0) { logger(LOG_FATAL, "Write failed: %s\n", strerror(errno)); exit(EXIT_FAILURE); } if (r != payloadlength) { logger(LOG_DEBUG, "Not all data written -" " requested %d, written %d\n", payloadlength, r); } payloadstart += r; payloadlength -= r; } } /* should never reach here */ return 0; }
virtual void operator()( Line& o ) { fallback(o); }
/** * Damage a file. * - The file must exist. * - The file size is not changed. * - The written data is SURELY different than the already existing one. * - The file timestamp is NOT modified. * - If it's a symlink nothing is done. */ void cmd_damage(const char* path, int size) { struct stat st; /* here a 0 size means to change nothing */ /* as also the timestamp should not be changed */ if (!size) return; if (lstat(path, &st) != 0) { /* LCOV_EXCL_START */ log_fatal("Error accessing %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (st.st_size == 0) return; if (S_ISREG(st.st_mode)) { off_t off; unsigned char* data; int f; /* not over the end */ if (size > st.st_size) size = st.st_size; /* start at random position inside the file */ if (size < st.st_size) off = rnd(st.st_size - size); else off = 0; data = malloc(size); f = open(path, O_RDWR | O_BINARY | O_NOFOLLOW); if (f < 0) { /* LCOV_EXCL_START */ log_fatal("Error creating file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (lseek(f, off, SEEK_SET) != off) { /* LCOV_EXCL_START */ log_fatal("Error seeking file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (read(f, data, size) != size) { /* LCOV_EXCL_START */ log_fatal("Error writing file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } rndnz_damage(data, size); if (lseek(f, off, SEEK_SET) != off) { /* LCOV_EXCL_START */ log_fatal("Error seeking file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (write(f, data, size) != size) { /* LCOV_EXCL_START */ log_fatal("Error writing file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (fallback(f, &st) != 0) { /* LCOV_EXCL_START */ log_fatal("Error setting time for file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } if (close(f) != 0) { /* LCOV_EXCL_START */ log_fatal("Error closing file %s\n", path); exit(EXIT_FAILURE); /* LCOV_EXCL_STOP */ } free(data); } }
void set_is_private() { executor(empty_cache_private); fallback(empty_cache_private); }
void set_is_super() { executor(empty_cache_super); fallback(empty_cache_super); }
void set_is_vcall() { executor(empty_cache_vcall); fallback(empty_cache_vcall); }
enum nss_status _nss_resolve_gethostbyname4_r( const char *name, struct gaih_addrtuple **pat, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL, *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; struct gaih_addrtuple *r_tuple, *r_tuple_first = NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; const char *canonical = NULL; size_t l, ms, idx; char *r_name; int c, r, i = 0; assert(name); assert(pat); assert(buffer); assert(errnop); assert(h_errnop); r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_message_new_method_call( bus, &req, "org.freedesktop.resolve1", "/org/freedesktop/resolve1", "org.freedesktop.resolve1.Manager", "ResolveHostname"); if (r < 0) goto fail; r = sd_bus_message_set_auto_start(req, false); if (r < 0) goto fail; r = sd_bus_message_append(req, "isit", 0, name, AF_UNSPEC, (uint64_t) 0); if (r < 0) goto fail; r = sd_bus_call(bus, req, DNS_CALL_TIMEOUT_USEC, &error, &reply); if (r < 0) { if (sd_bus_error_has_name(&error, _BUS_ERROR_DNS "NXDOMAIN")) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } if (bus_error_shall_fallback(&error)) { enum nss_status (*fallback)( const char *name, struct gaih_addrtuple **pat, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp); fallback = (enum nss_status (*)(const char *name, struct gaih_addrtuple **pat, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp)) find_fallback("libnss_dns.so.2", "_nss_dns_gethostbyname4_r"); if (fallback) return fallback(name, pat, buffer, buflen, errnop, h_errnop, ttlp); } *errnop = -r; *h_errnop = NO_RECOVERY; return NSS_STATUS_UNAVAIL; } c = count_addresses(reply, AF_UNSPEC, &canonical); if (c < 0) { r = c; goto fail; } if (c == 0) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } if (isempty(canonical)) canonical = name; l = strlen(canonical); ms = ALIGN(l+1) + ALIGN(sizeof(struct gaih_addrtuple)) * c; if (buflen < ms) { *errnop = ENOMEM; *h_errnop = TRY_AGAIN; return NSS_STATUS_TRYAGAIN; } /* First, append name */ r_name = buffer; memcpy(r_name, canonical, l+1); idx = ALIGN(l+1); /* Second, append addresses */ r_tuple_first = (struct gaih_addrtuple*) (buffer + idx); r = sd_bus_message_enter_container(reply, 'a', "(iiay)"); if (r < 0) goto fail; while ((r = sd_bus_message_enter_container(reply, 'r', "iiay")) > 0) { int family, ifindex; const void *a; size_t sz; assert_cc(sizeof(int32_t) == sizeof(int)); r = sd_bus_message_read(reply, "ii", &ifindex, &family); if (r < 0) goto fail; if (ifindex < 0) { r = -EINVAL; goto fail; } r = sd_bus_message_read_array(reply, 'y', &a, &sz); if (r < 0) goto fail; r = sd_bus_message_exit_container(reply); if (r < 0) goto fail; if (!IN_SET(family, AF_INET, AF_INET6)) continue; if (sz != FAMILY_ADDRESS_SIZE(family)) { r = -EINVAL; goto fail; } r_tuple = (struct gaih_addrtuple*) (buffer + idx); r_tuple->next = i == c-1 ? NULL : (struct gaih_addrtuple*) ((char*) r_tuple + ALIGN(sizeof(struct gaih_addrtuple))); r_tuple->name = r_name; r_tuple->family = family; r_tuple->scopeid = ifindex; memcpy(r_tuple->addr, a, sz); idx += ALIGN(sizeof(struct gaih_addrtuple)); i++; } if (r < 0) goto fail; assert(i == c); assert(idx == ms); if (*pat) **pat = *r_tuple_first; else *pat = r_tuple_first; if (ttlp) *ttlp = 0; /* Explicitly reset all error variables */ *errnop = 0; *h_errnop = NETDB_SUCCESS; h_errno = 0; return NSS_STATUS_SUCCESS; fail: *errnop = -r; *h_errnop = NO_DATA; return NSS_STATUS_UNAVAIL; }
void set_executor(CacheExecutor exec) { executor(exec); fallback(exec); }
enum nss_status _nss_resolve_gethostbyaddr2_r( const void* addr, socklen_t len, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp) { _cleanup_(sd_bus_message_unrefp) sd_bus_message *req = NULL, *reply = NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; char *r_name, *r_aliases, *r_addr, *r_addr_list; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; unsigned c = 0, i = 0; size_t ms = 0, idx; const char *n; int r, ifindex; assert(addr); assert(result); assert(buffer); assert(errnop); assert(h_errnop); if (!IN_SET(af, AF_INET, AF_INET6)) { *errnop = EAFNOSUPPORT; *h_errnop = NO_DATA; return NSS_STATUS_UNAVAIL; } if (len != FAMILY_ADDRESS_SIZE(af)) { *errnop = EINVAL; *h_errnop = NO_RECOVERY; return NSS_STATUS_UNAVAIL; } r = sd_bus_open_system(&bus); if (r < 0) goto fail; r = sd_bus_message_new_method_call( bus, &req, "org.freedesktop.resolve1", "/org/freedesktop/resolve1", "org.freedesktop.resolve1.Manager", "ResolveAddress"); if (r < 0) goto fail; r = sd_bus_message_set_auto_start(req, false); if (r < 0) goto fail; r = sd_bus_message_append(req, "ii", 0, af); if (r < 0) goto fail; r = sd_bus_message_append_array(req, 'y', addr, len); if (r < 0) goto fail; r = sd_bus_message_append(req, "t", (uint64_t) 0); if (r < 0) goto fail; r = sd_bus_call(bus, req, DNS_CALL_TIMEOUT_USEC, &error, &reply); if (r < 0) { if (sd_bus_error_has_name(&error, _BUS_ERROR_DNS "NXDOMAIN")) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } if (bus_error_shall_fallback(&error)) { enum nss_status (*fallback)( const void* addr, socklen_t len, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp); fallback = (enum nss_status (*)( const void* addr, socklen_t len, int af, struct hostent *result, char *buffer, size_t buflen, int *errnop, int *h_errnop, int32_t *ttlp)) find_fallback("libnss_dns.so.2", "_nss_dns_gethostbyaddr2_r"); if (fallback) return fallback(addr, len, af, result, buffer, buflen, errnop, h_errnop, ttlp); } *errnop = -r; *h_errnop = NO_RECOVERY; return NSS_STATUS_UNAVAIL; } r = sd_bus_message_enter_container(reply, 'a', "(is)"); if (r < 0) goto fail; while ((r = sd_bus_message_read(reply, "(is)", &ifindex, &n)) > 0) { if (ifindex < 0) { r = -EINVAL; goto fail; } c++; ms += ALIGN(strlen(n) + 1); } if (r < 0) goto fail; r = sd_bus_message_rewind(reply, false); if (r < 0) return r; if (c <= 0) { *errnop = ESRCH; *h_errnop = HOST_NOT_FOUND; return NSS_STATUS_NOTFOUND; } ms += ALIGN(len) + /* the address */ 2 * sizeof(char*) + /* pointers to the address, plus trailing NULL */ c * sizeof(char*); /* pointers to aliases, plus trailing NULL */ if (buflen < ms) { *errnop = ENOMEM; *h_errnop = TRY_AGAIN; return NSS_STATUS_TRYAGAIN; } /* First, place address */ r_addr = buffer; memcpy(r_addr, addr, len); idx = ALIGN(len); /* Second, place address list */ r_addr_list = buffer + idx; ((char**) r_addr_list)[0] = r_addr; ((char**) r_addr_list)[1] = NULL; idx += sizeof(char*) * 2; /* Third, reserve space for the aliases array */ r_aliases = buffer + idx; idx += sizeof(char*) * c; /* Fourth, place aliases */ i = 0; r_name = buffer + idx; while ((r = sd_bus_message_read(reply, "(is)", &ifindex, &n)) > 0) { char *p; size_t l; l = strlen(n); p = buffer + idx; memcpy(p, n, l+1); if (i > 1) ((char**) r_aliases)[i-1] = p; i++; idx += ALIGN(l+1); } if (r < 0) goto fail; ((char**) r_aliases)[c-1] = NULL; assert(idx == ms); result->h_name = r_name; result->h_aliases = (char**) r_aliases; result->h_addrtype = af; result->h_length = len; result->h_addr_list = (char**) r_addr_list; if (ttlp) *ttlp = 0; /* Explicitly reset all error variables */ *errnop = 0; *h_errnop = NETDB_SUCCESS; h_errno = 0; return NSS_STATUS_SUCCESS; fail: *errnop = -r; *h_errnop = NO_DATA; return NSS_STATUS_UNAVAIL; }
void Foam::solveLaplacianPDE::solve() { if(active_) { const fvMesh& mesh = refCast<const fvMesh>(obr_); dictionary sol=mesh.solutionDict().subDict(fieldName_+"LaplacianPDE"); FieldValueExpressionDriver &driver=driver_(); int nCorr=sol.lookupOrDefault<int>("nCorrectors", 0); if( nCorr==0 && steady_ ) { WarningIn("Foam::solveTransportPDE::solve()") << name_ << " is steady. It is recommended to have in " << sol.name() << " a nCorrectors>0" << endl; } for (int corr=0; corr<=nCorr; corr++) { driver.clearVariables(); driver.parse(lambdaExpression_); if(!driver.resultIsTyp<volScalarField>()) { FatalErrorIn("Foam::solveLaplacianPDE::solve()") << lambdaExpression_ << " does not evaluate to a scalar" << endl << exit(FatalError); } volScalarField lambdaField(driver.getResult<volScalarField>()); lambdaField.dimensions().reset(lambdaDimension_); driver.parse(sourceExpression_); if(!driver.resultIsTyp<volScalarField>()) { FatalErrorIn("Foam::solveLaplacianPDE::solve()") << sourceExpression_ << " does not evaluate to a scalar" << endl << exit(FatalError); } volScalarField sourceField(driver.getResult<volScalarField>()); sourceField.dimensions().reset(sourceDimension_); volScalarField &f=theField(); fvMatrix<scalar> eq( -fvm::laplacian(lambdaField,f,"laplacian(lambda,"+f.name()+")") == sourceField ); autoPtr<volScalarField> rhoField; if(needsRhoField()) { driver.parse(rhoExpression_); if(!driver.resultIsTyp<volScalarField>()) { FatalErrorIn("Foam::solveLaplacianPDE::solve()") << rhoExpression_ << " does not evaluate to a scalar" << endl << exit(FatalError); } rhoField.set( new volScalarField( driver.getResult<volScalarField>() ) ); rhoField().dimensions().reset(rhoDimension_); } #ifdef FOAM_HAS_FVOPTIONS if(needsRhoField()) { eq-=fvOptions()(rhoField(),f); } #endif if(!steady_) { fvMatrix<scalar> ddtMatrix(fvm::ddt(f)); if( !ddtMatrix.diagonal() && !ddtMatrix.symmetric() && !ddtMatrix.asymmetric() ) { // Adding would fail } else { eq+=rhoField()*ddtMatrix; } } if(sourceImplicitExpression_!="") { driver.parse(sourceImplicitExpression_); if(!driver.resultIsTyp<volScalarField>()) { FatalErrorIn("Foam::solveLaplacianPDE::solve()") << sourceImplicitExpression_ << " does not evaluate to a scalar" << endl << exit(FatalError); } volScalarField sourceImplicitField(driver.getResult<volScalarField>()); sourceImplicitField.dimensions().reset(sourceImplicitDimension_); if(sourceImplicitUseSuSp_) { eq-=fvm::SuSp(sourceImplicitField,f); } else { eq-=fvm::Sp(sourceImplicitField,f); } } if(doRelax(corr==nCorr)) { eq.relax(); } #ifdef FOAM_HAS_FVOPTIONS fvOptions().constrain(eq); #endif int nNonOrthCorr=sol.lookupOrDefault<int>("nNonOrthogonalCorrectors", 0); bool converged=true; for (int nonOrth=0; nonOrth<=nNonOrthCorr; nonOrth++) { volScalarField fallback( "fallback"+f.name(), f ); #ifdef FOAM_LDUMATRIX_SOLVERPERFORMANCE lduMatrix::solverPerformance perf=eq.solve(); #elif defined(FOAM_LDUSOLVERPERFORMANCE) lduSolverPerformance perf=eq.solve(); #else solverPerformance perf=eq.solve(); #endif if( !perf.converged() && restoreNonConvergedSteady() ) { WarningIn("Foam::solveTransportPDE::solve()") << "Solution for " << f.name() << " not converged. Restoring" << endl; f=fallback; converged=false; break; } } #ifdef FOAM_HAS_FVOPTIONS fvOptions().correct(f); #endif if(!converged) { break; } } } }