Exemplo n.º 1
0
sc_bool sc_fs_storage_initialize(const gchar *path, sc_bool clear)
{
    g_message("Initialize sc-storage from path: %s", path);
    g_snprintf(segments_path, MAX_PATH_LENGTH, "%s/segments.scdb", path);
    repo_path = g_strdup(path);

    g_message("\tFile memory engine: %s", sc_config_fm_engine());
    // load engine extension

#ifdef __MINGW32__
    g_snprintf(fm_engine_module_path, MAX_PATH_LENGTH, "libsc-fm-%s.dll", sc_config_fm_engine());
#elif WIN32
    g_snprintf(fm_engine_module_path, MAX_PATH_LENGTH, "sc-fm-%s.dll", sc_config_fm_engine());
#else
    g_snprintf(fm_engine_module_path, MAX_PATH_LENGTH, "libsc-fm-%s.so", sc_config_fm_engine());
#endif

    // try to load engine extension
    fFmEngineInitFunc func;
    fm_engine_module = g_module_open(fm_engine_module_path, G_MODULE_BIND_LOCAL);

    // skip non module files
    if (g_str_has_suffix(fm_engine_module_path, G_MODULE_SUFFIX) == TRUE)
    {
        if (fm_engine_module == null_ptr)
        {
            g_critical("Can't load module: %s. Error: %s", fm_engine_module_path, g_module_error());
        }
        else
        {
            g_message("Initialize file memory engine from: %s", fm_engine_module_path);
            if (g_module_symbol(fm_engine_module, "initialize", (gpointer*) &func) == FALSE)
            {
                g_critical("Can't find 'initialize' symbol in module: %s", fm_engine_module_path);
            }
            else
            {
                fm_engine = func(repo_path);
                if (fm_engine == 0)
                {
                    g_critical("Can't create file memory engine from: %s", fm_engine_module_path);
                    return SC_FALSE;
                }
            }
        }
    }

    // clear repository if needs
    if (clear == SC_TRUE)
    {
        g_message("Clear memory");
        if (g_file_test(segments_path, G_FILE_TEST_IS_REGULAR) && g_remove(segments_path) != 0)
            g_error("Can't delete segments file: %s", segments_path);

        g_message("Clear file memory");
        if (sc_fm_clear(fm_engine) != SC_RESULT_OK)
        {
            g_critical("Can't clear file memory");
            return SC_FALSE;
        }
    }

    return SC_TRUE;
}
int
main(int argc, char *argv[])
{
    GError *error = NULL;
    struct app app;
    int i;
    gboolean start_service = TRUE;

    if (argc < 2) {
        fprintf(stderr, "Missing action, see --help.\n");
        return EXIT_FAILURE;
    }

    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            print_help(argv[0]);
            return EXIT_SUCCESS;
        } 
        else if (strcmp(argv[i], "--dont-start-service") == 0) {
            start_service = FALSE;
        }
    }

    if (strcmp(argv[1], "status") == 0)
        app.action = do_status;
    else if (strcmp(argv[1], "monitor") == 0)
        app.action = do_monitor;
    else if (strcmp(argv[1], "write-lock") == 0)
        app.action = do_write_lock;
    else if (strcmp(argv[1], "scan") == 0)
        app.action = do_scan;
    else if (strcmp(argv[1], "stop") == 0)
        app.action = do_stop;
    else if (strcmp(argv[1], "help") == 0) {
        print_help(argv[0]);
        return EXIT_SUCCESS;
    } else {
        fprintf(stderr, "Unknown action '%s', see --help.\n", argv[1]);
        return EXIT_FAILURE;
    }

    if (start_service && !start_service_by_name())
        return EXIT_FAILURE;

    app.timer = NULL;
    app.loop = g_main_loop_new(NULL, FALSE);
    app.proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SESSION,
                                              G_DBUS_PROXY_FLAGS_NONE,
                                              NULL,
                                              "org.lightmediascanner",
                                              "/org/lightmediascanner/Scanner1",
                                              "org.lightmediascanner.Scanner1",
                                              NULL,
                                              &error);
    if (error) {
        g_error("Could not create proxy: %s", error->message);
        g_error_free(error);
        return EXIT_FAILURE;
    }

    app.argc = argc - 2;
    app.argv = argv + 2;
    app.ret = EXIT_SUCCESS;

    g_idle_add(do_action, &app);

    g_main_loop_run(app.loop);
    g_object_unref(app.proxy);
    g_main_loop_unref(app.loop);

    if (app.timer) {
        printf("Elapsed time: %0.3f seconds\n",
               g_timer_elapsed(app.timer, NULL));
        g_timer_destroy(app.timer);
    }

    return app.ret;
}
Exemplo n.º 3
0
void
gdk_visual_init (void)
{
    struct
    {
        BITMAPINFOHEADER bi;
        union
        {
            RGBQUAD colors[256];
            DWORD fields[256];
        } u;
    } bmi;
    HBITMAP hbm;

    int rastercaps, numcolors, sizepalette, bitspixel;

    system_visual = g_new (GdkVisualPrivate, 1);

    bitspixel = GetDeviceCaps (gdk_DC, BITSPIXEL);
    rastercaps = GetDeviceCaps (gdk_DC, RASTERCAPS);
    system_visual->xvisual = g_new (Visual, 1);
    system_visual->xvisual->visualid = 0;
    system_visual->xvisual->bitspixel = bitspixel;

    if (rastercaps & RC_PALETTE)
    {
        system_visual->visual.type = GDK_VISUAL_PSEUDO_COLOR;
        numcolors = GetDeviceCaps (gdk_DC, NUMCOLORS);
        sizepalette = GetDeviceCaps (gdk_DC, SIZEPALETTE);
        system_visual->xvisual->map_entries = sizepalette;
    }
    else if (bitspixel == 1)
    {
        system_visual->visual.type = GDK_VISUAL_STATIC_GRAY;
        system_visual->xvisual->map_entries = 2;
    }
    else if (bitspixel == 4)
    {
        system_visual->visual.type = GDK_VISUAL_STATIC_COLOR;
        system_visual->xvisual->map_entries = 16;
    }
    else if (bitspixel == 8)
    {
        system_visual->visual.type = GDK_VISUAL_STATIC_COLOR;
        system_visual->xvisual->map_entries = 256;
    }
    else if (bitspixel == 16)
    {
        system_visual->visual.type = GDK_VISUAL_TRUE_COLOR;
#if 1
        /* This code by Mike Enright,
         * see http://www.users.cts.com/sd/m/menright/display.html
         */
        memset (&bmi, 0, sizeof (bmi));
        bmi.bi.biSize = sizeof (bmi.bi);

        hbm = CreateCompatibleBitmap (gdk_DC, 1, 1);
        GetDIBits (gdk_DC, hbm, 0, 1, NULL,
                   (BITMAPINFO *) &bmi, DIB_RGB_COLORS);
        GetDIBits (gdk_DC, hbm, 0, 1, NULL,
                   (BITMAPINFO *) &bmi, DIB_RGB_COLORS);
        DeleteObject (hbm);

        if (bmi.bi.biCompression != BI_BITFIELDS)
        {
            /* Either BI_RGB or BI_RLE_something
             * .... or perhaps (!!) something else.
             * Theoretically biCompression might be
             * mmioFourCC('c','v','i','d') but I doubt it.
             */
            if (bmi.bi.biCompression == BI_RGB)
            {
                /* It's 555 */
                bitspixel = 15;
                system_visual->visual.red_mask   = 0x00007C00;
                system_visual->visual.green_mask = 0x000003E0;
                system_visual->visual.blue_mask  = 0x0000001F;
            }
            else
            {
                g_assert_not_reached ();
            }
        }
        else
        {
            DWORD allmasks =
                bmi.u.fields[0] | bmi.u.fields[1] | bmi.u.fields[2];
            int k = 0;
            while (allmasks)
            {
                if (allmasks&1)
                    k++;
                allmasks/=2;
            }
            bitspixel = k;
            system_visual->visual.red_mask = bmi.u.fields[0];
            system_visual->visual.green_mask = bmi.u.fields[1];
            system_visual->visual.blue_mask  = bmi.u.fields[2];
        }
#else
        /* Old, incorrect (but still working) code. */
#if 0
        system_visual->visual.red_mask   = 0x0000F800;
        system_visual->visual.green_mask = 0x000007E0;
        system_visual->visual.blue_mask  = 0x0000001F;
#else
        system_visual->visual.red_mask   = 0x00007C00;
        system_visual->visual.green_mask = 0x000003E0;
        system_visual->visual.blue_mask  = 0x0000001F;
#endif
#endif
    }
    else if (bitspixel == 24 || bitspixel == 32)
    {
        bitspixel = 24;
        system_visual->visual.type = GDK_VISUAL_TRUE_COLOR;
        system_visual->visual.red_mask   = 0x00FF0000;
        system_visual->visual.green_mask = 0x0000FF00;
        system_visual->visual.blue_mask  = 0x000000FF;
    }
    else
        g_error ("gdk_visual_init: unsupported BITSPIXEL: %d\n", bitspixel);

    system_visual->visual.depth = bitspixel;
    system_visual->visual.byte_order = GDK_LSB_FIRST;
    system_visual->visual.bits_per_rgb = 42; /* Not used? */

    if ((system_visual->visual.type == GDK_VISUAL_TRUE_COLOR) ||
            (system_visual->visual.type == GDK_VISUAL_DIRECT_COLOR))
    {
        gdk_visual_decompose_mask (system_visual->visual.red_mask,
                                   &system_visual->visual.red_shift,
                                   &system_visual->visual.red_prec);

        gdk_visual_decompose_mask (system_visual->visual.green_mask,
                                   &system_visual->visual.green_shift,
                                   &system_visual->visual.green_prec);

        gdk_visual_decompose_mask (system_visual->visual.blue_mask,
                                   &system_visual->visual.blue_shift,
                                   &system_visual->visual.blue_prec);
        system_visual->xvisual->map_entries =
            1 << (MAX (system_visual->visual.red_prec,
                       MAX (system_visual->visual.green_prec,
                            system_visual->visual.blue_prec)));
    }
    else
    {
        system_visual->visual.red_mask = 0;
        system_visual->visual.red_shift = 0;
        system_visual->visual.red_prec = 0;

        system_visual->visual.green_mask = 0;
        system_visual->visual.green_shift = 0;
        system_visual->visual.green_prec = 0;

        system_visual->visual.blue_mask = 0;
        system_visual->visual.blue_shift = 0;
        system_visual->visual.blue_prec = 0;
    }
    system_visual->visual.colormap_size = system_visual->xvisual->map_entries;

    available_depths[0] = system_visual->visual.depth;
    available_types[0] = system_visual->visual.type;
}
Exemplo n.º 4
0
gboolean
g_module_symbol (GModule *module, const gchar *symbol_name, gpointer *symbol)
{
	g_error ("%s", "g_module_open not implemented on this platform");
	return FALSE;
}
Exemplo n.º 5
0
gboolean
g_module_close (GModule *module)
{
	g_error ("%s", "g_module_open not implemented on this platform");
	return FALSE;
}
Exemplo n.º 6
0
/* Main Window Initialization */
void init_main_window(const gchar * glade_file)
{
	GladeXML *xml;
	GtkWidget *widget;
	GtkTextBuffer *txtbuf;
	char title[256];
	GtkStyle *style;

	xml = glade_xml_new(glade_file, "window1", NULL);
	if (!xml)
		g_error(_("GUI loading failed !\n"));
	glade_xml_signal_autoconnect(xml);

	main_wnd = glade_xml_get_widget(xml, "window1");
	hpaned = glade_xml_get_widget(xml, "hpaned1");
	vpaned = glade_xml_get_widget(xml, "vpaned1");
	tree1_w = glade_xml_get_widget(xml, "treeview1");
	tree2_w = glade_xml_get_widget(xml, "treeview2");
	text_w = glade_xml_get_widget(xml, "textview3");

	back_btn = glade_xml_get_widget(xml, "button1");
	gtk_widget_set_sensitive(back_btn, FALSE);

	widget = glade_xml_get_widget(xml, "show_name1");
	gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
				       show_name);

	widget = glade_xml_get_widget(xml, "show_range1");
	gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
				       show_range);

	widget = glade_xml_get_widget(xml, "show_data1");
	gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
				       show_value);

	save_btn = glade_xml_get_widget(xml, "button3");
	save_menu_item = glade_xml_get_widget(xml, "save1");
	conf_set_changed_callback(conf_changed);

	style = gtk_widget_get_style(main_wnd);
	widget = glade_xml_get_widget(xml, "toolbar1");

#if 0	/* Use stock Gtk icons instead */
	replace_button_icon(xml, main_wnd->window, style,
			    "button1", (gchar **) xpm_back);
	replace_button_icon(xml, main_wnd->window, style,
			    "button2", (gchar **) xpm_load);
	replace_button_icon(xml, main_wnd->window, style,
			    "button3", (gchar **) xpm_save);
#endif
	replace_button_icon(xml, main_wnd->window, style,
			    "button4", (gchar **) xpm_single_view);
	replace_button_icon(xml, main_wnd->window, style,
			    "button5", (gchar **) xpm_split_view);
	replace_button_icon(xml, main_wnd->window, style,
			    "button6", (gchar **) xpm_tree_view);

#if 0
	switch (view_mode) {
	case SINGLE_VIEW:
		widget = glade_xml_get_widget(xml, "button4");
		g_signal_emit_by_name(widget, "clicked");
		break;
	case SPLIT_VIEW:
		widget = glade_xml_get_widget(xml, "button5");
		g_signal_emit_by_name(widget, "clicked");
		break;
	case FULL_VIEW:
		widget = glade_xml_get_widget(xml, "button6");
		g_signal_emit_by_name(widget, "clicked");
		break;
	}
#endif
	txtbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w));
	tag1 = gtk_text_buffer_create_tag(txtbuf, "mytag1",
					  "foreground", "red",
					  "weight", PANGO_WEIGHT_BOLD,
					  NULL);
	tag2 = gtk_text_buffer_create_tag(txtbuf, "mytag2",
					  /*"style", PANGO_STYLE_OBLIQUE, */
					  NULL);

	sprintf(title, _("BaThos v%s Configuration"),
		getenv("KERNELVERSION"));
	gtk_window_set_title(GTK_WINDOW(main_wnd), title);

	gtk_widget_show(main_wnd);
}
Exemplo n.º 7
0
int
main (
    int	argc,
    char   *argv[]
)
{
    pgm_error_t* pgm_err = NULL;

    setlocale (LC_ALL, "");

    /* pre-initialise PGM messages module to add hook for GLib logging */
    pgm_messages_init();
    log_init();
    if (!pgm_init (&pgm_err)) {
        g_error ("Unable to start PGM engine: %s", pgm_err->message);
        pgm_error_free (pgm_err);
        pgm_messages_shutdown();
        return EXIT_FAILURE;
    }

    /* parse program arguments */
    const char* binary_name = strrchr (argv[0], '/');
    int c;
    while ((c = getopt (argc, argv, "s:n:p:r:f:K:N:lih")) != -1)
    {
        switch (c) {
        case 'n':
            g_network = optarg;
            break;
        case 's':
            g_port = atoi (optarg);
            break;
        case 'p':
            g_udp_encap_port = atoi (optarg);
            break;
        case 'r':
            g_max_rte = atoi (optarg);
            break;

        case 'f':
            g_fec = TRUE;
            break;
        case 'K':
            g_k = atoi (optarg);
            break;
        case 'N':
            g_n = atoi (optarg);
            break;

        case 'l':
            g_multicast_loop = TRUE;
            break;

        case 'i':
            pgm_if_print_all();
            pgm_messages_shutdown();
            return EXIT_SUCCESS;

        case 'h':
        case '?':
            pgm_messages_shutdown();
            usage (binary_name);
        }
    }

    if (g_fec && ( !g_k || !g_n )) {
        pgm_messages_shutdown();
        g_error ("Invalid Reed-Solomon parameters RS(%d, %d).", g_n, g_k);
        usage (binary_name);
    }

    /* setup signal handlers */
    signal (SIGSEGV, on_sigsegv);
#ifdef SIGHUP
    signal (SIGHUP, SIG_IGN);
#endif

    if (create_pgm_socket())
    {
        while (optind < argc) {
            const int status = pgm_send (g_sock, argv[optind], strlen(argv[optind]) + 1, NULL);
            if (PGM_IO_STATUS_NORMAL != status) {
                g_warning ("pgm_send failed.");
            }
            optind++;
        }
    }

    /* cleanup */
    if (g_sock) {
        pgm_close (g_sock, TRUE);
        g_sock = NULL;
    }
    pgm_shutdown();
    pgm_messages_shutdown();
    return EXIT_SUCCESS;
}
Exemplo n.º 8
0
/**
 * 更新连接池统计信息
 */
void update_conn_pool_status_in_state(network_connection_pool *pool,
		const gchar *username, pool_status_state state) {
	pool_status *pool_st = NULL;

	g_assert(pool);
	g_assert(username);

	g_rw_lock_reader_lock(&(pool->pool_status_lock));
	pool_st = g_hash_table_lookup(pool->conn_pool_status, username);
	if (pool_st == NULL ) {
		g_rw_lock_reader_unlock(&(pool->pool_status_lock));

		/** @note 后端连接初始化后的特殊处理,可能需要新建一个统计信息 */
		if (state == POOL_STATUS_STATE_INITIALIZED) {
			g_rw_lock_writer_lock(&(pool->pool_status_lock));
			pool_st = g_hash_table_lookup(pool->conn_pool_status, username);
			if (pool_st == NULL ) {
				gchar *user = NULL;
				pool_st = pool_status_new();
				if (pool_st == NULL ) {
					g_error("[%s]: create pool status for user failed, %s",
							G_STRLOC, username);
					g_rw_lock_writer_unlock(&(pool->pool_status_lock));
					return;
				}
				user = g_strdup(username);
				g_hash_table_insert(pool->conn_pool_status, user, pool_st);
			}
			g_mutex_lock(&pool_st->status_mutex);

			pool_st->conn_num_in_pending++;

			g_mutex_unlock(&pool_st->status_mutex);
			g_rw_lock_writer_unlock(&(pool->pool_status_lock));
		}

		return;
	}
	g_mutex_lock(&pool_st->status_mutex);

	switch (state) {
	/** 后端连接初始化 */
	case POOL_STATUS_STATE_INITIALIZED:
		pool_st->conn_num_in_pending++;
		break;
		/** 连接放入连接池(后端连接初始化成功) */
	case POOL_STATUS_STATE_PUT_INTO_POOL:
		pool_st->conn_num_in_idle++;
		/**@note Fall through*/
		/** 连接没建立(后端连接初始化失败) */
	case POOL_STATUS_STATE_NOT_CONNECTED:
		if (pool_st->conn_num_in_pending > 0) {
			pool_st->conn_num_in_pending--;
		}
		break;
		/** 从连接池取出连接 */
	case POOL_STATUS_STATE_GET_FROM_POOL:
		if (pool_st->conn_num_in_idle > 0) {
			pool_st->conn_num_in_idle--;
		}
		pool_st->conn_num_in_use++;
		break;
		/** 连接归还连接池(正常) */
	case POOL_STATUS_STATE_RETURN_TO_POOL:
		pool_st->conn_num_in_idle++;
		/**@note Fall through*/
		/** 连接断开(异常) */
	case POOL_STATUS_STATE_DISCONNECTED:
		if (pool_st->conn_num_in_use > 0) {
			pool_st->conn_num_in_use--;
		}
		break;
	case POOL_STATUS_STATE_REMOVE_FROM_POOL:
		pool_st->conn_num_in_idle--;
		break;
	default:
		g_assert_not_reached()
		;
		break;
	}

	g_mutex_unlock(&pool_st->status_mutex);
	g_rw_lock_reader_unlock(&(pool->pool_status_lock));
	return;
}
GPtrArray *PRT_load_production_type_list_from_stream (FILE *stream, const char *filename)
{
  GPtrArray *production_types;
  PRT_partial_production_type_list_t to_pass;
  XML_Parser parser;            /* to read the file */
  int xmlerr;
  char *linebuf = NULL;
  size_t bufsize = 0;
  ssize_t linelen;

#if DEBUG
  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "----- ENTER PRT_load_production_type_list_from_stream");
#endif

  if (stream == NULL)
    stream = stdin;
  if (filename == NULL)
    filename = "input";

  production_types = g_ptr_array_new();

  parser = XML_ParserCreate (NULL);
  if (parser == NULL)
    {
      g_warning ("failed to create parser for reading file of units");
      goto end;
    }

  to_pass.production_types = production_types;
  to_pass.production_type = NULL;
  to_pass.s = g_string_new (NULL);
  to_pass.filename = g_strdup( filename );
  to_pass.parser = parser;

  XML_SetUserData (parser, &to_pass);
  XML_SetElementHandler (parser, startPRTElement, endPRTElement);
  XML_SetCharacterDataHandler (parser, charDataPRT);

  while (1)
    {
      linelen = getline (&linebuf, &bufsize, stream);
      if (linelen == -1)
        {
          xmlerr = XML_Parse (parser, NULL, 0, 1);
          if (xmlerr == XML_STATUS_ERROR)
            {
              g_error ("%s at line %d in %s",
                       XML_ErrorString (XML_GetErrorCode (parser)),
                       XML_GetCurrentLineNumber (parser), filename);
            }
          break;
        }
      xmlerr = XML_Parse (parser, linebuf, linelen, 0);
      if (xmlerr == XML_STATUS_ERROR)
        {
          g_error ("%s at line %d in %s",
                   XML_ErrorString (XML_GetErrorCode (parser)),
                   XML_GetCurrentLineNumber (parser), filename);
        }
    }

  /* Clean up. */
  XML_ParserFree (parser);
  g_string_free (to_pass.s, TRUE);
  free (linebuf);

end:
#if DEBUG
  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "----- EXIT PRT_load_production_type_list_from_stream");
#endif
  return production_types;
}
Exemplo n.º 10
0
DasomMessage *dasom_recv_message (GSocket *socket)
{
  g_debug (G_STRLOC ": %s", G_STRFUNC);

  DasomMessage *message = dasom_message_new ();
  GError *error = NULL;
  gssize n_read = 0;

  n_read = g_socket_receive (socket,
                             (gchar *) message->header,
                             dasom_message_get_header_size (),
                             NULL, &error);

  if (G_UNLIKELY (n_read < dasom_message_get_header_size ()))
  {
    g_critical (G_STRLOC ": %s: received %"G_GSSIZE_FORMAT" less than %d",
                G_STRFUNC, n_read, message->header->data_len);

    if (error)
    {
      g_critical (G_STRLOC ": %s: %s", G_STRFUNC, error->message);
      g_error_free (error);
    }

    dasom_message_unref (message);

    return NULL;
  }

  if (message->header->data_len > 1)
  {
    dasom_message_set_body (message,
                            g_malloc0 (message->header->data_len),
                            message->header->data_len,
                            g_free);

    n_read = g_socket_receive (socket,
                               message->data,
                               message->header->data_len,
                               NULL, &error);

    if (G_UNLIKELY (n_read < message->header->data_len))
    {
      g_critical (G_STRLOC ": %s: received %"G_GSSIZE_FORMAT" less than %d",
                G_STRFUNC, n_read, message->header->data_len);

      if (error)
      {
        g_critical (G_STRLOC ": %s: %s", G_STRFUNC, error->message);
        g_error_free (error);
      }

      dasom_message_unref (message);

      return NULL;
    }
  }

  /* debug message */
  const gchar *name = dasom_message_get_name (message);
  if (name)
    g_debug ("recv: %s, fd: %d", name, g_socket_get_fd (socket));
  else
    g_error ("unknown message type");

  return message;
}
Exemplo n.º 11
0
static void
suspend_signal_handler (int _dummy, siginfo_t *info, void *context)
{
	int old_errno = errno;
	int hp_save_index = mono_hazard_pointer_save_for_signal_handler ();

	MonoThreadInfo *current = mono_thread_info_current ();

	THREADS_SUSPEND_DEBUG ("SIGNAL HANDLER FOR %p [%p]\n", mono_thread_info_get_tid (current), (void*)current->native_handle);
	if (current->syscall_break_signal) {
		current->syscall_break_signal = FALSE;
		THREADS_SUSPEND_DEBUG ("\tsyscall break for %p\n", mono_thread_info_get_tid (current));
		mono_threads_notify_initiator_of_abort (current);
		goto done;
	}

	/* Have we raced with self suspend? */
	if (!mono_threads_transition_finish_async_suspend (current)) {
		current->suspend_can_continue = TRUE;
		THREADS_SUSPEND_DEBUG ("\tlost race with self suspend %p\n", mono_thread_info_get_tid (current));
		/* Under full preemptive suspend, there is no self suspension,
		 * so no race.
		 *
		 * Under full cooperative suspend, there is no signal, so no
		 * race.
		 *
		 * Under hybrid a blocking thread could race done/abort
		 * blocking with the signal handler running: if the done/abort
		 * blocking win, they will wait for a resume - the signal
		 * handler should notify the suspend initiator that the thread
		 * suspended, and then immediately return and let the thread
		 * continue waiting on the resume semaphore.
		 */
		g_assert (mono_threads_is_hybrid_suspension_enabled ());
		mono_threads_notify_initiator_of_suspend (current);
		goto done;
	}

	/*
	 * If the thread is starting, then thread_state_init_from_sigctx returns FALSE,
	 * as the thread might have been attached without the domain or lmf having been
	 * initialized yet.
	 *
	 * One way to fix that is to keep the thread suspended (wait for the restart
	 * signal), and make sgen aware that even if a thread might be suspended, there
	 * would be cases where you cannot scan its stack/registers. That would in fact
	 * consist in removing the async suspend compensation, and treat the case directly
	 * in sgen. That's also how it was done in the sgen specific suspend code.
	 */

	/* thread_state_init_from_sigctx return FALSE if the current thread is starting or detaching and suspend can't continue. */
	current->suspend_can_continue = mono_threads_get_runtime_callbacks ()->thread_state_init_from_sigctx (&current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX], context);

	if (!current->suspend_can_continue)
		THREADS_SUSPEND_DEBUG ("\tThread is starting or detaching, failed to capture state %p\n", mono_thread_info_get_tid (current));

	/*
	Block the restart signal.
	We need to block the restart signal while posting to the suspend_ack semaphore or we race to sigsuspend,
	which might miss the signal and get stuck.
	*/
	pthread_sigmask (SIG_BLOCK, &suspend_ack_signal_mask, NULL);

	/* We're done suspending */
	mono_threads_notify_initiator_of_suspend (current);

	do {
		current->signal = 0;
		sigsuspend (&suspend_signal_mask);
	} while (current->signal != restart_signal_num);

	/* Unblock the restart signal. */
	pthread_sigmask (SIG_UNBLOCK, &suspend_ack_signal_mask, NULL);

	if (current->async_target) {
#if MONO_ARCH_HAS_MONO_CONTEXT
		MonoContext tmp = current->thread_saved_state [ASYNC_SUSPEND_STATE_INDEX].ctx;
		mono_threads_get_runtime_callbacks ()->setup_async_callback (&tmp, current->async_target, current->user_data);
		current->user_data = NULL;
		current->async_target = NULL;
		mono_monoctx_to_sigctx (&tmp, context);
#else
		g_error ("The new interruption machinery requires a working mono-context");
#endif
	}

	/* We're done resuming */
	mono_threads_notify_initiator_of_resume (current);

done:
	mono_hazard_pointer_restore_for_signal_handler (hp_save_index);
	mono_set_errno (old_errno);
}
Exemplo n.º 12
0
void
dasom_send_message (GSocket          *socket,
                    DasomMessageType  type,
                    gpointer          data,
                    guint16           data_len,
                    GDestroyNotify    data_destroy_func)
{
  g_debug (G_STRLOC ": %s: fd = %d", G_STRFUNC, g_socket_get_fd (socket));

  DasomMessage *message;
  const DasomMessageHeader *header;
  GError *error = NULL;
  gssize n_written;

  message = dasom_message_new_full (type, data, data_len, data_destroy_func);
  header  = dasom_message_get_header (message);

  n_written = g_socket_send (socket,
                             (gchar *) header,
                             dasom_message_get_header_size (),
                             NULL, &error);

  if (G_UNLIKELY (n_written < dasom_message_get_header_size ()))
  {
    g_critical (G_STRLOC ": %s: sent %"G_GSSIZE_FORMAT" less than %d",
                G_STRFUNC, n_written, dasom_message_get_header_size ());
    if (error)
    {
      g_critical (G_STRLOC ": %s: %s", G_STRFUNC, error->message);
      g_error_free (error);
    }

    dasom_message_unref (message);

    return;
  }

  if (G_LIKELY (message->header->data_len > 0))
  {
    n_written = g_socket_send (socket,
                               message->data,
                               message->header->data_len,
                               NULL, &error);

    if (G_UNLIKELY (n_written < message->header->data_len))
    {
      g_critical (G_STRLOC ": %s: sent %"G_GSSIZE_FORMAT" less than %d",
                  G_STRFUNC, n_written, message->header->data_len);

      if (error)
      {
        g_critical (G_STRLOC ": %s: %s", G_STRFUNC, error->message);
        g_error_free (error);
      }

      dasom_message_unref (message);

      return;
    }
  }

  /* debug message */
  const gchar *name = dasom_message_get_name (message);
  if (name)
    g_debug ("send: %s, fd: %d", name, g_socket_get_fd(socket));
  else
    g_error ("unknown message type");

  dasom_message_unref (message);
}
Exemplo n.º 13
0
sc_bool sc_fs_storage_write_to_path(sc_segment **segments)
{
    sc_uint32 idx = 0, header_size = 0;
    const sc_segment *segment = 0;
    sc_fs_storage_segments_header header;
    GChecksum * checksum = null_ptr;
    GIOChannel * output = null_ptr;
    gchar * tmp_filename = null_ptr;
    gsize bytes;
    sc_bool result = SC_TRUE;

    if (!g_file_test(repo_path, G_FILE_TEST_IS_DIR))
    {
        g_error("%s isn't a directory.", repo_path);
        return SC_FALSE;
    }

    // create temporary file

    output = _open_tmp_file(&tmp_filename);

    memset(&header, 0, sizeof(sc_fs_storage_segments_header));
    header.segments_num = 0;
    header.timestamp = g_get_real_time();
    header.version = sc_version_to_int(&SC_VERSION);

    g_io_channel_set_encoding(output, null_ptr, null_ptr);

    checksum = g_checksum_new(_checksum_type());
    g_checksum_reset(checksum);

    for (idx = 0; idx < SC_ADDR_SEG_MAX; idx++)
    {
        segment = segments[idx];
        if (segment == null_ptr)
            break; // stop save, because we allocate segment in order

        g_checksum_update(checksum, (guchar*)segment->elements, SC_SEG_ELEMENTS_SIZE_BYTE);
    }

    header.segments_num = idx;
    bytes = SC_STORAGE_SEG_CHECKSUM_SIZE;
    g_checksum_get_digest(checksum, header.checksum, &bytes);

    header_size = sizeof(header);
    if (g_io_channel_write_chars(output, (gchar*)&header_size, sizeof(header_size), &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != sizeof(header_size))
    {
        g_error("Can't write header size: %s", tmp_filename);
        result = SC_FALSE;
        goto clean;
    }

    if (g_io_channel_write_chars(output, (gchar*)&header, header_size, &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != header_size)
    {
        g_error("Can't write header: %s", tmp_filename);
        result = SC_FALSE;
        goto clean;
    }

    for (idx = 0; idx < header.segments_num; ++idx)
    {
        segment = segments[idx];
        g_assert(segment != null_ptr);

        if (g_io_channel_write_chars(output, (gchar*)segment->elements, SC_SEG_ELEMENTS_SIZE_BYTE, &bytes, null_ptr) != G_IO_STATUS_NORMAL || bytes != SC_SEG_ELEMENTS_SIZE_BYTE)
        {
            g_error("Can't write segment %d into %s", idx, tmp_filename);
            result = SC_FALSE;
            goto clean;
        }
    }

    if (result == SC_TRUE)
    {
        // rename main file
        if (g_file_test(tmp_filename, G_FILE_TEST_IS_REGULAR))
        {
            g_io_channel_shutdown(output, TRUE, NULL);
            output = null_ptr;

            if (g_rename(tmp_filename, segments_path) != 0)
            {
                g_error("Can't rename %s -> %s", tmp_filename, segments_path);
                result = SC_FALSE;
            }
        }

        // save file memory
        g_message("Save file memory state");
        if (sc_fm_save(fm_engine) != SC_RESULT_OK)
            g_critical("Error while saves file memory");
    }

    clean:
    {
        if (tmp_filename)
            g_free(tmp_filename);
        if (checksum)
            g_checksum_free(checksum);
        if (output)
            g_io_channel_shutdown(output, TRUE, null_ptr);
    }

    return result;
}
Exemplo n.º 14
0
sc_bool sc_fs_storage_read_from_path(sc_segment **segments, sc_uint32 *segments_num)
{
    if (g_file_test(repo_path, G_FILE_TEST_IS_DIR) == FALSE)
    {
        g_error("%s isn't a directory.", repo_path);
        return SC_FALSE;
    }

    if (g_file_test(segments_path, G_FILE_TEST_IS_REGULAR) == FALSE)
    {
        g_message("There are no segments in %s", segments_path);
        return SC_FALSE;
    }

    // open segments
    {
        GIOChannel * in_file = g_io_channel_new_file(segments_path, "r", null_ptr);
        sc_fs_storage_segments_header header;
        gsize bytes_num = 0;
        sc_uint32 i = 0, header_size = 0;
        GChecksum * checksum = null_ptr;
        sc_segment * seg = null_ptr;
        sc_bool is_valid = SC_TRUE;
        sc_uint8 calculated_checksum[SC_STORAGE_SEG_CHECKSUM_SIZE];

        g_assert(_checksum_get_size() == SC_STORAGE_SEG_CHECKSUM_SIZE);
        if (!in_file)
        {
            g_critical("Can't open segments from: %s", segments_path);
            return SC_FALSE;
        }

        if (g_io_channel_set_encoding(in_file, null_ptr, null_ptr) != G_IO_STATUS_NORMAL)
        {
            g_critical("Can't setup encoding: %s", segments_path);
            return SC_FALSE;
        }

        if ((g_io_channel_read_chars(in_file, (gchar*)&header_size, sizeof(header_size), &bytes_num, null_ptr) != G_IO_STATUS_NORMAL) || (bytes_num != sizeof(header_size)))
        {
            g_critical("Can't read header size");
            return SC_FALSE;
        }

        if (header_size != sizeof(header))
        {
            g_critical("Invalid header size %d != %d", header_size, (int)sizeof(header));
            return SC_FALSE;
        }

        if ((g_io_channel_read_chars(in_file, (gchar*)&header, sizeof(header), &bytes_num, null_ptr) != G_IO_STATUS_NORMAL) || (bytes_num != sizeof(header)))
        {
            g_critical("Can't read header of segments: %s", segments_path);
            return SC_FALSE;
        }

        *segments_num = header.segments_num;

        /// TODO: Check version

        checksum = g_checksum_new(_checksum_type());
        g_assert(checksum);

        g_checksum_reset(checksum);

        // chek data
        for (i = 0; i < *segments_num; ++i)
        {
            seg = sc_segment_new(i);
            segments[i] = seg;

            g_io_channel_read_chars(in_file, (gchar*)seg->elements, SC_SEG_ELEMENTS_SIZE_BYTE, &bytes_num, null_ptr);
            sc_segment_loaded(seg);
            if (bytes_num != SC_SEG_ELEMENTS_SIZE_BYTE)
            {
                g_error("Error while read data for segment: %d", i);
                is_valid = SC_FALSE;
                break;
            }
            g_checksum_update(checksum, (guchar*)seg->elements, SC_SEG_ELEMENTS_SIZE_BYTE);
        }

        if (is_valid == SC_TRUE)
        {
            // compare checksum
            g_checksum_get_digest(checksum, calculated_checksum, &bytes_num);
            if (bytes_num != SC_STORAGE_SEG_CHECKSUM_SIZE)
                is_valid = SC_FALSE;
            else
                is_valid = (memcmp(calculated_checksum, header.checksum, SC_STORAGE_SEG_CHECKSUM_SIZE) == 0) ? SC_TRUE : SC_FALSE;
        }

        if (is_valid == SC_FALSE)
        {
            *segments_num = 0;
            for (i = 0; i < SC_SEGMENT_MAX; ++i)
            {
                if (segments[i])
                {
                    sc_segment_free(segments[i]);
                    segments[i] = null_ptr;
                }
            }
        }

        g_checksum_free(checksum);
        g_io_channel_shutdown(in_file, FALSE, null_ptr);

        if (is_valid == SC_FALSE)
            return SC_FALSE;
    }

    g_message("Segments loaded: %u", *segments_num);

    g_assert(fm_engine != null_ptr);
    g_message("Check file memory state");
    sc_bool r = sc_fm_clean_state(fm_engine) == SC_RESULT_OK;

    if (r == SC_FALSE)
        g_error("File memory wasn't check properly");

    return r;
}
Exemplo n.º 15
0
static void
output_loop (gpointer data)
{
    GstPad *pad;
    GOmxCore *gomx;
    GOmxPort *out_port;
    GstOmxBaseFilter *self;
    GstFlowReturn ret = GST_FLOW_OK;

    pad = data;
    self = GST_OMX_BASE_FILTER (gst_pad_get_parent (pad));
    gomx = self->gomx;

    GST_LOG_OBJECT (self, "begin");

    /* do not bother if we have been setup to bail out */
    if ((ret = g_atomic_int_get (&self->last_pad_push_return)) != GST_FLOW_OK)
        goto leave;

    if (!self->ready)
    {
        g_error ("not ready");
        return;
    }

    out_port = self->out_port;

    if (G_LIKELY (out_port->enabled))
    {
        OMX_BUFFERHEADERTYPE *omx_buffer = NULL;

        GST_LOG_OBJECT (self, "request buffer");
        omx_buffer = g_omx_port_request_buffer (out_port);

        GST_LOG_OBJECT (self, "omx_buffer: %p", omx_buffer);

        if (G_UNLIKELY (!omx_buffer))
        {
            GST_WARNING_OBJECT (self, "null buffer: leaving");
            ret = GST_FLOW_WRONG_STATE;
            goto leave;
        }

        log_buffer (self, omx_buffer);

        if (G_LIKELY (omx_buffer->nFilledLen > 0))
        {
            GstBuffer *buf;

#if 1
            /** @todo remove this check */
            if (G_LIKELY (self->in_port->enabled))
            {
                GstCaps *caps = NULL;

                caps = gst_pad_get_negotiated_caps (self->srcpad);

                if (!caps)
                {
                    /** @todo We shouldn't be doing this. */
                    GST_WARNING_OBJECT (self, "faking settings changed notification");
                    if (gomx->settings_changed_cb)
                        gomx->settings_changed_cb (gomx);
                }
                else
                {
                    GST_LOG_OBJECT (self, "caps already fixed: %" GST_PTR_FORMAT, caps);
                    gst_caps_unref (caps);
                }
            }
#endif

            /* buf is always null when the output buffer pointer isn't shared. */
            buf = omx_buffer->pAppPrivate;

            /** @todo we need to move all the caps handling to one single
             * place, in the output loop probably. */
            if (G_UNLIKELY (omx_buffer->nFlags & 0x80))
            {
                GstCaps *caps = NULL;
                GstStructure *structure;
                GValue value = { 0 };

                caps = gst_pad_get_negotiated_caps (self->srcpad);
                caps = gst_caps_make_writable (caps);
                structure = gst_caps_get_structure (caps, 0);

                g_value_init (&value, GST_TYPE_BUFFER);
                buf = gst_buffer_new_and_alloc (omx_buffer->nFilledLen);
                memcpy (GST_BUFFER_DATA (buf), omx_buffer->pBuffer + omx_buffer->nOffset, omx_buffer->nFilledLen);
                gst_value_set_buffer (&value, buf);
                gst_buffer_unref (buf);
                gst_structure_set_value (structure, "codec_data", &value);
                g_value_unset (&value);

                gst_pad_set_caps (self->srcpad, caps);
            }
            else if (buf && !(omx_buffer->nFlags & OMX_BUFFERFLAG_EOS))
            {
                GST_BUFFER_SIZE (buf) = omx_buffer->nFilledLen;
                if (self->use_timestamps)
                {
                    GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (omx_buffer->nTimeStamp,
                                                                            GST_SECOND,
                                                                            OMX_TICKS_PER_SECOND);
                }

                omx_buffer->pAppPrivate = NULL;
                omx_buffer->pBuffer = NULL;

                ret = push_buffer (self, buf);

                gst_buffer_unref (buf);
            }
            else
            {
                /* This is only meant for the first OpenMAX buffers,
                 * which need to be pre-allocated. */
                /* Also for the very last one. */
                ret = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
                                                         GST_BUFFER_OFFSET_NONE,
                                                         omx_buffer->nFilledLen,
                                                         GST_PAD_CAPS (self->srcpad),
                                                         &buf);

                if (G_LIKELY (buf))
                {
                    memcpy (GST_BUFFER_DATA (buf), omx_buffer->pBuffer + omx_buffer->nOffset, omx_buffer->nFilledLen);
                    if (self->use_timestamps)
                    {
                        GST_BUFFER_TIMESTAMP (buf) = gst_util_uint64_scale_int (omx_buffer->nTimeStamp,
                                                                                GST_SECOND,
                                                                                OMX_TICKS_PER_SECOND);
                    }

                    if (self->share_output_buffer)
                    {
                        GST_WARNING_OBJECT (self, "couldn't zero-copy");
                        /* If pAppPrivate is NULL, it means it was a dummy
                         * allocation, free it. */
                        if (!omx_buffer->pAppPrivate)
                        {
                            g_free (omx_buffer->pBuffer);
                            omx_buffer->pBuffer = NULL;
                        }
                    }

                    ret = push_buffer (self, buf);
                }
                else
                {
                    GST_WARNING_OBJECT (self, "couldn't allocate buffer of size %lu",
                                        omx_buffer->nFilledLen);
                }
            }
        }
        else
        {
            GST_WARNING_OBJECT (self, "empty buffer");
        }

        if (G_UNLIKELY (omx_buffer->nFlags & OMX_BUFFERFLAG_EOS))
        {
            GST_DEBUG_OBJECT (self, "got eos");
            gst_pad_push_event (self->srcpad, gst_event_new_eos ());
            ret = GST_FLOW_UNEXPECTED;
            goto leave;
        }

        if (self->share_output_buffer &&
            !omx_buffer->pBuffer &&
            omx_buffer->nOffset == 0)
        {
            GstBuffer *buf;
            GstFlowReturn result;

            GST_LOG_OBJECT (self, "allocate buffer");
            result = gst_pad_alloc_buffer_and_set_caps (self->srcpad,
                                                        GST_BUFFER_OFFSET_NONE,
                                                        omx_buffer->nAllocLen,
                                                        GST_PAD_CAPS (self->srcpad),
                                                        &buf);

            if (G_LIKELY (result == GST_FLOW_OK))
            {
                gst_buffer_ref (buf);
                omx_buffer->pAppPrivate = buf;

                omx_buffer->pBuffer = GST_BUFFER_DATA (buf);
                omx_buffer->nAllocLen = GST_BUFFER_SIZE (buf);
            }
            else
            {
                GST_WARNING_OBJECT (self, "could not pad allocate buffer, using malloc");
                omx_buffer->pBuffer = g_malloc (omx_buffer->nAllocLen);
            }
        }

        if (self->share_output_buffer &&
            !omx_buffer->pBuffer)
        {
            GST_ERROR_OBJECT (self, "no input buffer to share");
        }

        omx_buffer->nFilledLen = 0;
        GST_LOG_OBJECT (self, "release_buffer");
        g_omx_port_release_buffer (out_port, omx_buffer);
    }

leave:

    self->last_pad_push_return = ret;

    if (gomx->omx_error != OMX_ErrorNone)
        ret = GST_FLOW_ERROR;

    if (ret != GST_FLOW_OK)
    {
        GST_INFO_OBJECT (self, "pause task, reason:  %s",
                         gst_flow_get_name (ret));
        gst_pad_pause_task (self->srcpad);
    }

    GST_LOG_OBJECT (self, "end");

    gst_object_unref (self);
}
Exemplo n.º 16
0
static HaskellObj
#ifdef GHC_RTS_USES_CAPABILITY
gtk2hs_value_as_haskellobj(Capability *cap, const GValue *value) {
#else
gtk2hs_value_as_haskellobj(const GValue *value) {
#endif
    switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
    case G_TYPE_INTERFACE:
        if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT))
            return rts_mkPtr(CAP g_value_get_object(value));
        else
            break;
    case G_TYPE_CHAR:
#if GLIB_CHECK_VERSION(2,31,0)
        return rts_mkChar(CAP g_value_get_schar(value));
#else
        return rts_mkChar(CAP g_value_get_char(value));
#endif
    case G_TYPE_UCHAR:
        return rts_mkChar(CAP g_value_get_uchar(value));
    case G_TYPE_BOOLEAN:
        return rts_mkBool(CAP g_value_get_boolean(value));
    case G_TYPE_INT:
        return rts_mkInt(CAP g_value_get_int(value));
    case G_TYPE_UINT:
        return rts_mkWord(CAP g_value_get_uint(value));
    case G_TYPE_LONG:
        return rts_mkInt(CAP g_value_get_long(value));
    case G_TYPE_ULONG:
        return rts_mkWord(CAP g_value_get_ulong(value));
/*    case G_TYPE_INT64:
        return rts_mkInt64(CAP g_value_get_int64(value));
    case G_TYPE_UINT64:
        return rts_mkWord64(CAP g_value_get_uint64(value));   */
    case G_TYPE_ENUM:
        return rts_mkInt(CAP g_value_get_enum(value));
    case G_TYPE_FLAGS:
        return rts_mkWord(CAP g_value_get_enum(value));
    case G_TYPE_FLOAT:
        return rts_mkFloat(CAP g_value_get_float(value));
    case G_TYPE_DOUBLE:
        return rts_mkDouble(CAP g_value_get_double(value));
    case G_TYPE_STRING:
        return rts_mkPtr(CAP (char *)g_value_get_string(value)); /* CHECKME: is the string freed? */
    case G_TYPE_POINTER:
        return rts_mkPtr(CAP g_value_get_pointer(value));
    case G_TYPE_BOXED:
        return rts_mkPtr(CAP g_value_get_boxed(value));
    case G_TYPE_PARAM:
        return rts_mkPtr(CAP g_value_get_param(value));
    case G_TYPE_OBJECT:
        return rts_mkPtr(CAP g_value_get_object(value));
    }
    g_error("gtk2hs_value_as_haskellobj: unable to handle GValue with type %s\n"
            "please report this as a bug to [email protected]",
            g_type_name(G_VALUE_TYPE(value)));
}

void
gtk2hs_value_from_haskellobj(GValue *value, HaskellObj obj) {

    switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
    case G_TYPE_INVALID:
    case G_TYPE_NONE:
        return;
    case G_TYPE_INTERFACE:
        /* we only handle interface types that have a GObject prereq */
        if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT)) {
            g_value_set_object(value, rts_getPtr(obj));
        } else {
            break;
        }
        return;
    case G_TYPE_CHAR:
#if GLIB_CHECK_VERSION(2,31,0)
        g_value_set_schar(value, rts_getChar(obj));
#else
        g_value_set_char(value, rts_getChar(obj));
#endif
        return;
    case G_TYPE_UCHAR:
#if GLIB_CHECK_VERSION(2,31,0)
        g_value_set_schar(value, rts_getChar(obj));
#else
        g_value_set_char(value, rts_getChar(obj));
#endif
        return;
    case G_TYPE_BOOLEAN:
        g_value_set_boolean(value, rts_getBool(obj));
        return;
    case G_TYPE_INT:
        g_value_set_int(value, rts_getInt(obj));
        return;
    case G_TYPE_UINT:
        g_value_set_uint(value, rts_getWord(obj));
        return;
    case G_TYPE_LONG:
        g_value_set_long(value, rts_getInt(obj));
        return;
    case G_TYPE_ULONG:
        g_value_set_ulong(value, rts_getWord(obj));
        return;
/*    case G_TYPE_INT64:
        g_value_set_int64(value, rts_getInt64(obj));
        return;
    case G_TYPE_UINT64:
        g_value_set_uint64(value, rts_getWord64(obj));
        return;                                         */
    case G_TYPE_ENUM:
        g_value_set_enum(value, rts_getInt(obj));
        return;
    case G_TYPE_FLAGS:
        g_value_set_flags(value, rts_getInt(obj));
        return;
    case G_TYPE_FLOAT:
        g_value_set_float(value, rts_getFloat(obj));
        return;
    case G_TYPE_DOUBLE:
        g_value_set_double(value, rts_getDouble(obj));
        return;
    case G_TYPE_STRING:
        g_value_set_string(value, rts_getPtr(obj));
        return;
    case G_TYPE_POINTER:
        g_value_set_pointer(value, rts_getPtr(obj));
        return;
/*    case G_TYPE_BOXED: {
        g_value_set_boxed(value, obj);
        break;
    }
    case G_TYPE_PARAM:
        g_value_set_param(value, (obj));
        break;                                          */
    case G_TYPE_OBJECT:
        g_value_set_object(value, rts_getPtr(obj));
        return;
    }
    g_error("gtk2hs_value_from_haskellobj: unable to handle GValue with type %s\n"
            "please report this as a bug to [email protected]",
            g_type_name(G_VALUE_TYPE(value)));
}
Exemplo n.º 17
0
gboolean
mono_thread_platform_create_thread (MonoThreadStart thread_fn, gpointer thread_data, gsize* const stack_size, MonoNativeThreadId *tid)
{
	pthread_attr_t attr;
	pthread_t thread;
	gint res;
	gsize set_stack_size;

	res = pthread_attr_init (&attr);
	if (res != 0)
		g_error ("%s: pthread_attr_init failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);

	if (stack_size)
		set_stack_size = *stack_size;
	else
		set_stack_size = 0;

#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
	if (set_stack_size == 0) {
#if HAVE_VALGRIND_MEMCHECK_H
		if (RUNNING_ON_VALGRIND)
			set_stack_size = 1 << 20;
		else
			set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
#else
		set_stack_size = (SIZEOF_VOID_P / 4) * 1024 * 1024;
#endif
	}

#ifdef PTHREAD_STACK_MIN
	if (set_stack_size < PTHREAD_STACK_MIN)
		set_stack_size = PTHREAD_STACK_MIN;
#endif

	res = pthread_attr_setstacksize (&attr, set_stack_size);
	if (res != 0)
		g_error ("%s: pthread_attr_setstacksize failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
#endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */

	/* Actually start the thread */
	res = mono_gc_pthread_create (&thread, &attr, (gpointer (*)(gpointer)) thread_fn, thread_data);
	if (res) {
		res = pthread_attr_destroy (&attr);
		if (res != 0)
			g_error ("%s: pthread_attr_destroy failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);

		return FALSE;
	}

	if (tid)
		*tid = thread;

	if (stack_size) {
		res = pthread_attr_getstacksize (&attr, stack_size);
		if (res != 0)
			g_error ("%s: pthread_attr_getstacksize failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);
	}

	res = pthread_attr_destroy (&attr);
	if (res != 0)
		g_error ("%s: pthread_attr_destroy failed, error: \"%s\" (%d)", __func__, g_strerror (res), res);

	return TRUE;
}
gint
gegl_buffer_iterator_add (GeglBufferIterator  *iterator,
                          GeglBuffer          *buffer,
                          const GeglRectangle *roi,
                          gint                 level,
                          const Babl          *format,
                          guint                flags,
                          GeglAbyssPolicy      abyss_policy)
{
  GeglBufferIterators *i = (gpointer)iterator;
  gint self = 0;
  if (i->iterators+1 > GEGL_BUFFER_MAX_ITERATORS)
    {
      g_error ("too many iterators (%i)", i->iterators+1);
    }

  if (i->iterators == 0) /* for sanity, we zero at init */
    {
      memset (i, 0, sizeof (GeglBufferIterators));
    }

  /* XXX: should assert that the passed in level matches
   * the level of the base iterator.
   */

  self = i->iterators++;

  if (!roi)
    roi = self==0?&(buffer->extent):&(i->rect[0]);
  i->rect[self]=*roi;

  i->buffer[self]= g_object_ref (buffer);

  if (format)
    i->format[self]=format;
  else
    i->format[self]=buffer->soft_format;
  i->flags[self]=flags;

  if (self==0) /* The first buffer which is always scan aligned */
    {
      i->flags[self] |= GEGL_BUFFER_SCAN_COMPATIBLE;
      gegl_buffer_tile_iterator_init (&i->i[self], i->buffer[self], i->rect[self], ((i->flags[self] & GEGL_BUFFER_WRITE) != 0), i->format[self], iterator->level);
    }
  else
    {
      /* we make all subsequently added iterators share the width and height of the first one */
      i->rect[self].width = i->rect[0].width;
      i->rect[self].height = i->rect[0].height;

      if (gegl_buffer_scan_compatible (i->buffer[0], i->rect[0].x, i->rect[0].y,
                                       i->buffer[self], i->rect[self].x, i->rect[self].y))
        {
          i->flags[self] |= GEGL_BUFFER_SCAN_COMPATIBLE;
          gegl_buffer_tile_iterator_init (&i->i[self], i->buffer[self], i->rect[self], ((i->flags[self] & GEGL_BUFFER_WRITE) != 0), i->format[self], iterator->level);
        }
    }

  i->buf[self] = NULL;

  if (i->format[self] == i->buffer[self]->soft_format)
    {
      i->flags[self] |= GEGL_BUFFER_FORMAT_COMPATIBLE;
    }
  return self;
}
Exemplo n.º 19
0
static
gboolean
create_pgm_socket (void)
{
    struct pgm_addrinfo_t* res = NULL;
    pgm_error_t* pgm_err = NULL;
    sa_family_t sa_family = AF_UNSPEC;

    /* parse network parameter into PGM socket address structure */
    if (!pgm_getaddrinfo (g_network, NULL, &res, &pgm_err)) {
        g_error ("Parsing network parameter: %s", pgm_err->message);
        goto err_abort;
    }

    sa_family = res->ai_send_addrs[0].gsr_group.ss_family;

    if (g_udp_encap_port) {
        if (!pgm_socket (&g_sock, sa_family, SOCK_SEQPACKET, IPPROTO_UDP, &pgm_err)) {
            g_error ("Creating PGM/UDP socket: %s", pgm_err->message);
            goto err_abort;
        }
        pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_UDP_ENCAP_UCAST_PORT, &g_udp_encap_port, sizeof(g_udp_encap_port));
        pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_UDP_ENCAP_MCAST_PORT, &g_udp_encap_port, sizeof(g_udp_encap_port));
    } else {
        if (!pgm_socket (&g_sock, sa_family, SOCK_SEQPACKET, IPPROTO_PGM, &pgm_err)) {
            g_error ("Creating PGM/IP socket: %s", pgm_err->message);
            goto err_abort;
        }
    }

    /* Use RFC 2113 tagging for PGM Router Assist */
    const int no_router_assist = 0;
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_IP_ROUTER_ALERT, &no_router_assist, sizeof(no_router_assist));

    pgm_drop_superuser();

    /* set PGM parameters */
    const int send_only = 1,
              ambient_spm = pgm_secs (30),
              heartbeat_spm[] = { pgm_msecs (100),
                                  pgm_msecs (100),
                                  pgm_msecs (100),
                                  pgm_msecs (100),
                                  pgm_msecs (1300),
                                  pgm_secs  (7),
                                  pgm_secs  (16),
                                  pgm_secs  (25),
                                  pgm_secs  (30)
                                };

    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_SEND_ONLY, &send_only, sizeof(send_only));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_MTU, &g_max_tpdu, sizeof(g_max_tpdu));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_TXW_SQNS, &g_sqns, sizeof(g_sqns));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_TXW_MAX_RTE, &g_max_rte, sizeof(g_max_rte));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_AMBIENT_SPM, &ambient_spm, sizeof(ambient_spm));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM, &heartbeat_spm, sizeof(heartbeat_spm));
    if (g_fec) {
        struct pgm_fecinfo_t fecinfo;
        fecinfo.block_size		= g_n;
        fecinfo.proactive_packets	= 0;
        fecinfo.group_size		= g_k;
        fecinfo.ondemand_parity_enabled	= TRUE;
        fecinfo.var_pktlen_enabled	= TRUE;
        pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_USE_FEC, &fecinfo, sizeof(fecinfo));
    }

    /* create global session identifier */
    struct pgm_sockaddr_t addr;
    memset (&addr, 0, sizeof(addr));
    addr.sa_port = g_port ? g_port : DEFAULT_DATA_DESTINATION_PORT;
    addr.sa_addr.sport = DEFAULT_DATA_SOURCE_PORT;
    if (!pgm_gsi_create_from_hostname (&addr.sa_addr.gsi, &pgm_err)) {
        g_error ("Creating GSI: %s", pgm_err->message);
        goto err_abort;
    }

    /* assign socket to specified address */
    struct pgm_interface_req_t if_req;
    memset (&if_req, 0, sizeof(if_req));
    if_req.ir_interface = res->ai_recv_addrs[0].gsr_interface;
    memcpy (&if_req.ir_address, &res->ai_send_addrs[0].gsr_addr, sizeof(struct sockaddr_storage));
    if (!pgm_bind3 (g_sock,
                    &addr, sizeof(addr),
                    &if_req, sizeof(if_req),	/* tx interface */
                    &if_req, sizeof(if_req),	/* rx interface */
                    &pgm_err))
    {
        g_error ("Binding PGM socket: %s", pgm_err->message);
        goto err_abort;
    }

    /* join IP multicast groups */
    for (unsigned i = 0; i < res->ai_recv_addrs_len; i++)
        pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_JOIN_GROUP, &res->ai_recv_addrs[i], sizeof(struct group_req));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_SEND_GROUP, &res->ai_send_addrs[0], sizeof(struct group_req));
    pgm_freeaddrinfo (res);

    /* set IP parameters */
    const int blocking = 0,
              multicast_loop = g_multicast_loop ? 1 : 0,
              multicast_hops = 16,
              dscp = 0x2e << 2;		/* Expedited Forwarding PHB for network elements, no ECN. */

    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_MULTICAST_LOOP, &multicast_loop, sizeof(multicast_loop));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_MULTICAST_HOPS, &multicast_hops, sizeof(multicast_hops));
    if (AF_INET6 != sa_family)
        pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_TOS, &dscp, sizeof(dscp));
    pgm_setsockopt (g_sock, IPPROTO_PGM, PGM_NOBLOCK, &blocking, sizeof(blocking));

    if (!pgm_connect (g_sock, &pgm_err)) {
        g_error ("Connecting PGM socket: %s", pgm_err->message);
        goto err_abort;
    }

    return TRUE;

err_abort:
    if (NULL != g_sock) {
        pgm_close (g_sock, FALSE);
        g_sock = NULL;
    }
    if (NULL != res) {
        pgm_freeaddrinfo (res);
        res = NULL;
    }
    if (NULL != pgm_err) {
        pgm_error_free (pgm_err);
        pgm_err = NULL;
    }
    return FALSE;
}
gboolean
gegl_buffer_iterator_next (GeglBufferIterator *iterator)
{
  GeglBufferIterators *i = (gpointer)iterator;
  gboolean result = FALSE;
  gint no;

  if (i->is_finished)
    g_error ("%s called on finished buffer iterator", G_STRFUNC);
  if (i->iteration_no == 0)
    {
      for (no=0; no<i->iterators;no++)
        {
          gint j;
          gboolean found = FALSE;
          for (j=0; j<no; j++)
            if (i->buffer[no]==i->buffer[j])
              {
                found = TRUE;
                break;
              }
          if (!found)
            gegl_buffer_lock (i->buffer[no]);

          if (gegl_cl_is_accelerated ())
            gegl_buffer_cl_cache_flush (i->buffer[no], &i->rect[no]);
        }
    }
  else
    {
      /* complete pending write work */
      for (no=0; no<i->iterators;no++)
        {
          if (i->flags[no] & GEGL_BUFFER_WRITE)
            {

              if (i->flags[no] & GEGL_BUFFER_SCAN_COMPATIBLE &&
                  i->flags[no] & GEGL_BUFFER_FORMAT_COMPATIBLE &&
                  i->roi[no].width == i->i[no].buffer->tile_storage->tile_width && (i->flags[no] & GEGL_BUFFER_FORMAT_COMPATIBLE))
                { /* direct access, don't need to do anything */
#if DEBUG_DIRECT
                   direct_write += i->roi[no].width * i->roi[no].height;
#endif
                }
              else
                {
#if DEBUG_DIRECT
                  in_direct_write += i->roi[no].width * i->roi[no].height;
#endif

                  ensure_buf (i, no);

  /* XXX: should perhaps use _set_unlocked, and keep the lock in the
   * iterator.
   */
                  gegl_buffer_set (i->buffer[no], &(i->roi[no]), 0, i->format[no], i->buf[no], GEGL_AUTO_ROWSTRIDE); /* XXX: use correct level */
                }
            }
        }
    }

  g_assert (i->iterators > 0);

  /* then we iterate all */
  for (no=0; no<i->iterators;no++)
    {
      if (i->flags[no] & GEGL_BUFFER_SCAN_COMPATIBLE)
        {
          gboolean res;
          res = gegl_buffer_tile_iterator_next (&i->i[no]);
          if (no == 0)
            {
              result = res;
            }
          i->roi[no] = i->i[no].roi2;

          /* since they were scan compatible this should be true */
          if (res != result)
            {
              g_print ("%i==%i != 0==%i\n", no, res, result);
            }
          g_assert (res == result);

          if ((i->flags[no] & GEGL_BUFFER_FORMAT_COMPATIBLE) &&
              i->roi[no].width == i->i[no].buffer->tile_storage->tile_width
           )
            {
              /* direct access */
              i->data[no]=i->i[no].sub_data;
#if DEBUG_DIRECT
              direct_read += i->roi[no].width * i->roi[no].height;
#endif
            }
          else
            {
              ensure_buf (i, no);

              if (i->flags[no] & GEGL_BUFFER_READ)
                {
                  gegl_buffer_get_unlocked (i->buffer[no], 1.0, &(i->roi[no]), i->format[no], i->buf[no], GEGL_AUTO_ROWSTRIDE);
                }

              i->data[no]=i->buf[no];
#if DEBUG_DIRECT
              in_direct_read += i->roi[no].width * i->roi[no].height;
#endif
            }
        }
      else
        {
          /* we copy the roi from iterator 0  */
          i->roi[no] = i->roi[0];
          i->roi[no].x += (i->rect[no].x-i->rect[0].x);
          i->roi[no].y += (i->rect[no].y-i->rect[0].y);

          ensure_buf (i, no);

          if (i->flags[no] & GEGL_BUFFER_READ)
            {
              gegl_buffer_get_unlocked (i->buffer[no], 1.0, &(i->roi[no]), i->format[no], i->buf[no], GEGL_AUTO_ROWSTRIDE);
            }
          i->data[no]=i->buf[no];

#if DEBUG_DIRECT
          in_direct_read += i->roi[no].width * i->roi[no].height;
#endif
        }
      i->length = i->roi[no].width * i->roi[no].height;
    }

  i->iteration_no++;

  if (result == FALSE)
    gegl_buffer_iterator_stop (iterator);

  return result;
}
Exemplo n.º 21
0
GModule *
g_module_open (const gchar *file, GModuleFlags flags)
{
	g_error ("%s", "g_module_open not implemented on this platform");
	return NULL;
}
Exemplo n.º 22
0
gint display_manpage_dbox()
{
	GladeXML *xml;
	GtkWidget *dbox;
	GtkTextBuffer *txtbuf;
	GtkWidget *text;
	FILE *fd;
	gchar *filename;
	gchar buffer[32768];
	gint len = 0;
	struct stat stbuf;
	gint result;
	PangoFontDescription *font_desc;

	filename = g_strconcat(inst_paths.manpage_dir, "Manpage.txt", NULL);

	if (access(filename, F_OK) == 0) 
	{
		if (stat(filename, &stbuf) != -1) 
		{
			len = stbuf.st_size;
			len -= 2;
		}
		if ((fd = fopen(filename, "r")) != NULL) 
		{
			memset(buffer, 0, sizeof(buffer));
			len = fread(buffer, 1, len, fd);
			fclose(fd);
		}
	}

	xml = glade_xml_new(tilp_paths_build_glade("manpage-2.glade"), "manpage_dbox", PACKAGE);
	if (!xml)
		g_error("GUI loading failed !\n");
	glade_xml_signal_autoconnect(xml);

	dbox = glade_xml_get_widget(xml, "manpage_dbox");
	text = glade_xml_get_widget(xml, "textview1");

	// Change font
	font_desc = pango_font_description_from_string ("Courier");
	gtk_widget_modify_font (text, font_desc);
	pango_font_description_free (font_desc);

	// Set text
	txtbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
	gtk_text_buffer_set_text(txtbuf, buffer, len);

	result = gtk_dialog_run(GTK_DIALOG(dbox));
	switch (result) 
	{
	case GTK_RESPONSE_OK:
		break;
	default:
		break;
	}

	gtk_widget_destroy(dbox);

	return 0;
}
Exemplo n.º 23
0
const gchar *
g_module_error (void)
{
	g_error ("%s", "g_module_open not implemented on this platform");
	return NULL;
}
Exemplo n.º 24
0
/**
 * Create a security token from host address and port using specified key.
 *
 * Optionally, extra contextual data may be given (i.e. the token is not
 * only based on the address and port) to make the token more unique to
 * a specific context.
 *
 * @param stg		the security token generator
 * @param n			key index to use
 * @param tok		where security token is written
 * @param addr		address of the host for which we're generating a token
 * @param port		port of the host for which we're generating a token
 * @param data		optional contextual data
 * @param len		length of contextual data
 */
static void
sectoken_generate_n(sectoken_gen_t *stg, size_t n,
	sectoken_t *tok, host_addr_t addr, uint16 port,
	const void *data, size_t len)
{
	char block[8];
	char enc[8];
	char *p = block;

	sectoken_gen_check(stg);
	g_assert(tok != NULL);
	g_assert(size_is_non_negative(n));
	g_assert(n < stg->keycnt);
	g_assert((NULL != data) == (len != 0));

	switch (host_addr_net(addr)) {
	case NET_TYPE_IPV4:
		p = poke_be32(p, host_addr_ipv4(addr));
		break;
	case NET_TYPE_IPV6:
		{
			uint val;

			val = binary_hash(host_addr_ipv6(&addr), 16);
			p = poke_be32(p, val);
		}
		break;
	case NET_TYPE_LOCAL:
	case NET_TYPE_NONE:
		g_error("unexpected address for security token generation: %s",
			host_addr_to_string(addr));
	}

	p = poke_be16(p, port);
	p = poke_be16(p, 0);		/* Filler */

	g_assert(p == &block[8]);

	STATIC_ASSERT(sizeof(tok->v) == sizeof(uint32));
	STATIC_ASSERT(sizeof(block) == sizeof(enc));

	tea_encrypt(&stg->keys[n], enc, block, sizeof block);

	/*
	 * If they gave contextual data, encrypt them by block of 8 bytes,
	 * filling the last partial block with zeroes if needed.
	 */

	if (data != NULL) {
		const void *q = data;
		size_t remain = len;
		char denc[8];

		STATIC_ASSERT(sizeof(denc) == sizeof(enc));

		while (remain != 0) {
			size_t fill = MIN(remain, 8U);
			unsigned i;

			if (fill != 8U)
				ZERO(&block);

			memcpy(block, q, fill);
			remain -= fill;
			q = const_ptr_add_offset(q, fill);

			/*
			 * Encrypt block of contextual data (possibly filled with trailing
			 * zeroes) and merge back the result into the main encryption
			 * output with XOR.
			 */

			tea_encrypt(&stg->keys[n], denc, block, sizeof block);

			for (i = 0; i < sizeof denc; i++)
				enc[i] ^= denc[i];
		}
	}

	poke_be32(tok->v, tea_squeeze(enc, sizeof enc));
}
Exemplo n.º 25
0
/* Parse and expand text after '$' character. return value has to be
   g_free()'d if `free_ret' is TRUE. */
char *parse_special(char **cmd, SERVER_REC *server, void *item,
		    char **arglist, int *free_ret, int *arg_used)
{
	static char **nested_orig_cmd = NULL; /* FIXME: KLUDGE! */
	char command, *value;

	char align_pad;
	int align, align_flags;

	char *nest_value;
	int brackets, nest_free;

	*free_ret = FALSE;

	command = **cmd; (*cmd)++;
	switch (command) {
	case '[':
		/* alignment */
		if (!get_alignment_args(cmd, &align, &align_flags,
					&align_pad) || **cmd == '\0') {
			(*cmd)--;
			return NULL;
		}
		break;
	default:
		command = 0;
		(*cmd)--;
	}

	nest_free = FALSE; nest_value = NULL;
	if (**cmd == '(') {
		/* subvariable */
		int toplevel = nested_orig_cmd == NULL;

		if (toplevel) nested_orig_cmd = cmd;
		(*cmd)++;
		if (**cmd != '$') {
			/* ... */
			nest_value = *cmd;
		} else {
			(*cmd)++;
			nest_value = parse_special(cmd, server, item, arglist,
						   &nest_free, arg_used);
		}

		while ((*nested_orig_cmd)[1] != '\0') {
			(*nested_orig_cmd)++;
			if (**nested_orig_cmd == ')')
				break;
		}
		cmd = &nest_value;

                if (toplevel) nested_orig_cmd = NULL;
	}

	if (**cmd != '{')
		brackets = FALSE;
	else {
		/* special value is inside {...} (foo${test}bar -> fooXXXbar) */
		(*cmd)++;
		brackets = TRUE;
	}

	value = get_special_value(cmd, server, item, arglist,
				  free_ret, arg_used);
	if (**cmd == '\0')
		g_error("parse_special() : buffer overflow!");

	if (brackets) {
		while (**cmd != '}' && (*cmd)[1] != '\0')
			(*cmd)++;
	}

	if (nest_free) g_free(nest_value);

	if (command == '[') {
		/* alignment */
		char *p;

		if (value == NULL) return "";

		p = get_alignment(value, align, align_flags, align_pad);
		if (*free_ret) g_free(value);

		*free_ret = TRUE;
		return p;
	}

	return value;
}
Exemplo n.º 26
0
/**
 * uploading function executed by the background" thread
 */
static void osm_traces_upload_thread ( OsmTracesInfo *oti, gpointer threaddata )
{
  /* Due to OSM limits, we have to enforce ele and time fields
   also don't upload invisible tracks */
  static GpxWritingOptions options = { TRUE, TRUE, FALSE, FALSE };
  FILE *file = NULL;
  gchar *filename = NULL;
  int fd;
  GError *error = NULL;
  int ret;

  g_assert(oti != NULL);

  /* Opening temporary file */
  fd = g_file_open_tmp("viking_osm_upload_XXXXXX.gpx", &filename, &error);
  if (fd < 0) {
    g_error(_("failed to open temporary file: %s"), strerror(errno));
    return;
  }
  g_clear_error(&error);
  g_debug("%s: temporary file = %s", __FUNCTION__, filename);

  /* Creating FILE* */
  file = fdopen(fd, "w");

  /* writing gpx file */
  if (oti->trk != NULL)
  {
    /* Upload only the selected track */
    if ( oti->anonymize_times )
    {
      VikTrack *trk = vik_track_copy(oti->trk, TRUE);
      vik_track_anonymize_times(trk);
      a_gpx_write_track_file(trk, file, &options);
      vik_track_free(trk);
    }
    else
      a_gpx_write_track_file(oti->trk, file, &options);
  }
  else
  {
    /* Upload the whole VikTrwLayer */
    a_gpx_write_file(oti->vtl, file, &options);
  }
  
  /* We can close the file */
  /* This also close the associated fd */
  fclose(file);
  file = NULL;

  /* finally, upload it */
  gint ans = osm_traces_upload_file(osm_user, osm_password, filename,
                   oti->name, oti->description, oti->tags, oti->vistype);

  //
  // Show result in statusbar or failure in dialog for user feedback
  //

  // Get current time to put into message to show when result was generated
  //  since need to show difference between operations (when displayed on statusbar)
  // NB If on dialog then don't need time.
  time_t timenow;
  struct tm* timeinfo;
  time ( &timenow );
  timeinfo = localtime ( &timenow );
  gchar timestr[80];
  // Compact time only - as days/date isn't very useful here
  strftime ( timestr, sizeof(timestr), "%X)", timeinfo );

  //
  // Test to see if window it was invoked on is still valid
  // Not sure if this test really works! (i.e. if the window was closed in the mean time)
  //
  if ( IS_VIK_WINDOW ((VikWindow *)VIK_GTK_WINDOW_FROM_LAYER(oti->vtl)) ) {
    gchar* msg;
    if ( ans == 0 ) {
      // Success
      msg = g_strdup_printf ( "%s (@%s)", _("Uploaded to OSM"), timestr );
    }
    // Use UPPER CASE for bad news :(
    else if ( ans < 0 ) {
      msg = g_strdup_printf ( "%s (@%s)", _("FAILED TO UPLOAD DATA TO OSM - CURL PROBLEM"), timestr );
    }
    else {
      msg = g_strdup_printf ( "%s : %s %d (@%s)", _("FAILED TO UPLOAD DATA TO OSM"), _("HTTP response code"), ans, timestr );
    }
    vik_window_statusbar_update ( (VikWindow*)VIK_GTK_WINDOW_FROM_LAYER(oti->vtl), msg, VIK_STATUSBAR_INFO );
    g_free (msg);
  }
  /* Removing temporary file */
  ret = g_unlink(filename);
  if (ret != 0) {
    g_critical(_("failed to unlink temporary file: %s"), strerror(errno));
  }
}
Exemplo n.º 27
0
void
gjstest_test_func_gjs_jsapi_util_error_throw(void)
{
    JSRuntime *runtime;
    JSContext *context;
    JSObject *global;
    jsval exc, value, previous;
    const char *s;

    /* create a runtime just to avoid tangling this test with all the
     * code surrounding how we create one normally in context.c
     */
    runtime = JS_NewRuntime(1024*1024 /* max bytes */);
    context = JS_NewContext(runtime, 8192);

    JS_BeginRequest(context);

    global = JS_NewObject(context, NULL, NULL, NULL);
    JS_SetGlobalObject(context, global);
    JS_InitStandardClasses(context, global);

    JS_SetErrorReporter(context, test_error_reporter);

    /* Test that we can throw */

    gjs_throw(context, "This is an exception %d", 42);

    g_assert(JS_IsExceptionPending(context));

    exc = JSVAL_VOID;
    JS_GetPendingException(context, &exc);
    g_assert(exc != JSVAL_VOID);

    value = JSVAL_VOID;
    JS_GetProperty(context, JSVAL_TO_OBJECT(exc), "message",
                   &value);

    g_assert(JSVAL_IS_STRING(value));

    /* JS_GetStringBytes() is broken for non-ASCII but that's OK here */
    s = JS_GetStringBytes(JSVAL_TO_STRING(value));
    g_assert(s != NULL);
    if (strcmp(s, "This is an exception 42") != 0) {
        g_error("Exception has wrong message '%s'",
                s);
    }

    /* keep this around before we clear it */
    previous = exc;
    JS_AddRoot(context, &previous);

    JS_ClearPendingException(context);

    g_assert(!JS_IsExceptionPending(context));

    /* Check that we don't overwrite a pending exception */
    JS_SetPendingException(context, previous);

    g_assert(JS_IsExceptionPending(context));

    gjs_throw(context, "Second different exception %s", "foo");

    g_assert(JS_IsExceptionPending(context));

    exc = JSVAL_VOID;
    JS_GetPendingException(context, &exc);
    g_assert(exc != JSVAL_VOID);
    g_assert(exc == previous);

    JS_RemoveRoot(context, &previous);

    JS_EndRequest(context);

    JS_DestroyContext(context);
    JS_DestroyRuntime(runtime);
    JS_ShutDown();
}
Exemplo n.º 28
0
static void
signal_monitor_generic_handler (SignalMonitor *m,
                                SignalName     signal,
                                GtkTreeModel  *model,
                                GtkTreeIter   *iter,
                                GtkTreePath   *path,
                                int           *new_order)
{
  Signal *s;

  if (g_queue_is_empty (m->queue))
    {
      gchar *path_str;

      path_str = gtk_tree_path_to_string (path);
      g_error ("Signal queue empty, got signal %s path %s",
               signal_name_to_string (signal), path_str);
      g_free (path_str);

      g_assert_not_reached ();
    }

  if (m->client != model)
    {
      g_error ("Model mismatch; expected %p, got %p",
               m->client, model);
      g_assert_not_reached ();
    }

  s = g_queue_peek_tail (m->queue);

#if 0
  /* For debugging: output signals that are coming in.  Leaks memory. */
  g_print ("signal=%s path=%s\n", signal_name_to_string (signal),
           gtk_tree_path_to_string (path));
#endif

  if (s->signal != signal ||
      (gtk_tree_path_get_depth (s->path) == 0 &&
       gtk_tree_path_get_depth (path) != 0) ||
      (gtk_tree_path_get_depth (s->path) != 0 &&
       gtk_tree_path_compare (s->path, path) != 0))
    {
      gchar *path_str, *s_path_str;

      s_path_str = gtk_tree_path_to_string (s->path);
      path_str = gtk_tree_path_to_string (path);

      g_error ("Signals don't match; expected signal %s path %s, got signal %s path %s",
               signal_name_to_string (s->signal), s_path_str,
               signal_name_to_string (signal), path_str);

      g_free (s_path_str);
      g_free (path_str);

      g_assert_not_reached ();
    }

  if (signal == ROWS_REORDERED && s->new_order != NULL)
    {
      int i, len;

      g_assert (new_order != NULL);

      len = gtk_tree_model_iter_n_children (model, iter);
      g_assert (s->len == len);

      for (i = 0; i < len; i++)
        g_assert (s->new_order[i] == new_order[i]);
    }

  s = g_queue_pop_tail (m->queue);

  signal_free (s);
}
Exemplo n.º 29
0
static void
run_position_expression_tests (void)
{
#if 0
  int i;
  MetaPositionExprEnv env;

  i = 0;
  while (i < (int) G_N_ELEMENTS (position_expression_tests))
    {
      GError *err;
      gboolean retval;
      const PositionExpressionTest *test;
      PosToken *tokens;
      int n_tokens;
      int x, y;

      test = &position_expression_tests[i];

      if (g_getenv ("META_PRINT_TESTS") != NULL)
        g_print ("Test expression: \"%s\" expecting x = %d y = %d",
                 test->expr, test->expected_x, test->expected_y);

      err = NULL;
      
      env.rect = meta_rect (test->rect.x, test->rect.y,
                            test->rect.width, test->rect.height);
      env.object_width = -1;
      env.object_height = -1;
      env.left_width = 0;
      env.right_width = 0;
      env.top_height = 0;
      env.bottom_height = 0;
      env.title_width = 5;
      env.title_height = 5;
      env.icon_width = 32;
      env.icon_height = 32;
      env.mini_icon_width = 16;
      env.mini_icon_height = 16;
      env.theme = NULL;

      if (err == NULL)
        {
          retval = meta_parse_position_expression (tokens, n_tokens,
                                                   &env,
                                                   &x, &y,
                                                   &err);
        }

      if (retval && err)
        g_error (_("position expression test returned TRUE but set error"));
      if (!retval && err == NULL)
        g_error (_("position expression test returned FALSE but didn't set error"));
      if (((int) test->expected_error) != NO_ERROR)
        {
          if (err == NULL)
            g_error (_("Error was expected but none given"));
          if (err->code != (int) test->expected_error)
            g_error (_("Error %d was expected but %d given"),
                     test->expected_error, err->code);
        }
      else
        {
          if (err)
            g_error (_("Error not expected but one was returned: %s"),
                     err->message);

          if (x != test->expected_x)
            g_error (_("x value was %d, %d was expected"), x, test->expected_x);

          if (y != test->expected_y)
            g_error (_("y value was %d, %d was expected"), y, test->expected_y);
        }

      if (err)
        g_error_free (err);

      meta_pos_tokens_free (tokens, n_tokens);
      ++i;
    }
#endif
}
Exemplo n.º 30
0
static void
preview_update (GimpPreview *preview)
{
  GimpDrawable *drawable;
  GimpPixelRgn  src_rgn;        /* Source image region */
  guchar       *src_ptr;        /* Current source pixel */
  guchar       *dst_ptr;        /* Current destination pixel */
  intneg       *neg_ptr;        /* Current negative pixel */
  gint          i;              /* Looping var */
  gint          y;              /* Current location in image */
  gint          width;          /* Byte width of the image */
  gint          x1, y1;
  gint          preview_width, preview_height;
  guchar       *preview_src, *preview_dst;
  intneg       *preview_neg;
  gint          img_bpp;        /* Bytes-per-pixel in image */

  void          (*filter)(int, guchar *, guchar *, intneg *, intneg *, intneg *);

  filter = NULL;

  compute_luts();

  gimp_preview_get_position (preview, &x1, &y1);
  gimp_preview_get_size (preview, &preview_width, &preview_height);

  drawable =
    gimp_drawable_preview_get_drawable (GIMP_DRAWABLE_PREVIEW (preview));

  img_bpp = gimp_drawable_bpp (drawable->drawable_id);


  preview_src = g_new (guchar, preview_width * preview_height * img_bpp);
  preview_neg = g_new (intneg, preview_width * preview_height * img_bpp);
  preview_dst = g_new (guchar, preview_width * preview_height * img_bpp);

  gimp_pixel_rgn_init (&src_rgn, drawable,
                       x1, y1, preview_width, preview_height,
                       FALSE, FALSE);

  width = preview_width * img_bpp;

  /*
   * Load the preview area...
   */

  gimp_pixel_rgn_get_rect (&src_rgn, preview_src, x1, y1,
                           preview_width, preview_height);

  for (i = width * preview_height, src_ptr = preview_src, neg_ptr = preview_neg;
       i > 0;
       i --)
    *neg_ptr++ = neg_lut[*src_ptr++];

  /*
   * Select the filter...
   */

  switch (img_bpp)
    {
    case 1:
      filter = gray_filter;
      break;
    case 2:
      filter = graya_filter;
      break;
    case 3:
      filter = rgb_filter;
      break;
    case 4:
      filter = rgba_filter;
      break;
    default:
      g_error ("Programmer stupidity error: img_bpp is %d\n",
               img_bpp);
    }

  /*
   * Sharpen...
   */

  memcpy (preview_dst, preview_src, width);
  memcpy (preview_dst + width * (preview_height - 1),
          preview_src + width * (preview_height - 1),
          width);

  for (y = preview_height - 2, src_ptr = preview_src + width,
           neg_ptr = preview_neg + width + img_bpp,
           dst_ptr = preview_dst + width;
       y > 0;
       y --, src_ptr += width, neg_ptr += width, dst_ptr += width)
    (*filter)(preview_width, src_ptr, dst_ptr, neg_ptr - width,
              neg_ptr, neg_ptr + width);

  gimp_preview_draw_buffer (preview, preview_dst, preview_width * img_bpp);

  g_free (preview_src);
  g_free (preview_neg);
  g_free (preview_dst);
}