static gboolean print_field_value(field_info *finfo, int cmd_line_index) { header_field_info *hfinfo; static char *fs_buf = NULL; char *fs_ptr = fs_buf; static GString *label_s = NULL; int fs_buf_len = FIELD_STR_INIT_LEN, fs_len; guint i; string_fmt_t *sf; guint32 uvalue; gint32 svalue; const true_false_string *tfstring = &tfs_true_false; hfinfo = finfo->hfinfo; if (!fs_buf) { fs_buf = g_malloc(fs_buf_len + 1); fs_ptr = fs_buf; } if (!label_s) { label_s = g_string_new(""); } if(finfo->value.ftype->val_to_string_repr) { /* * this field has an associated value, * e.g: ip.hdr_len */ fs_len = fvalue_string_repr_len(&finfo->value, FTREPR_DFILTER); while (fs_buf_len < fs_len) { fs_buf_len *= 2; fs_buf = g_realloc(fs_buf, fs_buf_len + 1); fs_ptr = fs_buf; } fvalue_to_string_repr(&finfo->value, FTREPR_DFILTER, fs_buf); /* String types are quoted. Remove them. */ if ((finfo->value.ftype->ftype == FT_STRING || finfo->value.ftype->ftype == FT_STRINGZ) && fs_len > 2) { fs_buf[fs_len - 1] = '\0'; fs_ptr++; } } if (string_fmts->len > 0 && finfo->hfinfo->strings) { g_string_truncate(label_s, 0); for (i = 0; i < string_fmts->len; i++) { sf = g_ptr_array_index(string_fmts, i); if (sf->plain) { g_string_append(label_s, sf->plain); } else { switch (sf->format) { case SF_NAME: g_string_append(label_s, hfinfo->name); break; case SF_NUMVAL: g_string_append(label_s, fs_ptr); break; case SF_STRVAL: switch(hfinfo->type) { case FT_BOOLEAN: uvalue = fvalue_get_uinteger(&finfo->value); tfstring = (const struct true_false_string*) hfinfo->strings; g_string_append(label_s, uvalue ? tfstring->true_string : tfstring->false_string); break; case FT_INT8: case FT_INT16: case FT_INT24: case FT_INT32: DISSECTOR_ASSERT(!hfinfo->bitmask); svalue = fvalue_get_sinteger(&finfo->value); if (hfinfo->display & BASE_RANGE_STRING) { g_string_append(label_s, rval_to_str(svalue, hfinfo->strings, "Unknown")); } else { g_string_append(label_s, val_to_str(svalue, cVALS(hfinfo->strings), "Unknown")); } case FT_UINT8: case FT_UINT16: case FT_UINT24: case FT_UINT32: uvalue = fvalue_get_uinteger(&finfo->value); if (!hfinfo->bitmask && hfinfo->display & BASE_RANGE_STRING) { g_string_append(label_s, rval_to_str(uvalue, hfinfo->strings, "Unknown")); } else { g_string_append(label_s, val_to_str(uvalue, cVALS(hfinfo->strings), "Unknown")); } break; default: break; } break; default: break; } } } printf(" %u=\"%s\"", cmd_line_index, label_s->str); return TRUE; } if(finfo->value.ftype->val_to_string_repr) { printf(" %u=\"%s\"", cmd_line_index, fs_ptr); return TRUE; } /* * This field doesn't have an associated value, * e.g. http * We return n.a. */ printf(" %u=\"n.a.\"", cmd_line_index); return TRUE; }
static GString* gwy_si_unit_format(GwySIUnit *siunit, const GwySIStyleSpec *fs, GString *string) { const gchar *prefix = "No GCC, this can't be used uninitialized"; GwySimpleUnit *unit; gint i, prefix_bearer, move_me_to_end; if (!string) string = g_string_new(""); else g_string_truncate(string, 0); /* if there is a single unit with negative exponent, move it to the end * TODO: we may want more sophistication here */ move_me_to_end = -1; if (siunit->units->len > 1) { for (i = 0; i < siunit->units->len; i++) { unit = &g_array_index(siunit->units, GwySimpleUnit, i); if (unit->power < 0) { if (move_me_to_end >= 0) { move_me_to_end = -1; break; } move_me_to_end = i; } } } /* find a victim to prepend a prefix to. mwhahaha */ prefix_bearer = -1; if (siunit->power10) { for (i = 0; i < siunit->units->len; i++) { if (i == move_me_to_end) continue; unit = &g_array_index(siunit->units, GwySimpleUnit, i); if (siunit->power10 % (3*abs(unit->power)) == 0) { prefix_bearer = i; break; } } } if (siunit->power10 && prefix_bearer < 0 && move_me_to_end >= 0) { unit = &g_array_index(siunit->units, GwySimpleUnit, move_me_to_end); if (siunit->power10 % (3*abs(unit->power)) == 0) prefix_bearer = move_me_to_end; } /* check whether we are not out of prefix range */ if (prefix_bearer >= 0) { unit = &g_array_index(siunit->units, GwySimpleUnit, prefix_bearer); prefix = gwy_si_unit_prefix(siunit->power10/unit->power); if (!prefix) prefix_bearer = -1; } /* if we were unable to place the prefix, we must add a power of 10 */ if (siunit->power10 && prefix_bearer < 0) { switch (siunit->power10) { case -1: g_string_append(string, "0.1"); break; case 1: g_string_append(string, "10"); break; case 2: g_string_append(string, "100"); break; default: if (fs->power10_prefix) g_string_append(string, fs->power10_prefix); g_string_append_printf(string, "%d", siunit->power10); if (fs->power_suffix) g_string_append(string, fs->power_suffix); break; } if (fs->power_unit_separator && siunit->units->len) g_string_append(string, fs->power_unit_separator); } /* append units */ for (i = 0; i < siunit->units->len; i++) { if (i == move_me_to_end) continue; if (i > 1 || (i && move_me_to_end)) { g_string_append(string, fs->unit_times); } unit = &g_array_index(siunit->units, GwySimpleUnit, i); if (i == prefix_bearer) g_string_append(string, prefix); g_string_append(string, g_quark_to_string(unit->unit)); if (unit->power != 1) { if (fs->power_prefix) g_string_append(string, fs->power_prefix); g_string_append_printf(string, "%d", unit->power); if (fs->power_suffix) g_string_append(string, fs->power_suffix); } } if (move_me_to_end >= 0) { g_string_append(string, fs->unit_division); unit = &g_array_index(siunit->units, GwySimpleUnit, move_me_to_end); if (move_me_to_end == prefix_bearer) g_string_append(string, prefix); g_string_append(string, g_quark_to_string(unit->unit)); if (unit->power != -1) { if (fs->power_prefix) g_string_append(string, fs->power_prefix); g_string_append_printf(string, "%d", -unit->power); if (fs->power_suffix) g_string_append(string, fs->power_suffix); } } return string; }
/* * Step 1: * Isolate RTF keywords and send them to rtf_parse_keyword; * Push and pop state at the start and end of RTF groups; * Send text to rtf_dispatch_char for further processing. */ static int rtf_parse(NMRtfContext *ctx) { int status; guchar ch; guchar hex_byte = 0; int hex_count = 2; int len; if (ctx->input == NULL) return NMRTF_OK; while (rtf_get_char(ctx, &ch) == NMRTF_OK) { if (ctx->depth < 0) return NMRTF_STACK_UNDERFLOW; /* if we're parsing binary data, handle it directly */ if (ctx->ris == NMRTF_STATE_BIN) { if ((status = rtf_dispatch_char(ctx, ch)) != NMRTF_OK) return status; } else { switch (ch) { case '{': if (ctx->depth > NMRTF_MAX_DEPTH) return NMRTF_STACK_OVERFLOW; rtf_flush_data(ctx); if ((status = rtf_push_state(ctx)) != NMRTF_OK) return status; break; case '}': rtf_flush_data(ctx); /* for some reason there is always an unwanted '\par' at the end */ if (ctx->rds == NMRTF_STATE_NORMAL) { len = ctx->output->len; if (ctx->output->str[len-1] == '\n') ctx->output = g_string_truncate(ctx->output, len-1); } if ((status = rtf_pop_state(ctx)) != NMRTF_OK) return status; if (ctx->depth < 0) return NMRTF_STACK_OVERFLOW; break; case '\\': if ((status = rtf_parse_keyword(ctx)) != NMRTF_OK) return status; break; case 0x0d: case 0x0a: /* cr and lf are noise characters... */ break; default: if (ctx->ris == NMRTF_STATE_NORMAL) { if ((status = rtf_dispatch_char(ctx, ch)) != NMRTF_OK) return status; } else { /* parsing a hex encoded character */ if (ctx->ris != NMRTF_STATE_HEX) return NMRTF_ASSERTION; hex_byte = hex_byte << 4; if (isdigit(ch)) hex_byte += (char) ch - '0'; else { if (islower(ch)) { if (ch < 'a' || ch > 'f') return NMRTF_INVALID_HEX; hex_byte += (char) ch - 'a' + 10; } else { if (ch < 'A' || ch > 'F') return NMRTF_INVALID_HEX; hex_byte += (char) ch - 'A' + 10; } } hex_count--; if (hex_count == 0) { if ((status = rtf_dispatch_char(ctx, hex_byte)) != NMRTF_OK) return status; hex_count = 2; hex_byte = 0; ctx->ris = NMRTF_STATE_NORMAL; } } break; } } } if (ctx->depth < 0) return NMRTF_STACK_OVERFLOW; if (ctx->depth > 0) return NMRTF_UNMATCHED_BRACE; return NMRTF_OK; }
static void db_getmailbox_info(T M, Connection_T c) { /* query mailbox for LIST results */ ResultSet_T r; char *mbxname, *name, *pattern; struct mailbox_match *mailbox_like = NULL; GString *fqname, *qs; int i=0, prml; PreparedStatement_T stmt; stmt = db_stmt_prepare(c, "SELECT " "CASE WHEN user_id IS NULL THEN 0 ELSE 1 END, " // subscription "owner_idnr, name, no_select, no_inferiors " "FROM %smailboxes b LEFT OUTER JOIN %ssubscription s ON " "b.mailbox_idnr = s.mailbox_id WHERE b.mailbox_idnr = ?", DBPFX, DBPFX); db_stmt_set_u64(stmt, 1, M->id); r = db_stmt_query(stmt); if (db_result_next(r)) { /* subsciption */ M->is_subscribed = db_result_get_bool(r, i++); /* owner_idnr */ M->owner_id = db_result_get_u64(r, i++); /* name */ name = g_strdup(db_result_get(r,i++)); if (MATCH(name, "INBOX")) { M->is_inbox = TRUE; M->is_subscribed = TRUE; } mbxname = mailbox_add_namespace(name, M->owner_id, M->owner_id); fqname = g_string_new(mbxname); fqname = g_string_truncate(fqname,IMAP_MAX_MAILBOX_NAMELEN); MailboxState_setName(M, fqname->str); g_string_free(fqname,TRUE); g_free(mbxname); /* no_select */ M->no_select=db_result_get_bool(r,i++); /* no_inferior */ M->no_inferiors=db_result_get_bool(r,i++); /* no_children search pattern*/ pattern = g_strdup_printf("%s/%%", name); mailbox_like = mailbox_match_new(pattern); g_free(pattern); g_free(name); } db_con_clear(c); qs = g_string_new(""); g_string_printf(qs, "SELECT COUNT(*) AS nr_children FROM %smailboxes WHERE owner_idnr = ? ", DBPFX); if (mailbox_like && mailbox_like->insensitive) g_string_append_printf(qs, "AND name %s ? ", db_get_sql(SQL_INSENSITIVE_LIKE)); if (mailbox_like && mailbox_like->sensitive) g_string_append_printf(qs, "AND name %s ? ", db_get_sql(SQL_SENSITIVE_LIKE)); stmt = db_stmt_prepare(c, qs->str); prml = 1; db_stmt_set_u64(stmt, prml++, M->owner_id); if (mailbox_like && mailbox_like->insensitive) db_stmt_set_str(stmt, prml++, mailbox_like->insensitive); if (mailbox_like && mailbox_like->sensitive) db_stmt_set_str(stmt, prml++, mailbox_like->sensitive); r = db_stmt_query(stmt); if (db_result_next(r)) { int nr_children = db_result_get_int(r,0); M->no_children=nr_children ? 0 : 1; } else { M->no_children=1; } mailbox_match_free(mailbox_like); g_string_free(qs, TRUE); }
gboolean cd_do_key_pressed (gpointer pUserData, GldiContainer *pContainer, guint iKeyVal, guint iModifierType, const gchar *string, int iKeyCode) { g_return_val_if_fail (cd_do_session_is_running (), GLDI_NOTIFICATION_LET_PASS); g_return_val_if_fail (myData.pCurrentDock != NULL, GLDI_NOTIFICATION_LET_PASS); const gchar *cKeyName = gdk_keyval_name (iKeyVal); guint32 iUnicodeChar = gdk_keyval_to_unicode (iKeyVal); cd_debug ("+ cKeyName : %s (%c, %s, %d)", cKeyName, iUnicodeChar, string, iKeyCode); if (myData.sCurrentText->len == 0) { GdkKeymapKey *keys = NULL; guint *keyvals = NULL; int i, n_entries = 0; int iKeyVal2; gdk_keymap_get_entries_for_keycode (gdk_keymap_get_default (), iKeyCode, &keys, &keyvals, &n_entries); for (i = 0; i < n_entries; i ++) { iKeyVal2 = keyvals[i]; if ((iKeyVal2 >= GDK_KEY_0 && iKeyVal2 <= GDK_KEY_9) || (iKeyVal2 >= GDK_KEY_KP_0 && iKeyVal2 <= GDK_KEY_KP_9)) { iKeyVal = iKeyVal2; break; } } g_free (keys); g_free (keyvals); } if (iKeyVal == GDK_KEY_Escape) // on clot la session. { // give the focus back to the window that had it before the user opened this session. if (myData.pPreviouslyActiveWindow != NULL) { gldi_window_show (myData.pPreviouslyActiveWindow); } cd_do_close_session (); } else if (iKeyVal == GDK_KEY_space && myData.sCurrentText->len == 0) // pas d'espace en debut de chaine. { // on rejette. } else if (iKeyVal >= GDK_KEY_Shift_L && iKeyVal <= GDK_KEY_Hyper_R) // on n'ecrit pas les modificateurs. { // on rejette. } else if (iKeyVal == GDK_KEY_Menu) // emulation du clic droit. { if (myData.pCurrentIcon != NULL) { myData.bIgnoreIconState = TRUE; gldi_icon_stop_animation (myData.pCurrentIcon); // car on va perdre le focus. myData.bIgnoreIconState = FALSE; GtkWidget *menu = gldi_container_build_menu (CAIRO_CONTAINER (myData.pCurrentDock), myData.pCurrentIcon); gldi_menu_popup (menu); } } else if (iKeyVal == GDK_KEY_BackSpace) // on efface la derniere lettre. { if (myData.sCurrentText->len > 0) { cd_debug ("we remove the last letter of %s (%d)", myData.sCurrentText->str, myData.sCurrentText->len); g_string_truncate (myData.sCurrentText, myData.sCurrentText->len-1); // on relance la recherche. if (myData.pCurrentIcon == NULL) // sinon l'icone actuelle convient toujours. cd_do_search_current_icon (FALSE); } } else if (iKeyVal == GDK_KEY_Tab) // jump to next icon. { if (myData.sCurrentText->len > 0) { //gboolean bPrevious = iModifierType & GDK_SHIFT_MASK; // on cherche l'icone suivante. cd_do_search_current_icon (TRUE); // pCurrentIcon peut etre NULL si elle s'est faite detruire pendant la recherche, auquel cas on cherchera juste normalement. } } else if (iKeyVal == GDK_KEY_Return) { if (myData.pCurrentIcon != NULL) { cd_debug ("we click on the icon '%s' [%d, %d]", myData.pCurrentIcon->cName, iModifierType, GDK_SHIFT_MASK); myData.bIgnoreIconState = TRUE; if (iModifierType & GDK_MOD1_MASK) // ALT { myData.bIgnoreIconState = TRUE; gldi_icon_stop_animation (myData.pCurrentIcon); // car aucune animation ne va la remplacer. myData.bIgnoreIconState = FALSE; gldi_object_notify (CAIRO_CONTAINER (myData.pCurrentDock), NOTIFICATION_MIDDLE_CLICK_ICON, myData.pCurrentIcon, myData.pCurrentDock); } else if (iModifierType & GDK_CONTROL_MASK) // CTRL { myData.bIgnoreIconState = TRUE; gldi_icon_stop_animation (myData.pCurrentIcon); // car on va perdre le focus. myData.bIgnoreIconState = FALSE; GtkWidget *menu = gldi_container_build_menu (CAIRO_CONTAINER (myData.pCurrentDock), myData.pCurrentIcon); gldi_menu_popup (menu); } else { cd_do_simulate_click (CAIRO_CONTAINER (myData.pCurrentDock), myData.pCurrentIcon, iModifierType); } gldi_icon_start_animation (myData.pCurrentIcon); myData.bIgnoreIconState = FALSE; myData.pCurrentIcon = NULL; // sinon on va interrompre l'animation en fermant la session. } cd_do_close_session (); } else if (iKeyVal == GDK_KEY_Left || iKeyVal == GDK_KEY_Right || iKeyVal == GDK_KEY_Up || iKeyVal == GDK_KEY_Down) { iKeyVal = _orient_arrow (pContainer, iKeyVal); if (iKeyVal == GDK_KEY_Up) { if (myData.pCurrentIcon != NULL && myData.pCurrentIcon->pSubDock != NULL) { cd_debug ("on monte dans le sous-dock %s", myData.pCurrentIcon->cName); Icon *pIcon = cairo_dock_get_first_icon (myData.pCurrentIcon->pSubDock->icons); cd_do_change_current_icon (pIcon, myData.pCurrentIcon->pSubDock); } } else if (iKeyVal == GDK_KEY_Down) { if (myData.pCurrentDock->iRefCount > 0) { CairoDock *pParentDock = NULL; Icon *pPointingIcon = cairo_dock_search_icon_pointing_on_dock (myData.pCurrentDock, &pParentDock); if (pPointingIcon != NULL) { cd_debug ("on redescend dans le dock parent via %s", pPointingIcon->cName); cd_do_change_current_icon (pPointingIcon, pParentDock); } } } else if (iKeyVal == GDK_KEY_Left) { if (myData.pCurrentDock->icons != NULL) { Icon *pPrevIcon = cairo_dock_get_previous_icon (myData.pCurrentDock->icons, myData.pCurrentIcon); if (CAIRO_DOCK_ICON_TYPE_IS_SEPARATOR (pPrevIcon)) pPrevIcon = cairo_dock_get_previous_icon (myData.pCurrentDock->icons, pPrevIcon); if (pPrevIcon == NULL) // pas trouve ou bien 1ere icone. { pPrevIcon = cairo_dock_get_last_icon (myData.pCurrentDock->icons); } cd_debug ("on se deplace a gauche sur %s", pPrevIcon ? pPrevIcon->cName : "none"); cd_do_change_current_icon (pPrevIcon, myData.pCurrentDock); } } else // Gdk_Right. { if (myData.pCurrentDock->icons != NULL) { Icon *pNextIcon = cairo_dock_get_next_icon (myData.pCurrentDock->icons, myData.pCurrentIcon); if (CAIRO_DOCK_ICON_TYPE_IS_SEPARATOR (pNextIcon)) pNextIcon = cairo_dock_get_next_icon (myData.pCurrentDock->icons, pNextIcon); if (pNextIcon == NULL) // pas trouve ou bien 1ere icone. { pNextIcon = cairo_dock_get_first_icon (myData.pCurrentDock->icons); } cd_debug ("on se deplace a gauche sur %s", pNextIcon ? pNextIcon->cName : "none"); cd_do_change_current_icon (pNextIcon, myData.pCurrentDock); } } } else if (iKeyVal == GDK_KEY_Page_Down || iKeyVal == GDK_KEY_Page_Up || iKeyVal == GDK_KEY_Home || iKeyVal == GDK_KEY_End) { if (iModifierType & GDK_CONTROL_MASK) // changement de dock principal { gpointer data[4] = {myData.pCurrentDock, NULL, GINT_TO_POINTER (FALSE), NULL}; gldi_docks_foreach_root ((GFunc) _find_next_dock, data); CairoDock *pNextDock = data[1]; if (pNextDock == NULL) pNextDock = data[3]; if (pNextDock != NULL) { Icon *pNextIcon = NULL; int n = g_list_length (pNextDock->icons); if (n > 0) { pNextIcon = g_list_nth_data (pNextDock->icons, (n-1) / 2); if (CAIRO_DOCK_ICON_TYPE_IS_SEPARATOR (pNextIcon) && n > 1) pNextIcon = g_list_nth_data (pNextDock->icons, (n+1) / 2); } cd_do_change_current_icon (pNextIcon, pNextDock); } } Icon *pIcon = (iKeyVal == GDK_KEY_Page_Up || iKeyVal == GDK_KEY_Home ? cairo_dock_get_first_icon (myData.pCurrentDock->icons) : cairo_dock_get_last_icon (myData.pCurrentDock->icons)); cd_debug ("on se deplace a l'extremite sur %s", pIcon ? pIcon->cName : "none"); cd_do_change_current_icon (pIcon, myData.pCurrentDock); } else if ( ((iKeyVal >= GDK_KEY_0 && iKeyVal <= GDK_KEY_9) || (iKeyVal >= GDK_KEY_KP_0 && iKeyVal <= GDK_KEY_KP_9)) && myData.sCurrentText->len == 0) { _activate_nth_icon (iKeyVal, iModifierType); } else if (string) /// utiliser l'unichar ... { cd_debug ("string:'%s'", string); g_string_append_c (myData.sCurrentText, *string); cd_do_search_current_icon (FALSE); } return GLDI_NOTIFICATION_INTERCEPT; }
/* Fill in more details of the DirItem for a directory item. * - Looks for an image (but maybe still NULL on error) * - Updates ITEM_FLAG_APPDIR * * link_target contains stat info for the link target for symlinks (or for the * item itself if not a link). */ static void examine_dir(const guchar *path, DirItem *item, struct stat *link_target) { struct stat info; static GString *tmp = NULL; uid_t uid = link_target->st_uid; if (!tmp) tmp = g_string_new(NULL); check_globicon(path, item); if (item->flags & ITEM_FLAG_MOUNT_POINT) { item->mime_type = inode_mountpoint; return; /* Try to avoid automounter problems */ } if (link_target->st_mode & S_IWOTH) return; /* Don't trust world-writable dirs */ /* Finding the icon: * * - If it contains a .DirIcon then that's the icon * - If it contains an AppRun then it's an application * - If it contains an AppRun but no .DirIcon then try to * use AppIcon.xpm as the icon. * * .DirIcon and AppRun must have the same owner as the * directory itself, to prevent abuse of /tmp, etc. * For symlinks, we want the symlink's owner. */ g_string_printf(tmp, "%s/.DirIcon", path); if (item->_image) goto no_diricon; /* Already got an icon */ if (mc_lstat(tmp->str, &info) != 0 || info.st_uid != uid) goto no_diricon; /* Missing, or wrong owner */ if (S_ISLNK(info.st_mode) && mc_stat(tmp->str, &info) != 0) goto no_diricon; /* Bad symlink */ if (info.st_size > MAX_ICON_SIZE || !S_ISREG(info.st_mode)) goto no_diricon; /* Too big, or non-regular file */ /* Try to load image; may still get NULL... */ item->_image = g_fscache_lookup(pixmap_cache, tmp->str); no_diricon: /* Try to find AppRun... */ g_string_truncate(tmp, tmp->len - 8); g_string_append(tmp, "AppRun"); if (mc_lstat(tmp->str, &info) != 0 || info.st_uid != uid) goto out; /* Missing, or wrong owner */ if (!(info.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) goto out; /* Not executable */ item->flags |= ITEM_FLAG_APPDIR; /* Try to load AppIcon.xpm... */ if (item->_image) goto out; /* Already got an icon */ g_string_truncate(tmp, tmp->len - 3); g_string_append(tmp, "Icon.xpm"); /* Note: since AppRun is valid we don't need to check AppIcon.xpm * so carefully. */ if (mc_stat(tmp->str, &info) != 0) goto out; /* Missing, or broken symlink */ if (info.st_size > MAX_ICON_SIZE || !S_ISREG(info.st_mode)) goto out; /* Too big, or non-regular file */ /* Try to load image; may still get NULL... */ item->_image = g_fscache_lookup(pixmap_cache, tmp->str); out: if ((item->flags & ITEM_FLAG_APPDIR) && !item->_image) { /* This is an application without an icon */ item->_image = im_appdir; g_object_ref(item->_image); } }
static gboolean renren_http_post (const gchar *token, const gchar *title, const gchar *body) { CURL *curl; CURLcode res; struct curl_slist *slist; gchar **kar, **var, *signature; GString *postdata; int i; kar = g_new (gchar *, 10); g_return_val_if_fail (kar, FALSE); var = g_new (gchar *, 10); if (var == NULL) { g_free (kar); return FALSE; } i = 0; kar[i] = g_strdup ("access_token"); var[i ++] = g_strdup (token); kar[i] = g_strdup ("v"); var[i ++] = g_strdup (renren_api_version); kar[i] = g_strdup ("method"); var[i ++] = g_strdup ("blog.addBlog"); kar[i] = g_strdup ("title"); var[i ++] = g_strdup (title); kar[i] = g_strdup ("content"); var[i ++] = g_strdup (body); kar[i] = g_strdup ("format"); var[i ++] = g_strdup ("XML"); kar[i] = NULL; var[i] = NULL; signature = renren_signature (kar, var); kar[i] = g_strdup ("sig"); var[i ++] = g_strdup (signature); kar[i] = NULL; var[i] = NULL; postdata = g_string_sized_new (4000); for (i = 0; kar[i]; ++ i) { g_string_append (postdata, kar[i]); g_string_append (postdata, "="); g_string_append (postdata, var[i]); g_string_append (postdata, "&"); } g_string_truncate (postdata, postdata->len - 1); // remove the last '&' curl = curl_easy_init (); g_return_val_if_fail (curl, FALSE); curl_easy_setopt (curl, CURLOPT_URL, renren_rest_uri); curl_easy_setopt (curl, CURLOPT_POSTFIELDS, postdata->str); slist = curl_slist_append (NULL, "Expect:"); slist = curl_slist_append (slist, "User-Agent: amblog renren 0.0.1"); curl_easy_setopt (curl, CURLOPT_HTTPHEADER, slist); #ifdef OAUTH_CURL_TIMEOUT curl_easy_setopt (curl, CURLOPT_TIMEOUT, OAUTH_CURL_TIMEOUT); curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); #endif res = curl_easy_perform (curl); curl_slist_free_all (slist); curl_easy_cleanup (curl); if (res == 200) { return TRUE; } else { return FALSE; } }
void log_stamp_format(LogStamp *stamp, GString *target, gint ts_format, glong zone_offset, gint frac_digits) { g_string_truncate(target, 0); log_stamp_append_format(stamp, target, ts_format, zone_offset, frac_digits); }
static GtkTextBuffer * read_boot_log (const char *file, int *seen_errors, GError **error) { char *content; char *content_utf8; gsize length; char *p, *q; GtkTextBuffer *buffer; GtkTextIter iter; GString *partial; if (!g_file_get_contents (file, &content, &length, error)) return NULL; content_utf8 = g_locale_to_utf8 (content, length, NULL, NULL, NULL); if (content_utf8) { g_free (content); content = content_utf8; } if (check_for_errors (file)) *seen_errors = 2; else *seen_errors = 0; buffer = gtk_text_buffer_new (NULL); gtk_text_buffer_create_tag (buffer, "blue", "foreground", "blue", NULL); gtk_text_buffer_create_tag (buffer, "green", "foreground", "green", NULL); gtk_text_buffer_create_tag (buffer, "red", "foreground", "red", NULL); gtk_text_buffer_create_tag (buffer, "yellow", "foreground", "yellow", NULL); partial = g_string_new (""); p = content; while (*p) { switch (*p) { case '\r': /* keep isolated \r */ if (p[1] != '\r' && p[-1] != '\r' && p[1] != '\n' && p[-1] != '\n') { gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert (buffer, &iter, p, 1); } p++; break; case '\t': gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert (buffer, &iter, " ", 8); p++; break; case '\033': if (strncmp (p, "\033[0;34m", 7) == 0 && (q = strstr (p, "\033[0;39m"))) { p += 7; gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert_with_tags_by_name (buffer, &iter, p, q - p, "blue", NULL); p = q + 7; } else if (strncmp (p, "\033[60G", 5) == 0) { gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert (buffer, &iter, "\t", 1); p += 5; } else if (strncmp (p, "\033[0;31m", 7) == 0 && (q = strstr (p, "\033[0;39m"))) { p += 7; gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert_with_tags_by_name (buffer, &iter, p, q - p, "red", NULL); p = q + 7; } else if (strncmp (p, "\033[0;32m", 7) == 0 && (q = strstr (p, "\033[0;39m"))) { p += 7; gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert_with_tags_by_name (buffer, &iter, p, q - p, "green", NULL); p = q + 7; } else if (strncmp (p, "\033[0;33m", 7) == 0 && (q = strstr (p, "\033[0;39m"))) { p += 7; gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert_with_tags_by_name (buffer, &iter, p, q - p, "yellow", NULL); p = q + 7; } else if (strncmp (p, "\033%G", 3) == 0) p += 3; else p++; break; default: /* GtkTextBuffer doesn't let us insert partial utf-8 characters */ g_string_append_c (partial, *p); if (g_utf8_get_char_validated (partial->str, partial->len) != (gunichar)-2) { gtk_text_buffer_get_end_iter (buffer, &iter); gtk_text_buffer_insert (buffer, &iter, partial->str, partial->len); g_string_truncate (partial, 0); } p++; break; } } g_string_free (partial, TRUE); g_free (content); return buffer; }
Package* parse_package_file (const char *path, gboolean ignore_requires, gboolean ignore_private_libs, gboolean ignore_requires_private) { FILE *f; Package *pkg; GString *str; gboolean one_line = FALSE; f = fopen (path, "r"); if (f == NULL) { verbose_error ("Failed to open '%s': %s\n", path, strerror (errno)); return NULL; } debug_spew ("Parsing package file '%s'\n", path); pkg = g_new0 (Package, 1); if (path) { pkg->pcfiledir = g_dirname (path); } else { debug_spew ("No pcfiledir determined for package\n"); pkg->pcfiledir = g_strdup ("???????"); } str = g_string_new (""); while (read_one_line (f, str)) { one_line = TRUE; parse_line (pkg, str->str, path, ignore_requires, ignore_private_libs, ignore_requires_private); g_string_truncate (str, 0); } if (!one_line) verbose_error ("Package file '%s' appears to be empty\n", path); g_string_free (str, TRUE); fclose(f); /* make ->requires_private include a copy of the public requires too */ pkg->requires_private = g_slist_concat(g_slist_copy (pkg->requires), pkg->requires_private); pkg->requires = g_slist_reverse (pkg->requires); pkg->requires_private = g_slist_reverse (pkg->requires_private); pkg->I_cflags = g_slist_reverse (pkg->I_cflags); pkg->other_cflags = g_slist_reverse (pkg->other_cflags); pkg->l_libs = g_slist_reverse (pkg->l_libs); pkg->L_libs = g_slist_reverse (pkg->L_libs); pkg->other_libs = g_slist_reverse (pkg->other_libs); return pkg; }
/** * Read an entire line from a file into a buffer. Lines may * be delimited with '\n', '\r', '\n\r', or '\r\n'. The delimiter * is not written into the buffer. Text after a '#' character is treated as * a comment and skipped. '\' can be used to escape a # character. * '\' proceding a line delimiter combines adjacent lines. A '\' proceding * any other character is ignored and written into the output buffer * unmodified. * * Return value: %FALSE if the stream was already at an EOF character. **/ static gboolean read_one_line (FILE *stream, GString *str) { gboolean quoted = FALSE; gboolean comment = FALSE; int n_read = 0; g_string_truncate (str, 0); while (1) { int c; c = getc (stream); if (c == EOF) { if (quoted) g_string_append_c (str, '\\'); goto done; } else n_read++; if (quoted) { quoted = FALSE; switch (c) { case '#': g_string_append_c (str, '#'); break; case '\r': case '\n': { int next_c = getc (stream); if (!(c == EOF || (c == '\r' && next_c == '\n') || (c == '\n' && next_c == '\r'))) ungetc (next_c, stream); break; } default: g_string_append_c (str, '\\'); g_string_append_c (str, c); } } else { switch (c) { case '#': comment = TRUE; break; case '\\': if (!comment) quoted = TRUE; break; case '\n': { int next_c = getc (stream); if (!(c == EOF || (c == '\r' && next_c == '\n') || (c == '\n' && next_c == '\r'))) ungetc (next_c, stream); goto done; } default: if (!comment) g_string_append_c (str, c); } } } done: return n_read > 0; }
static void grain_stat(GwyContainer *data, GwyRunType run) { GtkWidget *dialog, *table, *hbox, *button; GwyDataField *dfield, *mfield; GwySIUnit *siunit, *siunit2; GwySIValueFormat *vf, *vf2; gint xres, yres, ngrains; gdouble total_area, area, size, vol_0, vol_min, vol_laplace, bound_len, v; gdouble *values = NULL; gint *grains; GString *str, *str2; GPtrArray *report; const guchar *title; gchar *key, *value; gint row, id; guint i, maxlen; g_return_if_fail(run & STAT_RUN_MODES); gwy_app_data_browser_get_current(GWY_APP_DATA_FIELD, &dfield, GWY_APP_MASK_FIELD, &mfield, GWY_APP_DATA_FIELD_ID, &id, 0); g_return_if_fail(dfield); g_return_if_fail(mfield); report = g_ptr_array_sized_new(20); if (gwy_container_gis_string_by_name(data, "/filename", &title)) { g_ptr_array_add(report, _("File:")); g_ptr_array_add(report, g_strdup(title)); } key = g_strdup_printf("/%d/data/title", id); if (gwy_container_gis_string_by_name(data, key, &title)) { g_ptr_array_add(report, _("Data channel:")); g_ptr_array_add(report, g_strdup(title)); } g_free(key); /* Make empty line in the report */ g_ptr_array_add(report, NULL); g_ptr_array_add(report, NULL); xres = gwy_data_field_get_xres(mfield); yres = gwy_data_field_get_yres(mfield); total_area = gwy_data_field_get_xreal(dfield) *gwy_data_field_get_yreal(dfield); grains = g_new0(gint, xres*yres); ngrains = gwy_data_field_number_grains(mfield, grains); area = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_PROJECTED_AREA); size = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_EQUIV_SQUARE_SIDE); vol_0 = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_VOLUME_0); vol_min = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_VOLUME_MIN); vol_laplace = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_VOLUME_LAPLACE); bound_len = grains_get_total_value(dfield, ngrains, grains, &values, GWY_GRAIN_VALUE_FLAT_BOUNDARY_LENGTH); g_free(values); g_free(grains); dialog = gtk_dialog_new_with_buttons(_("Grain Statistics"), NULL, 0, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL); gwy_help_add_to_proc_dialog(GTK_DIALOG(dialog), GWY_HELP_DEFAULT); table = gtk_table_new(10, 2, FALSE); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), table); gtk_container_set_border_width(GTK_CONTAINER(table), 4); row = 0; str = g_string_new(NULL); str2 = g_string_new(NULL); g_string_printf(str, "%d", ngrains); add_report_row(GTK_TABLE(table), &row, _("Number of grains:"), str->str, str->str, report); siunit = gwy_data_field_get_si_unit_xy(dfield); siunit2 = gwy_si_unit_power(siunit, 2, NULL); v = area; vf = gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, NULL); vf2 = gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, NULL); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Total projected area (abs.):"), str->str, str2->str, report); g_string_printf(str, "%.2f %%", 100.0*area/total_area); add_report_row(GTK_TABLE(table), &row, _("Total projected area (rel.):"), str->str, str->str, report); v = area/ngrains; gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Mean grain area:"), str->str, str2->str, report); v = size/ngrains; gwy_si_unit_get_format_with_digits(siunit, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Mean grain size:"), str->str, str2->str, report); siunit = gwy_data_field_get_si_unit_z(dfield); gwy_si_unit_multiply(siunit2, siunit, siunit2); v = vol_0; gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Total grain volume (zero):"), str->str, str2->str, report); v = vol_min; gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Total grain volume (minimum):"), str->str, str2->str, report); v = vol_laplace; gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit2, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Total grain volume (laplacian):"), str->str, str2->str, report); v = bound_len; gwy_si_unit_get_format_with_digits(siunit, GWY_SI_UNIT_FORMAT_VFMARKUP, v, 3, vf); gwy_si_unit_get_format_with_digits(siunit, GWY_SI_UNIT_FORMAT_PLAIN, v, 3, vf2); g_string_printf(str, "%.*f %s", vf->precision, v/vf->magnitude, vf->units); g_string_printf(str2, "%.*f %s", vf2->precision, v/vf2->magnitude, vf2->units); add_report_row(GTK_TABLE(table), &row, _("Total projected boundary length:"), str->str, str2->str, report); gwy_si_unit_value_format_free(vf2); gwy_si_unit_value_format_free(vf); g_object_unref(siunit2); maxlen = 0; for (i = 0; i < report->len/2; i++) { key = (gchar*)g_ptr_array_index(report, 2*i); if (key) maxlen = MAX(strlen(key), maxlen); } g_string_truncate(str, 0); g_string_append(str, _("Grain Statistics")); g_string_append(str, "\n\n"); for (i = 0; i < report->len/2; i++) { key = (gchar*)g_ptr_array_index(report, 2*i); if (key) { value = (gchar*)g_ptr_array_index(report, 2*i + 1); g_string_append_printf(str, "%-*s %s\n", maxlen+1, key, value); g_free(value); } else g_string_append_c(str, '\n'); } g_ptr_array_free(report, TRUE); g_object_set_data(G_OBJECT(dialog), "report", str->str); hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), hbox, FALSE, FALSE, 0); button = grain_stats_add_aux_button(hbox, GTK_STOCK_SAVE, _("Save table to a file")); g_signal_connect_swapped(button, "clicked", G_CALLBACK(grain_stat_save), dialog); button = grain_stats_add_aux_button(hbox, GTK_STOCK_COPY, _("Copy table to clipboard")); g_signal_connect_swapped(button, "clicked", G_CALLBACK(grain_stat_copy), dialog); gtk_widget_show_all(dialog); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); g_string_free(str2, TRUE); g_string_free(str, TRUE); }
static gboolean request_del_recurse(DavServer *server, DavRequest *request, GString *url, GString *phys, GString *buffer, GString *failed) { struct stat st; if (-1 == stat(phys->str, &st)) { guint status; switch (errno) { case EACCES: status = 403; break; case ENOENT: case ENOTDIR: status = 404; break; default: /* TODO: log error */ status = 500; break; } /* TODO: encode url */ g_string_append_printf(failed, "<D:response><D:href>%s</D:href><D:status>HTTP/1.1 %i %s</D:status></D:response>\n", url->str, status, dav_response_status_str(status)); return FALSE; } else if (S_ISDIR(st.st_mode)) { guint curphyslen, cururllen; GDir *dir; gboolean recerrors = FALSE; dav_append_trailing_slash(phys); dav_append_trailing_slash(url); curphyslen = phys->len; cururllen = url->len; dir = g_dir_open(phys->str, 0, NULL); if (NULL != dir) { const char *entry; while (NULL != (entry = g_dir_read_name(dir))) { g_string_truncate(phys, curphyslen); g_string_append(phys, entry); g_string_truncate(url, cururllen); g_string_append(url, entry); if (!request_del_recurse(server, request, url, phys, buffer, failed)) { recerrors = TRUE; } } g_dir_close(dir); } g_string_truncate(phys, curphyslen-1); g_string_truncate(url, cururllen); if (-1 == rmdir(phys->str)) { guint status; switch (errno) { case EPERM: case EACCES: case EBUSY: case EROFS: status = 403; break; case EEXIST: case ENOTEMPTY: if (!recerrors) return TRUE; status = 403; break; case ENOENT: case ENOTDIR: status = 404; break; default: /* TODO: log error */ status = 500; break; } /* TODO: encode url */ g_string_append_printf(failed, "<D:response><D:href>%s</D:href><D:status>HTTP/1.1 %i %s</D:status></D:response>\n", url->str, status, dav_response_status_str(status)); return FALSE; } else { g_string_append_printf(buffer, "<D:href>%s</D:href>\n", url->str); return TRUE; } } else { if (-1 == unlink(phys->str)) { guint status; switch (errno) { case EPERM: case EACCES: case EBUSY: case EROFS: status = 403; break; case ENOENT: case ENOTDIR: status = 404; break; default: /* TODO: log error */ status = 500; break; } /* TODO: encode url */ g_string_append_printf(failed, "<D:response><D:href>%s</D:href><D:status>HTTP/1.1 %i %s</D:status></D:response>\n", url->str, status, dav_response_status_str(status)); return FALSE; } else { g_string_append_printf(buffer, "<D:href>%s</D:href>\n", url->str); return TRUE; } } }
static gboolean unescape_gstring (GString *string) { const gchar *from; gchar *to; /* * Meeks' theorum: unescaping can only shrink text. * for < etc. this is obvious, for  more * thought is required, but this is patently so. */ for (from = to = string->str; *from != '\0'; from++, to++) { *to = *from; if (*to == '\r') { *to = '\n'; if (from[1] == '\n') from++; } if (*from == '&') { from++; if (*from == '#') { gboolean is_hex = FALSE; gulong l; gchar *end = NULL; from++; if (*from == 'x') { is_hex = TRUE; from++; } /* digit is between start and p */ errno = 0; if (is_hex) l = strtoul (from, &end, 16); else l = strtoul (from, &end, 10); if (end == from || errno != 0) { return FALSE; } else if (*end != ';') { return FALSE; } else { /* characters XML 1.1 permits */ if ((0 < l && l <= 0xD7FF) || (0xE000 <= l && l <= 0xFFFD) || (0x10000 <= l && l <= 0x10FFFF)) { gchar buf[8]; char_str (l, buf); strcpy (to, buf); to += strlen (buf) - 1; from = end; } else { return FALSE; } } } else if (strncmp (from, "lt;", 3) == 0) { *to = '<'; from += 2; } else if (strncmp (from, "gt;", 3) == 0) { *to = '>'; from += 2; } else if (strncmp (from, "amp;", 4) == 0) { *to = '&'; from += 3; } else if (strncmp (from, "quot;", 5) == 0) { *to = '"'; from += 4; } else if (strncmp (from, "apos;", 5) == 0) { *to = '\''; from += 4; } else { return FALSE; } } } g_assert (to - string->str <= string->len); if (to - string->str != string->len) g_string_truncate (string, to - string->str); return TRUE; }
char* vfs_file_resolve_path( const char* cwd, const char* relative_path ) { GString* ret = g_string_sized_new( 4096 ); int len; gboolean strip_tail; g_return_val_if_fail( G_LIKELY(relative_path), NULL ); len = strlen( relative_path ); strip_tail = (0 == len || relative_path[len-1] != '/'); if( G_UNLIKELY(*relative_path != '/') ) /* relative path */ { if( G_UNLIKELY(relative_path[0] == '~') ) /* home dir */ { g_string_append( ret, g_get_home_dir()); ++relative_path; } else { if( ! cwd ) { char *cwd_new; cwd_new = g_get_current_dir(); g_string_append( ret, cwd_new ); g_free( cwd_new ); } else g_string_append( ret, cwd ); } } if( relative_path[0] != '/' && (0 == ret->len || ret->str[ ret->len - 1 ] != '/' ) ) g_string_append_c( ret, '/' ); while( G_LIKELY( *relative_path ) ) { if( G_UNLIKELY(*relative_path == '.') ) { if( relative_path[1] == '/' || relative_path[1] == '\0' ) /* current dir */ { relative_path += relative_path[1] ? 2 : 1; continue; } if( relative_path[1] == '.' && ( relative_path[2] == '/' || relative_path[2] == '\0') ) /* parent dir */ { gsize len = ret->len - 2; while( ret->str[ len ] != '/' ) --len; g_string_truncate( ret, len + 1 ); relative_path += relative_path[2] ? 3 : 2; continue; } } do { g_string_append_c( ret, *relative_path ); }while( G_LIKELY( *(relative_path++) != '/' && *relative_path ) ); } /* if original path contains tailing '/', preserve it; otherwise, remove it. */ if( strip_tail && G_LIKELY( ret->len > 1 ) && G_UNLIKELY( ret->str[ ret->len - 1 ] == '/' ) ) g_string_truncate( ret, ret->len - 1 ); return g_string_free( ret, FALSE ); }
static liHandlerResult expire(liVRequest *vr, gpointer param, gpointer *context) { struct tm tm; time_t expire_date; guint len; gint max_age; GString *date_str = vr->wrk->tmp_str; expire_rule *rule = param; guint num = rule->num; time_t now = (time_t)li_cur_ts(vr->wrk); UNUSED(context); if (rule->base == EXPIRE_ACCESS) { expire_date = now + num; max_age = num; } else { /* modification */ struct stat st; gint err; if (!vr->physical.path->len) return LI_HANDLER_GO_ON; switch (li_stat_cache_get(vr, vr->physical.path, &st, &err, NULL)) { case LI_HANDLER_GO_ON: break; case LI_HANDLER_WAIT_FOR_EVENT: return LI_HANDLER_WAIT_FOR_EVENT; default: return LI_HANDLER_GO_ON; } expire_date = st.st_mtime + num; if (expire_date < now) expire_date = now; max_age = expire_date - now; } /* format date */ g_string_set_size(date_str, 255); if (!gmtime_r(&expire_date, &tm)) { VR_ERROR(vr, "gmtime_r(%"G_GUINT64_FORMAT") failed: %s", (guint64)expire_date, g_strerror(errno)); return LI_HANDLER_GO_ON; } len = strftime(date_str->str, date_str->allocated_len, "%a, %d %b %Y %H:%M:%S GMT", &tm); if (len == 0) return LI_HANDLER_GO_ON; g_string_set_size(date_str, len); /* finally set the headers */ li_http_header_overwrite(vr->response.headers, CONST_STR_LEN("Expires"), GSTR_LEN(date_str)); g_string_truncate(date_str, 0); g_string_append_len(date_str, CONST_STR_LEN("max-age=")); li_string_append_int(date_str, max_age); li_http_header_append(vr->response.headers, CONST_STR_LEN("Cache-Control"), GSTR_LEN(date_str)); return LI_HANDLER_GO_ON; }
static void import_contacts (void) { EShell *shell; ESourceRegistry *registry; EClient *client = NULL; GList *list; gchar *name; GString *line; FILE *fp; gsize offset; const gchar *extension_name; GError *error = NULL; printf ("importing pine addressbook\n"); shell = e_shell_get_default (); registry = e_shell_get_registry (shell); extension_name = E_SOURCE_EXTENSION_ADDRESS_BOOK; name = g_build_filename (g_get_home_dir (), ".addressbook", NULL); fp = fopen (name, "r"); g_free (name); if (fp == NULL) return; list = e_source_registry_list_sources (registry, extension_name); if (list != NULL) { ESource *source; source = E_SOURCE (list->data); client = e_book_client_connect_sync (source, 30, NULL, &error); } else { /* No address books exist. */ g_warning ("%s: No address books exist.", G_STRFUNC); fclose (fp); return; } g_list_free_full (list, (GDestroyNotify) g_object_unref); if (error != NULL) { g_warning ( "%s: Failed to open book client: %s", G_STRFUNC, error ? error->message : "Unknown error"); g_clear_error (&error); fclose (fp); return; } line = g_string_new (""); g_string_set_size (line, 256); offset = 0; while (fgets (line->str + offset, 256, fp)) { gsize len; len = strlen (line->str + offset) + offset; if (line->str[len - 1] == '\n') g_string_truncate (line, len - 1); else if (!feof (fp)) { offset = len; g_string_set_size (line, len + 256); continue; } else { g_string_truncate (line, len); } import_contact (E_BOOK_CLIENT (client), line->str); offset = 0; } g_string_free (line, TRUE); fclose (fp); g_object_unref (client); }
void textbuffer_line2text(LINE_REC *line, int coloring, GString *str) { unsigned char cmd, *ptr, *tmp; g_return_if_fail(line != NULL); g_return_if_fail(str != NULL); g_string_truncate(str, 0); for (ptr = line->text;;) { if (*ptr != 0) { g_string_append_c(str, (char) *ptr); ptr++; continue; } ptr++; cmd = *ptr; ptr++; if (cmd == LINE_CMD_EOL) { /* end of line */ break; } if (cmd == LINE_CMD_CONTINUE) { /* line continues in another address.. */ memcpy(&tmp, ptr, sizeof(unsigned char *)); ptr = tmp; continue; } if (!coloring) { /* no colors, skip coloring commands */ if (cmd == LINE_COLOR_EXT || cmd == LINE_COLOR_EXT_BG) ptr++; #ifdef TERM_TRUECOLOR else if (cmd == LINE_COLOR_24) ptr+=4; #endif continue; } if ((cmd & LINE_CMD_EOL) == 0) { /* set color */ set_color(str, cmd); } else switch (cmd) { case LINE_CMD_UNDERLINE: g_string_append_c(str, 31); break; case LINE_CMD_REVERSE: g_string_append_c(str, 22); break; case LINE_CMD_BLINK: g_string_append_printf(str, "\004%c", FORMAT_STYLE_BLINK); break; case LINE_CMD_BOLD: g_string_append_printf(str, "\004%c", FORMAT_STYLE_BOLD); break; case LINE_CMD_ITALIC: g_string_append_printf(str, "\004%c", FORMAT_STYLE_ITALIC); break; case LINE_CMD_MONOSPACE: g_string_append_printf(str, "\004%c", FORMAT_STYLE_MONOSPACE); break; case LINE_CMD_COLOR0: g_string_append_printf(str, "\004%c%c", '0', FORMAT_COLOR_NOCHANGE); break; case LINE_CMD_INDENT: g_string_append_printf(str, "\004%c", FORMAT_STYLE_INDENT); break; case LINE_COLOR_EXT: format_ext_color(str, 0, *ptr++); break; case LINE_COLOR_EXT_BG: format_ext_color(str, 1, *ptr++); break; #ifdef TERM_TRUECOLOR case LINE_COLOR_24: g_string_append_printf(str, "\004%c", FORMAT_COLOR_24); break; #endif } } }
static void real_set_color_palette(MT_COLOR_PALETTE *pal) { GString *str; MT_COLOR *col; str = g_string_new(NULL); /* MT_BACKGROUND: */ col = &(*pal)[MT_BACKGROUND]; g_string_truncate(str, 0); COL2("bg", col); parse_rc_string(str->str, "*"); /* MT_FOREGROUND: */ col = &(*pal)[MT_FOREGROUND]; g_string_set_size(str, 0); COL2("fg", col); parse_rc_string(str->str, "*"); /* MT_WINDOW_BACKGROUND: */ col = &(*pal)[MT_WINDOW_BACKGROUND]; g_string_truncate(str, 0); COL2("base", col); parse_rc_string(str->str, "*"); /* MT_WINDOW_FOREGROUND: */ col = &(*pal)[MT_WINDOW_FOREGROUND]; g_string_truncate(str, 0); COL2("text", col); parse_rc_string(str->str, "*"); /* MT_BUTTON_BACKGROUND: */ col = &(*pal)[MT_BUTTON_BACKGROUND]; g_string_truncate(str, 0); COL2("bg", col); parse_rc_string(str->str, "*.GtkButton"); /* MT_BUTTON_FOREGROUND: */ col = &(*pal)[MT_BUTTON_FOREGROUND]; g_string_truncate(str, 0); COL2("text", col); parse_rc_string(str->str, "*.GtkButton"); /* MT_SELECTED_BACKGROUND: */ col = &(*pal)[MT_SELECTED_BACKGROUND]; g_string_truncate(str, 0); COL1("base", "SELECTED", col); COL1("base", "ACTIVE", col); COL1("bg", "SELECTED", col); parse_rc_string(str->str, "*"); g_string_truncate(str, 0); COL1("bg", "PRELIGHT", col); parse_rc_string(str->str, "*Menu*"); col = &(*pal)[MT_BACKGROUND]; g_string_truncate(str, 0); COL1("bg", "PRELIGHT", col); parse_rc_string(str->str, "*MenuBar*"); /* MT_SELECTED_FOREGROUND: */ col = &(*pal)[MT_SELECTED_FOREGROUND]; g_string_truncate(str, 0); COL1("text", "SELECTED", col); COL1("text", "ACTIVE", col); COL1("fg", "SELECTED", col); parse_rc_string(str->str, "*"); g_string_truncate(str, 0); COL1("fg", "PRELIGHT", col); COL1("text", "PRELIGHT", col); parse_rc_string(str->str, "*Menu*"); col = &(*pal)[MT_FOREGROUND]; g_string_truncate(str, 0); COL1("fg", "PRELIGHT", col); parse_rc_string(str->str, "*MenuBar*"); /* MT_DISABLED_BACKGROUND: */ col = &(*pal)[MT_DISABLED_BACKGROUND]; g_string_truncate(str, 0); COL1("base", "INSENSITIVE", col); parse_rc_string(str->str, "*"); /* MT_DISABLED_FOREGROUND: */ col = &(*pal)[MT_DISABLED_FOREGROUND]; g_string_truncate(str, 0); COL1("text", "INSENSITIVE", col); COL1("fg", "INSENSITIVE", col); /* COL1("bg", "INSENSITIVE", col); */ parse_rc_string(str->str, "*"); /* GtkOptionMenu: */ col = &(*pal)[MT_WINDOW_BACKGROUND]; g_string_truncate(str, 0); COL1("bg", "NORMAL", col); COL1("bg", "ACTIVE", col); COL1("bg", "PRELIGHT", col); parse_rc_string(str->str, "*.GtkOptionMenu"); col = &(*pal)[MT_WINDOW_FOREGROUND]; g_string_truncate(str, 0); COL1("fg", "NORMAL", col); COL1("fg", "PRELIGHT", col); parse_rc_string(str->str, "*.GtkOptionMenu.*"); g_string_free(str, TRUE); }
static void control_connection_io_input(void *s) { ControlConnection *self = (ControlConnection *) s; GString *command = NULL; GString *reply = NULL; gchar *nl; gint rc; gint orig_len; GList *iter; if (self->input_buffer->len > MAX_CONTROL_LINE_LENGTH) { /* too much data in input, drop the connection */ msg_error("Too much data in the control socket input buffer", NULL); control_connection_stop_watches(self); control_connection_free(self); return; } orig_len = self->input_buffer->len; /* NOTE: plus one for the terminating NUL */ g_string_set_size(self->input_buffer, self->input_buffer->len + 128 + 1); rc = self->read(self, self->input_buffer->str + orig_len, 128); if (rc < 0) { if (errno != EAGAIN) { msg_error("Error reading command on control channel, closing control channel", evt_tag_errno("error", errno), NULL); goto destroy_connection; } /* EAGAIN, should try again when data comes */ control_connection_update_watches(self); return; } else if (rc == 0) { msg_debug("EOF on control channel, closing connection", NULL); goto destroy_connection; } else { self->input_buffer->len = orig_len + rc; self->input_buffer->str[self->input_buffer->len] = 0; } /* here we have finished reading the input, check if there's a newline somewhere */ nl = strchr(self->input_buffer->str, '\n'); if (nl) { command = g_string_sized_new(128); /* command doesn't contain NL */ g_string_assign_len(command, self->input_buffer->str, nl - self->input_buffer->str); /* strip NL */ /*g_string_erase(self->input_buffer, 0, command->len + 1);*/ g_string_truncate(self->input_buffer, 0); } else { /* no EOL in the input buffer, wait for more data */ control_connection_update_watches(self); return; } for (iter = self->server->control_commands; iter != NULL; iter = iter->next) { if (strncmp(((ControlCommand*)iter->data)->command_name, command->str, strlen(((ControlCommand*)iter->data)->command_name)) == 0) { reply = ((ControlCommand*)iter->data)->func(command); control_connection_send_reply(self, reply); break; } } if (iter == NULL) { msg_error("Unknown command read on control channel, closing control channel", evt_tag_str("command", command->str), NULL); g_string_free(command, TRUE); goto destroy_connection; } control_connection_update_watches(self); g_string_free(command, TRUE); return; destroy_connection: control_connection_stop_watches(self); control_connection_free(self); }
/* * If the MONO_ENV_OPTIONS environment variable is set, it uses this as a * source of command line arguments that are passed to Mono before the * command line arguments specified in the command line. */ static int mono_main_with_options (int argc, char *argv []) { const char *env_options = getenv ("MONO_ENV_OPTIONS"); if (env_options != NULL){ GPtrArray *array = g_ptr_array_new (); GString *buffer = g_string_new (""); const char *p; int i; gboolean in_quotes = FALSE; char quote_char = '\0'; for (p = env_options; *p; p++){ switch (*p){ case ' ': case '\t': if (!in_quotes) { if (buffer->len != 0){ g_ptr_array_add (array, g_strdup (buffer->str)); g_string_truncate (buffer, 0); } } else { g_string_append_c (buffer, *p); } break; case '\\': if (p [1]){ g_string_append_c (buffer, p [1]); p++; } break; case '\'': case '"': if (in_quotes) { if (quote_char == *p) in_quotes = FALSE; else g_string_append_c (buffer, *p); } else { in_quotes = TRUE; quote_char = *p; } break; default: g_string_append_c (buffer, *p); break; } } if (in_quotes) { fprintf (stderr, "Unmatched quotes in value of MONO_ENV_OPTIONS: [%s]\n", env_options); exit (1); } if (buffer->len != 0) g_ptr_array_add (array, g_strdup (buffer->str)); g_string_free (buffer, TRUE); if (array->len > 0){ int new_argc = array->len + argc; char **new_argv = g_new (char *, new_argc + 1); int j; new_argv [0] = argv [0]; /* First the environment variable settings, to allow the command line options to override */ for (i = 0; i < array->len; i++) new_argv [i+1] = g_ptr_array_index (array, i); i++; for (j = 1; j < argc; j++) new_argv [i++] = argv [j]; new_argv [i] = NULL; argc = new_argc; argv = new_argv; }
static gboolean cached_dir_load_entries_recursive (CachedDir *dir, const char *dirname) { DIR *dp; struct dirent *dent; GString *fullpath; gsize fullpath_len; g_assert (dir != NULL); if (dir->have_read_entries) return TRUE; menu_verbose ("Attempting to read entries from %s (full path %s)\n", dir->name, dirname); dp = opendir (dirname); if (dp == NULL) { menu_verbose ("Unable to list directory \"%s\"\n", dirname); return FALSE; } cached_dir_ensure_monitor (dir, dirname); fullpath = g_string_new (dirname); if (fullpath->str[fullpath->len - 1] != G_DIR_SEPARATOR) g_string_append_c (fullpath, G_DIR_SEPARATOR); fullpath_len = fullpath->len; while ((dent = readdir (dp)) != NULL) { /* ignore . and .. */ if (dent->d_name[0] == '.' && (dent->d_name[1] == '\0' || (dent->d_name[1] == '.' && dent->d_name[2] == '\0'))) continue; g_string_append (fullpath, dent->d_name); if (g_str_has_suffix (dent->d_name, ".desktop") || g_str_has_suffix (dent->d_name, ".directory")) { cached_dir_add_entry (dir, dent->d_name, fullpath->str); } else /* Try recursing */ { cached_dir_add_subdir (dir, dent->d_name, fullpath->str); } g_string_truncate (fullpath, fullpath_len); } closedir (dp); g_string_free (fullpath, TRUE); dir->have_read_entries = TRUE; return TRUE; }
char *hexdecode_string(const char *str, GError **err) { size_t orig_len, new_len, i; GString *s; gchar *ret; if (!str) { s = g_string_sized_new(0); goto cleanup; } new_len = orig_len = strlen(str); for (i = 0; i < orig_len; i++) { if (str[i] == '%') { new_len -= 2; } } s = g_string_sized_new(new_len); for (i = 0; (orig_len > 2) && (i < orig_len-2); i++) { if (str[i] == '%') { gchar tmp = 0; size_t j; for (j = 1; j < 3; j++) { tmp <<= 4; if (str[i+j] >= '0' && str[i+j] <= '9') { tmp += str[i+j] - '0'; } else if (str[i+j] >= 'a' && str[i+j] <= 'f') { tmp += str[i+j] - 'a' + 10; } else if (str[i+j] >= 'A' && str[i+j] <= 'F') { tmp += str[i+j] - 'A' + 10; } else { /* error */ g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL, "Illegal character (non-hex) 0x%02hhx at offset %zd", str[i+j], i+j); g_string_truncate(s, 0); goto cleanup; } } if (!tmp) { g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL, "Encoded NULL at starting offset %zd", i); g_string_truncate(s, 0); goto cleanup; } g_string_append_c(s, tmp); i += 2; } else { g_string_append_c(s, str[i]); } } for ( /*nothing*/; i < orig_len; i++) { if (str[i] == '%') { g_set_error(err, am_util_error_quark(), AM_UTIL_ERROR_HEXDECODEINVAL, "'%%' found at offset %zd, but fewer than two characters follow it (%zd)", i, orig_len-i-1); g_string_truncate(s, 0); goto cleanup; } else { g_string_append_c(s, str[i]); } } cleanup: ret = s->str; g_string_free(s, FALSE); return ret; }
static gboolean entry_directory_foreach_recursive (EntryDirectory *ed, CachedDir *cd, GString *relative_path, EntryDirectoryForeachFunc func, DesktopEntrySet *set, gpointer user_data) { GSList *tmp; int relative_path_len; if (cd->deleted) return TRUE; relative_path_len = relative_path->len; tmp = cd->entries; while (tmp != NULL) { DesktopEntry *entry = tmp->data; if (desktop_entry_get_type (entry) == ed->entry_type) { gboolean ret; char *file_id; g_string_append (relative_path, desktop_entry_get_basename (entry)); file_id = get_desktop_file_id_from_path (ed, ed->entry_type, relative_path->str); ret = func (ed, entry, file_id, set, user_data); g_free (file_id); g_string_truncate (relative_path, relative_path_len); if (!ret) return FALSE; } tmp = tmp->next; } tmp = cd->subdirs; while (tmp != NULL) { CachedDir *subdir = tmp->data; g_string_append (relative_path, subdir->name); g_string_append_c (relative_path, G_DIR_SEPARATOR); if (!entry_directory_foreach_recursive (ed, subdir, relative_path, func, set, user_data)) return FALSE; g_string_truncate (relative_path, relative_path_len); tmp = tmp->next; } return TRUE; }
static void save_slot( const gchar* key, KvpValue* value, gpointer data ) { slot_info_t* pSlot_info = (slot_info_t*)data; gsize curlen; g_return_if_fail( key != NULL ); g_return_if_fail( value != NULL ); g_return_if_fail( data != NULL ); // Ignore if we've already run into a failure if ( !pSlot_info->is_ok ) { return; } curlen = pSlot_info->path->len; pSlot_info->pKvpValue = value; if ( curlen != 0 ) { (void)g_string_append( pSlot_info->path, "/" ); } (void)g_string_append( pSlot_info->path, key ); pSlot_info->value_type = value->get_type(); switch ( pSlot_info->value_type ) { case KvpValue::Type::FRAME: { auto pKvpFrame = value->get<KvpFrame*>(); auto guid = guid_new(); slot_info_t *pNewInfo = slot_info_copy( pSlot_info, guid ); KvpValue *oldValue = pSlot_info->pKvpValue; pSlot_info->pKvpValue = new KvpValue{guid}; pSlot_info->is_ok = gnc_sql_do_db_operation( pSlot_info->be, OP_DB_INSERT, TABLE_NAME, TABLE_NAME, pSlot_info, col_table ); g_return_if_fail( pSlot_info->is_ok ); pKvpFrame->for_each_slot(save_slot, pNewInfo); delete pSlot_info->pKvpValue; pSlot_info->pKvpValue = oldValue; g_string_free( pNewInfo->path, TRUE ); g_slice_free( slot_info_t, pNewInfo ); } break; case KvpValue::Type::GLIST: { GncGUID guid = guid_new_return(); slot_info_t *pNewInfo = slot_info_copy( pSlot_info, &guid ); KvpValue *oldValue = pSlot_info->pKvpValue; pSlot_info->pKvpValue = new KvpValue{&guid}; pSlot_info->is_ok = gnc_sql_do_db_operation( pSlot_info->be, OP_DB_INSERT, TABLE_NAME, TABLE_NAME, pSlot_info, col_table ); g_return_if_fail( pSlot_info->is_ok ); for (auto cursor = value->get<GList*>(); cursor; cursor = cursor->next) { auto val = static_cast<KvpValue*>(cursor->data); save_slot("", val, pNewInfo); } delete pSlot_info->pKvpValue; pSlot_info->pKvpValue = oldValue; g_string_free( pNewInfo->path, TRUE ); g_slice_free( slot_info_t, pNewInfo ); } break; default: { pSlot_info->is_ok = gnc_sql_do_db_operation( pSlot_info->be, OP_DB_INSERT, TABLE_NAME, TABLE_NAME, pSlot_info, col_table ); } break; } (void)g_string_truncate( pSlot_info->path, curlen ); }
void channel_set_mode(IRC_SERVER_REC *server, const char *channel, const char *mode) { IRC_CHANNEL_REC *chanrec; GString *tmode, *targs; char *modestr, *curmode, *orig, type, prevtype; int count; g_return_if_fail(IS_IRC_SERVER(server)); g_return_if_fail(channel != NULL && mode != NULL); tmode = g_string_new(NULL); targs = g_string_new(NULL); count = 0; chanrec = irc_channel_find(server, channel); if (chanrec != NULL) channel = chanrec->name; orig = modestr = g_strdup(mode); type = '+'; prevtype = '\0'; curmode = cmd_get_param(&modestr); for (;; curmode++) { if (*curmode == '\0') { /* support for +o nick +o nick2 */ curmode = cmd_get_param(&modestr); if (*curmode == '\0') break; } if (*curmode == '+' || *curmode == '-') { type = *curmode; continue; } if (count == server->max_modes_in_cmd && HAS_MODE_ARG(server, type, *curmode)) { irc_send_cmdv(server, "MODE %s %s%s", channel, tmode->str, targs->str); count = 0; prevtype = '\0'; g_string_truncate(tmode, 0); g_string_truncate(targs, 0); } if (type != prevtype) { prevtype = type; g_string_append_c(tmode, type); } g_string_append_c(tmode, *curmode); if (HAS_MODE_ARG(server, type, *curmode)) { char *arg; count++; arg = cmd_get_param(&modestr); if (*arg == '\0' && type == '-' && *curmode == 'k') { /* "/mode #channel -k" - no reason why it shouldn't work really, so append the key */ IRC_CHANNEL_REC *chanrec; chanrec = irc_channel_find(server, channel); if (chanrec != NULL && chanrec->key != NULL) arg = chanrec->key; } if (*arg != '\0') g_string_append_printf(targs, " %s", arg); } } if (tmode->len > 0) { irc_send_cmdv(server, "MODE %s %s%s", channel, tmode->str, targs->str); } g_string_free(tmode, TRUE); g_string_free(targs, TRUE); g_free(orig); }
static gboolean gwy_si_unit_parse(GwySIUnit *siunit, const gchar *string) { GwySimpleUnit unit; gdouble q; const gchar *end; gchar *p, *e; gint n, i, pfpower; GString *buf; gboolean dividing = FALSE; g_array_set_size(siunit->units, 0); siunit->power10 = 0; if (!string || !*string) return TRUE; /* give up when it looks too wild */ end = strpbrk(string, "\177\001\002\003\004\005\006\007" "\010\011\012\013\014\015\016\017" "\020\021\022\023\024\025\026\027" "\030\031\032\033\034\035\036\037" "!#$&()*,:;=?@\\[]_`|{}"); if (end) { g_warning("Invalid character 0x%02x", *end); return FALSE; } /* may start with a multiplier, but it must be a power of 10 */ q = g_ascii_strtod(string, (gchar**)&end); if (end != string) { string = end; siunit->power10 = ROUND(log10(q)); if (q <= 0 || fabs(log(q/pow10(siunit->power10))) > 1e-14) { g_warning("Bad multiplier %g", q); siunit->power10 = 0; } else if (g_str_has_prefix(string, "<sup>")) { string += strlen("<sup>"); n = strtol(string, (gchar**)&end, 10); if (end == string) g_warning("Bad exponent %s", string); else if (!g_str_has_prefix(end, "</sup>")) g_warning("Expected </sup> after exponent"); else siunit->power10 *= n; string = end; } else if (string[0] == '^') { string++; n = strtol(string, (gchar**)&end, 10); if (end == string) g_warning("Bad exponent %s", string); else siunit->power10 *= n; string = end; } } while (g_ascii_isspace(*string)) string++; buf = g_string_new(""); /* the rest are units */ while (*string) { /* units are separated with whitespace and maybe a division sign */ end = string; do { end = strpbrk(end, " /"); if (!end || end == string || *end != '/' || *(end-1) != '<') break; end++; } while (TRUE); if (!end) end = string + strlen(string); g_string_set_size(buf, 0); g_string_append_len(buf, string, end - string); /* fix sloppy notations */ if (buf->str[0] == '\272') { if (!buf->str[1]) g_string_assign(buf, "deg"); else { g_string_erase(buf, 0, 1); g_string_prepend(buf, "°"); } } else if (gwy_strequal(buf->str, "°")) g_string_assign(buf, "deg"); else if (buf->str[0] == '\305' && !buf->str[1]) g_string_assign(buf, "Å"); else if (gwy_strequal(buf->str, "Å")) g_string_assign(buf, "Å"); else if (gwy_strequal(buf->str, "AA")) g_string_assign(buf, "Å"); /* get prefix, but be careful not to split mol to mili-ol */ pfpower = 0; for (i = 0; i < G_N_ELEMENTS(known_units); i++) { if (g_str_has_prefix(buf->str, known_units[i]) && !g_ascii_isalpha(buf->str[strlen(known_units[i])])) break; } if (i == G_N_ELEMENTS(known_units) && strlen(buf->str) > 1) { for (i = 0; i < G_N_ELEMENTS(SI_prefixes); i++) { const gchar *pfx = SI_prefixes[i].prefix; if (g_str_has_prefix(buf->str, pfx) && g_ascii_isalpha(buf->str[strlen(pfx)])) { pfpower = SI_prefixes[i].power10; g_string_erase(buf, 0, strlen(pfx)); break; } } } /* get unit power */ unit.power = 1; if ((p = strstr(buf->str + 1, "<sup>"))) { unit.power = strtol(p + strlen("<sup>"), &e, 10); if (e == p + strlen("<sup>") || !g_str_has_prefix(e, "</sup>")) { g_warning("Bad power %s", p); unit.power = 1; } else if (!unit.power || abs(unit.power) > 12) { g_warning("Bad power %d", unit.power); unit.power = 1; } g_string_truncate(buf, p - buf->str); } else if ((p = strchr(buf->str + 1, '^'))) { unit.power = strtol(p + 1, &e, 10); if (e == p + 1 || *e) { g_warning("Bad power %s", p); unit.power = 1; } else if (!unit.power || abs(unit.power) > 12) { g_warning("Bad power %d", unit.power); unit.power = 1; } g_string_truncate(buf, p - buf->str); } else if (buf->len) { /* Are we really desperate? Yes, we are! */ i = buf->len; while (i && (g_ascii_isdigit(buf->str[i-1]) || buf->str[i-1] == '-')) i--; if (i != buf->len) { unit.power = strtol(buf->str + i, NULL, 10); if (!unit.power || abs(unit.power) > 12) { g_warning("Bad power %d", unit.power); unit.power = 1; } g_string_truncate(buf, i); } } /* handle some ugly, but quite common units */ if (gwy_strequal(buf->str, "Å")) { pfpower -= 10; g_string_assign(buf, "m"); } else if (gwy_strequal(buf->str, "%")) { pfpower -= 2; g_string_assign(buf, ""); } /* elementary sanity */ if (!g_utf8_validate(buf->str, -1, (const gchar**)&p)) { g_warning("Unit string is not valid UTF-8"); g_string_truncate(buf, p - buf->str); } if (!buf->len) { /* maybe it's just percentage. cross fingers and proceed. */ if (dividing) unit.power = -unit.power; siunit->power10 += unit.power * pfpower; } else if (!g_ascii_isalpha(buf->str[0]) && (guchar)buf->str[0] < 128) g_warning("Invalid base unit: %s", buf->str); else { /* append it */ unit.unit = g_quark_from_string(buf->str); if (dividing) unit.power = -unit.power; gwy_debug("<%s:%u> %d\n", buf->str, unit.unit, unit.power); siunit->power10 += unit.power * pfpower; g_array_append_val(siunit->units, unit); } /* TODO: scan known obscure units */ unit.traits = 0; /* get to the next token, looking for division */ while (g_ascii_isspace(*end)) end++; if (*end == '/') { if (dividing) g_warning("Cannot group multiple divisions"); dividing = TRUE; end++; while (g_ascii_isspace(*end)) end++; } string = end; } gwy_si_unit_canonicalize(siunit); return TRUE; }
static void help_category(GSList *cmdlist, int items) { WINDOW_REC *window; TEXT_DEST_REC dest; GString *str; GSList *tmp; int *columns, cols, rows, col, row, last_col_rows, max_width; char *linebuf, *format, *stripped; window = window_find_closest(NULL, NULL, MSGLEVEL_CLIENTCRAP); max_width = window->width; /* remove width of timestamp from max_width */ format_create_dest(&dest, NULL, NULL, MSGLEVEL_CLIENTCRAP, NULL); format = format_get_line_start(current_theme, &dest, time(NULL)); if (format != NULL) { stripped = strip_codes(format); max_width -= strlen(stripped); g_free(stripped); g_free(format); } /* calculate columns */ cols = get_max_column_count(cmdlist, get_cmd_length, max_width, 6, 1, 3, &columns, &rows); cmdlist = columns_sort_list(cmdlist, rows); /* rows in last column */ last_col_rows = rows-(cols*rows-g_slist_length(cmdlist)); if (last_col_rows == 0) last_col_rows = rows; str = g_string_new(NULL); linebuf = g_malloc(max_width+1); col = 0; row = 0; for (tmp = cmdlist; tmp != NULL; tmp = tmp->next) { COMMAND_REC *rec = tmp->data; memset(linebuf, ' ', columns[col]); linebuf[columns[col]] = '\0'; memcpy(linebuf, rec->cmd, strlen(rec->cmd)); g_string_append(str, linebuf); if (++col == cols) { printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP, "%s", str->str); g_string_truncate(str, 0); col = 0; row++; if (row == last_col_rows) cols--; } } if (str->len != 0) printtext(NULL, NULL, MSGLEVEL_CLIENTCRAP, "%s", str->str); g_slist_free(cmdlist); g_string_free(str, TRUE); g_free(columns); g_free(linebuf); }
GString * g_string_assign_len(GString *s, const char *str, gsize str_len) { g_string_truncate(s, 0); return g_string_append_len(s, str, str_len); }
/* SYNTAX: NAMES [-count | -ops -halfops -voices -normal] [<channels> | **] */ static void cmd_names(const char *data, SERVER_REC *server, WI_ITEM_REC *item) { CHANNEL_REC *chanrec; GHashTable *optlist; GString *unknowns; char *channel, **channels, **tmp; int flags; void *free_arg; g_return_if_fail(data != NULL); if (!IS_SERVER(server) || !server->connected) cmd_return_error(CMDERR_NOT_CONNECTED); if (!cmd_get_params(data, &free_arg, 1 | PARAM_FLAG_OPTIONS, "names", &optlist, &channel)) return; if (g_strcmp0(channel, "*") == 0 || *channel == '\0') { if (!IS_CHANNEL(item)) cmd_param_error(CMDERR_NOT_JOINED); channel = CHANNEL(item)->name; } flags = 0; if (g_hash_table_lookup(optlist, "ops") != NULL) flags |= CHANNEL_NICKLIST_FLAG_OPS; if (g_hash_table_lookup(optlist, "halfops") != NULL) flags |= CHANNEL_NICKLIST_FLAG_HALFOPS; if (g_hash_table_lookup(optlist, "voices") != NULL) flags |= CHANNEL_NICKLIST_FLAG_VOICES; if (g_hash_table_lookup(optlist, "normal") != NULL) flags |= CHANNEL_NICKLIST_FLAG_NORMAL; if (g_hash_table_lookup(optlist, "count") != NULL) flags |= CHANNEL_NICKLIST_FLAG_COUNT; if (flags == 0) flags = CHANNEL_NICKLIST_FLAG_ALL; unknowns = g_string_new(NULL); channels = g_strsplit(channel, ",", -1); for (tmp = channels; *tmp != NULL; tmp++) { chanrec = channel_find(server, *tmp); if (chanrec == NULL) g_string_append_printf(unknowns, "%s,", *tmp); else { fe_channels_nicklist(chanrec, flags); signal_stop(); } } g_strfreev(channels); if (unknowns->len > 1) g_string_truncate(unknowns, unknowns->len-1); if (unknowns->len > 0 && g_strcmp0(channel, unknowns->str) != 0) signal_emit("command names", 3, unknowns->str, server, item); g_string_free(unknowns, TRUE); cmd_params_free(free_arg); }