void convert_babylonfile(const char *filename, print_info_t print_info, bool strip_html)
{			
	struct stat stats;
	if (g_stat (filename, &stats) == -1)
	{
		print_info("File not exist!\n");
		return;
	}
	gchar *basefilename = g_path_get_basename(filename);
	gchar *ch = strrchr(basefilename, '.');
	if (ch)
		*ch = '\0';
	gchar *dirname = g_path_get_dirname(filename);
	FILE *tabfile;
	tabfile = g_fopen(filename,"r");

	gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
	size_t readsize = fread (buffer, 1, stats.st_size, tabfile);
	fclose (tabfile);
	buffer[readsize] = '\0';	
	
	GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);
	GArray *array2 = g_array_sized_new(FALSE,FALSE, sizeof(struct _synworditem),20000);
		
	gchar *p, *p1, *p2, *p3, *p4, *p5;
	p = buffer;
	if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters.
		p+=3;
	struct _worditem worditem;
	struct _synworditem synworditem;
	gint linenum=1;
	int stripmethod;
	if (strip_html)
		stripmethod = 0;
	else
		stripmethod = 1;
	std::string sametypesequence = "m";
	std::string bookname;
	std::string author;
	std::string email;
	std::string website;
	std::string description;
	std::string date;
	bool print_sameword;
	if (*p == '\n') {
		print_sameword = false;
		p++;
		linenum++;
		while (1) {
			if (*p == '\n') {
				p++;
				linenum++;
				break;
			}
			p++;
			p1 = strchr(p, '\n');
			if (!p1) {
				return;
			}
			*p1 = '\0';
			p1++;
			linenum++;
			if (g_str_has_prefix(p, "stripmethod=")) {
				p += sizeof("stripmethod=") -1;
				if (strcmp(p, "striphtml")==0)
					stripmethod = 0;
				else if (strcmp(p, "stripnewline")==0)
					stripmethod = 1;
				else if (strcmp(p, "keep")==0)
					stripmethod = 2;
			} else if (g_str_has_prefix(p, "sametypesequence=")) {
				p += sizeof("sametypesequence=") -1;
				sametypesequence = p;
			} else if (g_str_has_prefix(p, "bookname=")) {
				p += sizeof("bookname=") -1;
				bookname = p;
			} else if (g_str_has_prefix(p, "author=")) {
				p += sizeof("author=") -1;
				author = p;
			} else if (g_str_has_prefix(p, "email=")) {
				p += sizeof("email=") -1;
				email = p;
			} else if (g_str_has_prefix(p, "website=")) {
				p += sizeof("website=") -1;
				website = p;
			} else if (g_str_has_prefix(p, "date=")) {
				p += sizeof("date=") -1;
				date = p;
			} else if (g_str_has_prefix(p, "description=")) {
				p += sizeof("description=") -1;
				description = p;
			}
			p = p1;
		}
	} else {
		print_sameword = true;
	}
	while (1) {
		if (*p == '\0') {
                        print_info("Over\n");
                        break;
                }
		p1 = strchr(p,'\n');
		if (!p1) {
			gchar *str = g_strdup_printf("Error, no end line 1: %d\n", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p1 = '\0';
		p1++;
		linenum++;
		p2 = strchr(p1,'\n');
		if (!p2) {
			gchar *str = g_strdup_printf("Error, no end line 2: %d\n", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p2 = '\0';
		p2++;
		linenum++;
		p3=p2;
		if (*p3 != '\n') {
			gchar *str = g_strdup_printf("Error, not null line %d", linenum);
			print_info(str);
			g_free(str);
			return;
		}
		*p3='\0';
		p3++;
		linenum++;
		
		if (stripmethod == 0) {
			html_strstrip(p1, linenum-2, print_info);
		} else if (stripmethod == 1) {
			newline_strstrip(p1, linenum-2, print_info);
		} else if (stripmethod == 2) {
		}
		g_strstrip(p1);
		if (!(*p1)) {
			gchar *str = g_strdup_printf("%s-%d, bad definition!!!\n", basefilename, linenum-1);
			print_info(str);
			g_free(str);
			p= p3;
                        continue;
		}	
		
		p4 = strchr(p, '|');
		if (p4) {
			*p4 = '\0';
			worditem.word = p;
                        g_strstrip(worditem.word);
                        if (!worditem.word[0]) {
				gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
				print_info(str);
				g_free(str);
                                p=p3;
                                continue;
                        }
			worditem.definition = p1;
                        g_array_append_val(array, worditem);
			std::list <std::string> WordList;
			WordList.push_back(worditem.word);
			p4++;
			while (true) {
				p5 = strchr(p4, '|');
				if (p5) {
					*p5 = '\0';
					synworditem.synword = p4;
					g_strstrip(synworditem.synword);
                        		if (!synworditem.synword[0]) {
						gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
						print_info(str);
						g_free(str);
                				p4 = p5+1;
		                                continue;
                		        }
					bool find = false;
					for (std::list<std::string>::const_iterator it=WordList.begin(); it!=WordList.end(); ++it) {
						if (*it == synworditem.synword) {
							find= true;
							break;
						}
					}
					if (find) {
						if (print_sameword) {
							gchar *str = g_strdup_printf("Same word: %s\n", synworditem.synword);
							print_info(str);
							g_free(str);
						}
						p4 = p5+1;
						continue;
					} else {
						WordList.push_back(synworditem.synword);
					}
					synworditem.origword = worditem.word;
					synworditem.definition = worditem.definition;
					g_array_append_val(array2, synworditem);
					p4 = p5+1;
				} else {
					synworditem.synword = p4;
					g_strstrip(synworditem.synword);
                                        if (!synworditem.synword[0]) {
						gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
						print_info(str);
						g_free(str);
                                                break;
                                        }
					bool find = false;
					for (std::list<std::string>::const_iterator it=WordList.begin(); it!=WordList.end(); ++it) {
						if (*it == synworditem.synword) {
							find= true;
							break;
						}
					}
					if (find) {
						if (print_sameword) {
							gchar *str = g_strdup_printf("Same word: %s\n", synworditem.synword);
							print_info(str);
							g_free(str);
						}
						break;
					}
					synworditem.origword = worditem.word;
                                        synworditem.definition = worditem.definition;
                                        g_array_append_val(array2, synworditem);
					break;
				}
			}
		} else {
			worditem.word = p;
			g_strstrip(worditem.word);
			if (!worditem.word[0]) {
				gchar *str = g_strdup_printf("%s-%d, bad word!!!\n", basefilename, linenum-2);
				print_info(str);
				g_free(str);
				p=p3;
				continue;
			}
			worditem.definition = p1;
			g_array_append_val(array, worditem);
		}
		p= p3;
	}		
	g_array_sort(array,comparefunc);
	g_array_sort(array2,comparefunc2);

	gchar ifofilename[256];
	gchar idxfilename[256];
	gchar dicfilename[256];
	sprintf(ifofilename, "%s" G_DIR_SEPARATOR_S "%s.ifo", dirname, basefilename);
	sprintf(idxfilename, "%s" G_DIR_SEPARATOR_S "%s.idx", dirname, basefilename);
	sprintf(dicfilename, "%s" G_DIR_SEPARATOR_S "%s.dict", dirname, basefilename);
	FILE *ifofile = g_fopen(ifofilename,"wb");
	FILE *idxfile = g_fopen(idxfilename,"wb");
	FILE *dicfile = g_fopen(dicfilename,"wb");
	
	guint32 offset_old;
	guint32 tmpglong;
	struct _worditem *pworditem;
	gint definition_len;
	gulong i;
	for (i=0; i< array->len; i++) {
		offset_old = ftell(dicfile);
		pworditem = &g_array_index(array, struct _worditem, i);
		definition_len = strlen(pworditem->definition);
		fwrite(pworditem->definition, 1 ,definition_len,dicfile);
		fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
                tmpglong = g_htonl(offset_old);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
                tmpglong = g_htonl(definition_len);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);

	}
	fclose(idxfile);
	fclose(dicfile);

	gchar *str = g_strdup_printf("%s wordcount: %d\n", basefilename, array->len);
	print_info(str);
	g_free(str);

	if (array2->len) {
		gchar synfilename[256];
	        sprintf(synfilename, "%s" G_DIR_SEPARATOR_S "%s.syn", dirname, basefilename);
		FILE *synfile = g_fopen(synfilename,"wb");
		struct _synworditem *psynworditem;
		gint iFrom, iTo, iThisIndex, cmpint;
		bool bFound;
		for (i=0; i< array2->len; i++) {
			psynworditem = &g_array_index(array2, struct _synworditem, i);
			fwrite(psynworditem->synword, 1, strlen(psynworditem->synword)+1, synfile);
			bFound=false;
			iFrom=0;
			iTo=array->len-1;
			while (iFrom<=iTo) {
				iThisIndex=(iFrom+iTo)/2;
				pworditem = &g_array_index(array, struct _worditem, iThisIndex);
				cmpint = stardict_strcmp(psynworditem->origword, pworditem->word);
				if (cmpint>0)
					iFrom=iThisIndex+1;
				else if (cmpint<0)
					iTo=iThisIndex-1;
				else {
					bFound=true;
					break;
				}
				
			}
			if (!bFound) {
				gchar *str = g_strdup_printf("Error, %s not find.\n", psynworditem->origword);
				print_info(str);
				g_free(str);
				return;
			}
			do {
				if (iThisIndex==0)
					break;
				pworditem = &g_array_index(array, struct _worditem, iThisIndex-1);
				if (strcmp(psynworditem->origword, pworditem->word)==0)
					iThisIndex--;
				else
					break;
			} while (true);
			bFound=false;
			do {
				pworditem = &g_array_index(array, struct _worditem, iThisIndex);
				if (strcmp(psynworditem->origword, pworditem->word)==0) {
					if (psynworditem->definition == pworditem->definition) {
						bFound=true;
						break;
					} else
						iThisIndex++;
				} else
					break;
			} while (true);
			if (!bFound) {
				gchar *str = g_strdup_printf("Error, %s definition not find.\n", psynworditem->origword);
				print_info(str);
				g_free(str);
                                return;
                        }
			tmpglong = g_htonl(iThisIndex);
	                fwrite(&(tmpglong),sizeof(guint32),1, synfile);
		}
		fclose(synfile);
		gchar *str = g_strdup_printf("%s synwordcount: %d\n", basefilename, array2->len);
		print_info(str);
		g_free(str);
	}
static gboolean
ui_to_setting (CEPageIP4 *page)
{
        const gchar *method;
        gboolean ignore_auto_dns;
        gboolean ignore_auto_routes;
        gboolean never_default;
        GPtrArray *addresses = NULL;
        GArray *dns_servers = NULL;
        GPtrArray *routes = NULL;
        GList *children, *l;
        gboolean ret = TRUE;

        if (!gtk_switch_get_active (page->enabled)) {
                method = NM_SETTING_IP4_CONFIG_METHOD_DISABLED;
        } else {
                switch (gtk_combo_box_get_active (page->method)) {
                case IP4_METHOD_MANUAL:
                        method = NM_SETTING_IP4_CONFIG_METHOD_MANUAL;
                        break;
                case IP4_METHOD_LINK_LOCAL:
                        method = NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL;
                        break;
                default:
                case IP4_METHOD_AUTO:
                        method = NM_SETTING_IP4_CONFIG_METHOD_AUTO;
                        break;
                }
        }

        addresses = g_ptr_array_new_with_free_func (free_addr);
        children = gtk_container_get_children (GTK_CONTAINER (page->address_list));
        for (l = children; l; l = l->next) {
                GtkWidget *row = l->data;
                GtkEntry *entry;
                const gchar *text_address;
                const gchar *text_netmask;
                const gchar *text_gateway;
                struct in_addr tmp_addr;
                struct in_addr tmp_gateway = { 0 };
                guint32 prefix;
                guint32 empty_val = 0;
                GArray *addr;

                entry = GTK_ENTRY (g_object_get_data (G_OBJECT (row), "address"));
                if (!entry)
                        continue;

                text_address = gtk_entry_get_text (entry);
                text_netmask = gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (row), "network")));
                text_gateway = gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (row), "gateway")));

                if (!*text_address && !*text_netmask && !*text_gateway) {
                        /* ignore empty rows */
                        widget_unset_error (GTK_WIDGET (entry));
                        widget_unset_error (g_object_get_data (G_OBJECT (row), "network"));
                        widget_unset_error (g_object_get_data (G_OBJECT (row), "gateway"));
                        continue;
                }

                if (inet_pton (AF_INET, text_address, &tmp_addr) <= 0) {
                        widget_set_error (GTK_WIDGET (entry));
                        ret = FALSE;
                } else {
                        widget_unset_error (GTK_WIDGET (entry));
                }

                if (!parse_netmask (text_netmask, &prefix)) {
                        widget_set_error (g_object_get_data (G_OBJECT (row), "network"));
                        ret = FALSE;
                } else {
                        widget_unset_error (g_object_get_data (G_OBJECT (row), "network"));
                }

                if (text_gateway && *text_gateway && inet_pton (AF_INET, text_gateway, &tmp_gateway) <= 0) {
                        widget_set_error (g_object_get_data (G_OBJECT (row), "gateway"));
                        ret = FALSE;
                } else {
                        widget_unset_error (g_object_get_data (G_OBJECT (row), "gateway"));
                }

                if (!ret)
                        continue;

                addr = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
                g_array_append_val (addr, tmp_addr.s_addr);
                g_array_append_val (addr, prefix);
                if (tmp_gateway.s_addr)
                        g_array_append_val (addr, tmp_gateway.s_addr);
                else
                        g_array_append_val (addr, empty_val);
                g_ptr_array_add (addresses, addr);
        }
        g_list_free (children);

        if (addresses->len == 0) {
                g_ptr_array_free (addresses, TRUE);
                addresses = NULL;
        }

        dns_servers = g_array_new (FALSE, FALSE, sizeof (guint));
        children = gtk_container_get_children (GTK_CONTAINER (page->dns_list));
        for (l = children; l; l = l->next) {
                GtkWidget *row = l->data;
                GtkEntry *entry;
                const gchar *text;
                struct in_addr tmp_addr;

                entry = GTK_ENTRY (g_object_get_data (G_OBJECT (row), "address"));
                if (!entry)
                        continue;

                text = gtk_entry_get_text (entry);
                if (!*text) {
                        /* ignore empty rows */
                        widget_unset_error (GTK_WIDGET (entry));
                        continue;
                }

                if (inet_pton (AF_INET, text, &tmp_addr) <= 0) {
                        widget_set_error (GTK_WIDGET (entry));
                        ret = FALSE;
                } else {
                        widget_unset_error (GTK_WIDGET (entry));
                        g_array_append_val (dns_servers, tmp_addr.s_addr);
                }
        }
        g_list_free (children);


        routes = g_ptr_array_new_with_free_func (free_addr);
        children = gtk_container_get_children (GTK_CONTAINER (page->routes_list));
        for (l = children; l; l = l->next) {
                GtkWidget *row = l->data;
                GtkEntry *entry;
                const gchar *text_address;
                const gchar *text_netmask;
                const gchar *text_gateway;
                const gchar *text_metric;
                struct in_addr tmp_addr = { 0 };
                guint32 address, netmask, gateway, metric;
                GArray *route;

                entry = GTK_ENTRY (g_object_get_data (G_OBJECT (row), "address"));
                if (!entry)
                        continue;

                text_address = gtk_entry_get_text (entry);
                text_netmask = gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (row), "netmask")));
                text_gateway = gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (row), "gateway")));
                text_metric = gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (row), "metric")));

                if (!*text_address && !*text_netmask && !*text_gateway && !*text_metric) {
                        /* ignore empty rows */
                        continue;
                }

                if (inet_pton (AF_INET, text_address, &tmp_addr) <= 0) {
                        widget_set_error (GTK_WIDGET (entry));
                        ret = FALSE;
                } else {
                        widget_unset_error (GTK_WIDGET (entry));
                        address = tmp_addr.s_addr;
                }

                if (!parse_netmask (text_netmask, &netmask)) {
                        widget_set_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "netmask")));
                        ret = FALSE;
                } else {
                        widget_unset_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "netmask")));
                }

                if (inet_pton (AF_INET, text_gateway, &tmp_addr) <= 0) {
                        widget_set_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "gateway")));
                        ret = FALSE;
                } else {
                        widget_unset_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "gateway")));
                        gateway = tmp_addr.s_addr;
                }

                metric = 0;
                if (*text_metric) {
                        errno = 0;
                        metric = strtoul (text_metric, NULL, 10);
                        if (errno) {
                                widget_set_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "metric")));
                                ret = FALSE;
                        } else {
                                widget_unset_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "metric")));
                        }
                } else {
                        widget_unset_error (GTK_WIDGET (g_object_get_data (G_OBJECT (row), "metric")));
                }

                if (!ret)
                        continue;

                route = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 4);
                g_array_append_val (route, address);
                g_array_append_val (route, netmask);
                g_array_append_val (route, gateway);
                g_array_append_val (route, metric);
                g_ptr_array_add (routes, route);
        }
        g_list_free (children);

        if (routes->len == 0) {
                g_ptr_array_free (routes, TRUE);
                routes = NULL;
        }

        if (!ret)
                goto out;

        ignore_auto_dns = !gtk_switch_get_active (page->auto_dns);
        ignore_auto_routes = !gtk_switch_get_active (page->auto_routes);
        never_default = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (page->never_default));

        g_object_set (page->setting,
                      NM_SETTING_IP4_CONFIG_METHOD, method,
                      NM_SETTING_IP4_CONFIG_ADDRESSES, addresses,
                      NM_SETTING_IP4_CONFIG_DNS, dns_servers,
                      NM_SETTING_IP4_CONFIG_ROUTES, routes,
                      NM_SETTING_IP4_CONFIG_IGNORE_AUTO_DNS, ignore_auto_dns,
                      NM_SETTING_IP4_CONFIG_IGNORE_AUTO_ROUTES, ignore_auto_routes,
                      NM_SETTING_IP4_CONFIG_NEVER_DEFAULT, never_default,
                      NULL);

out:
        if (addresses)
                g_ptr_array_free (addresses, TRUE);

        if (dns_servers)
                g_array_free (dns_servers, TRUE);

        if (routes)
                g_ptr_array_free (routes, TRUE);

        return ret;
}
GArray *
mm_huawei_parse_prefmode_test (const gchar *response,
                               GError **error)
{
    gchar **split;
    guint i;
    MMModemMode all = MM_MODEM_MODE_NONE;
    GArray *out;

    response = mm_strip_tag (response, "^PREFMODE:");
    split = g_strsplit_set (response, " (,)\r\n", -1);
    if (!split) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "Unexpected ^PREFMODE format output");
        return NULL;
    }

    out = g_array_sized_new (FALSE,
                             FALSE,
                             sizeof (MMHuaweiPrefmodeCombination),
                             3);
    for (i = 0; split[i]; i++) {
        guint val;
        MMModemMode preferred = MM_MODEM_MODE_NONE;
        GError *inner_error = NULL;
        MMHuaweiPrefmodeCombination combination;

        if (split[i][0] == '\0')
            continue;

        if (!mm_get_uint_from_str (split[i], &val)) {
            mm_dbg ("Error parsing ^PREFMODE value: %s", split[i]);
            continue;
        }

        if (!mode_from_prefmode (val, &preferred, &inner_error)) {
            mm_dbg ("Unhandled ^PREFMODE: %s", inner_error->message);
            g_error_free (inner_error);
            continue;
        }

        combination.prefmode = val;
        combination.allowed = MM_MODEM_MODE_NONE; /* reset it later */
        combination.preferred = preferred;

        all |= preferred;

        g_array_append_val (out, combination);
    }
    g_strfreev (split);

    /* No value */
    if (out->len == 0) {
        g_array_unref (out);
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "^PREFMODE response contains no valid values");
        return NULL;
    }

    /* Single value listed; PREFERRED=NONE... */
    if (out->len == 1) {
        MMHuaweiPrefmodeCombination *combination;

        combination = &g_array_index (out, MMHuaweiPrefmodeCombination, 0);
        combination->allowed = all;
        combination->preferred = MM_MODEM_MODE_NONE;
    } else {
        /* Multiple values, reset ALLOWED */
        for (i = 0; i < out->len; i++) {
            MMHuaweiPrefmodeCombination *combination;

            combination = &g_array_index (out, MMHuaweiPrefmodeCombination, i);
            combination->allowed = all;
            if (combination->preferred == all)
                combination->preferred = MM_MODEM_MODE_NONE;
        }
    }

    return out;
}
Exemplo n.º 4
0
/**
 * gimp_scan_convert_stroke:
 * @sc:          a #GimpScanConvert context
 * @width:       line width in pixels
 * @join:        how lines should be joined
 * @cap:         how to render the end of lines
 * @miter:       convert a mitered join to a bevelled join if the miter would
 *               extend to a distance of more than @miter times @width from
 *               the actual join point
 * @dash_offset: offset to apply on the dash pattern
 * @dash_info:   dash pattern or %NULL for a solid line
 *
 * Stroke the content of a GimpScanConvert. The next
 * gimp_scan_convert_render() will result in the outline of the
 * polygon defined with the commands above.
 *
 * You cannot add additional polygons after this command.
 *
 * Note that if you have nonstandard resolution, "width" gives the
 * width (in pixels) for a vertical stroke, i.e. use the X resolution
 * to calculate the width of a stroke when operating with real world
 * units.
 */
void
gimp_scan_convert_stroke (GimpScanConvert *sc,
                          gdouble          width,
                          GimpJoinStyle    join,
                          GimpCapStyle     cap,
                          gdouble          miter,
                          gdouble          dash_offset,
                          GArray          *dash_info)
{
  sc->do_stroke = TRUE;
  sc->width = width;
  sc->join  = join;
  sc->cap   = cap;
  sc->miter = miter;
  if (sc->dash_info)
    {
      g_array_free (sc->dash_info, TRUE);
      sc->dash_info = NULL;
    }

  if (dash_info && dash_info->len >= 2)
    {
      gint          n_dashes;
      gdouble      *dashes;
      gint          i;

      dash_offset = dash_offset * MAX (width, 1.0);

      n_dashes = dash_info->len;
      dashes = g_new (gdouble, dash_info->len);

      for (i = 0; i < dash_info->len ; i++)
        dashes[i] = MAX (width, 1.0) * g_array_index (dash_info, gdouble, i);

      /* correct 0.0 in the first element (starts with a gap) */

      if (dashes[0] == 0.0)
        {
          gdouble first;

          first = dashes[1];

          /* shift the pattern to really starts with a dash and
           * use the offset to skip into it.
           */
          for (i = 0; i < dash_info->len - 2; i++)
            {
              dashes[i] = dashes[i+2];
              dash_offset += dashes[i];
            }

          if (dash_info->len % 2 == 1)
            {
              dashes[dash_info->len - 2] = first;
              n_dashes --;
            }
          else if (dash_info->len > 2)
           {
             dashes [dash_info->len - 3] += first;
             n_dashes -= 2;
           }
        }

      /* correct odd number of dash specifiers */

      if (n_dashes % 2 == 1)
        {
          gdouble last;

          last = dashes[n_dashes - 1];
          dashes[0]   += last;
          dash_offset += last;
          n_dashes --;
        }

      if (n_dashes >= 2)
        {
          sc->dash_info = g_array_sized_new (FALSE, FALSE,
                                             sizeof (gdouble), n_dashes);
          sc->dash_info = g_array_append_vals (sc->dash_info, dashes, n_dashes);
          sc->dash_offset = dash_offset;
        }

      g_free (dashes);
    }
}
Exemplo n.º 5
0
void convert(char *filename)
{
    struct stat stats;
    if (stat (filename, &stats) == -1)
    {
        printf("file not exist!\n");
        return;
    }
    gchar *basefilename = g_path_get_basename(filename);
    FILE *tabfile;
    tabfile = fopen(filename,"r");

    gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
    fread (buffer, 1, stats.st_size, tabfile);
    fclose (tabfile);
    buffer[stats.st_size] = '\0';

    GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);

    gchar *p, *p1, *p2, *p3;
    p = buffer;
    if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters.
        p+=3;
    struct _worditem worditem;
    glong linenum=1;
    while (1) {
        if (*p == '\0') {
            g_print("over\n");
            break;
        }
        p1 = strchr(p,'\n');
        if (!p1) {
            g_print("error, no end line\n");
            return;
        }
        *p1 = '\0';
        p1++;
        p2 = strchr(p,'[');
        if (!p2) {
            g_print("error, no [, %ld\n", linenum);
            return;
        }
        *p2 = '\0';
        p2++;
        p3 = strchr(p2, ']');
        if (!p3) {
            g_print("error, no ], %ld\n", linenum);
            return;
        }
        *p3 = '\0';
        p3++;
        worditem.word = p;
        to_pinyin(p2);
        worditem.pinyin = p2;
        to_definition(p3);
        worditem.definition = p3;
        g_strstrip(worditem.word);
        g_strstrip(worditem.pinyin);
        g_strstrip(worditem.definition);
        if (!worditem.word[0]) {
            g_print("%s-%ld, bad word!!!\n", basefilename, linenum);
            p= p1;
            linenum++;
            continue;
        }
        if (!worditem.pinyin[0]) {
            g_print("%s-%ld, bad pinyin!!!\n", basefilename, linenum);
        }
        if (!worditem.definition[0]) {
            g_print("%s-%ld, bad definition!!!\n", basefilename, linenum);
        }
        if (!worditem.pinyin[0] && !worditem.definition[0]) {
            g_print("%s-%ld, bad pinyin and definition!!!\n", basefilename, linenum);
            p= p1;
            linenum++;
            continue;
        }
        g_array_append_val(array, worditem);
        p= p1;
        linenum++;
    }
    g_array_sort(array,comparefunc);

    gchar idxfilename[256];
    gchar dicfilename[256];
    sprintf(idxfilename, "%s.idx", basefilename);
    sprintf(dicfilename, "%s.dict", basefilename);
    FILE *idxfile = fopen(idxfilename,"w");
    FILE *dicfile = fopen(dicfilename,"w");

    guint32 offset_old;
    guint32 tmpglong;
    struct _worditem *pworditem;
    gint pinyin_len;
    gint definition_len;
    gulong i;
    for (i=0; i< array->len; i++) {
        offset_old = ftell(dicfile);
        pworditem = &g_array_index(array, struct _worditem, i);
        pinyin_len = strlen(pworditem->pinyin);
        fwrite(pworditem->pinyin, 1 , pinyin_len+1,dicfile);
        definition_len = strlen(pworditem->definition);
        fwrite(pworditem->definition, 1 ,definition_len,dicfile);
        fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
        tmpglong = g_htonl(offset_old);
        fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
        tmpglong = g_htonl(pinyin_len+1+ definition_len);
        fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
    }
    fclose(idxfile);
    fclose(dicfile);
    g_print("%s wordcount: %d\n", basefilename, array->len);

    g_free(buffer);
    g_array_free(array,TRUE);

    gchar command[256];
    sprintf(command, "dictzip %s.dict", basefilename);
    system(command);

    g_free(basefilename);
}
Exemplo n.º 6
0
int
test_line_1(void * data) 
{
    mfp_procinfo * proctype = g_hash_table_lookup(mfp_proc_registry, "line~");
    mfp_processor * line = mfp_proc_create(proctype, 0, 1, (mfp_context *)data);
    mfp_sample * outp; 
    int snum;

    float tval[] = { 0.0, 1.0, 1.0, 
                     0.0, 0.0, 0.0, 
                     1.0, 1.0, 1.0 };

    GArray * env_1 = g_array_sized_new(TRUE, TRUE, sizeof(float), 6);

    printf("   test_line_1 \n ");
    for (snum=0; snum < 9; snum++) {
        g_array_append_val(env_1, tval[snum]);
    }

    if(!proctype || !line) {
        printf("FAIL: proctype=%p, proc=%p\n", proctype, line);
        return 0;
    }

    setparam_gpointer(line, "segments", env_1);
    line->needs_config = 1;

    mfp_proc_process(line);

    outp = line->outlet_buf[0]->data;

    if (outp[0] != 0) {
        printf("FAIL: outp[0] was %f not 0\n", outp[0]);
        return 0;
    }

    if (outp[22] != 0.5) {
        printf("FAIL: outp[22] was %f not 0.5\n", outp[22]);
        return 0;
    }

    if (outp[44] != 1.0) {
        printf("FAIL: outp[44] was %f not 1.0\n", outp[44]);
        return 0;
    }

    if (outp[45] != 0.0) {
        printf("FAIL: outp[45] was %f not 0.0\n", outp[45]);
        return 0;
    }

    if (outp[46] != 0.0) {
        printf("FAIL: outp[46] was %f not 0.0\n", outp[46]);
        return 0;
    }

    if (outp[88] != 0.0) {
        printf("FAIL: outp[88] was %f not 0.0\n", outp[89]);
        return 0;
    }

    if (outp[99] != 0.25) {
        printf("FAIL: outp[100] was %f not 0.25\n", outp[100]);
        return 0;
    }

    if (outp[134] != 1.0) {
        printf("FAIL: outp[134] was %f not 1.0\n", outp[134]);
        return 0;
    }


    printf("ok\n");
    return 1;
}
Exemplo n.º 7
0
static gboolean
ui_to_setting (CEPageIP4 *self)
{
	CEPageIP4Private *priv = CE_PAGE_IP4_GET_PRIVATE (self);
	GtkTreeModel *model;
	GtkTreeIter tree_iter;
	int int_method = IP4_METHOD_AUTO;
	const char *method;
	GArray *dns_servers = NULL;
	GSList *search_domains = NULL;
	GPtrArray *addresses = NULL;
	gboolean valid = FALSE, iter_valid;
	const char *text;
	gboolean ignore_auto_dns = FALSE;
	const char *dhcp_client_id = NULL;
	char **items = NULL, **iter;

	/* Method */
	if (gtk_combo_box_get_active_iter (priv->method, &tree_iter)) {
		gtk_tree_model_get (GTK_TREE_MODEL (priv->method_store), &tree_iter,
		                    METHOD_COL_NUM, &int_method, -1);
	}

	switch (int_method) {
	case IP4_METHOD_LINK_LOCAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL;
		break;
	case IP4_METHOD_MANUAL:
		method = NM_SETTING_IP4_CONFIG_METHOD_MANUAL;
		break;
	case IP4_METHOD_SHARED:
		method = NM_SETTING_IP4_CONFIG_METHOD_SHARED;
		break;
	case IP4_METHOD_AUTO_ADDRESSES:
		ignore_auto_dns = TRUE;
		/* fall through */
	default:
		method = NM_SETTING_IP4_CONFIG_METHOD_AUTO;
		break;
	}

	/* IP addresses */
	model = gtk_tree_view_get_model (priv->addr_list);
	iter_valid = gtk_tree_model_get_iter_first (model, &tree_iter);

	addresses = g_ptr_array_sized_new (1);
	while (iter_valid) {
		char *item = NULL;
		struct in_addr tmp_addr, tmp_gateway = { 0 };
		GArray *addr;
		guint32 empty_val = 0, prefix;

		gtk_tree_model_get (model, &tree_iter, COL_ADDRESS, &item, -1);
		if (!item || !inet_aton (item, &tmp_addr)) {
			g_warning ("%s: IPv4 address '%s' missing or invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		gtk_tree_model_get (model, &tree_iter, COL_PREFIX, &item, -1);
		if (!item) {
			g_warning ("%s: IPv4 prefix '%s' missing!",
			           __func__, item ? item : "<none>");
			goto out;
		}

		if (!parse_netmask (item, &prefix)) {
			g_warning ("%s: IPv4 prefix '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		/* Gateway is optional... */
		gtk_tree_model_get (model, &tree_iter, COL_GATEWAY, &item, -1);
		if (item && !inet_aton (item, &tmp_gateway)) {
			g_warning ("%s: IPv4 gateway '%s' invalid!",
			           __func__, item ? item : "<none>");
			g_free (item);
			goto out;
		}
		g_free (item);

		addr = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
		g_array_append_val (addr, tmp_addr.s_addr);
		g_array_append_val (addr, prefix);
		if (tmp_gateway.s_addr)
			g_array_append_val (addr, tmp_gateway.s_addr);
		else
			g_array_append_val (addr, empty_val);
		g_ptr_array_add (addresses, addr);

		iter_valid = gtk_tree_model_iter_next (model, &tree_iter);
	}

	/* Don't pass empty array to the setting */
	if (!addresses->len) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	/* DNS servers */
	dns_servers = g_array_new (FALSE, FALSE, sizeof (guint));

	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_servers));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			struct in_addr tmp_addr;
			char *stripped = g_strstrip (*iter);

			if (!strlen (stripped))
				continue;

			if (inet_pton (AF_INET, stripped, &tmp_addr))
				g_array_append_val (dns_servers, tmp_addr.s_addr);
			else {
				g_strfreev (items);
				goto out;
			}
		}
		g_strfreev (items);
	}

	/* Search domains */
	text = gtk_entry_get_text (GTK_ENTRY (priv->dns_searches));
	if (text && strlen (text)) {
		items = g_strsplit_set (text, ", ;:", 0);
		for (iter = items; *iter; iter++) {
			char *stripped = g_strstrip (*iter);

			if (strlen (stripped))
				search_domains = g_slist_prepend (search_domains, g_strdup (stripped));
		}

		if (items)
			g_strfreev (items);
	}

	search_domains = g_slist_reverse (search_domains);

	/* DHCP client ID */
	if (!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
		dhcp_client_id = gtk_entry_get_text (priv->dhcp_client_id);
		if (dhcp_client_id && !strlen (dhcp_client_id))
			dhcp_client_id = NULL;
	}

	/* Update setting */
	g_object_set (priv->setting,
				  NM_SETTING_IP4_CONFIG_METHOD, method,
				  NM_SETTING_IP4_CONFIG_ADDRESSES, addresses,
				  NM_SETTING_IP4_CONFIG_DNS, dns_servers,
				  NM_SETTING_IP4_CONFIG_DNS_SEARCH, search_domains,
				  NM_SETTING_IP4_CONFIG_IGNORE_AUTO_DNS, ignore_auto_dns,
				  NM_SETTING_IP4_CONFIG_DHCP_CLIENT_ID, dhcp_client_id,
				  NULL);
	valid = TRUE;

out:
	if (addresses) {
		g_ptr_array_foreach (addresses, (GFunc) free_one_addr, NULL);
		g_ptr_array_free (addresses, TRUE);
	}

	if (dns_servers)
		g_array_free (dns_servers, TRUE);

	g_slist_foreach (search_domains, (GFunc) g_free, NULL);
	g_slist_free (search_domains);

	return valid;
}
Exemplo n.º 8
0
static void ibus_handwrite_recog_init(IbusHandwriteRecog*obj)
{
	obj->matched =g_array_new(TRUE,TRUE,sizeof(MatchedChar));
	obj->strokes = g_array_sized_new(TRUE,TRUE,sizeof(LineStroke),0);
}
Exemplo n.º 9
0
static gboolean
panel_multiscreen_get_randr_monitors_for_screen (GdkScreen     *screen,
						 int           *monitors_ret,
						 GdkRectangle **geometries_ret)
{
#ifdef HAVE_RANDR
	Display            *xdisplay;
	Window              xroot;
	XRRScreenResources *resources;
	RROutput            primary;
	GArray             *geometries;
	int                 i;
	gboolean            driver_is_pre_randr_1_2;

	if (!have_randr)
		return FALSE;

	/* GTK+ 2.14.x uses the Xinerama API, instead of RANDR, to get the
	 * monitor geometries. It does this to avoid calling
	 * XRRGetScreenResources(), which is slow as it re-detects all the
	 * monitors --- note that XRRGetScreenResourcesCurrent() had not been
	 * introduced yet.  Using Xinerama in GTK+ has the bad side effect that
	 * gdk_screen_get_monitor_plug_name() will return NULL, as Xinerama
	 * does not provide that information, unlike RANDR.
	 *
	 * Here we need to identify the output names, so that we can put the
	 * built-in LCD in a laptop *before* all other outputs.  This is so
	 * that gnome-panel will normally prefer to appear on the "native"
	 * display rather than on an external monitor.
	 *
	 * To get the output names and geometries, we will not use
	 * gdk_screen_get_n_monitors() and friends, but rather we will call
	 * XRR*() directly.
	 *
	 * See https://bugzilla.novell.com/show_bug.cgi?id=479684 for this
	 * particular bug, and and
	 * http://bugzilla.gnome.org/show_bug.cgi?id=562944 for a more
	 * long-term solution.
	 */

	xdisplay = GDK_SCREEN_XDISPLAY (screen);
	xroot = GDK_WINDOW_XID (gdk_screen_get_root_window (screen));

#if (RANDR_MAJOR > 1 || (RANDR_MAJOR == 1 && RANDR_MINOR >= 3))
	if (have_randr_1_3) {
		resources = XRRGetScreenResourcesCurrent (xdisplay, xroot);
		if (resources->noutput == 0) {
			/* This might happen if nothing tried to get randr
			 * resources from the server before, so we need an
			 * active probe. See comment #27 in
			 * https://bugzilla.gnome.org/show_bug.cgi?id=597101 */
			XRRFreeScreenResources (resources);
			resources = XRRGetScreenResources (xdisplay, xroot);
		}
	} else
		resources = XRRGetScreenResources (xdisplay, xroot);
#else
	resources = XRRGetScreenResources (xdisplay, xroot);
#endif

	if (!resources)
		return FALSE;

	primary = None;
#if (RANDR_MAJOR > 1 || (RANDR_MAJOR == 1 && RANDR_MINOR >= 3))
	if (have_randr_1_3)
		primary = XRRGetOutputPrimary (xdisplay, xroot);
#endif

	geometries = g_array_sized_new (FALSE, FALSE,
					sizeof (GdkRectangle),
					resources->noutput);

	driver_is_pre_randr_1_2 = FALSE;

	for (i = 0; i < resources->noutput; i++) {
		XRROutputInfo *output;

		output = XRRGetOutputInfo (xdisplay, resources,
					   resources->outputs[i]);

		/* Drivers before RANDR 1.2 return "default" for the output
		 * name */
		if (g_strcmp0 (output->name, "default") == 0)
			driver_is_pre_randr_1_2 = TRUE;

		if (output->connection != RR_Disconnected &&
		    output->crtc != 0) {
			XRRCrtcInfo  *crtc;
			GdkRectangle  rect;

			crtc = XRRGetCrtcInfo (xdisplay, resources,
					       output->crtc);

			rect.x	    = crtc->x;
			rect.y	    = crtc->y;
			rect.width  = crtc->width;
			rect.height = crtc->height;

			XRRFreeCrtcInfo (crtc);

			if (_panel_multiscreen_output_should_be_first (xdisplay,
								       resources->outputs[i],
								       output, primary))
				g_array_prepend_vals (geometries, &rect, 1);
			else
				g_array_append_vals (geometries, &rect, 1);
		}

		XRRFreeOutputInfo (output);
	}

	XRRFreeScreenResources (resources);

	if (driver_is_pre_randr_1_2) {
		/* Drivers before RANDR 1.2 don't provide useful info about
		 * outputs */
		g_array_free (geometries, TRUE);
		return FALSE;
	}

	if (geometries->len == 0) {
		/* This can happen in at least one case:
		 * https://bugzilla.novell.com/show_bug.cgi?id=543876 where all
		 * monitors appear disconnected (possibly because the  screen
		 * is behing a KVM switch) -- see comment #8.
		 * There might be other cases too, so we stay on the safe side.
		 */
		g_array_free (geometries, TRUE);
		return FALSE;
	}

	*monitors_ret = geometries->len;
	*geometries_ret = (GdkRectangle *) g_array_free (geometries, FALSE);

	return TRUE;
#else
	return FALSE;
#endif
}
Exemplo n.º 10
0
static const GValue *
gda_data_access_wrapper_get_value_at (GdaDataModel *model, gint col, gint row, GError **error)
{
	GdaDataAccessWrapper *imodel;

	g_return_val_if_fail (GDA_IS_DATA_ACCESS_WRAPPER (model), NULL);
	imodel = (GdaDataAccessWrapper*) model;
	g_return_val_if_fail (imodel->priv, NULL);
	g_return_val_if_fail (imodel->priv->model, NULL);
	g_return_val_if_fail (row >= 0, NULL);

	if (col >= imodel->priv->nb_cols) {
		g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_COLUMN_OUT_OF_RANGE_ERROR,
			     _("Column %d out of range (0-%d)"), col, imodel->priv->nb_cols - 1);
		return NULL;
	}

	if (!imodel->priv->rows) {
		/* imodel->priv->model is a random access model, use it */
		if (imodel->priv->rows_mapping)
			return gda_data_model_get_value_at (imodel->priv->model, imodel->priv->rows_mapping [col],
							    row, error);
		else
			return gda_data_model_get_value_at (imodel->priv->model, col, row, error);
	}
	else {
		GdaRow *gda_row;
		gint tmp;
		tmp = row;
		gda_row = g_hash_table_lookup (imodel->priv->rows, &tmp);
		if (gda_row) {
			GValue *val = gda_row_get_value (gda_row, col);
			if (gda_row_value_is_valid (gda_row, val))
				return val;
			else
				return NULL;
		}
		else {
			g_assert (imodel->priv->iter);
			if (imodel->priv->iter_row < 0) {
				if (gda_data_model_iter_move_next (imodel->priv->iter)) {
					tmp = row;
					gda_row = g_hash_table_lookup (imodel->priv->rows, &tmp);
					if (row == imodel->priv->iter_row) {
						GValue *val = gda_row_get_value (gda_row, col);
						if (gda_row_value_is_valid (gda_row, val))
							return val;
						else
							return NULL;
					}
				}
				else {
					g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
						      "%s", _("Can't set iterator's position"));
					return NULL;
				}
			}
				
			gda_row = NULL;
			if (row != imodel->priv->iter_row) {
				if (row > imodel->priv->iter_row) {
					/* need to move forward */
					while ((imodel->priv->iter_row < row) && 
					       gda_data_model_iter_move_next (imodel->priv->iter));
				}
				else {
					/* need to move backwards */
					g_assert (imodel->priv->model_access_flags & GDA_DATA_MODEL_ACCESS_CURSOR_BACKWARD);
					while ((imodel->priv->iter_row > row) && 
					       gda_data_model_iter_move_prev (imodel->priv->iter)) ;
				}
			}

			if (! (imodel->priv->model_access_flags & GDA_DATA_MODEL_ACCESS_CURSOR_BACKWARD) ||
			    ! (imodel->priv->model_access_flags & GDA_DATA_MODEL_ACCESS_CURSOR_FORWARD)) {
				tmp = row;
				gda_row = g_hash_table_lookup (imodel->priv->rows, &tmp);

				if (gda_row) {
					GValue *val = gda_row_get_value (gda_row, col);
					if (gda_row_value_is_valid (gda_row, val))
						return val;
					else
						return NULL;
				}
			}
			else {
				/* in this case iter can be moved forward and backward at will => we only
				 * need to keep a pool of GdaRow for performances reasons */
				tmp = row;
				gda_row = g_hash_table_lookup (imodel->priv->rows, &tmp);

				if (!gda_row) {
					if (! imodel->priv->rows_buffer_array) {
						imodel->priv->rows_buffer_array = g_array_sized_new (FALSE, FALSE, 
												     sizeof (GdaRow*),
												     ROWS_POOL_SIZE);
						imodel->priv->rows_buffer_index = g_array_sized_new (FALSE, FALSE, 
												     sizeof (gint), 
												     ROWS_POOL_SIZE);
					}
					else if (imodel->priv->rows_buffer_array->len == ROWS_POOL_SIZE) {
						/* get rid of the oldest row (was model's index_row row)*/
						gint index_row;

						index_row = g_array_index (imodel->priv->rows_buffer_index, gint,
									   ROWS_POOL_SIZE - 1);
						g_array_remove_index (imodel->priv->rows_buffer_array,
								      ROWS_POOL_SIZE - 1);
						g_array_remove_index (imodel->priv->rows_buffer_index,
								      ROWS_POOL_SIZE - 1);
						g_hash_table_remove (imodel->priv->rows, &index_row);
					}
					if (gda_data_model_iter_move_to_row (imodel->priv->iter, row)) {
						gda_row = create_new_row (imodel);
						g_array_prepend_val (imodel->priv->rows_buffer_array, gda_row);
						g_array_prepend_val (imodel->priv->rows_buffer_index, imodel->priv->iter_row);
					}
				}

				GValue *val;
				val = gda_row ? gda_row_get_value (gda_row, col) : NULL;
				if (gda_row && gda_row_value_is_valid (gda_row, val))
					return val;
				else
					return NULL;
			}
		}
	}

	g_set_error (error, GDA_DATA_MODEL_ERROR, GDA_DATA_MODEL_ACCESS_ERROR,
		      "%s", _("Can't access data"));
	return NULL;
}
Exemplo n.º 11
0
rwsched_instance_t *
rwsched_instance_new(void)
{
  struct rwsched_instance_s *instance;

  // Allocate memory for the new instance

  // Register the rwsched instance types
  RW_CF_TYPE_REGISTER(rwsched_instance_ptr_t);
  RW_CF_TYPE_REGISTER(rwsched_tasklet_ptr_t);
  rwsched_CFRunLoopInit();
  rwsched_CFSocketInit();

  // Allocate the Master Resource-Tracking Handle
  g_rwresource_track_handle = RW_RESOURCE_TRACK_CREATE_CONTEXT("The Master Context");

  // Allocate a rwsched instance type and track it
  instance = RW_CF_TYPE_MALLOC0(sizeof(*instance), rwsched_instance_ptr_t);
  RW_CF_TYPE_VALIDATE(instance, rwsched_instance_ptr_t);

  // Set the instance configuration
  instance->config.single_thread = TRUE;

  // For now use libdispatch only
  instance->use_libdispatch_only = TRUE;
  // libdispatch_init();

  // Fake up a rwqueue placeholder object to use as the (NULL) DISPATCH_TARGET_QUEUE_DEFAULT
  RW_ASSERT(instance->use_libdispatch_only);
  instance->default_rwqueue = (rwsched_dispatch_queue_t) RW_MALLOC0_TYPE(sizeof(*instance->default_rwqueue), rwsched_dispatch_queue_t);
  RW_ASSERT_TYPE(instance->default_rwqueue, rwsched_dispatch_queue_t);
  instance->default_rwqueue->header.libdispatch_object._dq = DISPATCH_TARGET_QUEUE_DEFAULT;

  // Fake up a rwqueue placeholder object to use as DISPATCH_TARGET_QUEUE_MAIN
  RW_ASSERT(instance->use_libdispatch_only);
  instance->main_rwqueue = (rwsched_dispatch_queue_t) RW_MALLOC0_TYPE(sizeof(*instance->main_rwqueue), rwsched_dispatch_queue_t);
  RW_ASSERT_TYPE(instance->main_rwqueue, rwsched_dispatch_queue_t);
  instance->main_rwqueue->header.libdispatch_object._dq = dispatch_get_main_queue();

  // Fake up rwqueue placeholder objects for the usual four global
  // queues.  The pri values are not 0,1,2,3 or similar, they are
  // -MAX, -2, 0, 2.  We do not support arbitrary pri values, although
  // I think the dispatch API is intended to.
  RW_ASSERT(instance->use_libdispatch_only);
  RW_STATIC_ASSERT(RWSCHED_DISPATCH_QUEUE_GLOBAL_CT == 4);
  static long pris[RWSCHED_DISPATCH_QUEUE_GLOBAL_CT] = {
    DISPATCH_QUEUE_PRIORITY_HIGH,
    DISPATCH_QUEUE_PRIORITY_DEFAULT,
    DISPATCH_QUEUE_PRIORITY_LOW,
    DISPATCH_QUEUE_PRIORITY_BACKGROUND
  };
  int  i; for (i=0; i<RWSCHED_DISPATCH_QUEUE_GLOBAL_CT; i++) {
    instance->global_rwqueue[i].pri = pris[i];
    instance->global_rwqueue[i].rwq = (rwsched_dispatch_queue_t) RW_MALLOC0_TYPE(sizeof(*instance->global_rwqueue[i].rwq), rwsched_dispatch_queue_t);
    RW_ASSERT_TYPE(instance->global_rwqueue[i].rwq, rwsched_dispatch_queue_t);
    instance->global_rwqueue[i].rwq->header.libdispatch_object._dq = dispatch_get_global_queue(pris[i], 0);
    RW_ASSERT(instance->global_rwqueue[i].rwq->header.libdispatch_object._dq);
  }

  instance->main_cfrunloop_mode = kCFRunLoopDefaultMode;
  //instance->main_cfrunloop_mode = CFSTR("TimerMode");
  //instance->deferred_cfrunloop_mode = CFSTR("Deferred Mode");

  // Allocate an array of tasklet pointers and track it
  rwsched_tasklet_t *tasklet = NULL;
  instance->tasklet_array = g_array_sized_new(TRUE, TRUE, sizeof(void *), 256);
  g_array_append_val(instance->tasklet_array, tasklet);

  rwsched_instance_ref(instance);
  ck_pr_inc_32(&g_rwsched_instance_count);
  //RW_ASSERT(g_rwsched_instance_count <= 2);
  g_rwsched_instance = instance;

  instance->rwlog_instance = rwlog_init("RW.Sched");

  // Return the instance pointer
  return instance;
}
static GPtrArray *
read_ip4_addresses (GKeyFile *file,
			    const char *setting_name,
			    const char *key)
{
	GPtrArray *addresses;
	int i = 0;

	addresses = g_ptr_array_sized_new (3);

	/* Look for individual addresses */
	while (i++ < 1000) {
		gchar **tmp, **iter;
		char *key_name;
		gsize length = 0;
		int ret;
		GArray *address;
		guint32 empty = 0;
		int j;

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string_list (file, setting_name, key_name, &length, NULL);
		g_free (key_name);

		if (!tmp || !length)
			break; /* all done */

		if ((length < 2) || (length > 3)) {
			g_warning ("%s: ignoring invalid IPv4 address item '%s'", __func__, key_name);
			goto next;
		}

		/* convert the string array into IP addresses */
		address = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 3);
		for (iter = tmp, j = 0; *iter; iter++, j++) {
			struct in_addr addr;

			if (j == 1) {
				guint32 prefix = 0;

				/* prefix */
				if (!get_one_int (*iter, 32, key_name, &prefix)) {
					g_array_free (address, TRUE);
					goto next;
				}

				g_array_append_val (address, prefix);
			} else {
				/* address and gateway */
				ret = inet_pton (AF_INET, *iter, &addr);
				if (ret <= 0) {
					g_warning ("%s: ignoring invalid IPv4 %s element '%s'", __func__, key_name, *iter);
					g_array_free (address, TRUE);
					goto next;
				}
				g_array_append_val (address, addr.s_addr);
			}
		}

		/* fill in blank gateway if not specified */
		if (address->len == 2)
			g_array_append_val (address, empty);

		g_ptr_array_add (addresses, address);

next:
		g_strfreev (tmp);
	}

	if (addresses->len < 1) {
		g_ptr_array_free (addresses, TRUE);
		addresses = NULL;
	}

	return addresses;
}
static GPtrArray *
read_ip4_routes (GKeyFile *file,
			 const char *setting_name,
			 const char *key)
{
	GPtrArray *routes;
	int i = 0;

	routes = g_ptr_array_sized_new (3);

	/* Look for individual routes */
	while (i++ < 1000) {
		gchar **tmp, **iter;
		char *key_name;
		gsize length = 0;
		int ret;
		GArray *route;
		int j;

		key_name = g_strdup_printf ("%s%d", key, i);
		tmp = g_key_file_get_string_list (file, setting_name, key_name, &length, NULL);
		g_free (key_name);

		if (!tmp || !length)
			break; /* all done */

		if (length != 4) {
			g_warning ("%s: ignoring invalid IPv4 route item '%s'", __func__, key_name);
			goto next;
		}

		/* convert the string array into IP addresses */
		route = g_array_sized_new (FALSE, TRUE, sizeof (guint32), 4);
		for (iter = tmp, j = 0; *iter; iter++, j++) {
			struct in_addr addr;

			if (j == 1) {
				guint32 prefix = 0;

				/* prefix */
				if (!get_one_int (*iter, 32, key_name, &prefix)) {
					g_array_free (route, TRUE);
					goto next;
				}

				g_array_append_val (route, prefix);
			} else if (j == 3) {
				guint32 metric = 0;

				/* metric */
				if (!get_one_int (*iter, G_MAXUINT32, key_name, &metric)) {
					g_array_free (route, TRUE);
					goto next;
				}

				g_array_append_val (route, metric);
			} else {
				/* address and next hop */
				ret = inet_pton (AF_INET, *iter, &addr);
				if (ret <= 0) {
					g_warning ("%s: ignoring invalid IPv4 %s element '%s'", __func__, key_name, *iter);
					g_array_free (route, TRUE);
					goto next;
				}
				g_array_append_val (route, addr.s_addr);
			}
		}
		g_ptr_array_add (routes, route);

next:
		g_strfreev (tmp);
	}

	if (routes->len < 1) {
		g_ptr_array_free (routes, TRUE);
		routes = NULL;
	}

	return routes;
}
Exemplo n.º 14
0
static void
hanja_key_list_init(HanjaKeyList* list)
{
    list->all_modifiers = 0;
    list->keys = g_array_sized_new(FALSE, TRUE, sizeof(struct KeyEvent), 4);
}
Exemplo n.º 15
0
static void
pgd_annots_update_selected_text (PgdAnnotsDemo *demo)
{
    PopplerRectangle      doc_area, *rects = NULL, *r = NULL;
    gdouble               width, height;
    GArray               *quads_array = NULL;
    guint                 n_rects;
    gint                  i, lines = 0;
    GList                 *l_rects = NULL, *list;

    poppler_page_get_size (demo->page, &width, &height);

    doc_area.x1 = demo->start.x;
    doc_area.y1 = demo->start.y;
    doc_area.x2 = demo->stop.x;
    doc_area.y2 = demo->stop.y;

    if (! poppler_page_get_text_layout_for_area (demo->page, &doc_area,
                                                 &rects, &n_rects))
        return;

    r = g_slice_new (PopplerRectangle);
    r->x1 = G_MAXDOUBLE; r->y1 = G_MAXDOUBLE;
    r->x2 = G_MINDOUBLE; r->y2 = G_MINDOUBLE;

    for (i = 0; i < n_rects; i++) {
        /* Check if the rectangle belongs to the same line.
           On a new line, start a new target rectangle.
           On the same line, make an union of rectangles at
           the same line */
        if (ABS(r->y2 - rects[i].y2) > 0.0001) {
            if (i > 0)
                l_rects = g_list_append (l_rects, r);
            r = g_slice_new (PopplerRectangle);
            r->x1 = rects[i].x1;
            r->y1 = rects[i].y1;
            r->x2 = rects[i].x2;
            r->y2 = rects[i].y2;
            lines++;
        } else {
            r->x1 = MIN(r->x1, rects[i].x1);
            r->y1 = MIN(r->y1, rects[i].y1);
            r->x2 = MAX(r->x2, rects[i].x2);
            r->y2 = MAX(r->y2, rects[i].y2);
        }
    }

    l_rects = g_list_append (l_rects, r);
    l_rects = g_list_reverse (l_rects);

    quads_array = g_array_sized_new (TRUE, TRUE,
                                     sizeof (PopplerQuadrilateral),
                                     lines);
    g_array_set_size (quads_array, lines);

    for (list = l_rects, i = 0; list; list = list->next, i++) {
        PopplerQuadrilateral *quad;

        quad = &g_array_index (quads_array, PopplerQuadrilateral, i);
        r = (PopplerRectangle *)list->data;
        quad->p1.x = r->x1;
        quad->p1.y = height - r->y1;
        quad->p2.x = r->x2;
        quad->p2.y = height - r->y1;
        quad->p3.x = r->x1;
        quad->p3.y = height - r->y2;
        quad->p4.x = r->x2;
        quad->p4.y = height - r->y2;
        g_slice_free (PopplerRectangle, r);
    }

    poppler_annot_text_markup_set_quadrilaterals (POPPLER_ANNOT_TEXT_MARKUP (demo->active_annot), quads_array);
    g_array_free (quads_array, TRUE);
    g_free (rects);
    g_list_free (l_rects);
}
Exemplo n.º 16
0
PyObject *
pygi_get_property_value_real (PyGObject *instance,
                              const gchar *attr_name)
{
    GType g_type;
    GIPropertyInfo *property_info = NULL;
    char *property_name = g_strdup (attr_name);
    GParamSpec *pspec = NULL;
    GValue value = { 0, };
    GIArgument arg = { 0, };
    PyObject *py_value = NULL;
    GITypeInfo *type_info = NULL;
    GITransfer transfer;

    canonicalize_key (property_name);

    g_type = pyg_type_from_object ((PyObject *)instance);
    property_info = _pygi_lookup_property_from_g_type (g_type, property_name);

    if (property_info == NULL)
        goto out;

    pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (instance->obj),
                                          attr_name);
    if (pspec == NULL)
        goto out;

    g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (pspec));
    g_object_get_property (instance->obj, attr_name, &value);

    type_info = g_property_info_get_type (property_info);
    transfer = g_property_info_get_ownership_transfer (property_info);

    GITypeTag type_tag = g_type_info_get_tag (type_info);
    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            arg.v_boolean = g_value_get_boolean (&value);
            break;
        case GI_TYPE_TAG_INT8:
            arg.v_int8 = g_value_get_schar (&value);
            break;
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_INT32:
            if (G_VALUE_HOLDS_LONG (&value))
                arg.v_long = g_value_get_long (&value);
            else
                arg.v_int = g_value_get_int (&value);
            break;
        case GI_TYPE_TAG_INT64:
            if (G_VALUE_HOLDS_LONG (&value))
                arg.v_long = g_value_get_long (&value);
            else
                arg.v_int64 = g_value_get_int64 (&value);
            break;
        case GI_TYPE_TAG_UINT8:
            arg.v_uint8 = g_value_get_uchar (&value);
            break;
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_UINT32:
            if (G_VALUE_HOLDS_ULONG (&value))
                arg.v_ulong = g_value_get_ulong (&value);
            else
                arg.v_uint = g_value_get_uint (&value);
            break;
        case GI_TYPE_TAG_UINT64:
            if (G_VALUE_HOLDS_ULONG (&value))
                arg.v_ulong = g_value_get_ulong (&value);
            else
                arg.v_uint64 = g_value_get_uint64 (&value);
            break;
        case GI_TYPE_TAG_FLOAT:
            arg.v_float = g_value_get_float (&value);
            break;
        case GI_TYPE_TAG_DOUBLE:
            arg.v_double = g_value_get_double (&value);
            break;
        case GI_TYPE_TAG_GTYPE:
            arg.v_size = g_value_get_gtype (&value);
            break;
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            arg.v_string = g_value_dup_string (&value);
            break;
        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info;
            GIInfoType info_type;
            GType type;

            info = g_type_info_get_interface (type_info);
            type = g_registered_type_info_get_g_type (info);
            info_type = g_base_info_get_type (info);

            g_base_info_unref (info);

            switch (info_type) {
                case GI_INFO_TYPE_ENUM:
                    arg.v_int32 = g_value_get_enum (&value);
                    break;
                case GI_INFO_TYPE_INTERFACE:
                case GI_INFO_TYPE_OBJECT:
                    arg.v_pointer = g_value_get_object (&value);
                    break;
                case GI_INFO_TYPE_BOXED:
                case GI_INFO_TYPE_STRUCT:
                case GI_INFO_TYPE_UNION:

                    if (g_type_is_a (type, G_TYPE_BOXED)) {
                        arg.v_pointer = g_value_get_boxed (&value);
                    } else if (g_type_is_a (type, G_TYPE_POINTER)) {
                        arg.v_pointer = g_value_get_pointer (&value);
                    } else {
                        PyErr_Format (PyExc_NotImplementedError,
                                      "Retrieving properties of type '%s' is not implemented",
                                      g_type_name (type));
                    }
                    break;
                default:
                    PyErr_Format (PyExc_NotImplementedError,
                                  "Retrieving properties of type '%s' is not implemented",
                                  g_type_name (type));
                    goto out;
            }
            break;
        }
        case GI_TYPE_TAG_GHASH:
            arg.v_pointer = g_value_get_boxed (&value);
            break;
        case GI_TYPE_TAG_GLIST:
            arg.v_pointer = g_value_get_pointer (&value);
            break;
        case GI_TYPE_TAG_ARRAY:
        {
            gchar** strings;
            GArray *arg_items;
            int i;

            strings = g_value_get_boxed (&value);
            if (strings == NULL)
                arg.v_pointer = NULL;
            else {
                arg_items = g_array_sized_new (TRUE, TRUE, sizeof (GIArgument), g_strv_length (strings));
                g_array_set_size (arg_items, g_strv_length (strings));
                for (i = 0; strings[i] != NULL; ++i) {
                    g_array_index (arg_items, GIArgument, i).v_string = strings[i];
                }
                arg.v_pointer = arg_items;
            }
            break;
        }
        default:
            PyErr_Format (PyExc_NotImplementedError,
                          "Retrieving properties of type %s is not implemented",
                          g_type_tag_to_string (g_type_info_get_tag (type_info)));
            goto out;
    }

    py_value = _pygi_argument_to_object (&arg, type_info, transfer);

out:
    g_free (property_name);
    if (property_info != NULL)
        g_base_info_unref (property_info);
    if (type_info != NULL)
        g_base_info_unref (type_info);

    return py_value;
}
Exemplo n.º 17
0
/**
 * world_new:
 *
 **/
World*
world_new(
    RMeshGroup*             groups
    )
{
    World* world;
    WorldNode node;
    gchar* group_name;
    RMesh* group;
    GHashTableIter iter;
    gchar** tokens;
    guint id, id1, id2;

    world = g_slice_new0(World);
    world->nodes = g_array_sized_new(
        FALSE,
        TRUE,
        sizeof(WorldNode),
        g_hash_table_size(groups->groups));
    world->groups = groups;

    id = 0;

    g_hash_table_iter_init(&iter, world->groups->groups);
    while(g_hash_table_iter_next(&iter, (gpointer)&group_name, (gpointer)&group))
    {
        if(!g_str_has_prefix(group_name, "R"))
        {
            continue;
        }

        tokens = g_strsplit(group_name, "_", 0);
        id1 = g_ascii_strtoll(tokens[1], NULL, 10);
        g_strfreev(tokens);

        node.room.id = id1;
        node.room.type = WORLD_ROOM;
        node.room.mesh = group;
        r_mesh_compute_bbox(node.room.mesh, 0, node.room.bbox);
        node.room.portals = NULL;
        node.room.scultures = NULL;
        g_array_append_val(world->nodes, node);

        id++;
    }
    g_array_sort(world->nodes, _world_node_compare);

    g_hash_table_iter_init(&iter, world->groups->groups);
    while(g_hash_table_iter_next(&iter, (gpointer)&group_name, (gpointer)&group))
    {
        if(!g_str_has_prefix(group_name, "P"))
        {
            continue;
        }

        tokens = g_strsplit(group_name, "_", 0);
        id1 = g_ascii_strtoll(tokens[1], NULL, 10);
        id2 = g_ascii_strtoll(tokens[2], NULL, 10);
        g_strfreev(tokens);

        node.portal.id = id;
        node.portal.type = WORLD_PORTAL;
        node.portal.mesh = group;
        r_mesh_compute_bbox(node.portal.mesh, 0, node.portal.bbox);
        node.portal.front = &g_array_index(world->nodes, WorldNode, id1);
        node.portal.back = &g_array_index(world->nodes, WorldNode, id2);
        g_array_append_val(world->nodes, node);

        node.portal.front->room.portals = g_list_prepend(
            node.portal.front->room.portals,
            &g_array_index(world->nodes, WorldNode, id)
            );
        node.portal.back->room.portals = g_list_prepend(
            node.portal.back->room.portals,
            &g_array_index(world->nodes, WorldNode, id)
            );

        id++;
    }

    g_hash_table_iter_init(&iter, world->groups->groups);
    while (g_hash_table_iter_next(&iter, (gpointer)&group_name, (gpointer)&group))
    {
        if(!g_str_has_prefix(group_name, "S"))
        {
            continue;
        }

        tokens = g_strsplit(group_name, "_", 0);
        id1 = g_ascii_strtoll(tokens[1], NULL, 10);
        g_strfreev(tokens);

        node.sculture.id = id;
        node.sculture.type = WORLD_SCULTURE;
        node.sculture.mesh = group;
        r_mesh_compute_bbox(node.sculture.mesh, 0, node.sculture.bbox);
        node.sculture.owner = &g_array_index(world->nodes, WorldNode, id1);
        g_array_append_val(world->nodes, node);

        node.sculture.owner->room.scultures = g_list_prepend(
            node.sculture.owner->room.scultures,
            &g_array_index(world->nodes, WorldNode, id)
            );

        id++;
    }

    return world;
}
Exemplo n.º 18
0
void builddata(gchar *datafilename, glong &wordcount, glong &idxfilesize, glong &synwordcount, std::list<std::string> *TagList, std::list<std::string> *ElementList)
{
	struct stat stats;
	if (stat (datafilename, &stats) == -1) {
		printf("File %s not exist!\n", datafilename);
		return;
	}
	FILE *datafile;
	datafile = fopen(datafilename,"r");
	gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
	size_t fread_size;
	fread_size = fread (buffer, 1, stats.st_size, datafile);
	if (fread_size != (size_t)stats.st_size) {
		g_print("fread error!\n");
	}
	fclose (datafile);
	buffer[stats.st_size] = '\0';

	GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);
	GArray *array2 = g_array_sized_new(FALSE,FALSE, sizeof(struct _synworditem),20000);
	gchar *p, *p1, *p2, *p3, *p4, *p5;
	p = buffer;
	struct _worditem worditem;
	while (1) {
		//p1 = strstr(p, "<单词块>"); //Powerword 2007
		p1 = strstr(p, "<CK>"); //Powerword 2012
		if (!p1) {
			g_print("over\n");
			break;
		}
		//p1 += strlen("<单词块>");
		p1 += strlen("<CK>");
		//p2 = strstr(p1, "</单词块>");
		p2 = strstr(p1, "</CK>");
		if (!p2) {
			//g_print("Error, no </单词块>\n");
			g_print("Error, no </CK>\n");
			return;
		}
		*p2='\0';
		//p2 += strlen("</单词块>");
		p2 += strlen("</CK>");
		//p3 = strstr(p1, "<单词>");
		p3 = strstr(p1, "<DC>");
		p5 = p1;
		while (g_ascii_isspace(*p5))
			p5++;
		if (p5!=p3) {
			//g_print("Warning, not begin with <单词>.\n");
			g_print("Warning, not begin with <DC>.\n");
		}
		if (!p3) {
			//g_print("Error, no <单词>\n");
			g_print("Error, no <DC>\n");
			return;
		}
		//p3 += strlen("<单词>");
		p3 += strlen("<DC>");
		//p4 = strstr(p3, "</单词>");
		p4 = strstr(p3, "</DC>");
		if (!p4) {
			//g_print("Error, no </单词>\n");
			g_print("Error, no </DC>\n");
			return;
		}
		*p4='\0';
		//p4 += strlen("</单词>");
		p4 += strlen("</DC>");
		worditem.word = get_cdata(p3);
		if (!worditem.word) {
			return;
		}
		if (!worditem.word[0]) {
			g_print("Bad word!\n");
			p = p2;
			continue;
		}
		while (g_ascii_isspace(*p4)) {
			p4++;
		}
		worditem.definition = p4;
		g_strstrip(worditem.definition);
		if (!worditem.definition[0]) {
			g_print("Bad definition!\n");
			return;
		}
		ParseUserData Data;
		Data.word = worditem.word;
		Data.definition = worditem.definition;
		std::list<std::string> WordList;
		Data.WordList = &WordList;
		Data.array = array2;
		Data.TagList = TagList;
		Data.ElementList = ElementList;
		parse_definition(worditem.definition, &Data);
		g_array_append_val(array, worditem);
		p = p2;
	}
	g_array_sort(array,comparefunc);
	g_array_sort(array2,comparefunc2);

	gchar *basefilename = g_strdup(datafilename);
	p = strchr(basefilename, '.');
	if (p)
		*p='\0';
	gchar idxfilename[256];
	gchar dicfilename[256];
	sprintf(idxfilename, "powerword2012_%s.idx", basefilename);
	sprintf(dicfilename, "powerword2012_%s.dict", basefilename);
	FILE *idxfile = fopen(idxfilename,"w");
	FILE *dicfile = fopen(dicfilename,"w");

	guint32 offset_old;
        guint32 tmpglong;
        struct _worditem *pworditem;         gint definition_len;
        gulong i;
        for (i=0; i< array->len; i++) {
                offset_old = ftell(dicfile);
                pworditem = &g_array_index(array, struct _worditem, i);
                definition_len = strlen(pworditem->definition);
                fwrite(pworditem->definition, 1 ,definition_len,dicfile);
                fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
                tmpglong = g_htonl(offset_old);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
                tmpglong = g_htonl(definition_len);
                fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
        }
	idxfilesize = ftell(idxfile);
        fclose(idxfile);
	fclose(dicfile);
	g_print("%s wordcount: %d\n", datafilename, array->len);
	wordcount = array->len;

	synwordcount = array2->len;
	if (array2->len) {
                gchar synfilename[256];
                sprintf(synfilename, "powerword2012_%s.syn", basefilename);
                FILE *synfile = fopen(synfilename,"w");
                struct _synworditem *psynworditem;
                gint iFrom, iTo, iThisIndex, cmpint;
                bool bFound;
                for (i=0; i< array2->len; i++) {
                        psynworditem = &g_array_index(array2, struct _synworditem, i);
                        fwrite(psynworditem->synword, 1, strlen(psynworditem->synword)+1, synfile);
			g_free(psynworditem->synword);
                        bFound=false;
                        iFrom=0;
                        iTo=array->len-1;
                        while (iFrom<=iTo) {
                                iThisIndex=(iFrom+iTo)/2;
                                pworditem = &g_array_index(array, struct _worditem, iThisIndex);
                                cmpint = stardict_strcmp(psynworditem->origword, pworditem->word);
                                if (cmpint>0)
                                        iFrom=iThisIndex+1;
                                else if (cmpint<0)
                                        iTo=iThisIndex-1;
                                else {
                                        bFound=true;
                                        break;
                                }

                        }
                        if (!bFound) {
                                g_print("Error, %s not find.\n", psynworditem->origword);
                                return;
                        }
                        do {
                                if (iThisIndex==0)
                                        break;
                                pworditem = &g_array_index(array, struct _worditem, iThisIndex-1);
				if (strcmp(psynworditem->origword, pworditem->word)==0)
                                        iThisIndex--;
                                else
                                        break;
                        } while (true);
                        bFound=false;
                        do {
                                pworditem = &g_array_index(array, struct _worditem, iThisIndex);
                                if (strcmp(psynworditem->origword, pworditem->word)==0) {
                                        if (psynworditem->definition == pworditem->definition) {
                                                bFound=true;
                                                break;
                                        } else
                                                iThisIndex++;
                                } else
                                        break;
                        } while (true);
                        if (!bFound) {
                                g_print("Error, %s definition not find.\n", psynworditem->origword);
                                return;
                        }
                        tmpglong = g_htonl(iThisIndex);
                        fwrite(&(tmpglong),sizeof(guint32),1, synfile);
                }
                fclose(synfile);
                g_print("synwordcount: %d\n", array2->len);
        }
Exemplo n.º 19
0
int
test_buffer_2(void * data)
{
    mfp_procinfo * line_t = g_hash_table_lookup(mfp_proc_registry, "line~");
    mfp_procinfo * buf_t = g_hash_table_lookup(mfp_proc_registry, "buffer~");
    mfp_processor * line = mfp_proc_create(line_t, 0, 1, (mfp_context *)data);
    mfp_processor * b = mfp_proc_create(buf_t, 2, 1, (mfp_context *)data);
    GArray * lparm = g_array_sized_new(TRUE, TRUE, sizeof(float), 3);
    builtin_buffer_data * info = (builtin_buffer_data *)b->data;
    int blocksize = ((mfp_context *)data)->blocksize;
    int i;
    int fail=0;
    float ft;

    ft = (float)(1000.0*(((mfp_context *)data)->blocksize/2)/((mfp_context *)data)->samplerate);
    g_array_append_val(lparm, ft); 
    ft = 5.0;
    g_array_append_val(lparm, ft);
    ft = 0.0;
    g_array_append_val(lparm, ft);


    setparam_float(b, "buf_mode", 3.0);
    setparam_float(b, "rec_channels", 1.0);
    setparam_float(b, "rec_enabled", 1.0);
    setparam_float(b, "trig_channel", 0.0);
    setparam_float(b, "trig_thresh", 2.0);
    setparam_float(b, "channels", 1.0);
    setparam_float(b, "size", ((mfp_context *)data)->blocksize);

    mfp_proc_connect(line, 0, b, 0);

    mfp_dsp_schedule((mfp_context *)data);
    mfp_dsp_run((mfp_context *)data);

    /* give alloc thread time to work */
    usleep(100000);

    /* bang the line~ */ 
    setparam_gpointer(line, "segments", lparm);
    line->needs_config = 1;
    mfp_dsp_run((mfp_context *)data);

    if((info->buf_active.shm_fd == -1) 
        || (info->buf_active.buf_size != blocksize*sizeof(float))
        || (info->chan_count != 1) 
        || (info->chan_size != blocksize)) {
        printf("config fail %d %d %d %d\n", info->buf_active.shm_fd, 
                info->buf_active.buf_size, 
                info->chan_count, info->chan_size);
        return 0;
    }

    for(i=0; i < blocksize; i++) {
        if (i < blocksize/2.0) {
            if (info->buf_base == NULL || ((float *)(info->buf_base))[i] != 5.0) {
                printf("Fail at %d (%f should be 5.0)\n", i, ((float *)(info->buf_base))[i]);
                fail = 1;
            }
        }
        else {
            if (info->buf_base == NULL || ((float *)(info->buf_base))[i] != 0.0) {
                printf("Fail at %d (%f should be 0.0)\n", i, ((float *)(info->buf_base))[i]);
                fail = 1;
            }
        }
    }
    if (fail)
        return 0;
    return 1;
}
Exemplo n.º 20
0
Arquivo: quick.c Projeto: idispatch/mc
int
quick_dialog_skip (quick_dialog_t * quick_dlg, int nskip)
{
    int len;
    int blen = 0;
    int x, y;                   /* current positions */
    int y1 = 0;                 /* bottom of 1st column in case of two columns */
    int y2 = -1;                /* start of two columns */
    int width1 = 0;             /* width of single column */
    int width2 = 0;             /* width of each of two columns */
    gboolean have_groupbox = FALSE;
    gboolean two_columns = FALSE;
    gboolean put_buttons = FALSE;

    /* x position of 1st column is 3 */
    const int x1 = 3;
    /* x position of 2nd column is 4 and it will be fixed later, after creation of all widgets */
    int x2 = 4;

    GArray *widgets;
    size_t i;
    quick_widget_t *quick_widget;
    WGroupbox *g = NULL;
    WDialog *dd;
    GList *input_labels = NULL; /* Widgets not directly requested by the user. */
    int return_val;

    len = str_term_width1 (I18N (quick_dlg->title)) + 6;
    quick_dlg->cols = MAX (quick_dlg->cols, len);

    y = 1;
    x = x1;

    /* create widgets */
    widgets = g_array_sized_new (FALSE, FALSE, sizeof (quick_widget_item_t), 8);

    for (quick_widget = quick_dlg->widgets; quick_widget->widget_type != quick_end; quick_widget++)
    {
        quick_widget_item_t item = { NULL, quick_widget };
        int width = 0;

        switch (quick_widget->widget_type)
        {
        case quick_checkbox:
            item.widget =
                WIDGET (check_new
                        (++y, x, *quick_widget->u.checkbox.state,
                         I18N (quick_widget->u.checkbox.text)));
            g_array_append_val (widgets, item);
            width = item.widget->cols;
            if (g != NULL)
                width += 2;
            if (two_columns)
                width2 = MAX (width2, width);
            else
                width1 = MAX (width1, width);
            break;

        case quick_button:
            /* single button */
            item.widget = WIDGET (button_new (++y, x, quick_widget->u.button.action,
                                              quick_widget->u.button.action == B_ENTER ?
                                              DEFPUSH_BUTTON : NORMAL_BUTTON,
                                              I18N (quick_widget->u.button.text),
                                              quick_widget->u.button.callback));
            g_array_append_val (widgets, item);
            width = item.widget->cols;
            if (g != NULL)
                width += 2;
            if (two_columns)
                width2 = MAX (width2, width);
            else
                width1 = MAX (width1, width);
            break;

        case quick_input:
            *quick_widget->u.input.result = NULL;
            y++;
            if (quick_widget->u.input.label_location != input_label_none)
            {
                quick_create_labeled_input (widgets, &y, x, quick_widget, &width);
                input_labels = g_list_prepend (input_labels, quick_widget->u.input.label);
            }
            else
            {
                item.widget = WIDGET (quick_create_input (y, x, quick_widget));
                g_array_append_val (widgets, item);
                width = item.widget->cols;
            }
            if (g != NULL)
                width += 2;
            if (two_columns)
                width2 = MAX (width2, width);
            else
                width1 = MAX (width1, width);
            break;

        case quick_label:
            item.widget = WIDGET (label_new (++y, x, I18N (quick_widget->u.label.text)));
            g_array_append_val (widgets, item);
            y += item.widget->lines - 1;
            width = item.widget->cols;
            if (g != NULL)
                width += 2;
            if (two_columns)
                width2 = MAX (width2, width);
            else
                width1 = MAX (width1, width);
            break;

        case quick_radio:
            {
                WRadio *r;
                char **items = NULL;

                /* create the copy of radio_items to avoid mwmory leak */
                items = g_new (char *, quick_widget->u.radio.count + 1);
                for (i = 0; i < (size_t) quick_widget->u.radio.count; i++)
                    items[i] = g_strdup (_(quick_widget->u.radio.items[i]));
                items[i] = NULL;

                r = radio_new (++y, x, quick_widget->u.radio.count, (const char **) items);
                r->pos = r->sel = *quick_widget->u.radio.value;
                g_strfreev (items);
                item.widget = WIDGET (r);
                g_array_append_val (widgets, item);
                y += item.widget->lines - 1;
                width = item.widget->cols;
                if (g != NULL)
                    width += 2;
                if (two_columns)
                    width2 = MAX (width2, width);
                else
                    width1 = MAX (width1, width);
            }
            break;

        case quick_start_groupbox:
            I18N (quick_widget->u.groupbox.title);
            len = str_term_width1 (quick_widget->u.groupbox.title);
            g = groupbox_new (++y, x, 1, len + 4, quick_widget->u.groupbox.title);
            item.widget = WIDGET (g);
            g_array_append_val (widgets, item);
            have_groupbox = TRUE;
            break;

        case quick_stop_groupbox:
            if (g != NULL)
            {
                Widget *w = WIDGET (g);

                y++;
                w->lines = y + 1 - w->y;
                g = NULL;

                g_array_append_val (widgets, item);
            }
            break;

        case quick_separator:
            y++;
            if (quick_widget->u.separator.line)
            {
                item.widget = WIDGET (hline_new (y, x, 1));
                g_array_append_val (widgets, item);
            }
            break;

        case quick_start_columns:
            y2 = y;
            g_array_append_val (widgets, item);
            two_columns = TRUE;
            break;

        case quick_next_column:
            x = x2;
            y1 = y;
            y = y2;
            break;

        case quick_stop_columns:
            x = x1;
            y = MAX (y1, y);
            g_array_append_val (widgets, item);
            two_columns = FALSE;
            break;

        case quick_buttons:
            /* start put several buttons in bottom line */
            if (quick_widget->u.separator.space)
            {
                y++;

                if (quick_widget->u.separator.line)
                    item.widget = WIDGET (hline_new (y, 1, -1));
            }

            g_array_append_val (widgets, item);

            /* several buttons in bottom line */
            y++;
            quick_widget++;
            for (; quick_widget->widget_type == quick_button; quick_widget++)
            {
                item.widget = WIDGET (button_new (y, x++, quick_widget->u.button.action,
                                                  quick_widget->u.button.action == B_ENTER ?
                                                  DEFPUSH_BUTTON : NORMAL_BUTTON,
                                                  I18N (quick_widget->u.button.text),
                                                  quick_widget->u.button.callback));
                item.quick_widget = quick_widget;
                g_array_append_val (widgets, item);
                blen += item.widget->cols + 1;
            }

            /* stop dialog build here */
            blen--;
            quick_widget->widget_type = quick_end;
            quick_widget--;
            break;

        default:
            break;
        }
    }

    /* adjust dialog width */
    quick_dlg->cols = MAX (quick_dlg->cols, blen + 6);
    if (have_groupbox)
    {
        if (width1 != 0)
            width1 += 2;
        if (width2 != 0)
            width2 += 2;
    }
    if (width2 == 0)
        len = width1 + 6;
    else
    {
        len = width2 * 2 + 7;
        if (width1 != 0)
            len = MAX (len, width1 + 6);
    }

    quick_dlg->cols = MAX (quick_dlg->cols, len);
    width1 = quick_dlg->cols - 6;
    width2 = (quick_dlg->cols - 7) / 2;

    if (quick_dlg->x == -1 || quick_dlg->y == -1)
        dd = dlg_create (TRUE, 0, 0, y + 3, quick_dlg->cols, WPOS_CENTER | WPOS_TRYUP, FALSE,
                         dialog_colors, quick_dlg->callback, quick_dlg->mouse_callback,
                         quick_dlg->help, quick_dlg->title);
    else
        dd = dlg_create (TRUE, quick_dlg->y, quick_dlg->x, y + 3, quick_dlg->cols,
                         WPOS_KEEP_DEFAULT, FALSE, dialog_colors, quick_dlg->callback,
                         quick_dlg->mouse_callback, quick_dlg->help, quick_dlg->title);

    /* add widgets into the dialog */
    x2 = x1 + width2 + 1;
    g = NULL;
    two_columns = FALSE;
    x = (WIDGET (dd)->cols - blen) / 2;

    for (i = 0; i < widgets->len; i++)
    {
        quick_widget_item_t *item;
        int column_width;

        item = &g_array_index (widgets, quick_widget_item_t, i);
        column_width = two_columns ? width2 : width1;

        /* adjust widget width and x position */
        switch (item->quick_widget->widget_type)
        {
        case quick_label:
            {
                quick_widget_t *input = item->quick_widget->u.label.input;

                if (input != NULL && input->u.input.label_location == input_label_right)
                {
                    /* location of this label will be adjusted later */
                    break;
                }
            }
            /* fall through */
        case quick_checkbox:
        case quick_radio:
            if (item->widget->x != x1)
                item->widget->x = x2;
            if (g != NULL)
                item->widget->x += 2;
            break;

        case quick_button:
            if (!put_buttons)
            {
                if (item->widget->x != x1)
                    item->widget->x = x2;
                if (g != NULL)
                    item->widget->x += 2;
            }
            else
            {
                item->widget->x = x;
                x += item->widget->cols + 1;
            }
            break;

        case quick_input:
            {
                Widget *label = WIDGET (INPUT (item->widget)->label);
                int width = column_width;

                if (g != NULL)
                    width -= 4;

                switch (item->quick_widget->u.input.label_location)
                {
                case input_label_left:
                    /* label was adjusted before; adjust input line */
                    item->widget->x = label->x + label->cols + 1 - WIDGET (label->owner)->x;
                    item->widget->cols = width - label->cols - 1;
                    break;

                case input_label_right:
                    if (item->widget->x != x1)
                        item->widget->x = x2;
                    if (g != NULL)
                        item->widget->x += 2;
                    item->widget->cols = width - label->cols - 1;
                    label->x = item->widget->x + item->widget->cols + 1;
                    break;

                default:
                    if (item->widget->x != x1)
                        item->widget->x = x2;
                    if (g != NULL)
                        item->widget->x += 2;
                    item->widget->cols = width;
                    break;
                }

                /* forced update internal variables of inpuit line */
                widget_set_size (item->widget, item->widget->y, item->widget->x, 1,
                                 item->widget->cols);
            }
            break;

        case quick_start_groupbox:
            g = GROUPBOX (item->widget);
            if (item->widget->x != x1)
                item->widget->x = x2;
            item->widget->cols = column_width;
            break;

        case quick_stop_groupbox:
            g = NULL;
            break;

        case quick_separator:
            if (item->widget != NULL)
            {
                if (g != NULL)
                {
                    Widget *wg = WIDGET (g);

                    HLINE (item->widget)->auto_adjust_cols = FALSE;
                    item->widget->x = wg->x + 1 - WIDGET (wg->owner)->x;
                    item->widget->cols = wg->cols;
                }
                else if (two_columns)
                {
                    HLINE (item->widget)->auto_adjust_cols = FALSE;
                    if (item->widget->x != x1)
                        item->widget->x = x2;
                    item->widget->x--;
                    item->widget->cols = column_width + 2;
                }
                else
                    HLINE (item->widget)->auto_adjust_cols = TRUE;
            }
            break;

        case quick_start_columns:
            two_columns = TRUE;
            break;

        case quick_stop_columns:
            two_columns = FALSE;
            break;

        case quick_buttons:
            /* several buttons in bottom line */
            put_buttons = TRUE;
            break;

        default:
            break;
        }

        if (item->widget != NULL)
        {
            unsigned long id;

            /* add widget into dialog */
            item->widget->options |= item->quick_widget->options;       /* FIXME: cannot reset flags, setup only */
            item->widget->state |= item->quick_widget->state;   /* FIXME: cannot reset flags, setup only */
            id = add_widget_autopos (dd, item->widget, item->quick_widget->pos_flags, NULL);
            if (item->quick_widget->id != NULL)
                *item->quick_widget->id = id;
        }
    }

    while (nskip-- != 0)
        dlg_set_current_widget_next (dd);

    return_val = dlg_run (dd);

    /* Get the data if we found something interesting */
    if (return_val != B_CANCEL)
        for (i = 0; i < widgets->len; i++)
        {
            quick_widget_item_t *item;

            item = &g_array_index (widgets, quick_widget_item_t, i);

            switch (item->quick_widget->widget_type)
            {
            case quick_checkbox:
                *item->quick_widget->u.checkbox.state = CHECK (item->widget)->state;
                break;

            case quick_input:
                if ((quick_widget->u.input.completion_flags & INPUT_COMPLETE_CD) != 0)
                    *item->quick_widget->u.input.result =
                        tilde_expand (INPUT (item->widget)->buffer);
                else
                    *item->quick_widget->u.input.result = g_strdup (INPUT (item->widget)->buffer);
                break;

            case quick_radio:
                *item->quick_widget->u.radio.value = RADIO (item->widget)->sel;
                break;

            default:
                break;
            }
        }

    dlg_destroy (dd);

    g_list_free_full (input_labels, g_free);    /* destroy input labels created before */
    g_array_free (widgets, TRUE);

    return return_val;
}
Exemplo n.º 21
0
static GstFlowReturn
gst_objectsinteraction_chain(GstPad *pad, GstBuffer *buf)
{
    GstObjectsInteraction *filter;

    // sanity checks
    g_return_val_if_fail(pad != NULL, GST_FLOW_ERROR);
    g_return_val_if_fail(buf != NULL, GST_FLOW_ERROR);

    filter = GST_OBJECTSINTERACTION(GST_OBJECT_PARENT(pad));
    filter->image->imageData = (char*) GST_BUFFER_DATA(buf);

    // Process all objects
    if ((filter->object_in_array != NULL) && (filter->object_in_array->len > 0)) {
        // Find interceptions rects pairs
        guint i, j;

        for (i = 0; i < filter->object_in_array->len; ++i) {
            for (j = i + 1; j < filter->object_in_array->len; ++j) {
                InstanceObjectIn obj_a, obj_b;
                gint             interception;

                obj_a = g_array_index(filter->object_in_array, InstanceObjectIn, i);
                obj_b = g_array_index(filter->object_in_array, InstanceObjectIn, j);
                interception = 100 * MIN(rectIntercept(&obj_a.rect, &obj_b.rect), rectIntercept(&obj_b.rect, &obj_a.rect));

                if (interception) {
                    GstEvent     *event;
                    GstMessage   *message;
                    GstStructure *structure;
                    CvRect        rect;

                    // Interception percentage
                    rect = rectIntersection(&obj_a.rect, &obj_b.rect);

                    if (filter->verbose)
                        GST_INFO_OBJECT(filter, "INTERCEPTION %i%%: rect_a(%i, %i, %i, %i), rect_b(%i, %i, %i, %i), rect_intercept(%i, %i, %i, %i)\n",
                                        interception,
                                        obj_a.rect.x, obj_a.rect.y, obj_a.rect.width, obj_a.rect.height,
                                        obj_b.rect.x, obj_b.rect.y, obj_b.rect.width, obj_b.rect.height,
                                        rect.x, rect.y, rect.width, rect.height);

                    // Draw intercept rect and label
                    if (filter->display) {
                        char *label;
                        float font_scaling;

                        cvRectangle(filter->image,
                                    cvPoint(rect.x, rect.y),
                                    cvPoint(rect.x + rect.width, rect.y + rect.height),
                                    PRINT_COLOR, -1, 8, 0);
                        font_scaling = ((filter->image->width * filter->image->height) > (320 * 240)) ? 0.5f : 0.3f;
                        label = g_strdup_printf("%i+%i (%i%%)", obj_a.id, obj_b.id, interception);
                        printText(filter->image, cvPoint(rect.x + (rect.width / 2), rect.y + (rect.height / 2)), label, PRINT_COLOR, font_scaling, 1);
                        g_free(label);
                    }

                    // Send downstream event and bus message with the rect info
                    structure = gst_structure_new("object-interaction",
                                                  "id_a",       G_TYPE_UINT,   obj_a.id,
                                                  "id_b",       G_TYPE_UINT,   obj_b.id,
                                                  "percentage", G_TYPE_UINT,   interception,
                                                  "x",          G_TYPE_UINT,   rect.x,
                                                  "y",          G_TYPE_UINT,   rect.y,
                                                  "width",      G_TYPE_UINT,   rect.width,
                                                  "height",     G_TYPE_UINT,   rect.height,
                                                  "timestamp",  G_TYPE_UINT64, GST_BUFFER_TIMESTAMP(buf),
                                                  NULL);
                    message = gst_message_new_element(GST_OBJECT(filter), gst_structure_copy(structure));
                    gst_element_post_message(GST_ELEMENT(filter), message);
                    event = gst_event_new_custom(GST_EVENT_CUSTOM_DOWNSTREAM, structure);
                    gst_pad_push_event(filter->srcpad, event);

                }
            }
        }

    }

    // Clean objects
    g_array_free(filter->object_in_array, TRUE);
    filter->object_in_array = g_array_sized_new(FALSE, FALSE, sizeof(InstanceObjectIn), 1);

    gst_buffer_set_data(buf, (guint8*) filter->image->imageData, (guint) filter->image->imageSize);
    return gst_pad_push(filter->srcpad, buf);
}
Exemplo n.º 22
0
/**
 * g_byte_array_new:
 * @Returns: the new #GByteArray.
 *
 * Creates a new #GByteArray with a reference count of 1.
 **/
GByteArray* g_byte_array_new (void)
{
  return (GByteArray*) g_array_sized_new (FALSE, FALSE, 1, 0);
}
Exemplo n.º 23
0
static gboolean
ensure_allowed_raw_caps (GstVaapiPluginBase * plugin)
{
  GArray *formats, *out_formats;
  GstVaapiSurface *surface;
  GstVaapiDisplay *display;
  guint i;
  GstCaps *out_caps;
  gboolean ret = FALSE;

  if (plugin->allowed_raw_caps)
    return TRUE;

  out_formats = formats = NULL;
  surface = NULL;

  display = gst_vaapi_display_ref (plugin->display);
  formats = gst_vaapi_display_get_image_formats (display);
  if (!formats)
    goto bail;

  out_formats =
      g_array_sized_new (FALSE, FALSE, sizeof (GstVideoFormat), formats->len);
  if (!out_formats)
    goto bail;

  surface =
      gst_vaapi_surface_new (display, GST_VAAPI_CHROMA_TYPE_YUV420, 64, 64);
  if (!surface)
    goto bail;

  for (i = 0; i < formats->len; i++) {
    const GstVideoFormat format = g_array_index (formats, GstVideoFormat, i);
    GstVaapiImage *image;

    if (format == GST_VIDEO_FORMAT_UNKNOWN)
      continue;
    image = gst_vaapi_image_new (display, format, 64, 64);
    if (!image)
      continue;
    if (gst_vaapi_surface_put_image (surface, image))
      g_array_append_val (out_formats, format);
    gst_vaapi_object_unref (image);
  }

  out_caps = gst_vaapi_video_format_new_template_caps_from_list (out_formats);
  if (!out_caps)
    goto bail;

  gst_caps_replace (&plugin->allowed_raw_caps, out_caps);
  gst_caps_unref (out_caps);
  ret = TRUE;

bail:
  if (formats)
    g_array_unref (formats);
  if (out_formats)
    g_array_unref (out_formats);
  if (surface)
    gst_vaapi_object_unref (surface);
  gst_vaapi_display_unref (display);

  return ret;
}
Exemplo n.º 24
0
/**
 * g_byte_array_sized_new:
 * @reserved_size: number of bytes preallocated.
 * @Returns: the new #GByteArray.
 *
 * Creates a new #GByteArray with @reserved_size bytes preallocated.
 * This avoids frequent reallocation, if you are going to add many
 * bytes to the array. Note however that the size of the array is still
 * 0.
 **/
GByteArray* g_byte_array_sized_new (guint reserved_size)
{
  return (GByteArray*) g_array_sized_new (FALSE, FALSE, 1, reserved_size);
}
Exemplo n.º 25
0
static void restore_state(session_callback_type type, gpointer data, gpointer user_data) {
    JsonParser* jp = NULL;
    JsonReader* jr = NULL;

    const gchar* sqs;
    saved_state* s = NULL;

    GError* err = NULL;

    /* Is it the callback we're interested in? */
    if (type != SPOP_SESSION_LOGGED_IN)
        return;

    /* First disable the callback so it's not called again */
    session_remove_callback(restore_state, NULL);

    g_debug("savestate: reading saved state...");
    s = g_new0(saved_state, 1);

    /* Read and parse state file */
    jp = json_parser_new();
    if (!json_parser_load_from_file(jp, g_state_file_path, &err)) {
        g_warning("savestate: error while reading state file: %s", err->message);
        goto restorestate_error;
    }

    jr = json_reader_new(json_parser_get_root(jp));

    /* Read basic state */
    if (!json_reader_read_member(jr, "status")) goto restorestate_jr_error;
    sqs = json_reader_get_string_value(jr);
    json_reader_end_member(jr);
    if      (strcmp(sqs, "stopped")) s->qs = STOPPED;
    else if (strcmp(sqs, "playing")) s->qs = PLAYING;
    else if (strcmp(sqs, "paused"))  s->qs = PAUSED;
    else {
        g_warning("savestate: bad value for queue status: %s", sqs);
        goto restorestate_error;
    }

    if (!json_reader_read_member(jr, "repeat")) goto restorestate_jr_error;
    s->repeat = json_reader_get_boolean_value(jr);
    json_reader_end_member(jr);

    if (!json_reader_read_member(jr, "shuffle")) goto restorestate_jr_error;
    s->shuffle = json_reader_get_boolean_value(jr);
    json_reader_end_member(jr);

    if (!json_reader_read_member(jr, "current_track")) goto restorestate_jr_error;
    s->cur_track = json_reader_get_int_value(jr);
    json_reader_end_member(jr);

    /* Now read tracks URIs */
    if (!json_reader_read_member(jr, "tracks")) goto restorestate_jr_error;
    if (!json_reader_is_array(jr)) {
        g_warning("savestate: error while parsing JSON: tracks is not an array");
        goto restorestate_error;
    }
    gint tracks = json_reader_count_elements(jr);
    if (s->cur_track >= tracks) {
        g_warning("savestate: incoherent state file: cur_track >= tracks");
        goto restorestate_error;
    }

    s->tracks = g_array_sized_new(FALSE, FALSE, sizeof(sp_track*), tracks);
    if (!s->tracks)
        g_error("Can't allocate array of %d tracks.", tracks);

    size_t i;
    gboolean can_restore_now = TRUE;
    for (i=0; i < tracks; i++) {
        json_reader_read_element(jr, i);
        const gchar* uri = json_reader_get_string_value(jr);
        json_reader_end_element(jr);

        sp_link* lnk = sp_link_create_from_string(uri);
        sp_linktype lt = sp_link_type(lnk);
        if (lt != SP_LINKTYPE_TRACK) {
            g_warning("savestate: invalid link type for track %zu: %d", i, lt);
            sp_link_release(lnk);
            goto restorestate_error;
        }
        sp_track* tr = sp_link_as_track(lnk);
        sp_track_add_ref(tr);
        sp_link_release(lnk);
        g_array_append_val(s->tracks, tr);
        if (!sp_track_is_loaded(tr))
            can_restore_now = FALSE;
    }

    /* If possible, restore now, else wait for all tracks to be loaded */
    if (can_restore_now)
        really_restore_state(s);
    else {
        g_timeout_add(100, (GSourceFunc) really_restore_state, s);
        g_debug("savestate: waiting for all tracks to be loaded before restoring saved state...");
    }

    /* Add a notification callback */
    if (!interface_notify_add_callback(savestate_notification_callback, NULL))
        g_error("Could not add savestate callback.");

    goto restorestate_clean;

 restorestate_jr_error:
    err = (GError*) json_reader_get_error(jr);
    g_warning("savestate: error while parsing JSON: %s", err->message);

 restorestate_error:
    if (s) {
        if (s->tracks)
            g_array_free(s->tracks, TRUE);
        g_free(s);
    }

 restorestate_clean:
    if (jp)
        g_object_unref(jp);
    if (jr)
        g_object_unref(jr);
}
Exemplo n.º 26
0
void convert(const char *filename, print_info_t print_info)
{			
	struct stat stats;
	if (g_stat (filename, &stats) == -1)
	{
		print_info("File not exist!\n");
		return;
	}
	gchar *basefilename = g_path_get_basename(filename);
	gchar *ch = strrchr(basefilename, '.');
	if (ch)
		*ch = '\0';
	gchar *dirname = g_path_get_dirname(filename);
	FILE *tabfile;
	tabfile = g_fopen(filename,"r");

	gchar *buffer = (gchar *)g_malloc (stats.st_size + 1);
	size_t readsize = fread (buffer, 1, stats.st_size, tabfile);
	fclose (tabfile);
	buffer[readsize] = '\0';	
	
	GArray *array = g_array_sized_new(FALSE,FALSE, sizeof(struct _worditem),20000);
		
	gchar *p, *p1, *p2;
	p = buffer;
	if ((guchar)*p==0xEF && (guchar)*(p+1)==0xBB && (guchar)*(p+2)==0xBF) // UTF-8 order characters.
		p+=3;
	struct _worditem worditem;
	glong linenum=1;
	while (1) {
		if (*p == '\0') {
                        print_info("Convert over.\n");
                        break;
                }
		p1 = strchr(p,'\n');
		if (!p1) {
			print_info("Error, no new line at the end\n");
			return;
		}
		*p1 = '\0';
		p1++;
		p2 = strchr(p,'=');
		if (!p2) {
			gchar *str = g_strdup_printf("Warning, no separater, %ld\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
			linenum++;
			continue;
		}
		*p2 = '\0';
		p2++;
		worditem.word = p;
		worditem.definition = p2;
		my_strstrip(worditem.definition, linenum, print_info);
		g_strstrip(worditem.word);
		g_strstrip(worditem.definition);
		if (!worditem.word[0]) {
			gchar *str = g_strdup_printf("Warning: line %ld, bad word!\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
                	linenum++;
			continue;
		}
		if (!worditem.definition[0]) {
			gchar *str = g_strdup_printf("Warning: line %ld, bad definition!\n", linenum);
			print_info(str);
			g_free(str);
			p= p1;
                        linenum++;
                        continue;
		}
		g_array_append_val(array, worditem);			
		p= p1;				
		linenum++;
	}		
	g_array_sort(array,comparefunc);
		
	gchar ifofilename[256];
	gchar idxfilename[256];
	gchar dicfilename[256];
	sprintf(ifofilename, "%s" G_DIR_SEPARATOR_S "%s.ifo", dirname, basefilename);
	sprintf(idxfilename, "%s" G_DIR_SEPARATOR_S "%s.idx", dirname, basefilename);
	sprintf(dicfilename, "%s" G_DIR_SEPARATOR_S "%s.dict", dirname, basefilename);
	FILE *ifofile = g_fopen(ifofilename,"wb");
	if (!ifofile) {
		print_info("Write to ifo file failed!\n");
		return;
	}
	FILE *idxfile = g_fopen(idxfilename,"wb");
	if (!idxfile) {
		print_info("Write to idx file failed!\n");
		return;
	}
	FILE *dicfile = g_fopen(dicfilename,"wb");
	if (!dicfile) {
		print_info("Write to dict file failed!\n");
		return;
	}

	guint32 offset_old;
	guint32 tmpglong;
	struct _worditem *pworditem;
	gint definition_len;
	gulong i;
	for (i=0; i< array->len; i++) {
		offset_old = ftell(dicfile);
		pworditem = &g_array_index(array, struct _worditem, i);
		definition_len = strlen(pworditem->definition);
		fwrite(pworditem->definition, 1 ,definition_len,dicfile);
		fwrite(pworditem->word,sizeof(gchar),strlen(pworditem->word)+1,idxfile);
		tmpglong = g_htonl(offset_old);
		fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
		tmpglong = g_htonl(definition_len);
		fwrite(&(tmpglong),sizeof(guint32),1,idxfile);
	}
	fclose(idxfile);
	fclose(dicfile);

	gchar *str = g_strdup_printf("%s wordcount: %d\n", basefilename, array->len);
	print_info(str);
	g_free(str);

#ifndef _WIN32
	gchar command[256];
        sprintf(command, "dictzip %s", dicfilename);
        system(command);
#endif

	g_stat(idxfilename, &stats);
	fprintf(ifofile, "StarDict's dict ifo file\nversion=2.4.2\nwordcount=%d\nidxfilesize=%ld\nbookname=%s\nsametypesequence=m\n", array->len, stats.st_size, basefilename);
	fclose(ifofile);

	g_free(buffer);
	g_array_free(array,TRUE);

	g_free(basefilename);
	g_free(dirname);
}
Exemplo n.º 27
0
static GArray *
parse_mode_combination_string_list (const gchar *modes_str,
                                    GError **error)
{
    GArray *supported_mode_combinations;
    gchar **mode_combinations;
    MMModemMode all = MM_MODEM_MODE_NONE;
    gboolean has_all = FALSE;
    guint i;

    mode_combinations = g_strsplit (modes_str, ",", -1);
    supported_mode_combinations = g_array_sized_new (FALSE,
                                                     FALSE,
                                                     sizeof (MMHuaweiSyscfgexCombination),
                                                     g_strv_length (mode_combinations));
    g_array_set_clear_func (supported_mode_combinations,
                            (GDestroyNotify)huawei_syscfgex_combination_free);

    for (i = 0; mode_combinations[i]; i++) {
        MMHuaweiSyscfgexCombination combination;

        mode_combinations[i] = mm_strip_quotes (mode_combinations[i]);
        if (!parse_mode_combination_string (mode_combinations[i],
                                            &combination.allowed,
                                            &combination.preferred))
            continue;

        if (combination.allowed != MM_MODEM_MODE_ANY) {
            combination.mode_str = g_strdup (mode_combinations[i]);
            g_array_append_val (supported_mode_combinations, combination);

            all |= combination.allowed;
        } else {
            /* don't add the all_combination here, we may have more
             * combinations in the loop afterwards */
            has_all = TRUE;
        }
    }

    g_strfreev (mode_combinations);

    /* Add here the all_combination */
    if (has_all) {
        MMHuaweiSyscfgexCombination combination;

        combination.allowed = all;
        combination.preferred = MM_MODEM_MODE_NONE;
        combination.mode_str = g_strdup ("00");
        g_array_append_val (supported_mode_combinations, combination);
    }

    /* If we didn't build a valid array of combinations, return an error */
    if (supported_mode_combinations->len == 0) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "Cannot parse list of allowed mode combinations: '%s'",
                     modes_str);
        g_array_unref (supported_mode_combinations);
        return NULL;
    }

    return supported_mode_combinations;
}
Exemplo n.º 28
0
Arquivo: util.c Projeto: Chainie/mc
void
load_file_position (const vfs_path_t * filename_vpath, long *line, long *column, off_t * offset,
                    GArray ** bookmarks)
{
    char *fn;
    FILE *f;
    char buf[MC_MAXPATHLEN + 100];
    const size_t len = vfs_path_len (filename_vpath);
    char *filename;

    /* defaults */
    *line = 1;
    *column = 0;
    *offset = 0;

    /* open file with positions */
    fn = mc_config_get_full_path (MC_FILEPOS_FILE);
    f = fopen (fn, "r");
    g_free (fn);
    if (f == NULL)
        return;

    /* prepare array for serialized bookmarks */
    if (bookmarks != NULL)
        *bookmarks = g_array_sized_new (FALSE, FALSE, sizeof (size_t), MAX_SAVED_BOOKMARKS);
    filename = vfs_path_to_str (filename_vpath);

    while (fgets (buf, sizeof (buf), f) != NULL)
    {
        const char *p;
        gchar **pos_tokens;

        /* check if the filename matches the beginning of string */
        if (strncmp (buf, filename, len) != 0)
            continue;

        /* followed by single space */
        if (buf[len] != ' ')
            continue;

        /* and string without spaces */
        p = &buf[len + 1];
        if (strchr (p, ' ') != NULL)
            continue;

        pos_tokens = g_strsplit (p, ";", 3 + MAX_SAVED_BOOKMARKS);
        if (pos_tokens[0] == NULL)
        {
            *line = 1;
            *column = 0;
            *offset = 0;
        }
        else
        {
            *line = strtol (pos_tokens[0], NULL, 10);
            if (pos_tokens[1] == NULL)
            {
                *column = 0;
                *offset = 0;
            }
            else
            {
                *column = strtol (pos_tokens[1], NULL, 10);
                if (pos_tokens[2] == NULL)
                    *offset = 0;
                else if (bookmarks != NULL)
                {
                    size_t i;

                    *offset = (off_t) g_ascii_strtoll (pos_tokens[2], NULL, 10);

                    for (i = 0; i < MAX_SAVED_BOOKMARKS && pos_tokens[3 + i] != NULL; i++)
                    {
                        size_t val;

                        val = strtoul (pos_tokens[3 + i], NULL, 10);
                        g_array_append_val (*bookmarks, val);
                    }
                }
            }
        }

        g_strfreev (pos_tokens);
    }

    g_free (filename);
    fclose (f);
}
Exemplo n.º 29
0
static GArray *
parse_syscfg_modes (const gchar *modes_str,
                    const gchar *acqorder_str,
                    GError **error)
{
    GArray *out;
    gchar **split;
    guint i;
    gint min_acqorder = 0;
    gint max_acqorder = 0;

    /* Start parsing acquisition order */
    if (!sscanf (acqorder_str, "%d-%d", &min_acqorder, &max_acqorder))
        mm_dbg ("Error parsing ^SYSCFG acquisition order range (%s)", acqorder_str);

    /* Just in case, we default to supporting only auto */
    if (max_acqorder < min_acqorder) {
        min_acqorder = 0;
        max_acqorder = 0;
    }

    /* Now parse modes */
    split = g_strsplit (modes_str, ",", -1);
    out = g_array_sized_new (FALSE,
                             FALSE,
                             sizeof (MMHuaweiSyscfgCombination),
                             g_strv_length (split));
    for (i = 0; split[i]; i++) {
        guint val;
        guint allowed = MM_MODEM_MODE_NONE;
        GError *inner_error = NULL;
        MMHuaweiSyscfgCombination combination;

        if (!mm_get_uint_from_str (mm_strip_quotes (split[i]), &val)) {
            mm_dbg ("Error parsing ^SYSCFG mode value: %s", split[i]);
            continue;
        }

        if (!mode_from_syscfg (val, &allowed, &inner_error)) {
            if (inner_error) {
                mm_dbg ("Unhandled ^SYSCFG: %s", inner_error->message);
                g_error_free (inner_error);
            }
            continue;
        }

        switch (allowed) {
        case MM_MODEM_MODE_2G:
        case MM_MODEM_MODE_3G:
            /* single mode */
            combination.allowed = allowed;
            combination.preferred = MM_MODEM_MODE_NONE;
            combination.mode = val;
            combination.acqorder = 0;
            g_array_append_val (out, combination);
            break;
        case (MM_MODEM_MODE_2G | MM_MODEM_MODE_3G):
            /* 2G and 3G; auto */
            combination.allowed = allowed;
            combination.mode = val;
            if (min_acqorder == 0) {
                combination.preferred = MM_MODEM_MODE_NONE;
                combination.acqorder = 0;
                g_array_append_val (out, combination);
            }
            /* 2G and 3G; 2G preferred */
            if (min_acqorder <= 1 && max_acqorder >= 1) {
                combination.preferred = MM_MODEM_MODE_2G;
                combination.acqorder = 1;
                g_array_append_val (out, combination);
            }
            /* 2G and 3G; 3G preferred */
            if (min_acqorder <= 2 && max_acqorder >= 2) {
                combination.preferred = MM_MODEM_MODE_3G;
                combination.acqorder = 2;
                g_array_append_val (out, combination);
            }
            break;
        default:
            g_assert_not_reached ();
        }
    }

    g_strfreev (split);

    /* If we didn't build a valid array of combinations, return an error */
    if (out->len == 0) {
        g_set_error (error,
                     MM_CORE_ERROR,
                     MM_CORE_ERROR_FAILED,
                     "Cannot parse list of allowed mode combinations: '%s,%s'",
                     modes_str,
                     acqorder_str);
        g_array_unref (out);
        return NULL;
    }

    return out;
}
FullTree* qsearch_make_fulltree(QSearchTree *clt, const gsl_matrix *dm) {
    
    int i,j; 
    int node_count = clt->total_node_count;
    int leaf_count = (node_count + 2)/2;
    
    FullTree *tree = malloc(sizeof(FullTree));
    tree->node_count = node_count;
    
    tree->data = malloc(sizeof(Misc));
    
    ((Misc *)tree->data)->nodes = malloc(sizeof(FullNode) * node_count);
    ((Misc *)tree->data)->tmpA  = g_array_sized_new(FALSE, FALSE, sizeof(guint32), node_count);
    ((Misc *)tree->data)->tmpB  = g_array_sized_new(FALSE, FALSE, sizeof(guint32), node_count);

    FullNode *map = get_nodes(tree);
    
    GArray *todo = g_array_sized_new(FALSE, FALSE, sizeof(guint32), node_count - leaf_count);
    g_array_set_size(todo, node_count-leaf_count);

    for (i = 0; i < node_count; ++i) {
        FullNode *node = (map + i);
        
        for (j = 0; j < 3; ++j) {
            map[i].connections[j] = -1;
            map[i].leaf_count[j] = 0;
            map[i].dist[j] = 0;
        }
        
        guint8 *node_branch = malloc(sizeof(guint8) * node_count);
        node->node_branch = node_branch;

        if (i < leaf_count) {
            for (j=0; j < node_count; ++j) node_branch[j] = 0;
            node->leaf_count[0] = leaf_count - 1;
        } else {
            for (j = 0; j < node_count; ++j) node_branch[j] = -1;
            g_array_index(todo, guint32, i - leaf_count) = i;
        } 
    }
     
    // set connections (construct tree)
    for (i = 0; i < node_count; ++i) {

        QSearchNeighborList *cln = g_ptr_array_index(clt->n, i);
        // add to connected nodes
        for (j = 0; j < cln->n->len; ++j) {
            int node = g_array_index(cln->n, guint32, j);
        
            // find unfilled branch
            int branch = find_branch(map[node].connections, -1);
            map[node].connections[branch] = i; // set connection
            
            if (i < leaf_count) {
                map[node].leaf_count[branch] = 1; // set leaf
            }
            map[node].node_branch[i] = branch; // leaf can be found in branch

            // set connection back to this node
            branch = find_branch(map[i].connections, -1);
            map[i].connections[branch] = node;
            map[i].node_branch[node] = branch;
        }
    }
    
    // every iteration, this loop progresses by at least finishing one node. Worst case is n^3 (for 'linear' trees)
    while (todo->len > 0) {
        for (i = 0; i < todo->len; ++i) {
            
            int this_node = g_array_index(todo, guint32, i); 
                        
            for (j = 0; j < 3; ++j) {
                int connected_node = map[this_node].connections[j];
                int branch = find_branch(map[connected_node].connections, this_node);

                if (map[connected_node].leaf_count[branch] == 0) {
                    int first = (3 + j-1) % 3;
                    int second = (j + 1)  % 3;
                    if (map[this_node].leaf_count[first] != 0 && map[this_node].leaf_count[second] != 0) {
                        map[connected_node].leaf_count[branch] = map[this_node].leaf_count[first] + map[this_node].leaf_count[second];
                        
                        // set the node_branch information
                        int k;
                        for (k = 0; k < node_count; ++k) {
                            // node present in one of the two branches pointing away from this
                            int node_present = k==this_node || map[this_node].node_branch[k] == first || map[this_node].node_branch[k] == second;
                            
                            if (node_present) map[connected_node].node_branch[k] = branch;
                        }
                    }
                }
            }
        }
        
        for (i = 0; i < todo->len; ++i) {
            
            int this_node = g_array_index(todo, guint32, i);
             
            // we are done when all entries are set for this node, AND there are no pending assignments to neighbours

            // are all entries set for this node?
            for (j = 0; j < 3; ++j) {
                if (map[this_node].leaf_count[j] == 0) { 
                    break;
                }
            }

            // are there pending assignments? (we could do the assignments here, but that would duplicate code)
            int done = 1;
            for (j = 0; j < 3; ++j) {
                if (this_node < leaf_count) continue;
                int connected_node = map[this_node].connections[j];
                // find connection
                int branch = find_branch(map[connected_node].connections, this_node);
                if (map[connected_node].leaf_count[branch] == 0) {
                    done = 0;
                    break;
                }
            }
            
            if (done) {
                //printf("Removing node %d, counts %d %d %d\n", i, map[this_node].leaf_count[0], map[this_node].leaf_count[1], map[this_node].leaf_count[2]);
                g_array_remove_index_fast(todo, i);
                --i;
            }
        }
    }
    
    g_array_free(todo, TRUE); 
    
    int k; 
    // now fill in the distances
    for (i=leaf_count; i < node_count; ++i) {
        for (j = 0; j < leaf_count; ++j) {
            for (k = j+1; k < leaf_count; ++k) {

                int b1 = map[i].node_branch[j];
                int b2 = map[i].node_branch[k];
                
                if (b1 == b2) continue;

                int b3 = 3 - b1 - b2;

                map[i].dist[b3] += gsl_matrix_get(dm, j, k);
            }
        }
    }
    
    set_score(tree);
    
    return tree;
}