void init_tray_appindicator()
{
  g_timeout_add(200, tray_appindicator_create, NULL);
} 
void MediaPlayerPrivateGStreamerBase::muteChanged()
{
    if (m_muteTimerHandler)
        g_source_remove(m_muteTimerHandler);
    m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
}
示例#3
0
int main(int argc, char *argv[])
{
    unsigned int i;
    int opt;
    int help = 0;
    int console = 0;
    char port_name[32];
    pthread_t dt;
#ifdef HAVE_LASH
    lash_args_t *lash_args = lash_extract_args(&argc, &argv);
     lash_event_t *event;
#endif

    auto_begin_threshold = db2lin(DEFAULT_AUTO_BEGIN_THRESHOLD);
    auto_end_threshold = db2lin(DEFAULT_AUTO_END_THRESHOLD);

    while ((opt = getopt(argc, argv, "hic:t:n:p:f:sab:e:T:o:")) != -1) {
	switch (opt) {
	case 'h':
	    help = 1;
	    break;
	case 'i':
	    console = 1;
	    break;
	case 'c':
	    num_ports = atoi(optarg);
	    DEBUG(1, "ports: %d\n", num_ports);
	    break;
	case 't':
	    buf_length = atoi(optarg);
	    DEBUG(1, "buffer: %ds\n", buf_length);
	    break;
	case 'n':
	    client_name = optarg;
	    DEBUG(1, "client name: %s\n", client_name);
	    break;
	case 'p':
	    prefix = optarg;
	    DEBUG(1, "prefix: %s\n", prefix);
	    break;
	case 'f':
	    format_name = optarg;
	    break;
	case 's':
	    safe_filename = 1;
	    break;
	case 'a':
	    auto_record = 1;
	    break;
	case 'b':
	    auto_begin_threshold = db2lin(atof(optarg));
	    break;
	case 'e':
	    auto_end_threshold = db2lin(atof(optarg));
	    break;
	case 'T':
	    auto_end_time = atoi(optarg);
	    break;
	case 'o':
#ifdef HAVE_LIBLO
	    osc_port = optarg;
#endif
	    break;
	default:
	    num_ports = 0;
	    break;
	}
    }

    if (optind != argc) {
	num_ports = argc - optind;
    }

    if (num_ports < 1 || num_ports > MAX_PORTS || help) {
	fprintf(stderr, "Usage %s: [-h] [-i] [-c channels] [-n jack-name]\n\t"
			"[-t buffer-length] [-p file prefix] [-f format]\n\t"
			"[-a] [-b begin-threshold] [-e end-threshold] [-T end-time]\n\t"
			"[port-name ...]\n\n", argv[0]);
	fprintf(stderr, "\t-h\tshow this help\n");
	fprintf(stderr, "\t-i\tinteractive mode (console instead of X11) also enabled\n\t\tif DISPLAY is unset\n");
	fprintf(stderr, "\t-c\tspecify number of recording channels\n");
	fprintf(stderr, "\t-n\tspecify the JACK name timemachine will use\n");
	fprintf(stderr, "\t-t\tspecify the pre-recording buffer length\n");
	fprintf(stderr, "\t-p\tspecify the saved file prefix, may include path\n");
	fprintf(stderr, "\t-s\tuse safer characters in filename (windows compatibility)\n");
	fprintf(stderr, "\t-f\tspecify the saved file format\n");
	fprintf(stderr, "\t-a\tenable automatic sound-triggered recording\n");
	fprintf(stderr, "\t-b\tspecify threshold above which automatic recording will begin\n");
	fprintf(stderr, "\t-e\tspecify threshold below which automatic recording will end\n");
	fprintf(stderr, "\t-T\tspecify silence length before automatic recording ends\n");
#ifdef HAVE_LIBLO
	fprintf(stderr, "\t-o\tspecify the OSC port timemachine will listen on\n");
#endif
	fprintf(stderr, "\n");
	fprintf(stderr, "\tchannels must be in the range 1-8, default %d\n",
			DEFAULT_NUM_PORTS);
	fprintf(stderr, "\tjack-name, default \"%s\"\n", DEFAULT_CLIENT_NAME);
	fprintf(stderr, "\tfile-prefix, default \"%s\"\n", DEFAULT_PREFIX);
	fprintf(stderr, "\tbuffer-length, default %d secs\n", DEFAULT_BUF_LENGTH);
	fprintf(stderr, "\tformat, default '%s', options: wav, w64\n", DEFAULT_FORMAT);
	fprintf(stderr, "\tbegin-threshold, default %.1f dB\n", DEFAULT_AUTO_BEGIN_THRESHOLD);
	fprintf(stderr, "\tend-threshold, default %.1f dB\n", DEFAULT_AUTO_END_THRESHOLD);
	fprintf(stderr, "\tend-time, default %d secs\n", DEFAULT_AUTO_END_TIME);
#ifdef HAVE_LIBLO
	fprintf(stderr, "\tosc-port, default %s\n", DEFAULT_OSC_PORT);
#endif
	fprintf(stderr, "\n");
	fprintf(stderr, "specifying port names to connect to on the command line overrides -c\n\n");
	exit(1);
    }

    if (!strcasecmp(format_name, "wav")) {
	format_sf = SF_FORMAT_WAV | SF_FORMAT_FLOAT;
    }
#ifdef HAVE_W64
    if (!strcasecmp(format_name, "w64")) {
	format_sf = SF_FORMAT_W64 | SF_FORMAT_FLOAT;
    }
#endif

    if (format_sf == 0) {
	fprintf(stderr, "Unknown format '%s'\n", format_name);
    }

    /* Register with jack */
    if ((client = jack_client_open(client_name, 0, NULL)) == 0) {
	DEBUG(0, "jack server not running?\n");
	exit(1);
    }
    DEBUG(1, "registering as %s\n", client_name);

    process_init(buf_length);

#ifdef HAVE_LASH
    lash_client = lash_init (lash_args, "TimeMachine",
                     0, /* would be LASH_Config_Data_Set etc. */
                     LASH_PROTOCOL (2,0));
    if (!lash_client) {
	DEBUG(1, "could not initialise LASH\n");
    }
    event = lash_event_new_with_type(LASH_Client_Name);
    lash_event_set_string(event, client_name);
    lash_send_event(lash_client, event);
#endif

    jack_set_process_callback(client, process, 0);

    if (jack_activate(client)) {
	DEBUG(0, "cannot activate JACK client");
	exit(1);
    }
#ifdef HAVE_LASH
    lash_jack_client_name(lash_client, client_name);
#endif

    /* Create the jack ports */
    for (i = 0; i < num_ports; i++) {
	jack_port_t *port;

	snprintf(port_name, 31, "in_%d", i + 1);
	ports[i] = jack_port_register(client, port_name,
				      JACK_DEFAULT_AUDIO_TYPE,
				      JackPortIsInput, 0);
	if (optind != argc) {
	    port = jack_port_by_name(client, argv[optind+i]);
	    if (port == NULL) {
		fprintf(stderr, "Can't find port '%s'\n", port_name);
		continue;
	    }
	    if (jack_connect(client, argv[optind+i], jack_port_name(ports[i]))) {
		fprintf(stderr, "Cannot connect port '%s' to '%s'\n",
			argv[optind+i], jack_port_name(ports[i]));
	    }
	}
    }

    /* Start the disk thread */
    pthread_create(&dt, NULL, (void *)&writer_thread, NULL);

#ifdef HAVE_LIBREADLINE
    if (console || !getenv("DISPLAY") || getenv("DISPLAY")[0] == '\0') {
#ifdef HAVE_LIBLO
      lo_server_thread st = lo_server_thread_new(osc_port, NULL);
      if (st) {
	  lo_server_thread_add_method(st, "/start", "", osc_handler_nox, (void *)1);
	  lo_server_thread_add_method(st, "/stop", "", osc_handler_nox, (void *)0);
	  lo_server_thread_start(st);
	  printf("Listening for OSC requests on osc.udp://localhost:%s\n",
	    osc_port);
      }
#endif

      int done = 0;
      while (!done) {
	char *line = readline("TimeMachine> ");
	if (!line) {
	  printf("EOF\n");
	  break;
	}
	if (line && *line) {
	  add_history(line);
	  if (strncmp(line, "q", 1) == 0) done = 1;
	  else if (strncmp(line, "start", 3) == 0) recording_start();
	  else if (strncmp(line, "stop", 3) == 0) recording_stop();
	  else if (strncmp(line, "help", 3) == 0) {
	    printf("Commands: start stop\n");
	  } else {
	    printf("Unknown command\n");
          }
	}
	free(line);
      }
    } else
#endif
    {
      gtk_init(&argc, &argv);

      add_pixmap_directory(PACKAGE_DATA_DIR "/" PACKAGE "/pixmaps");
      add_pixmap_directory("pixmaps");
      add_pixmap_directory("../pixmaps");

      img_on = create_pixbuf("on.png");
      img_off = create_pixbuf("off.png");
      img_busy = create_pixbuf("busy.png");
      icon_on = create_pixbuf("on-icon.png");
      icon_off = create_pixbuf("off-icon.png");

      main_window = create_window(client_name);
      gtk_window_set_icon(GTK_WINDOW(main_window), icon_off);
      gtk_widget_show(main_window);

      bind_meters();
      g_timeout_add(100, meter_tick, NULL);

#ifdef HAVE_LIBLO
    lo_server_thread st = lo_server_thread_new(osc_port, NULL);
    if (st) {
	lo_server_thread_add_method(st, "/start", "", osc_handler, (void *)1);
	lo_server_thread_add_method(st, "/stop", "", osc_handler, (void *)0);
	lo_server_thread_start(st);
	printf("Listening for OSC requests on osc.udp://localhost:%s\n",
	       osc_port);
    }
#endif

#ifdef HAVE_LASH
      gtk_idle_add(idle_cb, lash_client);
#endif

      gtk_main();
    }

    cleanup();

    /* We can't ever get here, but it keeps gcc quiet */
    return 0;
}
示例#4
0
static ssize_t
crm_cs_flush(gpointer data)
{
    int sent = 0;
    ssize_t rc = 0;
    int queue_len = 0;
    static unsigned int last_sent = 0;
    cpg_handle_t *handle = (cpg_handle_t *)data;

    if (*handle == 0) {
        crm_trace("Connection is dead");
        return pcmk_ok;
    }

    queue_len = g_list_length(cs_message_queue);
    if ((queue_len % 1000) == 0 && queue_len > 1) {
        crm_err("CPG queue has grown to %d", queue_len);

    } else if (queue_len == CS_SEND_MAX) {
        crm_warn("CPG queue has grown to %d", queue_len);
    }

    if (cs_message_timer) {
        /* There is already a timer, wait until it goes off */
        crm_trace("Timer active %d", cs_message_timer);
        return pcmk_ok;
    }

    while (cs_message_queue && sent < CS_SEND_MAX) {
        struct iovec *iov = cs_message_queue->data;

        errno = 0;
        rc = cpg_mcast_joined(*handle, CPG_TYPE_AGREED, iov, 1);

        if (rc != CS_OK) {
            break;
        }

        sent++;
        last_sent++;
        crm_trace("CPG message sent, size=%d", iov->iov_len);

        cs_message_queue = g_list_remove(cs_message_queue, iov);
        free(iov->iov_base);
        free(iov);
    }

    queue_len -= sent;
    if (sent > 1 || cs_message_queue) {
        crm_info("Sent %d CPG messages  (%d remaining, last=%u): %s (%d)",
                 sent, queue_len, last_sent, ais_error2text(rc), rc);
    } else {
        crm_trace("Sent %d CPG messages  (%d remaining, last=%u): %s (%d)",
                  sent, queue_len, last_sent, ais_error2text(rc), rc);
    }

    if (cs_message_queue) {
        uint32_t delay_ms = 100;
        if(rc != CS_OK) {
            /* Proportionally more if sending failed but cap at 1s */
            delay_ms = QB_MIN(1000, CS_SEND_MAX + (10 * queue_len));
        }
        cs_message_timer = g_timeout_add(delay_ms, crm_cs_flush_cb, data);
    }

    return rc;
}
示例#5
0
int
main (int argc, char *argv[])
{
	PortableServer_ObjectId *objid;
	PortableServer_POA poa;
	GOptionContext *ctx;
	GOptionGroup *goption_group;
	GError *error = NULL;
        GMainLoop *loop;

	CORBA_Environment ev;
	CORBA_ORB orb;
	GSList *reg_env = NULL;

	signal (SIGINT, do_exit);
	signal (SIGTERM, do_exit);

        g_thread_init (NULL);

	CORBA_exception_init (&ev);
	orb = bonobo_activation_init (argc, argv);

	g_set_prgname ("bonobo-activation-empty-server");
	ctx = g_option_context_new (NULL);
	goption_group = bonobo_activation_get_goption_group ();
	g_option_context_set_main_group (ctx, goption_group);
	if (!g_option_context_parse (ctx, &argc, &argv, &error)) {
		g_printerr ("%s\n", error->message);
		g_error_free (error);
		exit (1);
	}
	g_option_context_free (ctx);

	POA_Empty__init (&poa_empty_servant, &ev);

	poa = (PortableServer_POA)
		CORBA_ORB_resolve_initial_references (orb, "RootPOA", &ev);
	objid = PortableServer_POA_activate_object (poa, &poa_empty_servant, &ev);

	empty_client = PortableServer_POA_servant_to_reference (poa,
								&poa_empty_servant,
								&ev);
	if (!empty_client) {
		printf ("Cannot get objref\n");
		return 1;
	}

#ifndef G_OS_WIN32
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "DISPLAY", getenv ("DISPLAY"));
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "SESSION_MANAGER", getenv ("SESSION_MANAGER"));
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "AUDIODEV", getenv ("AUDIODEV"));
#endif
	reg_env = bonobo_activation_registration_env_set (
			reg_env, "LANG", getenv ("LANG"));

        /*
         * NB. It is imperative to register the server that is being
         * requested last - or we can still race in the activation daemon.
         */
	bonobo_activation_register_active_server ("OAFIID:Empty2:19991025", empty_client, reg_env);
        g_usleep (500000); /* 1/2 sec */
	bonobo_activation_register_active_server ("OAFIID:Empty:19991025", empty_client, reg_env);

	bonobo_activation_registration_env_free (reg_env);

	PortableServer_POAManager_activate
		(PortableServer_POA__get_the_POAManager (poa, &ev), &ev);

        /* run the CORBA main loop for a couple of seconds then quit */
        loop = g_main_loop_new (NULL, FALSE);
        g_timeout_add (1000, (GSourceFunc) g_main_loop_quit, loop);
        g_main_loop_run (loop);

	bonobo_activation_active_server_unregister ("OAFIID:Empty:19991025", empty_client);
	bonobo_activation_active_server_unregister ("OAFIID:Empty2:19991025", empty_client);

	PortableServer_POA_deactivate_object (poa, objid, &ev);

	return 0;
}
示例#6
0
文件: files.c 项目: Jeija/gtkterm
void ecriture(gpointer data, gint source)
{
	static gchar buffer[BUFFER_EMISSION];
	static gchar *current_buffer;
	static gint bytes_to_write;
	gint bytes_written;
	gchar *car;

	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(ProgressBar), (gfloat)car_written/(gfloat)nb_car );

	if(car_written < nb_car)
	{
		/* Read the file only if buffer totally sent or if buffer empty */
		if(current_buffer_position == bytes_read)
		{
			bytes_read = read(Fichier, buffer, BUFFER_EMISSION);

			current_buffer_position = 0;
			current_buffer = buffer;
			bytes_to_write = bytes_read;
		}

		if(current_buffer == NULL)
		{
			/* something went wrong... */
			g_free(str);
			str = g_strdup_printf(_("Error sending file\n"));
			show_message(str, MSG_ERR);
			close_all();
			return;
		}

		car = current_buffer;

		if(config.delai != 0 || config.car != -1)
		{
			/* search for next LF */
			bytes_to_write = current_buffer_position;
			while(*car != LINE_FEED && bytes_to_write < bytes_read)
			{
				car++;
				bytes_to_write++;
			}
			if(*car == LINE_FEED)
				bytes_to_write++;
		}

		/* write to serial port */
		bytes_written = send_serial(current_buffer, bytes_to_write - current_buffer_position);

		if(bytes_written == -1)
		{
			/* Problem while writing, stop file transfer */
			g_free(str);
			str = g_strdup_printf(_("Error sending file: %s\n"), strerror(errno));
			show_message(str, MSG_ERR);
			close_all();
			return;
		}

		car_written += bytes_written;
		current_buffer_position += bytes_written;
		current_buffer += bytes_written;

		gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(ProgressBar), (gfloat)car_written/(gfloat)nb_car );

		if(config.delai != 0 && *car == LINE_FEED)
		{
			remove_input();
			g_timeout_add(config.delai, (GSourceFunc)timer, NULL);
			waiting_for_timer = TRUE;
		}
		else if(config.car != -1 && *car == LINE_FEED)
		{
			remove_input();
			waiting_for_char = TRUE;
		}
	}
	else
	{
		close_all();
		return;
	}
	return;
}
示例#7
0
gboolean qaul_configure(gpointer data)
{
    // initialize qaul library
    if(qaulConfigureCounter == 0)
    {
        // everything is fine
        Qaullib_ConfigStart();
        qaulConfigureCounter = 3;
    }

    // check authorization
    if(qaulConfigureCounter == 10)
    {
        // nothing to be done here
    	qaulConfigureCounter = 20;
    }

    // TODO: enable networking

    // get network interface
    if(qaulConfigureCounter == 20)
    {
        // check if interface has been configured manually
    	if(Qaullib_GetInterfaceManual())
    	{
    		printf("[configure] interface manually configured\n");
    		if(qaul_network_device_get_by_interface(Qaullib_GetInterface(), network_dbus_connection, &network_device))
    			network_interface_found = 1;
    		else
    			printf("[configure] manually configured interface \"%s\" not found\n", Qaullib_GetInterface());
    	}
    	// find wifi interface
    	else
    	{
    		if(qaul_network_find_wifi(network_dbus_connection, &network_device))
    			network_interface_found = 1;
    		else
    			printf("[configure] no wifi interface found\n");
    	}

    	// TODO: enable wifi

    	qaulConfigureCounter = 21;
    }

    // configure network interface
    if(qaulConfigureCounter == 21)
    {
        if(network_interface_found)
        {
        	printf("[configure] network interface %s\n", network_device.interface);

        	// get network configuration
        	strncpy(network_settings.ipv4_address, Qaullib_GetIP(), sizeof(network_settings.ipv4_address));
        	Qaullib_GetConfString("net.gateway", network_settings.ipv4_gateway);
        	network_settings.ipv4_netmask = Qaullib_GetConfInt("net.mask");
        	strncpy(network_settings.ipv4_dns1, "5.45.96.220", sizeof(network_settings.ipv4_dns1));
        	strncpy(network_settings.ipv4_dns2, "185.82.22.133", sizeof(network_settings.ipv4_dns2));
        	network_settings.wifi_channel = Qaullib_GetConfInt("wifi.channel");
        	Qaullib_GetConfString("wifi.ssid", network_settings.wifi_ssid);

        	// add network configuration
        	if(qaul_network_settings_add(network_dbus_connection, &network_settings, &network_device))
        	{
        		printf("[configure] network connection setting added: %s\n", network_settings.dbus_connection_path);

        		// activate configuration
        		if(qaul_network_connection_activate(network_dbus_connection, &network_settings, &network_device))
        			printf("[configure] network connection activated: %s\n", network_settings.dbus_active_connection_path);
        		else
        			printf("[configure] network connection not activated\n");
        	}
        	else
        		printf("[configure] network connection settings not added\n");
        }

    	qaulConfigureCounter = 29;
    }

    // check if username is set
    if(qaulConfigureCounter == 30)
    {
        if(Qaullib_ExistsUsername())
			qaulConfigureCounter = 40;
        else
        {
            // wait
            qaulConfigureCounter--;
        }
    }

    // start olsrd
    if(qaulConfigureCounter == 40)
    {
        printf("[configure] start olsrd \n");

        // start olsrd
        qaul_olsrdStart();

        qaulConfigureCounter = 44;
    }

    // connect ipc
    if(qaulConfigureCounter == 45)
    {
        printf("[configure] connect ipc \n");
        Qaullib_IpcConnect();
        qaulConfigureCounter = 46;
    }

    // start captive portal
    if(qaulConfigureCounter == 46)
    {
    	printf("[configure] start captive portal \n");
    	Qaullib_SetConfVoIP();
        Qaullib_UDP_StartServer();
        Qaullib_CaptiveStart();

        // configure firewall
        qaul_startPortForwarding();

        qaulConfigureCounter = 50;
    }

    // start timers
    if(qaulConfigureCounter == 50)
    {
        printf("[configure] timers \n");

		// start timers
		qaulTimerEvents = g_timeout_add(10, qaul_timerSocket, NULL);
		qaulTimerSockets = g_timeout_add(100, qaul_timerEvent, NULL);
		qaulTimerTopology = g_timeout_add(5000, qaul_timerTopology, NULL);

        Qaullib_ConfigurationFinished();

        qaulConfigureCounter = 60;
    }

    // end configuration
	if(qaulConfigureCounter == 60)
	{
		printf("[configure] finished \n");
		return FALSE;
	}

	qaulConfigureCounter++;
	return TRUE;
}
示例#8
0
void irc_commands_init(void)
{
	tmpstr = g_string_new(NULL);

	settings_add_str("misc", "quit_message", "leaving");
	settings_add_str("misc", "part_message", "");
	settings_add_int("misc", "knockout_time", 300);
	settings_add_str("misc", "wall_format", "[Wall/$0] $1-");

	knockout_tag = g_timeout_add(KNOCKOUT_TIMECHECK, (GSourceFunc) knockout_timeout, NULL);

	signal_add("server connected", (SIGNAL_FUNC) sig_connected);
	command_bind("server", NULL, (SIGNAL_FUNC) cmd_server);
	command_bind("connect", NULL, (SIGNAL_FUNC) cmd_connect);
	command_bind("notice", NULL, (SIGNAL_FUNC) cmd_notice);
	command_bind("ctcp", NULL, (SIGNAL_FUNC) cmd_ctcp);
	command_bind("nctcp", NULL, (SIGNAL_FUNC) cmd_nctcp);
	command_bind("part", NULL, (SIGNAL_FUNC) cmd_part);
	command_bind("kick", NULL, (SIGNAL_FUNC) cmd_kick);
	command_bind("topic", NULL, (SIGNAL_FUNC) cmd_topic);
	command_bind("invite", NULL, (SIGNAL_FUNC) cmd_invite);
	command_bind("list", NULL, (SIGNAL_FUNC) cmd_list);
	command_bind("who", NULL, (SIGNAL_FUNC) cmd_who);
	command_bind("names", NULL, (SIGNAL_FUNC) cmd_names);
	command_bind("nick", NULL, (SIGNAL_FUNC) cmd_nick);
	/* SYNTAX: NOTE <command> [&<password>] [+|-<flags>] [<arguments>] */
	command_bind("note", NULL, (SIGNAL_FUNC) command_self);
	command_bind("whois", NULL, (SIGNAL_FUNC) cmd_whois);
	command_bind("whowas", NULL, (SIGNAL_FUNC) cmd_whowas);
	command_bind("ping", NULL, (SIGNAL_FUNC) cmd_ping);
	/* SYNTAX: KILL <nick> <reason> */
	command_bind("kill", NULL, (SIGNAL_FUNC) command_2self);
	command_bind("away", NULL, (SIGNAL_FUNC) cmd_away);
	/* SYNTAX: ISON <nicks> */
	command_bind("ison", NULL, (SIGNAL_FUNC) command_1self);
	/* SYNTAX: ADMIN [<server>|<nickname>] */
	command_bind("admin", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: INFO [<server>] */
	command_bind("info", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: LINKS [[<server>] <mask>] */
	command_bind("links", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: LUSERS [<server mask> [<remote server>]] */
	command_bind("lusers", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: MAP */
	command_bind("map", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: MOTD [<server>|<nick>] */
	command_bind("motd", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: REHASH */
	command_bind("rehash", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: STATS <type> [<server>] */
	command_bind("stats", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: TIME [<server>|<nick>] */
	command_bind("time", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: TRACE [<server>|<nick>] */
	command_bind("trace", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: VERSION [<server>|<nick>] */
	command_bind("version", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: SERVLIST [<server mask>] */
	command_bind("servlist", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: SILENCE [[+|-]<[email protected]>]
	           SILENCE [<nick>] */
	command_bind("silence", NULL, (SIGNAL_FUNC) command_self);
	command_bind("unsilence", NULL, (SIGNAL_FUNC) cmd_unsilence);
	command_bind("sconnect", NULL, (SIGNAL_FUNC) cmd_sconnect);
	/* SYNTAX: SQUERY <service> [<commands>] */
	command_bind("squery", NULL, (SIGNAL_FUNC) command_2self);
	command_bind("deop", NULL, (SIGNAL_FUNC) cmd_deop);
	/* SYNTAX: DIE */
	command_bind("die", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: HASH */
	command_bind("hash", NULL, (SIGNAL_FUNC) command_self);
	command_bind("oper", NULL, (SIGNAL_FUNC) cmd_oper);
	/* SYNTAX: RESTART */
	command_bind("restart", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: RPING <server> */
	command_bind("rping", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: SQUIT <server>|<mask> <reason> */
	command_bind("squit", NULL, (SIGNAL_FUNC) command_2self);
	/* SYNTAX: UPING <server> */
	command_bind("uping", NULL, (SIGNAL_FUNC) command_self);
	/* SYNTAX: USERHOST <nicks> */
	command_bind("userhost", NULL, (SIGNAL_FUNC) command_self);
	command_bind("quote", NULL, (SIGNAL_FUNC) cmd_quote);
	command_bind("wall", NULL, (SIGNAL_FUNC) cmd_wall);
	command_bind("wait", NULL, (SIGNAL_FUNC) cmd_wait);
	/* SYNTAX: WALLOPS <message> */
	command_bind("wallops", NULL, (SIGNAL_FUNC) command_1self);
	/* SYNTAX: WALLCHOPS <channel> <message> */
	command_bind("wallchops", NULL, (SIGNAL_FUNC) command_2self);
	command_bind("cycle", NULL, (SIGNAL_FUNC) cmd_cycle);
	command_bind("kickban", NULL, (SIGNAL_FUNC) cmd_kickban);
	command_bind("knockout", NULL, (SIGNAL_FUNC) cmd_knockout);

	signal_add("channel destroyed", (SIGNAL_FUNC) sig_channel_destroyed);
	signal_add("server disconnected", (SIGNAL_FUNC) sig_server_disconnected);
	signal_add("nickchange over", (SIGNAL_FUNC) sig_nickchange_over);
	signal_add("whois not found", (SIGNAL_FUNC) sig_whois_not_found);
	signal_add("whois event", (SIGNAL_FUNC) event_whois);
	signal_add("whowas event", (SIGNAL_FUNC) event_whowas);

	command_set_options("connect", "+ircnet +host");
	command_set_options("topic", "delete");
	command_set_options("list", "yes");
	command_set_options("away", "one all");
	command_set_options("whois", "yes");
}
示例#9
0
static gboolean mail_filtering_hook(gpointer source, gpointer data)
{
	MailFilteringData *mail_filtering_data = (MailFilteringData *) source;
	MsgInfo *msginfo = mail_filtering_data->msginfo;
	gboolean is_spam = FALSE, error = FALSE;
	static gboolean warned_error = FALSE;
	FILE *fp = NULL;
	int pid = 0;
	int status;

	/* SPAMASSASSIN_DISABLED : keep test for compatibility purpose */
	if (!config.enable || config.transport == SPAMASSASSIN_DISABLED) {
		log_warning(LOG_PROTOCOL, _("SpamAssassin plugin is disabled by its preferences.\n"));
		return FALSE;
	}
	debug_print("Filtering message %d\n", msginfo->msgnum);
	if (message_callback != NULL)
		message_callback(_("SpamAssassin: filtering message..."));

	if ((fp = procmsg_open_message(msginfo)) == NULL) {
		debug_print("failed to open message file\n");
		return FALSE;
	}

	if (config.whitelist_ab) {
		gchar *ab_folderpath;
		gboolean whitelisted = FALSE;

		if (*config.whitelist_ab_folder == '\0' ||
			strcasecmp(config.whitelist_ab_folder, "Any") == 0) {
			/* match the whole addressbook */
			ab_folderpath = NULL;
		} else {
			/* match the specific book/folder of the addressbook */
			ab_folderpath = config.whitelist_ab_folder;
		}

		start_address_completion(ab_folderpath);
		if (msginfo->from && 
		    sa_found_in_addressbook(msginfo->from))
				whitelisted = TRUE;
		end_address_completion();
		
		if (whitelisted) {
			debug_print("message is ham (whitelisted)\n");
			fclose(fp);
			return FALSE;
		}
	}
	pid = fork();
	if (pid == 0) {
		_exit(msg_is_spam(fp));
	} else {
		gint running = 0;

		running |= CHILD_RUNNING;

		g_timeout_add(50, timeout_func, &running);
		running |= TIMEOUT_RUNNING;

		while(running & CHILD_RUNNING) {
			int ret;

			ret = waitpid(pid, &status, WNOHANG);
			if (ret == pid) {
				if (WIFEXITED(status)) {
					MsgStatus result = MSG_IS_HAM;
					running &= ~CHILD_RUNNING;
					result = WEXITSTATUS(status);
    					is_spam = (result == MSG_IS_SPAM) ? TRUE : FALSE;
					error = (result == MSG_FILTERING_ERROR);
				}
			} if (ret < 0) {
				running &= ~CHILD_RUNNING;
			} /* ret == 0 continue */
	    
			g_main_context_iteration(NULL, TRUE);
    		}

		while (running & TIMEOUT_RUNNING)
			g_main_context_iteration(NULL, TRUE);
	}

	fclose(fp);

	if (is_spam) {
		debug_print("message is spam\n");
		procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
		if (config.receive_spam) {
			FolderItem *save_folder = NULL;

			if ((!config.save_folder) ||
			    (config.save_folder[0] == '\0') ||
			    ((save_folder = folder_find_item_from_identifier(config.save_folder)) == NULL)) {
			 	if (mail_filtering_data->account && mail_filtering_data->account->set_trash_folder) {
					save_folder = folder_find_item_from_identifier(
						mail_filtering_data->account->trash_folder);
					if (save_folder)
						debug_print("found trash folder from account's advanced settings\n");
				}
				if (save_folder == NULL && mail_filtering_data->account &&
				    mail_filtering_data->account->folder) {
				    	save_folder = mail_filtering_data->account->folder->trash;
					if (save_folder)
						debug_print("found trash folder from account's trash\n");
				}
				if (save_folder == NULL && mail_filtering_data->account &&
				    !mail_filtering_data->account->folder)  {
					if (mail_filtering_data->account->inbox) {
						FolderItem *item = folder_find_item_from_identifier(
							mail_filtering_data->account->inbox);
						if (item && item->folder->trash) {
							save_folder = item->folder->trash;
							debug_print("found trash folder from account's inbox\n");
						}
					} 
					if (!save_folder && mail_filtering_data->account->local_inbox) {
						FolderItem *item = folder_find_item_from_identifier(
							mail_filtering_data->account->local_inbox);
						if (item && item->folder->trash) {
							save_folder = item->folder->trash;
							debug_print("found trash folder from account's local_inbox\n");
						}
					}
				}
				if (save_folder == NULL) {
					debug_print("using default trash folder\n");
					save_folder = folder_get_default_trash();
				}
			}
			if (config.mark_as_read)
				procmsg_msginfo_unset_flags(msginfo, ~0, 0);
			procmsg_msginfo_set_flags(msginfo, MSG_SPAM, 0);
			msginfo->filter_op = IS_MOVE;
			msginfo->to_filter_folder = save_folder;
		} else {
			folder_item_remove_msg(msginfo->folder, msginfo->msgnum);
		}

		return TRUE;
	} else {
		debug_print("message is ham\n");
		procmsg_msginfo_unset_flags(msginfo, MSG_SPAM, 0);
	}
	
	if (error) {
		gchar *msg = _("The SpamAssassin plugin couldn't filter "
					   "a message. The probable cause of the error "
					   "is an unreachable spamd daemon. Please make "
					   "sure spamd is running and accessible.");
		if (!prefs_common.no_recv_err_panel) {
			if (!warned_error) {
				alertpanel_error("%s", msg);
			}
			warned_error = TRUE;
		} else {
			log_error(LOG_PROTOCOL, "%s\n", msg);
		}
	}
	
	return FALSE;
}
示例#10
0
void scheduleDispatchFunctionsOnMainThread()
{
    g_timeout_add(0, timeoutFired, 0);
}
示例#11
0
static int _progress(Prefs * prefs, char * argv[])
{
	Progress p;
	struct stat st;
	GtkWidget * vbox;
	GtkWidget * hbox;
	GtkSizeGroup * left;
	GtkSizeGroup * right;
	GtkWidget * widget;
	PangoFontDescription * bold;
	char const * q;
	unsigned long id;
  
	memset(&p, 0, sizeof(p));
	p.prefs = prefs;
	if(prefs->bufsiz == 0)
		errno = EINVAL;
	if(prefs->bufsiz == 0 || (p.buf = malloc(prefs->bufsiz)) == NULL)
		return _progress_error(&p, "malloc", 1);
	p.bufsiz = prefs->bufsiz;
	if(pipe(p.fds) != 0)
		return _progress_error(&p, "pipe", 1);
	if((p.pid = fork()) == -1)
	{
		close(p.fds[0]);
		close(p.fds[1]);
		return _progress_error(&p, "fork", 1);
	}
	if(p.pid != 0)
		return _progress_exec(&p, argv);
	close(p.fds[0]);
	if(gettimeofday(&p.tv, NULL) != 0)
		return _progress_error(&p, "gettimeofday", 1);
	if(prefs->filename == NULL)
		prefs->filename = _("Standard input");
	else if((p.fd = open(prefs->filename, O_RDONLY)) < 0)
		return _progress_error(&p, prefs->filename, 1);
	else if(fstat(p.fd, &st) == 0 && S_ISREG(st.st_mode))
		prefs->length = st.st_size;
	p.in_channel = g_io_channel_unix_new(p.fd);
	g_io_channel_set_encoding(p.in_channel, NULL, NULL);
	p.in_id = 0;
	g_idle_add(_progress_idle_in, &p);
	p.out_channel = g_io_channel_unix_new(p.fds[1]);
	g_io_channel_set_encoding(p.out_channel, NULL, NULL);
	p.out_id = 0;
	/* graphical interface */
	if((prefs->flags & PREFS_x) == 0)
	{
		p.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
#if GTK_CHECK_VERSION(3, 0, 0) && !GTK_CHECK_VERSION(3, 14, 0)
		gtk_window_set_has_resize_grip(GTK_WINDOW(p.window), FALSE);
#endif
		gtk_window_set_title(GTK_WINDOW(p.window), prefs->title != NULL
				? prefs->title : _("Progress"));
		g_signal_connect_swapped(p.window, "delete-event", G_CALLBACK(
					_progress_closex), p.window);
	}
	else
	{
		p.window = gtk_plug_new(0);
		g_signal_connect_swapped(p.window, "embedded", G_CALLBACK(
					_progress_embedded), &p);
	}
#if GTK_CHECK_VERSION(3, 0, 0)
	vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
	hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
#else
	vbox = gtk_vbox_new(FALSE, 0);
	hbox = gtk_hbox_new(FALSE, 0);
#endif
	left = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
	right = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
	/* file */
	widget = gtk_label_new(_("File: "));
	bold = pango_font_description_new();
	pango_font_description_set_weight(bold, PANGO_WEIGHT_BOLD);
#if GTK_CHECK_VERSION(3, 0, 0)
	gtk_widget_override_font(widget, bold);
	g_object_set(widget, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_widget_modify_font(widget, bold);
	gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(left, widget);
	gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
	if((q = g_filename_to_utf8(prefs->filename, -1, NULL, NULL, NULL))
			== NULL)
		q = prefs->filename;
	widget = gtk_label_new(q);
	gtk_label_set_ellipsize(GTK_LABEL(widget), PANGO_ELLIPSIZE_MIDDLE);
#if GTK_CHECK_VERSION(3, 0, 0)
	g_object_set(widget, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(right, widget);
	gtk_box_pack_start(GTK_BOX(hbox), widget, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 0);
	/* done */
#if GTK_CHECK_VERSION(3, 0, 0)
	hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
#else
	hbox = gtk_hbox_new(FALSE, 0);
#endif
	widget = gtk_label_new(_("Done: "));
#if GTK_CHECK_VERSION(3, 0, 0)
	gtk_widget_override_font(widget, bold);
	g_object_set(widget, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_widget_modify_font(widget, bold);
	gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(left, widget);
	gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
	p.done = gtk_label_new(_("0.0 kB"));
#if GTK_CHECK_VERSION(3, 0, 0)
	g_object_set(p.done, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_misc_set_alignment(GTK_MISC(p.done), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(right, p.done);
	gtk_box_pack_start(GTK_BOX(hbox), p.done, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4);
	/* remaining */
#if GTK_CHECK_VERSION(3, 0, 0)
	hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
#else
	hbox = gtk_hbox_new(FALSE, 0);
#endif
	widget = gtk_label_new(_("Remaining: "));
#if GTK_CHECK_VERSION(3, 0, 0)
	gtk_widget_override_font(widget, bold);
	g_object_set(widget, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_widget_modify_font(widget, bold);
	gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(left, widget);
	gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
	p.remaining = gtk_label_new("");
	g_timeout_add(250, _progress_timeout, &p);
#if GTK_CHECK_VERSION(3, 0, 0)
	g_object_set(p.remaining, "halign", GTK_ALIGN_START, NULL);
#else
	gtk_misc_set_alignment(GTK_MISC(p.remaining), 0.0, 0.5);
#endif
	gtk_size_group_add_widget(right, p.remaining);
	gtk_box_pack_start(GTK_BOX(hbox), p.remaining, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4);
	/* progress */
	p.progress = gtk_progress_bar_new();
	p.pulse = 0;
	if(prefs->prefix != NULL)
	{
#if GTK_CHECK_VERSION(3, 0, 0)
		hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
#else
		hbox = gtk_hbox_new(FALSE, 0);
#endif
		widget = gtk_label_new(prefs->prefix);
#if GTK_CHECK_VERSION(3, 0, 0)
		g_object_set(widget, "halign", GTK_ALIGN_START, NULL);
#else
		gtk_misc_set_alignment(GTK_MISC(widget), 0.0, 0.5);
#endif
		gtk_size_group_add_widget(left, widget);
		gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
		gtk_size_group_add_widget(right, p.progress);
		gtk_box_pack_start(GTK_BOX(hbox), p.progress, TRUE, TRUE, 0);
		gtk_box_pack_start(GTK_BOX(vbox), hbox, TRUE, TRUE, 4);
	}
	else
		gtk_box_pack_start(GTK_BOX(vbox), p.progress, TRUE, TRUE, 4);
	/* cancel */
#if GTK_CHECK_VERSION(3, 0, 0)
	hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
#else
	hbox = gtk_hbox_new(FALSE, 0);
#endif
#if GTK_CHECK_VERSION(3, 10, 0)
	widget = gtk_button_new_with_label(_("Cancel"));
	gtk_button_set_image(GTK_BUTTON(widget),
			gtk_image_new_from_icon_name(GTK_STOCK_CANCEL,
				GTK_ICON_SIZE_BUTTON));
#else
	widget = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
#endif
	g_signal_connect(G_OBJECT(widget), "clicked", G_CALLBACK(
				_progress_cancel), NULL);
	gtk_box_pack_end(GTK_BOX(hbox), widget, FALSE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0);
	gtk_container_add(GTK_CONTAINER(p.window), vbox);
	gtk_container_set_border_width(GTK_CONTAINER(p.window), 4);
	gtk_widget_show_all(vbox);
	if((prefs->flags & PREFS_x) == 0)
		/* show the window */
		gtk_widget_show(p.window);
	else
	{
		/* print the window ID and force a flush */
		id = gtk_plug_get_id(GTK_PLUG(p.window));
		printf("%lu\n", id);
		fclose(stdout);
	}
	gtk_main();
	close(p.fd);
	close(p.fds[1]);
	return p.ret;
}
示例#12
0
bool_t mpris2_init (void)
{
    GError * error = NULL;
    bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, & error);

    if (! bus)
    {
        fprintf (stderr, "mpris2: %s\n", error->message);
        g_error_free (error);
        return FALSE;
    }

    g_bus_own_name_on_connection (bus, "org.mpris.MediaPlayer2.audacious", 0,
     NULL, NULL, NULL, NULL);

    object_core = (GObject *) mpris_media_player2_skeleton_new ();

    g_object_set (object_core,
     "can-quit", TRUE,
     "can-raise", TRUE,
     "desktop-entry", "audacious",
     "identity", "Audacious",
     NULL);

    g_signal_connect (object_core, "handle-quit", (GCallback) quit_cb, NULL);
    g_signal_connect (object_core, "handle-raise", (GCallback) raise_cb, NULL);

    object_player = (GObject *) mpris_media_player2_player_skeleton_new ();

    g_object_set (object_player,
     "can-control", TRUE,
     "can-go-next", TRUE,
     "can-go-previous", TRUE,
     "can-pause", TRUE,
     "can-play", TRUE,
     "can-seek", TRUE,
     NULL);

    update_timer = g_timeout_add (250, (GSourceFunc) update, object_player);
    update_playback_status (NULL, object_player);

    if (aud_drct_get_playing () && aud_drct_get_ready ())
        emit_seek (NULL, object_player);

    hook_associate ("playback begin", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback pause", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback stop", (HookFunction) update_playback_status, object_player);
    hook_associate ("playback unpause", (HookFunction) update_playback_status, object_player);

    hook_associate ("playlist set playing", (HookFunction) update_metadata, object_player);
    hook_associate ("playlist position", (HookFunction) update_metadata, object_player);
    hook_associate ("playlist update", (HookFunction) update_metadata, object_player);

    hook_associate ("playback ready", (HookFunction) emit_seek, object_player);
    hook_associate ("playback seek", (HookFunction) emit_seek, object_player);

    g_signal_connect (object_player, "handle-next", (GCallback) next_cb, NULL);
    g_signal_connect (object_player, "handle-pause", (GCallback) pause_cb, NULL);
    g_signal_connect (object_player, "handle-play", (GCallback) play_cb, NULL);
    g_signal_connect (object_player, "handle-play-pause", (GCallback) play_pause_cb, NULL);
    g_signal_connect (object_player, "handle-previous", (GCallback) previous_cb, NULL);
    g_signal_connect (object_player, "handle-seek", (GCallback) seek_cb, NULL);
    g_signal_connect (object_player, "handle-set-position", (GCallback) set_position_cb, NULL);
    g_signal_connect (object_player, "handle-stop", (GCallback) stop_cb, NULL);

    g_signal_connect (object_player, "notify::volume", (GCallback) volume_changed, NULL);

    if (! g_dbus_interface_skeleton_export ((GDBusInterfaceSkeleton *)
     object_core, bus, "/org/mpris/MediaPlayer2", & error) ||
     ! g_dbus_interface_skeleton_export ((GDBusInterfaceSkeleton *)
     object_player, bus, "/org/mpris/MediaPlayer2", & error))
    {
        mpris2_cleanup ();
        fprintf (stderr, "mpris2: %s\n", error->message);
        g_error_free (error);
        return FALSE;
    }

    return TRUE;
}
示例#13
0
文件: curve.c 项目: seank/MegaTunix
/*!
 \brief displays a live marker for the Y axis (horizontal Line)
 \param curve (MtxCurve *) pointer to curve
 */
void mtx_curve_set_y_marker_value (MtxCurve *curve, gfloat value)
{
	MtxCurvePrivate *priv = NULL;
	gint i = 0;
	gfloat x = 0.0;
	gfloat y = 0.0;
	gfloat d1 = 0.0;
	gfloat d2 = 0.0;
	gboolean get_peak_cross = FALSE;
	g_return_if_fail (MTX_IS_CURVE (curve));
	priv = MTX_CURVE_GET_PRIVATE(curve);

#if GTK_MINOR_VERSION >= 18
	if (!gtk_widget_is_sensitive(GTK_WIDGET(curve)))
		return;
#else
	if (!GTK_WIDGET_IS_SENSITIVE(GTK_WIDGET(curve)))
		return;
#endif
	if (priv->y_marker == value)
		return;
	/* IF marker is clamped beyond ranges, don't bother updating*/
	if (((value < priv->lowest_y) && (priv->y_marker_clamp == LOW)) || ((value > priv->highest_y) && (priv->y_marker_clamp == HIGH)))
		return;

	/* Filter out jitter to within 1% */
	if (fabs(value-priv->y_marker) < (fabs(priv->highest_y-priv->lowest_y)/100.0))
		return;

	g_object_freeze_notify (G_OBJECT (curve));
	if (value <priv->lowest_y)
	{
		priv->y_marker = priv->lowest_y;
		priv->y_marker_clamp = LOW;
	}
	else if (value > priv->highest_y)
	{
		priv->y_marker = priv->highest_y;
		priv->y_marker_clamp = HIGH;
	}
	else
	{
		priv->y_marker = value;
		priv->y_marker_clamp = NONE;
	}
	if (value > priv->peak_y_marker)
	{
		priv->peak_y_marker = value > priv->highest_y ? priv->highest_y:value;
		get_peak_cross = TRUE;
		if (priv->y_peak_timeout)
		{
			g_source_remove(priv->y_peak_timeout);
			priv->y_peak_timeout = -1;
		}
	}
	else
	{
		priv->y_draw_peak = TRUE;
		g_object_set_data(G_OBJECT(curve),"axis",GINT_TO_POINTER(_Y_));
		if (priv->y_peak_timeout <= 0)
			priv->y_peak_timeout = g_timeout_add(5000,(GSourceFunc)cancel_peak,(gpointer)curve);
	}
	for (i = 0;i<priv->num_points - 1;i++)
	{
		if (value < priv->coords[0].y)
		{
			priv->x_at_y_marker = priv->coords[0].x;
			if (0 != priv->marker_proximity_vertex)
			{
				priv->marker_proximity_vertex = 0;
				g_signal_emit_by_name((gpointer)curve, "marker-proximity");
			}
		}
		else if (value > priv->coords[priv->num_points-1].y)
		{
			priv->x_at_y_marker = priv->coords[priv->num_points-1].x;
			if (get_peak_cross)
				priv->peak_x_at_y_marker = priv->x_at_y_marker;
			if (priv->num_points-1 != priv->marker_proximity_vertex)
			{
				priv->marker_proximity_vertex = priv->num_points-1;
				g_signal_emit_by_name((gpointer)curve, "marker-proximity");
			}
		}
		else if ((value > priv->coords[i].y) && (value < priv->coords[i+1].y))
		{
			if (get_intersection(priv->coords[i].x,priv->coords[i].y,priv->coords[i+1].x,priv->coords[i+1].y,0,value,priv->w,value,&x,&y))
			{
				priv->x_at_y_marker = x;
				if (get_peak_cross)
					priv->peak_x_at_y_marker = x;
				d1 = sqrt(pow((priv->coords[i].x-x),2)+ pow((priv->coords[i].y-value),2));
				d2 = sqrt(pow((priv->coords[i+1].x-x),2)+ pow((priv->coords[i+1].y-value),2));
				if (d1 < d2)
				{
					if (i != priv->marker_proximity_vertex)
					{
						priv->marker_proximity_vertex = i;
						g_signal_emit_by_name((gpointer)curve, "marker-proximity");
					}
				}
				else
				{
					if (i+1 != priv->marker_proximity_vertex)
					{
						priv->marker_proximity_vertex = i+1;
						g_signal_emit_by_name((gpointer)curve, "marker-proximity");
					}
				}

			}
			else
				printf("couldn't find intersection\n");
			break;
		}
	}
	g_object_thaw_notify (G_OBJECT (curve));
	mtx_curve_redraw(curve,FALSE);
	return;
}
示例#14
0
文件: wqqqqchat.c 项目: wiiiky/qchat
static void _on_auto_scroll(GtkWidget * view, GdkRectangle * alloc,
							gpointer data)
{
	g_timeout_add(50, on_timeout_scroll, data);
}
示例#15
0
static void
ViewAutoDrawerUpdate(ViewAutoDrawer *that, // IN
                     gboolean immediate)   // IN
{
   ViewAutoDrawerPrivate *priv = that->priv;
   GtkWidget *toplevel = gtk_widget_get_toplevel(GTK_WIDGET(that));
   GtkWindow *window;

   if (!toplevel || !gtk_widget_is_toplevel(toplevel)) {
      // The autoDrawer cannot function properly without a toplevel.
      return;
   }
   window = GTK_WINDOW(toplevel);

   /*
    * We decide to open the drawer by OR'ing several conditions. Evaluating a
    * condition can have the side-effect of setting 'immediate' to TRUE, so we
    * cannot stop evaluating the conditions after we have found one to be TRUE.
    */

   priv->opened = FALSE;

   /* Is the AutoDrawer pinned? */

   if (priv->pinned) {
      immediate = TRUE;

      priv->opened = TRUE;
   }

   /* Is the mouse cursor inside the event box? */

   {
      int x;
      int y;

      gtk_widget_get_pointer(priv->evBox, &x, &y);
      g_assert(gtk_container_get_border_width(   GTK_CONTAINER(priv->evBox))
                                              == 0);
      if (   (guint)x < (guint)priv->evBox->allocation.width
          && (guint)y < (guint)priv->evBox->allocation.height) {
         priv->opened = TRUE;
      }
   }

   /* If there is a focused widget, is it inside the event box? */

   {
      GtkWidget *focus;

      focus = gtk_window_get_focus(window);
      if (focus && gtk_widget_is_ancestor(focus, priv->evBox)) {
         /*
          * Override the default 'immediate' to make sure the 'over' widget
          * immediately appears along with the widget the focused widget.
          */
         immediate = TRUE;

         priv->opened = TRUE;
      }
   }

   /* If input is grabbed, is it on behalf of a widget inside the event box? */

   if (!priv->inputUngrabbed) {
      GtkWidget *grabbed = NULL;

      if (window->group && window->group->grabs) {
         grabbed = GTK_WIDGET(window->group->grabs->data);
      }
      if (!grabbed) {
         grabbed = gtk_grab_get_current();
      }
//      g_assert(grabbed);

      if (GTK_IS_MENU(grabbed)) {
         /*
          * With cascading menus, the deepest menu owns the grab. Traverse the
          * menu hierarchy up until we reach the attach widget for the whole
          * hierarchy.
          */

         for (;;) {
            GtkWidget *menuAttach;
            GtkWidget *menuItemParent;

            menuAttach = gtk_menu_get_attach_widget(GTK_MENU(grabbed));
            if (!menuAttach) {
               /*
                * It is unfortunately not mandatory for a menu to have a proper
                * attach widget set.
                */
               break;
            }

            grabbed = menuAttach;
            if (!GTK_IS_MENU_ITEM(grabbed)) {
               break;
            }

            menuItemParent = gtk_widget_get_parent(grabbed);
            g_return_if_fail(menuItemParent);
            if (!GTK_IS_MENU(menuItemParent)) {
               break;
            }

            grabbed = menuItemParent;
         }
      }

      if (gtk_widget_is_ancestor(grabbed, priv->evBox)) {
         /*
          * Override the default 'immediate' to make sure the 'over' widget
          * immediately appears along with the widget the grab happens on
          * behalf of.
          */
         immediate = TRUE;

         priv->opened = TRUE;
      }
   }

   if (priv->delayConnection) {
      g_source_remove(priv->delayConnection);
   }
   if (immediate) {
      ViewAutoDrawerEnforce(that, FALSE);
   } else {
      priv->delayConnection = g_timeout_add(priv->delayValue,
         (GSourceFunc)ViewAutoDrawerOnEnforceDelay, that);
   }
}
/*******************************************************************************
*	Main
*
********************************************************************************/
int main(int argc, char** argv)
{
	IoT_Error_t rc = NONE_ERROR;
	int32_t i = 0;
	int ret =0;

	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	char CurrentWD[PATH_MAX + 1];

	char cafileName[] = "/rootCA.crt";
	char clientCRTName[] = "/aws.crt";
	char clientKeyName[] = "/aws.key";

	char* thingID;

	//
	//Register ctrl-c handler
	//
	signal(SIGINT, CTRL_C_Handler);

	//
	//Parse Input-parameters
	//
	parseInputArgsForConnectParams(argc, argv);

	//
	// Get the ThingID/MachineID
	//
	thingID = GetMachineID();

	//
	// Export GPIO12 for LED output
	//
	ret = Export_GPIO(GPIO12); 	//Export GPIO12 for LED output
	if (ret != 0) {
		ERROR("Could not export LED GPIO");
	}

	//
	//Register Event-handler for Vol+/- button
	//
	ret = RegisterEventHandler(VOL_UP_EVENT, On_VolUp_ButtonPress, (void*) thingID);
	if (ret != 0) {
		ERROR("Could not register EventHandler");
	}

	ret = RegisterEventHandler(VOL_DOWN_EVENT, On_VolDown_ButtonPress,(void*) thingID);
	if (ret != 0) {
		ERROR("Could not register EventHandler");
	}


	//
	//Create the mainloop for polling the button events
	//
	loop = g_main_loop_new( NULL, false );
	if(!loop) {
		ERROR("Could not Create Main loop");
		return -1;
	}

	//
	//Setting path to private key and certificates
	//
	sprintf(rootCA, "%s%s", certDirectory, cafileName);
	sprintf(clientCRT, "%s%s", certDirectory, clientCRTName);
	sprintf(clientKey, "%s%s", certDirectory, clientKeyName);

	INFO("ThingID:       %s", thingID);
	INFO("AWS IoT SDK:   %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
	INFO("rootCA:        %s", rootCA);
	INFO("clientCRT:     %s", clientCRT);
	INFO("clientKey:     %s\n", clientKey);

	struct stat reqFileStat;
	if (stat(rootCA, &reqFileStat) < 0 || stat(clientCRT, &reqFileStat) < 0 ||
	    stat(clientKey, &reqFileStat) < 0)
	{
		ERROR("Root certificate and client certificate and key MUST be present.");
		exit(1);
	}

	//
	// Connect MQTT client
	//
	INFO("Connecting to %s:%d", HostAddress, port);
	rc = MQTT_Connect(HostAddress,port, thingID, rootCA, clientCRT, clientKey);
	if (NONE_ERROR != rc) {
		ERROR("Error[%d] connecting to %s:%d", rc, HostAddress, port);
	}

	//
	// Subscribe to LED status-changes topic
	//
        char topic[512];
        sprintf(topic, led_state_sub_topic, thingID);
	INFO("Subscribing to topic:%s", topic);
	rc = MQTT_Subscribe(topic, QOS_0, MQTTcallbackHandler);
	if (NONE_ERROR != rc) {
		ERROR("Error[%d] subscribing to topic: %s", rc, led_state_sub_topic);
	}


	//iot_mqtt_yield(1000); 	//TODO: clarify

	//
	//Hook in  a function into main loop that calls iot_mqtt_yield in regular intervals
	//
	g_timeout_add(1000, timer_func, 0);



	//
	//start the main loop
	//This call is blocking until the main loop is exited with a call to g_main_loop_quit(loop)
	//from the CTRL-C handler;
	INFO("Entering main-loop, please press ctrl-c to quit the demo-app:");
	g_main_loop_run( loop );	


	INFO("Cleaning up application ...");
	
	//Unsubscribe from Topics

	//Disconnect MQTT connection

	//Unregister GPIO-EventHandlers

	//UnExport GPIO's

	//Destroy main loop
	if(loop)
		g_main_loop_unref(loop);

	return rc;
}
示例#17
0
/** Initiate delayed processing of upower battery status changes
 */
static void
mcebat_update_schedule(void)
{
    if( !mcebat_update_id )
        mcebat_update_id = g_timeout_add(UPDATE_DELAY, mcebat_update_cb, 0);
}
static gint
process_event (GtkWidget *widget, GdkEvent *event, gpointer data G_GNUC_UNUSED)
{
  static GtkWidget *original_widget = NULL;
  static GdkCursor *cursor = NULL;

  switch (event->type) {
    case GDK_BUTTON_PRESS:
		if (event->button.button != gstroke_get_mouse_button()) {
			/* Similar to the bug below catch when any other button is
			 * clicked after the middle button is clicked (but possibly
			 * not released)
			 */
			gstroke_cancel(event);	
			original_widget = NULL;
			break;
		}

      original_widget = widget; /* remeber the widget where
                                   the stroke started */

      gstroke_invisible_window_init (widget);

      record_stroke_segment (widget);

	  if (cursor == NULL)
		  cursor = gdk_cursor_new(GDK_PENCIL);

      gdk_pointer_grab (widget->window, FALSE,
			GDK_BUTTON_RELEASE_MASK, NULL, cursor,
			event->button.time);
      timer_id = g_timeout_add (GSTROKE_TIMEOUT_DURATION,
				  gstroke_timeout, widget);
      return TRUE;

    case GDK_BUTTON_RELEASE:
      if ((event->button.button != gstroke_get_mouse_button())
	  || (original_widget == NULL)) {

		/* Nice bug when you hold down one button and press another. */
		/* We'll just cancel the gesture instead. */
		gstroke_cancel(event);
		original_widget = NULL;
		break;
	  }

      last_mouse_position.invalid = TRUE;
      original_widget = NULL;
      g_source_remove (timer_id);
      gdk_pointer_ungrab (event->button.time);
      timer_id = 0;

      {
	char result[GSTROKE_MAX_SEQUENCE];
	struct gstroke_metrics *metrics;

	metrics = (struct gstroke_metrics *)g_object_get_data(G_OBJECT (widget),
														  GSTROKE_METRICS);
		if (gstroke_draw_strokes()) {
			/* get rid of the invisible stroke window */
			XUnmapWindow (gstroke_disp, gstroke_window);
			XFlush (gstroke_disp);
		}

	_gstroke_canonical (result, metrics);
	gstroke_execute (widget, result);
	return FALSE;
      }
      return TRUE;
    default:
      break;
  }

  return FALSE;
}
示例#19
0
GtkWidget*
gtk_xtbin_new (GdkWindow *parent_window, String * f)
{
  GtkXtBin *xtbin;
  gpointer user_data;

  assert(parent_window != NULL);
  xtbin = g_object_new (GTK_TYPE_XTBIN, NULL);

  if (!xtbin)
    return (GtkWidget*)NULL;

  if (f)
    fallback = f;

  /* Initialize the Xt toolkit */
  xtbin->parent_window = parent_window;

  xt_client_init(&(xtbin->xtclient), 
      GDK_VISUAL_XVISUAL(gdk_rgb_get_visual()),
      GDK_COLORMAP_XCOLORMAP(gdk_rgb_get_colormap()),
      gdk_rgb_get_visual()->depth);

  if (!xtbin->xtclient.xtdisplay) {
    /* If XtOpenDisplay failed, we can't go any further.
     *  Bail out.
     */
#ifdef DEBUG_XTBIN
    printf("gtk_xtbin_init: XtOpenDisplay() returned NULL.\n");
#endif
    g_free (xtbin);
    return (GtkWidget *)NULL;
  }

  /* If this is the first running widget, hook this display into the
     mainloop */
  if (0 == num_widgets) {
    int           cnumber;
    /*
     * hook Xt event loop into the glib event loop.
     */

    /* the assumption is that gtk_init has already been called */
    GSource* gs = g_source_new(&xt_event_funcs, sizeof(GSource));
      if (!gs) {
       return NULL;
      }
    
    g_source_set_priority(gs, GDK_PRIORITY_EVENTS);
    g_source_set_can_recurse(gs, TRUE);
    tag = g_source_attach(gs, (GMainContext*)NULL);
#ifdef VMS
    cnumber = XConnectionNumber(xtdisplay);
#else
    cnumber = ConnectionNumber(xtdisplay);
#endif
    xt_event_poll_fd.fd = cnumber;
    xt_event_poll_fd.events = G_IO_IN; 
    xt_event_poll_fd.revents = 0;    /* hmm... is this correct? */

    g_main_context_add_poll ((GMainContext*)NULL, 
                             &xt_event_poll_fd, 
                             G_PRIORITY_LOW);
    /* add a timer so that we can poll and process Xt timers */
    xt_polling_timer_id =
      g_timeout_add(25,
                    (GtkFunction)xt_event_polling_timer_callback,
                    xtdisplay);
  }

  /* Bump up our usage count */
  num_widgets++;

  /* Build the hierachy */
  xtbin->xtdisplay = xtbin->xtclient.xtdisplay;
  gtk_widget_set_parent_window(GTK_WIDGET(xtbin), parent_window);
  gdk_window_get_user_data(xtbin->parent_window, &user_data);
  if (user_data)
    gtk_container_add(GTK_CONTAINER(user_data), GTK_WIDGET(xtbin));

  return GTK_WIDGET (xtbin);
}
示例#20
0
文件: main.c 项目: Tilka/ncdc
int main(int argc, char **argv) {
  setlocale(LC_ALL, "");
  // Early logging goes to stderr
  stderrlog = stderr;

  // parse commandline options
  GOptionContext *optx = g_option_context_new("- NCurses Direct Connect");
  g_option_context_add_main_entries(optx, cli_options, NULL);
  GError *err = NULL;
  if(!g_option_context_parse(optx, &argc, &argv, &err)) {
    puts(err->message);
    exit(1);
  }
  g_option_context_free(optx);

  // check that the current locale is UTF-8. Things aren't going to work otherwise
  if(!g_get_charset(NULL)) {
    puts("WARNING: Your current locale is not set to UTF-8.");
    puts("Non-ASCII characters may not display correctly.");
    puts("Hit Ctrl+c to abort ncdc, or the return key to continue anyway.");
    getchar();
  }

  // init stuff
  init_crypt();
  g_thread_init(NULL);

  // Create main loop
  main_loop = g_main_loop_new(NULL, FALSE);

  // setup logging
  g_log_set_handler(NULL, G_LOG_FATAL_MASK | G_LOG_FLAG_FATAL | G_LOG_LEVEL_ERROR, log_fatal, NULL);
  g_log_set_default_handler(log_redirect, NULL);

  // Init database & variables
  db_init();
  vars_init();

  // open log file
  char *errlog = g_build_filename(db_dir, "stderr.log", NULL);
  if(!(stderrlog = fopen(errlog, "w"))) {
    fprintf(stderr, "ERROR: Couldn't open %s for writing: %s\n", errlog, strerror(errno));
    exit(1);
  }
  g_free(errlog);

  // Init more stuff
  hub_init_global();
  net_init_global();
  listen_global_init();
  cc_global_init();
  dl_init_global();
  ui_cmdhist_init("history");
  ui_init(bracketed_paste);
  geoip_reinit(4);
  geoip_reinit(6);

  // setup SIGWINCH
  struct sigaction act;
  sigemptyset(&act.sa_mask);
  act.sa_flags = SA_RESTART;
  act.sa_handler = catch_sigwinch;
  if(sigaction(SIGWINCH, &act, NULL) < 0)
    g_error("Can't setup SIGWINCH: %s", g_strerror(errno));

  // setup SIGTERM
  act.sa_handler = catch_sigterm;
  if(sigaction(SIGTERM, &act, NULL) < 0)
    g_error("Can't setup SIGTERM: %s", g_strerror(errno));

  // setup SIGHUP
  act.sa_handler = catch_sighup;
  if(sigaction(SIGHUP, &act, NULL) < 0)
    g_error("Can't setup SIGHUP: %s", g_strerror(errno));

  // setup SIGUSR1
  act.sa_handler = catch_sigusr1;
  if(sigaction(SIGUSR1, &act, NULL) < 0)
    g_error("Can't setup SIGUSR1: %s", g_strerror(errno));

  // setup SIGPIPE
  act.sa_handler = catch_sigpipe;
  if(sigaction(SIGPIPE, &act, NULL) < 0)
    g_error("Can't setup SIGPIPE: %s", g_strerror(errno));

  fl_init();
  if(auto_open)
    open_autoconnect();

  // add some watches and start the main loop
  GIOChannel *in = g_io_channel_unix_new(STDIN_FILENO);
  g_io_add_watch(in, G_IO_IN, stdin_read, NULL);

  GSource *sighandle = g_source_new(&sighandle_funcs, sizeof(GSource));
  g_source_set_priority(sighandle, G_PRIORITY_HIGH);
  g_source_set_callback(sighandle, sighandle_sourcefunc, NULL, NULL);
  g_source_attach(sighandle, NULL);
  g_source_unref(sighandle);

  g_timeout_add_seconds_full(G_PRIORITY_HIGH, 1, one_second_timer, NULL, NULL);
  g_timeout_add(100, screen_update_check, NULL);
  int maxage = var_get_int(0, VAR_filelist_maxage);
  g_timeout_add_seconds_full(G_PRIORITY_LOW, CLAMP(maxage, 3600, 24*3600), dl_fl_clean, NULL, NULL);

  g_main_loop_run(main_loop);

  // cleanup
  if(!main_noterm) {
    erase();
    refresh();
    endwin();
    if(bracketed_paste)
      ui_set_bracketed_paste(0);

    printf("Flushing unsaved data to disk...");
    fflush(stdout);
  }
  ui_cmdhist_close();
  cc_global_close();
  fl_flush(NULL);
  dl_close_global();
  db_close();
  gnutls_global_deinit();
  if(!main_noterm)
    printf(" Done!\n");

  g_debug("Clean shutdown.");
  return 0;
}
示例#21
0
int main(int argc, char *argv[])
{
	char qaulUserPath[MAX_PATH_LEN];
	char qaulTmpPath[MAX_PATH_LEN];
	char qaulTmpPath2[MAX_PATH_LEN];

	qaulConfigureCounter = 0;
	qaulTimerEvents = 0;
	qaulTimerSockets = 0;
	qaulTimerTopology = 0;
	network_interface_found = 0;

	// initialize glib types
	g_type_init();

	// set paths
	sprintf(qaulUserPath, "%s/.qaul", (char*)g_get_home_dir());
	printf ("qaul.net home directory is %s\n", qaulUserPath);

	// create qaul user directory
	if(!g_file_test(qaulUserPath, G_FILE_TEST_EXISTS))
	{
		// create directory
		// http://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
		if(g_mkdir(qaulUserPath, S_IRUSR|S_IWUSR|S_IXUSR)== -1)
			printf("qaul.net home directory %s creation error.\n", qaulUserPath);
	}
	// check if we have to update
	sprintf(qaulTmpPath, "%s/%s", qaulUserPath, QAUL_VERSION);
	if(!g_file_test(qaulTmpPath, G_FILE_TEST_EXISTS))
	{
		printf("Update user folder to qaul.net version %s\n", QAUL_VERSION);
		// copy www folder
		sprintf(qaulTmpPath, "%s/www", QAUL_ROOT_PATH);
		sprintf(qaulTmpPath2, "%s/www", qaulUserPath);
		if(!qaul_copyDirectory(qaulTmpPath, qaulTmpPath2))
			printf("qaul copy directory error. source: %s target: %s\n", qaulTmpPath, qaulTmpPath2);
		// TODO: update data base
		// remove old data base if it exists
		sprintf(qaulTmpPath, "%s/qaullib.db", qaulUserPath);
		if(g_file_test(qaulTmpPath, G_FILE_TEST_EXISTS))
			if(g_remove(qaulTmpPath) == -1)
				printf("qaul.net database %s removal error\n", qaulTmpPath);
		// create qaul version file
		sprintf(qaulTmpPath, "%s/%s", qaulUserPath, QAUL_VERSION);
		if(!g_file_test(qaulTmpPath, G_FILE_TEST_EXISTS))
			if(!g_creat(qaulTmpPath, S_IRUSR|S_IWUSR) == -1)
				printf("qaul.net version file %s creation error\n", qaulTmpPath);
	}

	Qaullib_Init(qaulUserPath);
	// set configuration
	Qaullib_SetConf(QAUL_CONF_INTERFACE);
	// enable debug menu
	qaul_conf_debug = 1;

	if(!Qaullib_WebserverStart())
		printf("Webserver startup failed\n");

	// initialize dbus connection
	qaul_dbus_init(&network_dbus_connection);
	// start configuration timer
	qaulConfigureTimer = g_timeout_add(500, qaul_configure, NULL);

	// open window
	gtk_init(&argc,&argv);

    // Create a window that will contain the browser instance
    qaulMainWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(qaulMainWindow), 400, 592);
    gtk_window_set_title(GTK_WINDOW(qaulMainWindow), "qaul.net - قول");
    sprintf(qaulTmpPath, "%s/app_icon.png", QAUL_ROOT_PATH);
    gtk_window_set_icon(GTK_WINDOW(qaulMainWindow), create_pixbuf(qaulTmpPath));

    // Create a browser instance
    WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());

    // Create a scrollable area, and put the browser instance into it
    GtkWidget *scrolledWindow = gtk_scrolled_window_new(NULL, NULL);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledWindow),
            GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
    gtk_container_add(GTK_CONTAINER(scrolledWindow), GTK_WIDGET(webView));

    // Set up callbacks so that if either the main window or the browser instance is
    // closed, the program will exit
    g_signal_connect(qaulMainWindow, "destroy", G_CALLBACK(destroyWindowCb), NULL);
    g_signal_connect(webView, "close-web-view", G_CALLBACK(closeWebViewCb), qaulMainWindow);

    // Put the scrollable area into the main window
    gtk_container_add(GTK_CONTAINER(qaulMainWindow), scrolledWindow);

    // Load a web page into the browser instance
    webkit_web_view_load_uri(webView, "http://127.0.0.1:8081/qaul.html");

    // Make sure that when the browser area becomes visible, it will get mouse
    // and keyboard events
    gtk_widget_grab_focus(GTK_WIDGET(webView));

    // Make sure the main window and all its contents are visible
    gtk_widget_show_all(qaulMainWindow);

    // Run the main GTK+ event loop
    gtk_main();

    return 0;
}
示例#22
0
文件: main.c 项目: rosedu/osmo
int main(int argc, char **argv) {

GUI *appGUI = NULL;
CALENDAR *cal = NULL;
TASKS *tsk = NULL;
CONTACTS *cnt = NULL;
NOTES *nte = NULL;
OPTIONS *opt = NULL;
GtkWidget *info_dialog;
gchar tmpbuf[BUFFER_SIZE];
gint response = -1;
struct flock *s_lock = NULL;
int fhandle;

GOptionContext *cmd_context;
gboolean cmd_calendar = FALSE;
gboolean cmd_check_events = FALSE;
gint cmd_check_ndays_events = 0;
gchar *cmd_cfg_path = NULL;
gboolean cmd_tiny_gui = FALSE;

GOptionEntry cmd_options[] = {
    { "calendar",   'c', 0, G_OPTION_ARG_NONE, &cmd_calendar, N_("Show small calendar window"), NULL  },
    { "check",      'e', 0, G_OPTION_ARG_NONE, &cmd_check_events, N_("Check for events since last run"), NULL  },
    { "days",       'd', 0, G_OPTION_ARG_INT, &cmd_check_ndays_events, N_("Number of days to check forward for events (default: 0)"), NULL  },
    { "config",     's', 0, G_OPTION_ARG_STRING, &cmd_cfg_path, N_("Set absolute path for settings and data files"), "PATH"  },
    { "tinygui",    't', 0, G_OPTION_ARG_NONE, &cmd_tiny_gui, N_("Modify GUI to use Osmo on low resolutions"), NULL  },
    { NULL }
};

    appGUI = g_new0 (GUI, 1);
    g_return_val_if_fail (appGUI != NULL, -1);

    cal = g_new0 (CALENDAR, 1);
    g_return_val_if_fail (cal != NULL, -1);
    tsk = g_new0 (TASKS, 1);
    g_return_val_if_fail (tsk != NULL, -1);
    cnt = g_new0 (CONTACTS, 1);
    g_return_val_if_fail (cnt != NULL, -1);
    nte = g_new0 (NOTES, 1);
    g_return_val_if_fail (nte != NULL, -1);

    opt = g_new0 (OPTIONS, 1);
    g_return_val_if_fail (opt != NULL, -1);

    /* register modules */
    appGUI->cal = cal;
    appGUI->tsk = tsk;
    appGUI->cnt = cnt;
    appGUI->nte = nte;
    appGUI->opt = opt;

    appGUI->run_date = utl_get_current_julian ();
    appGUI->run_time = get_seconds_for_today ();
    appGUI->key_counter = 0;

    /* default values */
    appGUI->hovering_over_link = FALSE;
    appGUI->hand_cursor = NULL;
    appGUI->regular_cursor = NULL;
    appGUI->gui_url_tag = NULL;
    appGUI->trayicon_popup_menu = NULL;

    appGUI->calendar_only = FALSE;
    appGUI->check_events = FALSE;
    appGUI->tiny_gui = FALSE;
    appGUI->save_status = 0;
    appGUI->print_font_size = 10;

	appGUI->cal->date = g_date_new ();
	g_return_val_if_fail (appGUI->cal->date != NULL, -1);
	g_date_set_time_t (appGUI->cal->date, time (NULL));

    appGUI->tsk->id_counter = 0;
    appGUI->tsk->tasks_panel_status = FALSE;
    appGUI->tsk->tasks_filter_disabled = FALSE;
    appGUI->tsk->tasks_list_store = NULL;
    appGUI->tsk->notifications = NULL;

    appGUI->cnt->photo_image = NULL;
    appGUI->cnt->contacts_uim_widget = NULL;
    appGUI->cnt->contacts_panel_status = FALSE;
    appGUI->cnt->contacts_filter_disabled = TRUE;
    appGUI->cnt->export_button = NULL;
    appGUI->cnt->output_file_entry = NULL;

    appGUI->opt->options_counter = 0;

    setlocale (LC_ALL, "");
    bindtextdomain (PACKAGE, LOCALEDIR);
    bind_textdomain_codeset (PACKAGE, "UTF-8");
    textdomain (PACKAGE);

    if (argc == 2 && (!strncmp(argv[1], "--help", 6) || (argv[1][0] == '-' && argv[1][1] == '?'))) {
        fprintf(stderr, "\nOSMO v%s - %s\n", VERSION, _("a handy personal organizer"));
        fprintf(stderr, "Copyright (c) 2007-2008 Tomasz Maka <[email protected]>\n\n");
    }

    cmd_context = g_option_context_new(NULL);
    g_option_context_add_main_entries(cmd_context, cmd_options, TRANSLATION_DOMAIN);
    g_option_context_parse(cmd_context, &argc, &argv, NULL);
    g_option_context_free(cmd_context);

    appGUI->calendar_only = cmd_calendar;
    appGUI->check_events = cmd_check_events;
    appGUI->check_ndays_events = cmd_check_ndays_events;
    appGUI->config_path = cmd_cfg_path;
    appGUI->tiny_gui = cmd_tiny_gui;

    if (prefs_get_config_filename (CONFIG_FILENAME, appGUI) == NULL) {
        fprintf(stderr, "%s\n", _("ERROR: Cannot create config files"));
        goto finish;
    }

    s_lock = g_new0 (struct flock, 1);
	s_lock->l_type = F_WRLCK;
	s_lock->l_whence = SEEK_SET;
	s_lock->l_start = 0;
	s_lock->l_len = 0;

    prefs_read_config (appGUI);

    close(creat(prefs_get_config_filename (RUN_FLAG_FILE, appGUI), S_IRUSR | S_IWUSR));     /* create lock file */

    gtk_init (&argc, &argv);

    fhandle = open(prefs_get_config_filename (RUN_FLAG_FILE, appGUI), O_RDWR);

    if (fhandle) {
		if (fcntl(fhandle, F_SETLK, s_lock) == -1) {
            close (fhandle);

            g_snprintf (tmpbuf, BUFFER_SIZE, "%s %s\n\n%s",
                        _("Another copy of OSMO is already running."),
                        _("Simultaneously use two or more copies of OSMO can be a cause of data loss."),
                        _("Do you really want to continue?"));

            info_dialog = gtk_message_dialog_new_with_markup (GTK_WINDOW_TOPLEVEL, GTK_DIALOG_MODAL,
                                                  GTK_MESSAGE_WARNING, GTK_BUTTONS_YES_NO, tmpbuf);

            gtk_window_set_title(GTK_WINDOW(info_dialog), _("Warning"));
            gtk_window_set_position(GTK_WINDOW(info_dialog), GTK_WIN_POS_CENTER);
            gtk_widget_show (info_dialog);

            response = gtk_dialog_run(GTK_DIALOG(info_dialog));
            gtk_widget_destroy(info_dialog);

            if (response == GTK_RESPONSE_NO || response == GTK_RESPONSE_DELETE_EVENT) {
                goto finish;
            }
        }
    }

	notify_init("Osmo notification");

    if (appGUI->calendar_only != TRUE) {

        /* setup timer at 1000ms (1s) interval */
		g_timeout_add (1000, (GtkFunction) time_handler, appGUI);

    }

    config.run_counter++;

    if (gui_create_window (appGUI) == TRUE) {
        gtk_main ();
    }

    if (appGUI->calendar_only == FALSE) {
        config.lastrun_date = utl_get_current_julian ();
        config.lastrun_time = get_seconds_for_today();
    }

    if (appGUI->check_events == FALSE) {
        prefs_write_config (appGUI);
    }

    if (fhandle) {
    	s_lock->l_type = F_UNLCK;
    	fcntl(fhandle, F_SETLK, s_lock);
        close (fhandle);
    }

finish:
	g_date_free (appGUI->cal->date);
	g_free (opt);
	g_free (nte);
	g_free (cnt);
	g_free (tsk);
	g_free (cal);
	g_free (appGUI);
	g_free (s_lock);
	return 0;
}
示例#23
0
文件: mgobj.c 项目: LordJagged/mosh
MOSHEXPORT
int
mglib_add_timeout(unsigned int interval, void* func, void* data){
    return g_timeout_add(interval,func,data);
}
示例#24
0
文件: eve.c 项目: Tetralet/hime
// return TRUE if the key press is processed
gboolean ProcessKeyPress(KeySym keysym, u_int kev_state)
{
#if 0
  dbg("key press %x %x\n", keysym, kev_state);
#endif
  destroy_phrase_save_menu();

  disp_win_kbm_capslock();
  check_CS();

  if (current_CS->client_win)
    focus_win = current_CS->client_win;

  if (callback_str_buffer && strlen(callback_str_buffer)) {
    send_text(callback_str_buffer);
    callback_str_buffer[0]=0;
    return TRUE;
  }

  if (force_preedit) {
    force_preedit=0;
    return 1;
  }

  if (keysym == XK_space) {
#if 0
    dbg("state %x\n", kev->state);
    dbg("%x\n", Mod4Mask);
#endif
    if (
      ((kev_state & (ControlMask|Mod1Mask|ShiftMask))==ControlMask && hime_im_toggle_keys==Control_Space) ||
      ((kev_state & Mod1Mask) && hime_im_toggle_keys==Alt_Space) ||
      ((kev_state & ShiftMask) && hime_im_toggle_keys==Shift_Space) ||
      ((kev_state & Mod4Mask) && hime_im_toggle_keys==Windows_Space)
    ) {
      if (current_method_type() == method_type_TSIN) {
        tsin_set_eng_ch(1);
      }

      toggle_im_enabled();
      return TRUE;
    }
  }

  if (keysym == XK_space && (kev_state & ShiftMask)) {
    if (last_keysym != XK_Shift_L && last_keysym != XK_Shift_R)
      return FALSE;

    toggle_half_full_char();

    return TRUE;
  }


  if ((kev_state & (Mod1Mask|ShiftMask)) == (Mod1Mask|ShiftMask)) {
    if (current_CS->im_state != HIME_STATE_DISABLED || hime_eng_phrase_enabled)
      return feed_phrase(keysym, kev_state);
    else
      return 0;
  }

//  dbg("state %x\n", kev_state);
  if (current_CS->im_state == HIME_STATE_ENG_FULL) {
    return full_char_proc(keysym);
  }


  if ((kev_state & ControlMask) && (kev_state&(Mod1Mask|Mod5Mask))) {
    if (keysym == 'g' || keysym == 'r') {
      send_output_buffer_bak();
      return TRUE;
    }

    if (!hime_enable_ctrl_alt_switch)
      return FALSE;

    int kidx = hime_switch_keys_lookup(keysym);
    if (kidx < 0)
      return FALSE;

    if (inmd[kidx].method_type == method_type_SYMBOL_TABLE) {
      toggle_symbol_table();
      return TRUE;
    }

    if (!inmd[kidx].cname)
      return FALSE;

    current_CS->im_state = HIME_STATE_CHINESE;
    init_in_method(kidx);

    return TRUE;
  }

  last_keysym = keysym;

  if (current_CS->im_state == HIME_STATE_DISABLED) {
    return FALSE;
  }

  if (!current_CS->b_hime_protocol) {
  if (((keysym == XK_Control_L || keysym == XK_Control_R)
                   && (kev_state & ShiftMask)) ||
      ((keysym == XK_Shift_L || keysym == XK_Shift_R)
                   && (kev_state & ControlMask))) {
     cycle_next_in_method();
     return TRUE;
  }
  }

  if (current_CS->b_raise_window && keysym>=' ' && keysym < 127) {
    if (timeout_handle)
      g_source_remove(timeout_handle);
    timeout_handle = g_timeout_add(200, timeout_raise_window, NULL);
  }

  if (kev_state & ControlMask) {
    if (feed_phrase(keysym, kev_state))
      return TRUE;
  }

  switch(current_method_type()) {
    case method_type_PHO:
      return feedkey_pho(keysym, kev_state);
#if USE_TSIN
    case method_type_TSIN:
      return feedkey_pp(keysym, kev_state);
#endif
    case method_type_MODULE:
      if (!module_cb())
        return FALSE;
      return module_cb()->module_feedkey(keysym, kev_state);
    default:
      return feedkey_gtab(keysym, kev_state);
  }

  return FALSE;
}
示例#25
0
文件: plcommon.c 项目: kij/deadbeef
void draw_column_data (DdbListview *listview, cairo_t *cr, DdbListviewIter it, DdbListviewIter group_it, int column, int group_y, int group_height, int group_pinned, int grp_next_y, int x, int y, int width, int height) {
    const char *ctitle;
    int cwidth;
    int calign_right;
    col_info_t *cinf;
    int minheight;
    int res = ddb_listview_column_get_info (listview, column, &ctitle, &cwidth, &calign_right, &minheight, (void **)&cinf);
    if (res == -1) {
        return;
    }

    DB_playItem_t *playing_track = deadbeef->streamer_get_playing_track ();
    int theming = !gtkui_override_listview_colors ();

    if (cinf->id == DB_COLUMN_ALBUM_ART) {
        if (theming) {
#if GTK_CHECK_VERSION(3,0,0)
            cairo_rectangle (cr, x, y, width, height);
            cairo_clip (cr);
            gtk_paint_flat_box (gtk_widget_get_style (theme_treeview), cr, GTK_STATE_NORMAL, GTK_SHADOW_NONE, theme_treeview, "cell_even_ruled", x-1, y, width+2, height);
            cairo_reset_clip (cr);
#else
            GdkRectangle clip = {
                .x = x,
                .y = y,
                .width = width,
                .height = height,
            };
            gtk_paint_flat_box (gtk_widget_get_style (theme_treeview), gtk_widget_get_window (listview->list), GTK_STATE_NORMAL, GTK_SHADOW_NONE, &clip, theme_treeview, "cell_even_ruled", x-1, y, width+2, height);
#endif
        }
        else {
            GdkColor clr;
            gtkui_get_listview_even_row_color (&clr);
            cairo_set_source_rgb (cr, clr.red/65535.f, clr.green/65535.f, clr.blue/65535.f);
            cairo_rectangle (cr, x, y, width, height);
            cairo_fill (cr);
        }
        int real_art_width = width - ART_PADDING_HORZ * 2;
        if (real_art_width > 0 && group_it) {
            const char *album = deadbeef->pl_find_meta (group_it, "album");
            const char *artist = deadbeef->pl_find_meta (group_it, "artist");
            if (!album || !*album) {
                album = deadbeef->pl_find_meta (group_it, "title");
            }
            if (listview->new_cover_size != real_art_width) {
                listview->new_cover_size = real_art_width;
                if (listview->cover_refresh_timeout_id) {
                    g_source_remove (listview->cover_refresh_timeout_id);
                    listview->cover_refresh_timeout_id = 0;
                }
                if (listview->cover_size == -1) {
                    listview->cover_size = real_art_width;
                }
                else {
                    if (!listview->cover_refresh_timeout_id) {
                        listview->cover_refresh_timeout_id = g_timeout_add (1000, deferred_cover_load_cb, listview);
                    }
                }
            }
            int art_width = listview->cover_size;
            int art_y = y; // dest y
            int art_h = height;
            int sy; // source y
            if (group_y < ART_PADDING_VERT) {
                art_y = y - group_y + ART_PADDING_VERT;
                art_h = height - (art_y - y);
                sy = group_y;
            }
            else {
                sy = group_y - ART_PADDING_VERT;
            }
            int h = cwidth - group_y;
            h = min (height, art_h);

            int hq = 0;
            GdkPixbuf *pixbuf = get_cover_art_callb (deadbeef->pl_find_meta (((DB_playItem_t *)group_it), ":URI"), artist, album, real_art_width == art_width ? art_width : -1, redraw_playlist_single, listview);
            if (!pixbuf) {
                pixbuf = cover_get_default_pixbuf ();
            }
            if (pixbuf) {
                art_width = gdk_pixbuf_get_width (pixbuf);
                float art_scale = (float)real_art_width / art_width;
                int pw = real_art_width;
                int ph;
                if (gdk_pixbuf_get_width (pixbuf) < gdk_pixbuf_get_height (pixbuf)) {
                    art_scale *= (float)gdk_pixbuf_get_width (pixbuf) / gdk_pixbuf_get_height (pixbuf);
                }

                if (group_pinned == 1 && gtkui_groups_pinned) {
                    ph = group_height;
                }
                else {
                    ph = pw;
                }

                if (sy < ph)
                {
                    cairo_save (cr);
                    if (group_pinned == 1 && gtkui_groups_pinned) {
                        int ph_real = gdk_pixbuf_get_height (pixbuf);
                        if (grp_next_y <= ph_real * art_scale + listview->grouptitle_height) {
                            cairo_rectangle (cr, x + ART_PADDING_HORZ, grp_next_y - ph_real * art_scale, pw, ph);
                            cairo_translate (cr, (x + ART_PADDING_HORZ)-0, grp_next_y - ph_real * art_scale);
                        }
                        else {
                            cairo_rectangle (cr, x + ART_PADDING_HORZ, listview->grouptitle_height, pw, ph);
                            cairo_translate (cr, (x + ART_PADDING_HORZ)-0, listview->grouptitle_height);
                        }
                    }
                    else {
                        ph -= sy;
                        ph = min (ph, h);
                        cairo_rectangle (cr, x + ART_PADDING_HORZ, art_y, pw, ph);
                        cairo_translate (cr, (x + ART_PADDING_HORZ)-0, art_y - sy);
                    }
                    cairo_scale (cr, art_scale, art_scale);
                    gdk_cairo_set_source_pixbuf (cr, pixbuf, 0, 0);
                    cairo_pattern_set_filter (cairo_get_source(cr), gtkui_is_default_pixbuf (pixbuf) ? CAIRO_FILTER_GAUSSIAN : CAIRO_FILTER_FAST);
                    cairo_fill (cr);
                    cairo_restore (cr);
                }
                g_object_unref (pixbuf);
            }
        }
    }
示例#26
0
文件: pdf.c 项目: Debian/gpdftext
gboolean
open_file (Ebook * ebook, const gchar * filename)
{
	GtkProgressBar * progressbar;
	GtkStatusbar * statusbar;
	guint id;
	GtkWidget * window;
	PopplerRectangle * rect;
	GError * err;
	gint G_GNUC_UNUSED pages;
	gchar * uri, * msg;
	GVfs * vfs;
	GFileInfo * ginfo;
	GError * result;
	GConfValue *value;
	gboolean lines, hyphens, pagenums;

	vfs = g_vfs_get_default ();

	if (g_vfs_is_active(vfs))
		ebook->gfile = g_vfs_get_file_for_path (vfs, filename);
	else
		ebook->gfile = g_file_new_for_commandline_arg (filename);
	ginfo = g_file_query_info (ebook->gfile, G_FILE_ATTRIBUTE_STANDARD_SIZE,
		G_FILE_QUERY_INFO_NONE, NULL, &result);
	if (0 == g_file_info_get_attribute_uint64 (ginfo, 
		G_FILE_ATTRIBUTE_STANDARD_SIZE))
	{
		g_object_unref (ebook->gfile);
		g_object_unref (ginfo);
		g_warning ("%s", result->message);
		return FALSE;
	}
	uri = g_file_get_uri (ebook->gfile);
	err = NULL;
	pages = 0;
	rect = poppler_rectangle_new ();
	rect->x1 = rect->y1 = 0;
	window = GTK_WIDGET(gtk_builder_get_object (ebook->builder, "gpdfwindow"));
	progressbar = GTK_PROGRESS_BAR(gtk_builder_get_object (ebook->builder, "progressbar"));
	gtk_progress_bar_set_fraction (progressbar, 0.0);
	statusbar = GTK_STATUSBAR(gtk_builder_get_object (ebook->builder, "statusbar"));
	id = gtk_statusbar_get_context_id (statusbar, PACKAGE);
	msg = g_strconcat (_("Loading ebook:"), g_file_get_basename (ebook->gfile), NULL);
	gtk_statusbar_push (statusbar, id, msg);
	ebook->PDFDoc = poppler_document_new_from_file (uri, NULL, &err);
	gtk_progress_bar_set_fraction (progressbar, 0.0);

	/* long lines support */
	value = gconf_client_get(ebook->client, ebook->long_lines.key, NULL);
	if (value)
		lines = gconf_value_get_bool(value);
	else
		lines = TRUE;

	/* page numbers support */
	value = gconf_client_get(ebook->client, ebook->page_number.key, NULL);
	if (value)
		pagenums = gconf_value_get_bool(value);
	else
		pagenums = TRUE;

	/* join hyphens support */
	value = gconf_client_get(ebook->client, ebook->join_hyphens.key, NULL);
	if (value)
		hyphens = gconf_value_get_bool(value);
	else
		hyphens = TRUE;

	if (POPPLER_IS_DOCUMENT (ebook->PDFDoc))
	{
#ifdef HAVE_GTKSPELL
		GtkSpell *spell;
		gchar * G_GNUC_UNUSED lang;
#endif
		GtkWidget * G_GNUC_UNUSED spell_check;
		GtkTextView * text_view;
		GtkTextBuffer * buffer;
		gboolean state;
		static Equeue queue;

		spell_check = GTK_WIDGET(gtk_builder_get_object (ebook->builder, "spellcheckmenuitem"));
		text_view = GTK_TEXT_VIEW(gtk_builder_get_object (ebook->builder, "textview"));
		buffer = gtk_text_view_get_buffer (text_view);
		state = gconf_client_get_bool (ebook->client, ebook->spell_check.key, NULL);
#ifdef HAVE_GTKSPELL
		spell = gtkspell_get_from_text_view (text_view);
		lang = gconf_client_get_string (ebook->client, ebook->language.key, NULL);
		/* updating the text area with spell enabled is very slow */
		if (state)
			gtkspell_detach (spell);
#endif
		pages = poppler_document_get_n_pages (ebook->PDFDoc);
		queue.ebook = ebook;
		queue.c = 0;
		queue.lines = lines;
		queue.hyphens = hyphens;
		queue.pagenums = pagenums;
		queue.rect = rect;
		/* whether to enable spell once all pages are loaded. */
		queue.spell_state = state;
		/* loading a file is a single user action */
		gtk_text_buffer_begin_user_action (buffer);
		g_timeout_add (30, load_pdf, &queue);
	}
	else
	{
		g_message ("err: %s", err->message);
		return FALSE;
	}
	msg = g_strconcat (PACKAGE, " - ", g_file_get_basename (ebook->gfile), NULL);
	gtk_window_set_title (GTK_WINDOW(window), msg);
	return TRUE;
}
示例#27
0
static void test_webkit_atk_get_text_at_offset(void)
{
    WebKitWebView* webView;
    AtkObject *obj;
    GMainLoop* loop;
    AtkText* text_obj;
    char* text;

    webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
    g_object_ref_sink(webView);
    webkit_web_view_load_string(webView, contents, NULL, NULL, NULL);
    loop = g_main_loop_new(NULL, TRUE);

    g_timeout_add(100, (GSourceFunc)bail_out, loop);
    g_main_loop_run(loop);

    /* Get to the inner AtkText object */
    obj = gtk_widget_get_accessible(GTK_WIDGET(webView));
    g_assert(obj);
    obj = atk_object_ref_accessible_child(obj, 0);
    g_assert(obj);
    obj = atk_object_ref_accessible_child(obj, 0);
    g_assert(obj);

    text_obj = ATK_TEXT(obj);
    g_assert(ATK_IS_TEXT(text_obj));

    text = atk_text_get_text(text_obj, 0, -1);
    g_assert_cmpstr(text, ==, "This is a test. This is the second sentence. And this the third.");
    g_free(text);

    /* ATK_TEXT_BOUNDARY_CHAR */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "T", 0, 1);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "h", 1, 2);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_CHAR,
                           0, "", 0, 0);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_CHAR,
                           1, "T", 0, 1);
    
    /* ATK_TEXT_BOUNDARY_WORD_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           0, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           4, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           10, "test. ", 10, 16);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           58, "third.", 58, 64);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           5, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           7, "This ", 0, 5);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           0, "is ", 5, 8);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           4, "is ", 5, 8);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_START,
                           3, "is ", 5, 8);

    /* ATK_TEXT_BOUNDARY_WORD_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           0, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           9, " test", 9, 14);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, "This", 0, 4);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           7, " is", 4, 7);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           5, " a", 7, 9);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           4, " a", 7, 9);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_WORD_END,
                           58, " third", 57, 63);

    /* ATK_TEXT_BOUNDARY_SENTENCE_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           0, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           0, "This is the second sentence. ", 16, 45);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "This is the second sentence. ", 16, 45);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           16, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           44, "This is a test. ", 0, 16);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_START,
                           15, "", 0, 0);

    /* ATK_TEXT_BOUNDARY_SENTENCE_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           0, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           16, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           17, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           0, " This is the second sentence.", 15, 44);

    test_get_text_function(text_obj, atk_text_get_text_after_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, " And this the third.", 44, 64);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           16, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           15, "This is a test.", 0, 15);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           14, "", 0, 0);

    test_get_text_function(text_obj, atk_text_get_text_before_offset, ATK_TEXT_BOUNDARY_SENTENCE_END,
                           44, " This is the second sentence.", 15, 44);

    /* It's trick to test these properly right now, since our a11y
       implementation splits different lines in different a11y
       items */
    /* ATK_TEXT_BOUNDARY_LINE_START */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_LINE_START,
                           0, "This is a test. This is the second sentence. And this the third.", 0, 64);

    /* ATK_TEXT_BOUNDARY_LINE_END */
    test_get_text_function(text_obj, atk_text_get_text_at_offset, ATK_TEXT_BOUNDARY_LINE_END,
                           0, "This is a test. This is the second sentence. And this the third.", 0, 64);

    g_object_unref(webView);
}
gint
dialog_I (PlugInImageVals * image_vals,
          PlugInDrawableVals * drawable_vals,
          PlugInVals * vals,
          PlugInUIVals * ui_vals,
          PlugInColVals * col_vals,
          PlugInDialogVals * dialog_vals)
{
    gint32 image_ID;
    gint32 layer_ID;
    gint orig_width, orig_height;
    GtkWidget *main_hbox;
    GtkWidget *vbox;
    GtkWidget *vbox2;
    GtkWidget *vbox3;
    GtkWidget *hbox;
    GtkWidget *hbox2;
    GtkWidget *frame;

    GtkWidget *filler;
    GtkWidget *pres_use_image;
    GtkWidget *disc_use_image;
    GtkWidget *rigmask_use_image;
    //GtkWidget *noninter_button;
    GtkWidget *resetvalues_event_box;
    GtkWidget *resetvalues_button;
    GtkWidget *resetvalues_icon;

    GtkWidget *flatten_event_box;
    GtkWidget *flatten_button;
    GtkWidget *flatten_icon;
    GtkWidget *show_info_event_box;
    GtkWidget *show_info_button;
    GtkWidget *show_info_icon;
    GtkWidget *dump_event_box;
    GtkWidget *dump_button;
    GtkWidget *dump_icon;
    //GtkWidget *lastvalues_event_box;
    //GtkWidget *lastvalues_button;
    //GtkWidget *lastvalues_icon;
    gboolean has_mask = FALSE;
    GimpUnit unit;
    gdouble xres, yres;
    GtkWidget * v_separator;
    GtkWidget *info_title_label;
    GtkWidget * info_label;

    CarverData * carver_data;

    image_ID = image_vals->image_ID;
    layer_ID = drawable_vals->layer_ID;

    state = g_new (PlugInVals, 1);
    memcpy (state, vals, sizeof (PlugInVals));

    ui_state = g_new (PlugInUIVals, 1);
    memcpy (ui_state, ui_vals, sizeof (PlugInUIVals));

    dialog_state = dialog_vals;

    orig_width = gimp_drawable_width (layer_ID);
    orig_height = gimp_drawable_height (layer_ID);

    g_assert (gimp_drawable_is_layer (layer_ID) == TRUE);

    interface_I_data.orig_width = orig_width;
    interface_I_data.orig_height = orig_height;
    interface_I_data.col_vals = col_vals;
    interface_I_data.vmap_layer_ID = -1;

    reader_go = TRUE;

    if (gimp_layer_get_mask (layer_ID) != -1)
    {
        has_mask = TRUE;
    }

    dlg = gtk_dialog_new_with_buttons (_("GIMP LiquidRescale Plug-In"),
                                       NULL, 0,
                                       //GIMP_STOCK_RESET, RESPONSE_RESET,
                                       //GTK_STOCK_REFRESH, RESPONSE_REFRESH,
                                       GTK_STOCK_GO_BACK, RESPONSE_NONINTERACTIVE,
                                       GTK_STOCK_CLOSE, GTK_RESPONSE_OK, NULL);

    gtk_window_set_resizable (GTK_WINDOW (dlg), FALSE);

    gtk_window_set_keep_above(GTK_WINDOW (dlg), TRUE);

    if (dialog_state->has_pos)
    {
        //printf("move window, x,y=%i,%i\n", dialog_state->x, dialog_state->y); fflush(stdout);
        gtk_window_move (GTK_WINDOW(dlg), dialog_state->x, dialog_state->y);
        dialog_state->has_pos = FALSE;
    }

    g_signal_connect (dlg, "response", G_CALLBACK (callback_dialog_I_response),
                      (gpointer) (NULL));

    /* dlg_tips = gtk_tooltips_new (); */

    main_hbox = gtk_hbox_new (FALSE, 12);
    gtk_container_set_border_width (GTK_CONTAINER (main_hbox), 12);
    gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area(GTK_DIALOG (dlg))), main_hbox);

    vbox = gtk_vbox_new (FALSE, 12);
    gtk_box_pack_start (GTK_BOX (main_hbox), vbox, TRUE, TRUE, 0);
    gtk_widget_show (vbox);

    /*  New size  */

    frame = gimp_frame_new (_("Set width and height"));
    gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0);
    gtk_widget_show (frame);

    hbox = gtk_hbox_new (FALSE, 4);
    gtk_container_add (GTK_CONTAINER (frame), hbox);
    gtk_widget_show (hbox);

    vbox3 = gtk_vbox_new (FALSE, 4);
    gtk_box_pack_start (GTK_BOX (hbox), vbox3, FALSE, FALSE, 0);
    gtk_widget_show (vbox3);

    unit = gimp_image_get_unit (image_ID);
    gimp_image_get_resolution (image_ID, &xres, &yres);

    coordinates =
        alt_coordinates_new (unit, "%p", TRUE, TRUE, SPIN_BUTTON_WIDTH,
                             ALT_SIZE_ENTRY_UPDATE_SIZE, ui_state->chain_active,
                             TRUE, _("Width:"), state->new_width, xres, 2,
                             GIMP_MAX_IMAGE_SIZE, 0, orig_width,
                             _("Height:"), state->new_height, yres, 2,
                             GIMP_MAX_IMAGE_SIZE, 0, orig_height);

    interface_I_data.coordinates = coordinates;

    g_signal_connect (ALT_SIZE_ENTRY (coordinates), "value-changed",
                      G_CALLBACK (callback_size_changed),
                      (gpointer) & interface_I_data);

    g_signal_connect (ALT_SIZE_ENTRY (coordinates), "refval-changed",
                      G_CALLBACK (callback_size_changed),
                      (gpointer) & interface_I_data);

    g_signal_connect (ALT_SIZE_ENTRY (coordinates), "coordinates-alarm",
                      G_CALLBACK (callback_alarm_triggered),
                      (gpointer) & interface_I_data);

    gtk_box_pack_start (GTK_BOX (vbox3), coordinates, FALSE, FALSE, 0);
    gtk_widget_show (coordinates);

    /* Aux layer usage icons */

    hbox2 = gtk_hbox_new (FALSE, 10);
    gtk_container_set_border_width (GTK_CONTAINER (hbox2), 4);
    gtk_box_pack_start (GTK_BOX (vbox3), hbox2, FALSE, FALSE, 0);
    gtk_widget_show (hbox2);

    filler = gtk_image_new ();
    gtk_box_pack_start (GTK_BOX (hbox2), filler, TRUE, TRUE, 0);
    gtk_widget_show (filler);
    filler = gtk_image_new ();
    gtk_box_pack_end (GTK_BOX (hbox2), filler, TRUE, TRUE, 0);
    gtk_widget_show (filler);

    pres_use_image = gtk_image_new_from_stock (GIMP_STOCK_CHANNEL_GREEN,
                     GTK_ICON_SIZE_MENU);

    gtk_box_pack_start (GTK_BOX (hbox2), pres_use_image, FALSE, FALSE, 0);

    gtk_widget_show (pres_use_image);

    disc_use_image = gtk_image_new_from_stock (GIMP_STOCK_CHANNEL_RED,
                     GTK_ICON_SIZE_MENU);

    gtk_box_pack_start (GTK_BOX (hbox2), disc_use_image, FALSE, FALSE, 0);

    gtk_widget_show (disc_use_image);

    rigmask_use_image = gtk_image_new_from_stock (GIMP_STOCK_CHANNEL_BLUE,
                        GTK_ICON_SIZE_MENU);

    gtk_widget_show (rigmask_use_image);

    gtk_box_pack_start (GTK_BOX (hbox2), rigmask_use_image, FALSE, FALSE, 0);

    update_info_aux_use_icons(vals, ui_vals, pres_use_image, disc_use_image, rigmask_use_image);


    /* Reset size button */

    vbox2 = gtk_vbox_new (FALSE, 4);
    gtk_box_pack_end (GTK_BOX (hbox), vbox2, FALSE, FALSE, 0);
    gtk_widget_show (vbox2);

    resetvalues_event_box = gtk_event_box_new ();
    gtk_box_pack_start (GTK_BOX (vbox2), resetvalues_event_box, FALSE, FALSE,
                        0);
    gtk_widget_show (resetvalues_event_box);

    gimp_help_set_help_data (resetvalues_event_box,
                             _
                             ("Reset width and height to their original values"),
                             NULL);

    resetvalues_button = gtk_button_new ();
    resetvalues_icon =
        gtk_image_new_from_stock (GIMP_STOCK_RESET, GTK_ICON_SIZE_MENU);
    gtk_container_add (GTK_CONTAINER (resetvalues_button), resetvalues_icon);
    gtk_widget_show (resetvalues_icon);
    gtk_container_add (GTK_CONTAINER (resetvalues_event_box),
                       resetvalues_button);
    gtk_widget_show (resetvalues_button);

    g_signal_connect (resetvalues_button, "clicked",
                      G_CALLBACK (callback_resetvalues_button),
                      (gpointer) & interface_I_data);

    /* Map info */

    v_separator = gtk_vseparator_new();
    gtk_box_pack_start (GTK_BOX (main_hbox), v_separator, TRUE, TRUE, 0);
    gtk_widget_show(v_separator);

    vbox = gtk_vbox_new (FALSE, 4);
    gtk_box_pack_start (GTK_BOX (main_hbox), vbox, FALSE, FALSE, 0);
    gtk_widget_show (vbox);

    hbox2 = gtk_hbox_new (FALSE, 4);
    gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, FALSE, 0);
    gtk_widget_show (hbox2);

    info_title_label = gtk_label_new ("");
    /* Please keep the <b> and </b> tags in translations */
    gtk_label_set_markup(GTK_LABEL(info_title_label), _("<b>Map</b>"));
    gtk_box_pack_start (GTK_BOX (hbox2), info_title_label, FALSE, FALSE, 0);
    gtk_widget_show (info_title_label);

    hbox = gtk_hbox_new (FALSE, 12);
    gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
    gtk_widget_show (hbox);

    vbox2 = gtk_vbox_new (FALSE, 4);
    gtk_box_pack_start (GTK_BOX (hbox), vbox2, FALSE, FALSE, 0);
    gtk_widget_show (vbox2);

    show_info_event_box = gtk_event_box_new ();
    gtk_box_pack_start (GTK_BOX (vbox2), show_info_event_box, FALSE, FALSE,
                        0);
    gtk_widget_show (show_info_event_box);

    gimp_help_set_help_data (show_info_event_box,
                             _
                             ("Show/hide internal map information"),
                             NULL);

    show_info_button = gtk_toggle_button_new ();
    show_info_icon =
        gtk_image_new_from_stock (GTK_STOCK_INFO, GTK_ICON_SIZE_MENU);
    gtk_container_add (GTK_CONTAINER (show_info_button), show_info_icon);
    gtk_widget_show (show_info_icon);
    gtk_container_add (GTK_CONTAINER (show_info_event_box),
                       show_info_button);
    gtk_widget_show (show_info_button);

    g_signal_connect (show_info_button, "toggled",
                      G_CALLBACK (callback_show_info_button),
                      (gpointer) & interface_I_data);


    flatten_event_box = gtk_event_box_new ();
    gtk_box_pack_start (GTK_BOX (vbox2), flatten_event_box, FALSE, FALSE,
                        0);
    gtk_widget_show (flatten_event_box);

    gimp_help_set_help_data (flatten_event_box,
                             _
                             ("Reset the internal map"),
                             NULL);

    flatten_button = gtk_button_new ();
    flatten_icon =
        gtk_image_new_from_stock (GIMP_STOCK_RESET, GTK_ICON_SIZE_MENU);
    gtk_container_add (GTK_CONTAINER (flatten_button), flatten_icon);
    gtk_widget_show (flatten_icon);
    gtk_container_add (GTK_CONTAINER (flatten_event_box),
                       flatten_button);
    gtk_widget_show (flatten_button);

    g_signal_connect (flatten_button, "clicked",
                      G_CALLBACK (callback_flatten_button),
                      (gpointer) & interface_I_data);

    dump_event_box = gtk_event_box_new ();
    gtk_box_pack_start (GTK_BOX (vbox2), dump_event_box, FALSE, FALSE,
                        0);
    gtk_widget_show (dump_event_box);

    gimp_help_set_help_data (dump_event_box,
                             _
                             ("Dump the internal map on a new layer (RGB images only)"),
                             NULL);

    dump_button = gtk_button_new ();
    dump_icon =
        gtk_image_new_from_stock (GIMP_STOCK_VISIBLE, GTK_ICON_SIZE_MENU);
    gtk_container_add (GTK_CONTAINER (dump_button), dump_icon);
    gtk_widget_show (dump_icon);
    gtk_container_add (GTK_CONTAINER (dump_event_box),
                       dump_button);
    gtk_widget_show (dump_button);

    g_signal_connect (dump_button, "clicked",
                      G_CALLBACK (callback_dump_button),
                      (gpointer) & interface_I_data);

    gtk_widget_set_sensitive(dump_button, FALSE);
    interface_I_data.dump_button = dump_button;

    info_label = gtk_label_new("");
    //set_info_label_text (info_label, orig_width, orig_height, 0, 0, state->enl_step / 100);
    gtk_label_set_selectable(GTK_LABEL(info_label), TRUE);
    //gtk_container_add (GTK_CONTAINER (info_frame), info_label);
    gtk_box_pack_start (GTK_BOX (hbox), info_label, TRUE, TRUE, 0);
    gtk_label_set_justify(GTK_LABEL (info_label), GTK_JUSTIFY_LEFT);
    gtk_widget_show (info_label);

    //interface_I_data.info_frame = info_frame;
    interface_I_data.info_label = info_label;

    callback_show_info_button(show_info_button, (gpointer) &interface_I_data);


    /*
    noninter_button = gtk_button_new_with_mnemonic ("_Non-interactive");

    g_signal_connect (GTK_BUTTON (noninter_button), "clicked",
                      G_CALLBACK (callback_noninter_button), (gpointer) dlg);

    gtk_box_pack_start (GTK_BOX (vbox2), noninter_button, FALSE, FALSE, 0);
    gtk_widget_show (noninter_button);
    */

    /* Initialize the carver */

    AUX_LAYER_STATUS(state->pres_layer_ID, ui_state->pres_status);
    AUX_LAYER_STATUS(state->disc_layer_ID, ui_state->disc_status);
    AUX_LAYER_STATUS(state->rigmask_layer_ID, ui_state->rigmask_status);
    gimp_image_undo_group_start(image_ID);
    carver_data = render_init_carver(image_vals, drawable_vals, state, TRUE);
    gimp_image_undo_group_end(image_ID);
    if (carver_data == NULL)
    {
        return RESPONSE_FATAL;
    }
    interface_I_data.carver_data = carver_data;

    image_vals->image_ID = carver_data->image_ID;
    drawable_vals->layer_ID = carver_data->layer_ID;

    set_info_label_text (&interface_I_data);

    //set_alarm (ALARM_DELAY);
    size_changed = 1;

    /* register size reader */

    g_timeout_add (READER_INTERVAL, check_size_changes, NULL);

    /*  Show the main containers  */

    gtk_widget_show (main_hbox);
    gtk_widget_show (dlg);
    gtk_main ();


    lqr_carver_destroy (carver_data->carver);

    switch (dialog_I_response)
    {
    case RESPONSE_NONINTERACTIVE:
        switch (state->output_target)
        {
        case OUTPUT_TARGET_NEW_LAYER:
        case OUTPUT_TARGET_NEW_IMAGE:
            state->output_target = OUTPUT_TARGET_SAME_LAYER;
            break;
        case OUTPUT_TARGET_SAME_LAYER:
        default:
            break;
        }
    case GTK_RESPONSE_OK:
        /*  Save ui values  */
        ui_state->chain_active =
            gimp_chain_button_get_active (GIMP_COORDINATES_CHAINBUTTON
                                          (coordinates));

        /* save all */
        memcpy (vals, state, sizeof (PlugInVals));
        memcpy (ui_vals, ui_state, sizeof (PlugInUIVals));
        break;
    default:
        break;
    }

    gtk_widget_destroy (dlg);

    reader_go = FALSE;

    return dialog_I_response;
}
示例#29
0
/* run in a thread (SDL overlay)*/
void *main_loop(void *data)
{
    struct ALL_DATA *all_data = (struct ALL_DATA *) data;

    struct VidState *s = all_data->s;
    struct paRecordData *pdata = all_data->pdata;
    struct GLOBAL *global = all_data->global;
    struct focusData *AFdata = all_data->AFdata;
    struct vdIn *videoIn = all_data->videoIn;

    struct particle* particles = NULL; //for the particles video effect

    SDL_Event event;
    /*the main SDL surface*/
    SDL_Surface *pscreen = NULL;
    SDL_Overlay *overlay = NULL;
    SDL_Rect drect;

    int width = global->width;
    int height = global->height;
    int format = global->format;

    SAMPLE vuPeak[2];  // The maximum vuLevel seen recently
    int vuPeakFreeze[2]; // The vuPeak values will be frozen for this many frames.
    vuPeak[0] = vuPeak[1] = 0;
    vuPeakFreeze[0] = vuPeakFreeze[1] = 0;

    BYTE *p = NULL;

    Control *focus_control = NULL;
    int last_focus = 0;

    if (global->AFcontrol)
    {
        focus_control = get_ctrl_by_id(s->control_list, AFdata->id);
        get_ctrl(videoIn->fd, s->control_list, AFdata->id, all_data);
        last_focus = focus_control->value;
        /*make sure we wait for focus to settle on first check*/
        if (last_focus < 0) last_focus = AFdata->f_max;
    }

    gboolean capVid = FALSE;
    gboolean signalquit = FALSE;

    /*------------------------------ SDL init video ---------------------*/
    if(!global->no_display)
    {
        overlay = video_init(data, &(pscreen));

        if(overlay == NULL)
        {
            g_print("FATAL: Couldn't create yuv overlay - please disable hardware accelaration\n");
            signalquit = TRUE; /*exit video thread*/
        }
        else
        {
            p = (unsigned char *) overlay->pixels[0];

            drect.x = 0;
            drect.y = 0;
            drect.w = pscreen->w;
            drect.h = pscreen->h;
        }
    }

    while (!signalquit)
    {
        __LOCK_MUTEX(__VMUTEX);
            capVid = videoIn->capVid;
            signalquit = videoIn->signalquit;
        __UNLOCK_MUTEX(__VMUTEX);

        /*-------------------------- Grab Frame ----------------------------------*/
        if (uvcGrab(videoIn, format, width, height, &global->fps, &global->fps_num) < 0)
        {
            g_printerr("Error grabbing image \n");
            continue;
        }
        else
        {
            if(!videoIn->timestamp)
            {
                global->skip_n++; //skip this frame
            }

            if(capVid)
            {
                if(global->framecount < 1)
                {
					/*reset video start time to first frame capture time */
					global->Vidstarttime = videoIn->timestamp;
					/** set current time for audio ts(0) reference (MONOTONIC)
					 *  only used if we have no audio capture before video
					 */
					__LOCK_MUTEX(__AMUTEX);
						pdata->ts_ref = ns_time_monotonic();
					__UNLOCK_MUTEX(__AMUTEX);
					//printf("video ts ref: %llu audio ts_ ref: %llu\n",global->Vidstarttime, pdata->ts_ref);
					global->v_ts = 0;
                }
                else
                {
                    global->v_ts = videoIn->timestamp - global->Vidstarttime;
                    /*always use the last frame time stamp for video stop time*/
                    global->Vidstoptime = videoIn->timestamp;
                }
            }

            if (global->FpsCount && !global->no_display)
            {/* sets fps count in window title bar */
                global->frmCount++;
                if (global->DispFps>0)
                { /*set every 2 sec*/
                    g_snprintf(global->WVcaption,24,"GUVCVideo - %3.2f fps",global->DispFps);
                    SDL_WM_SetCaption(global->WVcaption, NULL);

                    global->frmCount=0;/*resets*/
                    global->DispFps=0;
                }
            }

            /*---------------- autofocus control ------------------*/

            if (global->AFcontrol && (global->autofocus || AFdata->setFocus))
            { /*AFdata = NULL if no focus control*/
                if (AFdata->focus < 0)
                {
                    /*starting autofocus*/
                    AFdata->focus = AFdata->left; /*start left*/
                    focus_control->value = AFdata->focus;
                    if (set_ctrl (videoIn->fd, s->control_list, AFdata->id) != 0)
                        g_printerr("ERROR: couldn't set focus to %d\n", AFdata->focus);
                    /*number of frames until focus is stable*/
                    /*1.4 ms focus time - every 1 step*/
                    AFdata->focus_wait = (int) abs(AFdata->focus-last_focus)*1.4/(1000/global->fps)+1;
                    last_focus = AFdata->focus;
                }
                else
                {
                    if (AFdata->focus_wait == 0)
                    {
                        AFdata->sharpness=getSharpness (videoIn->framebuffer, width, height, 5);
                        if (global->debug)
                            g_print("sharp=%d focus_sharp=%d foc=%d right=%d left=%d ind=%d flag=%d\n",
                                AFdata->sharpness,AFdata->focus_sharpness,
                                AFdata->focus, AFdata->right, AFdata->left,
                                AFdata->ind, AFdata->flag);
                        AFdata->focus=getFocusVal (AFdata);
                        if ((AFdata->focus != last_focus))
                        {
                            focus_control->value = AFdata->focus;
                            if (set_ctrl (videoIn->fd, s->control_list, AFdata->id) != 0)
                                g_printerr("ERROR: couldn't set focus to %d\n",
                                    AFdata->focus);
                            /*number of frames until focus is stable*/
                            /*1.4 ms focus time - every 1 step*/
                            AFdata->focus_wait = (int) abs(AFdata->focus-last_focus)*1.4/(1000/global->fps)+1;
                        }
                        last_focus = AFdata->focus;
                    }
                    else
                    {
                        AFdata->focus_wait--;
                        if (global->debug) g_print("Wait Frame: %d\n",AFdata->focus_wait);
                    }
                }
            }
        }
        /*------------------------- Filter Frame ---------------------------------*/
        __LOCK_MUTEX(__GMUTEX);
        if(global->Frame_Flags>0)
        {
            if((global->Frame_Flags & YUV_PARTICLES)==YUV_PARTICLES)
                particles = particles_effect(videoIn->framebuffer, width, height, 20, 4, particles);

            if((global->Frame_Flags & YUV_MIRROR)==YUV_MIRROR)
                yuyv_mirror(videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_UPTURN)==YUV_UPTURN)
                yuyv_upturn(videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_NEGATE)==YUV_NEGATE)
                yuyv_negative (videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_MONOCR)==YUV_MONOCR)
                yuyv_monochrome (videoIn->framebuffer, width, height);

            if((global->Frame_Flags & YUV_PIECES)==YUV_PIECES)
                pieces (videoIn->framebuffer, width, height, 16 );

        }
        __UNLOCK_MUTEX(__GMUTEX);
        /*-------------------------capture Image----------------------------------*/
        if (videoIn->capImage)
        {
            /*
             * format and resolution can change(enabled) while capturing the frame
             * but you would need to be speedy gonzalez to press two buttons
             * at almost the same time :D
             */
            int ret = 0;
            if((ret=store_picture(all_data)) < 0)
                g_printerr("saved image to:%s ...Failed \n",videoIn->ImageFName);
            else if (!ret && global->debug) g_print("saved image to:%s ...OK \n",videoIn->ImageFName);

            videoIn->capImage=FALSE;
        }
        /*---------------------------capture Video---------------------------------*/
        if (capVid && !(global->skip_n))
        {
            __LOCK_MUTEX(__VMUTEX);
                if(videoIn->VidCapStop) videoIn->VidCapStop = FALSE;
            __UNLOCK_MUTEX(__VMUTEX);
            int res=0;

			/* format and resolution don't change(disabled) while capturing video
			 * store_video_frame may sleep if needed to avoid buffer overrun
			 */
            if((res=store_video_frame(all_data))<0) g_printerr("WARNING: droped frame (%i)\n",res);

        } /*video and audio capture have stopped */
        else
        {
            __LOCK_MUTEX(__VMUTEX);
                if(!(videoIn->VidCapStop)) videoIn->VidCapStop=TRUE;
            __UNLOCK_MUTEX(__VMUTEX);
        }

        /* decrease skip frame count */
        if (global->skip_n > 0)
        {
            if (global->debug && capVid) g_print("skiping frame %d...\n", global->skip_n);
            global->skip_n--;
        }

        __LOCK_MUTEX( __AMUTEX );
            if (global->Sound_enable && capVid) pdata->skip_n = global->skip_n;
        __UNLOCK_MUTEX( __AMUTEX );

        /*------------------------- Display Frame --------------------------------*/
        if(!global->no_display)
        {
			if (global->osdFlags && pdata->audio_buff[0])
			{
				draw_vu_meter(width, height, vuPeak, vuPeakFreeze, data);
			}
            SDL_LockYUVOverlay(overlay);
            memcpy(p, videoIn->framebuffer, width * height * 2);
            SDL_UnlockYUVOverlay(overlay);
            SDL_DisplayYUVOverlay(overlay, &drect);

            /*------------------------- Read Key events ------------------------------*/
            /* Poll for events */
            while( SDL_PollEvent(&event) )
            {
                //printf("event type:%i  event key:%i\n", event.type, event.key.keysym.scancode);
                if(event.type==SDL_KEYDOWN)
                {
                    if (videoIn->PanTilt)
                    {
                        switch( event.key.keysym.sym )
                        {
                            /* Keyboard event */
                            /* Pass the event data onto PrintKeyInfo() */
                            case SDLK_DOWN:
                                /*Tilt Down*/
                                uvcPanTilt (videoIn->fd, s->control_list, 0, 1);
                                break;

                            case SDLK_UP:
                                /*Tilt UP*/
                                uvcPanTilt (videoIn->fd, s->control_list, 0, -1);
                                break;

                            case SDLK_LEFT:
                                /*Pan Left*/
                                uvcPanTilt (videoIn->fd, s->control_list, 1, 1);
                                break;

                            case SDLK_RIGHT:
                                /*Pan Right*/
                                uvcPanTilt (videoIn->fd, s->control_list, 1, -1);
                                break;
                            default:
                                break;
                        }
                    }
                    switch( event.key.keysym.scancode )
                    {
                        case 220: /*webcam button*/
                            //gdk_threads_enter();
                           	if (all_data->global->default_action == 0)
                           		g_main_context_invoke(NULL, image_capture_callback, (gpointer) all_data);
							else
                            	g_main_context_invoke(NULL, video_capture_callback, (gpointer) all_data);
                       
                            break;
                    }
                    switch( event.key.keysym.sym )
                    {
                        case SDLK_q:
                            //shutDown
                            g_timeout_add(200, shutd_timer, all_data);
                            g_print("q pressed - Quiting...\n");
                            break;
                        case SDLK_SPACE:
							{
                            if(global->AFcontrol > 0)
                                setfocus_clicked(NULL, all_data);
							}
                            break;
                        case SDLK_i:
							g_main_context_invoke(NULL, image_capture_callback, (gpointer) all_data);
							break;
						case SDLK_v:
							g_main_context_invoke(NULL, video_capture_callback, (gpointer) all_data);
							break;
                        default:
                            break;
                    }
                }
                if(event.type==SDL_VIDEORESIZE)
                {
                    pscreen =
                        SDL_SetVideoMode(event.resize.w,
                                 event.resize.h,
                                 global->bpp,
                                 SDL_VIDEO_Flags);
                    drect.w = event.resize.w;
                    drect.h = event.resize.h;
                }
                if(event.type==SDL_QUIT)
                {
                    //shutDown
                    g_timeout_add(200, shutd_timer, all_data);
                }
            }
        }
        /* if set make the thread sleep - default no sleep (full throttle)*/
        if(global->vid_sleep) sleep_ms(global->vid_sleep);

        /*------------------------------------------*/
        /*  restart video (new resolution/format)   */
        /*------------------------------------------*/
        if (global->change_res)
        {
            g_print("setting new resolution (%d x %d)\n", global->width, global->height);
            /*clean up */

            if(particles) g_free(particles);
            particles = NULL;

            if (global->debug) g_print("cleaning buffer allocations\n");
            fflush(NULL);//flush all output buffers

            if(!global->no_display)
            {
                SDL_FreeYUVOverlay(overlay);
                overlay = NULL;
            }
            /*init device*/
            restart_v4l2(videoIn, global);
            /*set new resolution for video thread*/
            width = global->width;
            height = global->height;
            format = global->format;
            /* restart SDL with new values*/
            if(!global->no_display)
            {
                overlay = video_init(data, &(pscreen));
                if(overlay == NULL)
                {
                    g_print("FATAL: Couldn't create yuv overlay - please disable hardware accelaration\n");
                    signalquit = TRUE; /*exit video thread*/
                }
                else
                {
                    if (global->debug) g_print("yuv overlay created (%ix%i).\n", overlay->w, overlay->h);
                    p = (unsigned char *) overlay->pixels[0];

                    drect.x = 0;
                    drect.y = 0;
                    drect.w = pscreen->w;
                    drect.h = pscreen->h;

                    global->change_res = FALSE;
                }
            }
            else global->change_res = FALSE;
        }

    }/*loop end*/

    __LOCK_MUTEX(__VMUTEX);
        capVid = videoIn->capVid;
    __UNLOCK_MUTEX(__VMUTEX);
    /*check if thread exited while in Video capture mode*/
    if (capVid)
    {
        /*stop capture*/
        if (global->debug) g_print("stoping Video capture\n");
        //global->Vidstoptime = ns_time_monotonic(); /*this is set in IO thread*/
        videoIn->VidCapStop=TRUE;
        capVid = FALSE;
        __LOCK_MUTEX(__VMUTEX);
            videoIn->capVid = capVid;
        __UNLOCK_MUTEX(__VMUTEX);
        __LOCK_MUTEX(__AMUTEX);
            pdata->capVid = capVid;
        __UNLOCK_MUTEX(__AMUTEX);
        /*join IO thread*/
        if (global->debug) g_print("Shuting Down IO Thread\n");
        __THREAD_JOIN( all_data->IO_thread );
        if (global->debug) g_print("IO Thread finished\n");
    }

    if (global->debug) g_print("Thread terminated...\n");
    p = NULL;
    if(particles) g_free(particles);
    particles=NULL;

    if (global->debug) g_print("cleaning Thread allocations: 100%%\n");
    fflush(NULL);//flush all output buffers

    if(!global->no_display)
    {
        if(overlay)
            SDL_FreeYUVOverlay(overlay);
        //SDL_FreeSurface(pscreen);

        SDL_Quit();
    }

    if (global->debug) g_print("Video thread completed\n");

    global = NULL;
    AFdata = NULL;
    videoIn = NULL;
    return ((void *) 0);
}
示例#30
0
int main (int argc, char* argv[]) {
    GtkWidget *window;
    GtkWidget *scrollo, *scrollo2;
    GtkWidget *playaline;
    GtkWidget *speedknob, *speedknob2, *zoomxknob, *zoomyknob;
    GtkWidget *vbox1, *vbox2, *hbox;

    gtk_init (&argc, &argv);

    // jack_client
    jack_client_t *client = jack_client_open( "phatplaya", 0, NULL );
    p1 = jack_port_register( client, "out1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
    p2 = jack_port_register( client, "out2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
    p3 = jack_port_register( client, "out3", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
    p4 = jack_port_register( client, "out4", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
    
    // audio stream
    s1 = phat_audiostream_new( argv[1] );
    phat_audiostream_set_speed( PHAT_AUDIOSTREAM(s1), 1.0 );

    s2 = phat_audiostream_new( argv[1] );
    phat_audiostream_set_speed( PHAT_AUDIOSTREAM(s2), 1.0 );

    // run jack
    jack_set_process_callback( client, (JackProcessCallback) jack_process, s1 );
    jack_activate( client );

    /* main window */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (window), "Scrollo Demo (phatplaya)");
    gtk_container_set_border_width (GTK_CONTAINER (window), SPACING);
    gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER);
    g_signal_connect (G_OBJECT (window), "delete-event",
                      G_CALLBACK (gtk_main_quit), NULL);

    // boxen
    hbox = gtk_hbox_new (FALSE, SPACING);
    gtk_container_add (GTK_CONTAINER (window), hbox);
    gtk_widget_show (hbox);

    vbox1 = gtk_vbox_new (FALSE, SPACING);
    gtk_box_pack_start (GTK_BOX (hbox), vbox1, FALSE, TRUE, 0);
    gtk_widget_show (vbox1);

    vbox2 = gtk_vbox_new (FALSE, SPACING);
    gtk_box_pack_end (GTK_BOX (hbox), vbox2, TRUE, TRUE, 0);
    gtk_widget_show (vbox2);

    // knobs
    speedknob = phat_knob_new_with_range( 1.0, 0.9, 1.1, 0.001 );
    gtk_box_pack_start (GTK_BOX (vbox1), speedknob, FALSE, TRUE, 0);
    gtk_widget_show( speedknob );

    speedknob2 = phat_knob_new_with_range( 1.0, 0.9, 1.1, 0.001 );
    gtk_box_pack_start (GTK_BOX (vbox1), speedknob2, FALSE, TRUE, 0);
    gtk_widget_show( speedknob2 );

    zoomxknob = phat_knob_new_with_range( 5.0, 0.2, 20.1, 0.1 );
    gtk_box_pack_end (GTK_BOX (vbox1), zoomxknob, FALSE, TRUE, 0);
    gtk_widget_show( zoomxknob );

    zoomyknob = phat_knob_new_with_range( 1, 0.001, 40.0, 0.01 );
    gtk_box_pack_end (GTK_BOX (vbox1), zoomyknob, FALSE, TRUE, 0);
    gtk_widget_show( zoomyknob );

    // upper playaline
    playaline = phat_playaline_new( GTK_DIR_DOWN );
    gtk_box_pack_start (GTK_BOX (vbox2), playaline, FALSE, TRUE, 0);
    gtk_widget_show (playaline);

    // the scrollo
    scrollo = phat_scrolloscope_new( GTK_DIR_DOWN );
    phat_scrolloscope_set_audio_stream( PHAT_SCROLLOSCOPE(scrollo), PHAT_AUDIOSTREAM(s1) );

    // connect knobs;
    g_signal_connect (G_OBJECT (speedknob), "value-changed",
                      G_CALLBACK (speedknob_cb), scrollo );
    g_signal_connect (G_OBJECT (zoomxknob), "value-changed",
                      G_CALLBACK (zoomxknob_cb), scrollo );
    g_signal_connect (G_OBJECT (zoomyknob), "value-changed",
                      G_CALLBACK (zoomyknob_cb), scrollo );
     

    gtk_box_pack_start (GTK_BOX (vbox2), scrollo, TRUE, TRUE, 0);
    gtk_widget_show (scrollo);

    scrollo2 = phat_scrolloscope_new( GTK_DIR_UP );
    phat_scrolloscope_set_audio_stream( PHAT_SCROLLOSCOPE(scrollo2), PHAT_AUDIOSTREAM(s2) );

    // connect knobs;
    g_signal_connect (G_OBJECT (speedknob2), "value-changed",
                      G_CALLBACK (speedknob_cb), scrollo2 );
    g_signal_connect (G_OBJECT (zoomxknob), "value-changed",
                      G_CALLBACK (zoomxknob_cb), scrollo2 );
    g_signal_connect (G_OBJECT (zoomyknob), "value-changed",
                      G_CALLBACK (zoomyknob_cb), scrollo2 );
     

    gtk_box_pack_start (GTK_BOX (vbox2), scrollo2, TRUE, TRUE, 0);
    gtk_widget_show (scrollo2);
    
    playaline = phat_playaline_new( GTK_DIR_UP );
    gtk_box_pack_end (GTK_BOX (vbox2), playaline, FALSE, TRUE, 0);
    gtk_widget_show (playaline);

    gtk_widget_show (window);


    g_timeout_add( 15, (GSourceFunc) scroll_func, scrollo );
    g_timeout_add( 15, (GSourceFunc) scroll_func, scrollo2 );
    gtk_main ( );

    jack_deactivate( client );
    return 0;
}