Example #1
0
static void
indicator_workrave_start(IndicatorWorkrave *self)
{
  IndicatorWorkravePrivate *priv = INDICATOR_WORKRAVE_GET_PRIVATE(self);

  if (priv->alive)
    {
      return;
    }

  priv->owner_id = g_bus_own_name(G_BUS_TYPE_SESSION,
                                  DBUS_NAME,
                                  G_BUS_NAME_OWNER_FLAGS_NONE,
                                  on_bus_acquired,
                                  NULL,
                                  NULL,
                                  self,
                                  NULL);

  GError *error = NULL;

  if (error == NULL)
    {
      GVariant *result = g_dbus_proxy_call_sync(priv->workrave_ui_proxy,
                                                "Embed",
                                                g_variant_new("(bs)", TRUE, DBUS_NAME),
                                                G_DBUS_CALL_FLAGS_NONE,
                                                -1,
                                                NULL,
                                                &error);

      if (error != NULL)
        {
          g_warning("Could not request embedding for %s: %s", WORKRAVE_INDICATOR_SERVICE_NAME, error->message);
        }
      else
        {
          if (result != NULL)
            {
              g_variant_unref(result);
            }
        }
    }

  if (error == NULL)
    {
      GVariant *result = g_dbus_proxy_call_sync(priv->workrave_ui_proxy,
                                                "GetTrayIconEnabled",
                                                NULL,
                                                G_DBUS_CALL_FLAGS_NONE,
                                                -1,
                                                NULL,
                                                &error);

      if (error != NULL)
        {
          g_warning("Could not request tray icon enabled for %s: %s", WORKRAVE_INDICATOR_SERVICE_NAME, error->message);
        }
      else
        {
          if (result != NULL)
            {
              g_variant_get(result, "(b)", &priv->force_icon);
              g_variant_unref(result);
            }
        }
    }

  if (error == NULL)
    {
      GVariant *result = g_dbus_proxy_call_sync(priv->workrave_core_proxy,
                                                "GetOperationMode",
                                                NULL,
                                                G_DBUS_CALL_FLAGS_NONE,
                                                -1,
                                                NULL,
                                                &error);

      if (error != NULL)
        {
          g_warning("Could not request operation mode for %s: %s", WORKRAVE_INDICATOR_SERVICE_NAME, error->message);
        }
      else
        {
          gchar *mode;
          g_variant_get(result, "(s)", &mode);
          workrave_timerbox_set_operation_mode(priv->timerbox, mode);
          g_variant_unref(result);
        }
    }

  if (error == NULL)
    {
      priv->timer = g_timeout_add_seconds(10, on_timer, self);
      priv->alive = TRUE;
      priv->update_count = 0;
    }
  else
    {
      g_error_free(error);
    }
}
static void
update_persona (EmpathyPersonaStore *self,
    FolksPersona *persona)
{
  EmpathyPersonaStorePriv *priv = GET_PRIV (self);
  GtkTreePath *path;
  gboolean do_set_active = FALSE;
  gboolean do_set_refresh = FALSE;
  const gchar *alias;

  path = find_persona (self, persona);
  alias = folks_aliasable_get_alias (FOLKS_ALIASABLE (persona));

  if (path == NULL)
    {
      DEBUG ("Contact:'%s' in list:NO, should be:YES", alias);

      add_persona (self, persona);

      if (priv->show_active)
        {
          do_set_active = TRUE;
          DEBUG ("Set active (contact added)");
        }
    }
  else
    {
      FolksPersonaStore *store;
      EmpathyContact *contact;
      GtkTreeIter iter;
      GdkPixbuf *pixbuf_avatar;
      GdkPixbuf *pixbuf_status;
      gboolean now_online = FALSE;
      gboolean was_online = TRUE;

      DEBUG ("Contact:'%s' in list:YES, should be:YES", alias);

      gtk_tree_model_get_iter (GTK_TREE_MODEL (self), &iter, path);
      gtk_tree_path_free (path);

      /* Get online state now. */
      now_online = folks_presence_is_online (FOLKS_PRESENCE (persona));

      /* Get online state before. */
      gtk_tree_model_get (GTK_TREE_MODEL (self), &iter,
          EMPATHY_PERSONA_STORE_COL_IS_ONLINE, &was_online,
          -1);

      /* Is this really an update or an online/offline. */
      if (priv->show_active)
        {
          if (was_online != now_online)
            {
              do_set_active = TRUE;
              do_set_refresh = TRUE;

              DEBUG ("Set active (contact updated %s)",
                  was_online ? "online  -> offline" : "offline -> online");
            }
          else
            {
              /* Was TRUE for presence updates. */
              /* do_set_active = FALSE;  */
              do_set_refresh = TRUE;
              DEBUG ("Set active (contact updated)");
            }
        }

      /* We still need to use EmpathyContact for the capabilities stuff */
      contact = empathy_contact_dup_from_tp_contact (tpf_persona_get_contact (
          TPF_PERSONA (persona)));
      store = folks_persona_get_store (persona);

      pixbuf_avatar = empathy_pixbuf_avatar_from_contact_scaled (contact,
          32, 32);
      pixbuf_status = get_persona_status_icon (self, persona);

      gtk_list_store_set (GTK_LIST_STORE (self), &iter,
          EMPATHY_PERSONA_STORE_COL_ICON_STATUS, pixbuf_status,
          EMPATHY_PERSONA_STORE_COL_PIXBUF_AVATAR, pixbuf_avatar,
          EMPATHY_PERSONA_STORE_COL_PIXBUF_AVATAR_VISIBLE, priv->show_avatars,
          EMPATHY_PERSONA_STORE_COL_NAME, alias,
          EMPATHY_PERSONA_STORE_COL_ACCOUNT_NAME,
              folks_persona_store_get_display_name (store),
          EMPATHY_PERSONA_STORE_COL_DISPLAY_ID,
              folks_persona_get_display_id (persona),
          EMPATHY_PERSONA_STORE_COL_PRESENCE_TYPE,
              folks_presence_get_presence_type (FOLKS_PRESENCE (persona)),
          EMPATHY_PERSONA_STORE_COL_STATUS,
              folks_presence_get_presence_message (FOLKS_PRESENCE (persona)),
          EMPATHY_PERSONA_STORE_COL_IS_ONLINE, now_online,
          EMPATHY_PERSONA_STORE_COL_CAN_AUDIO_CALL,
              empathy_contact_get_capabilities (contact) &
                EMPATHY_CAPABILITIES_AUDIO,
          EMPATHY_PERSONA_STORE_COL_CAN_VIDEO_CALL,
              empathy_contact_get_capabilities (contact) &
                EMPATHY_CAPABILITIES_VIDEO,
          -1);

      g_object_unref (contact);

      if (pixbuf_avatar)
        g_object_unref (pixbuf_avatar);
    }

  if (priv->show_active && do_set_active)
    {
      persona_set_active (self, persona, do_set_active, do_set_refresh);

      if (do_set_active)
        {
          ShowActiveData *data;

          data = persona_active_new (self, persona, FALSE);
          data->timeout = g_timeout_add_seconds (ACTIVE_USER_SHOW_TIME,
              (GSourceFunc) persona_active_cb,
              data);
        }
    }

  /* FIXME: when someone goes online then offline quickly, the
   * first timeout sets the user to be inactive and the second
   * timeout removes the user from the contact list, really we
   * should remove the first timeout.
   */
}
Example #3
0
static gboolean
new_game_2_cb (GtkWidget * widget, gpointer data)
{
  if (!paused) {
    if (!keyboard_id)
      keyboard_id = g_signal_connect (G_OBJECT (stage),
                                      "key-press-event",
                                      G_CALLBACK (key_press_cb), NULL);
#ifdef GGZ_CLIENT
    if (!main_id && ggz_network_mode && network_is_host ()) {
      main_id = g_timeout_add (GAMEDELAY * (properties->gamespeed + NETDELAY),
                               (GSourceFunc) network_loop, NULL);
    } else
#endif
    if (!main_id && !ggz_network_mode) {
      main_id = g_timeout_add (GAMEDELAY * properties->gamespeed,
                               (GSourceFunc) main_loop, NULL);
    }
#ifdef GGZ_CLIENT
    if (!add_bonus_id && network_is_host ()) {
#else
    if (!add_bonus_id) {
#endif
      add_bonus_id = g_timeout_add (BONUSDELAY *
                                    properties->gamespeed,
                                    (GSourceFunc) add_bonus_cb, NULL);
    }
  }

  dummy_id = 0;

  return FALSE;
}

gboolean
new_game (void)
{
  int i;

  gtk_action_set_sensitive (new_network_action, FALSE);

  if (ggz_network_mode) {
    gtk_action_set_sensitive (pause_action, FALSE);
  } else {
    gtk_action_set_sensitive (pause_action, TRUE);
  }
  gtk_action_set_sensitive (end_game_action, TRUE);
  gtk_action_set_sensitive (preferences_action, !ggz_network_mode);

  if (game_running ()) {
    end_game (FALSE);
    main_id = 0;
  }

  if (ggz_network_mode || !properties->random) {
    current_level = properties->startlevel;
  } else {
    current_level = rand () % MAXLEVEL + 1;
  }

  hide_logo ();
  gnibbles_init ();
  gnibbles_board_level_new (board, current_level);
  gnibbles_board_level_add_bonus (board, 1);

  for (i = 0; i < properties->numworms; i++) {
    if (!clutter_actor_get_stage (worms[i]->actors))
      clutter_container_add_actor (CLUTTER_CONTAINER (stage), worms[i]->actors);
    gnibbles_worm_show (worms[i]);
  }

  paused = 0;
  gtk_action_set_visible (pause_action, !paused);
  gtk_action_set_visible (resume_action, paused);
  gtk_action_set_visible (player_list_action, ggz_network_mode);

  if (restart_id) {
    g_source_remove (restart_id);
    restart_id = 0;
  }

  if (add_bonus_id) {
    g_source_remove (add_bonus_id);
    add_bonus_id = 0;
  }

  if (dummy_id)
    g_source_remove (dummy_id);

  dummy_id = g_timeout_add_seconds (1, (GSourceFunc) new_game_2_cb, NULL);

  network_gui_update ();

  return TRUE;
}
/* thumbnail_thread is invoked as a separate thread to to make thumbnails. */
static gpointer
thumbnail_thread_start (gpointer data)
{
	NautilusThumbnailInfo *info = NULL;
	GdkPixbuf *pixbuf;
	time_t current_orig_mtime = 0;
	time_t current_time;
	GList *node;

	/* We loop until there are no more thumbails to make, at which point
	   we exit the thread. */
	for (;;) {
#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Locking mutex\n");
#endif
		pthread_mutex_lock (&thumbnails_mutex);

		/*********************************
		 * MUTEX LOCKED
		 *********************************/

		/* Pop the last thumbnail we just made off the head of the
		   list and free it. I did this here so we only have to lock
		   the mutex once per thumbnail, rather than once before
		   creating it and once after.
		   Don't pop the thumbnail off the queue if the original file
		   mtime of the request changed. Then we need to redo the thumbnail.
		*/
		if (currently_thumbnailing &&
		    currently_thumbnailing->original_file_mtime == current_orig_mtime) {
			g_assert (info == currently_thumbnailing);
			node = g_hash_table_lookup (thumbnails_to_make_hash, info->image_uri);
			g_assert (node != NULL);
			g_hash_table_remove (thumbnails_to_make_hash, info->image_uri);
			free_thumbnail_info (info);
			g_queue_delete_link ((GQueue *)&thumbnails_to_make, node);
		}
		currently_thumbnailing = NULL;

		/* If there are no more thumbnails to make, reset the
		   thumbnail_thread_is_running flag, unlock the mutex, and
		   exit the thread. */
		if (g_queue_is_empty ((GQueue *)&thumbnails_to_make)) {
#ifdef DEBUG_THUMBNAILS
			g_message ("(Thumbnail Thread) Exiting\n");
#endif
			thumbnail_thread_is_running = FALSE;
			pthread_mutex_unlock (&thumbnails_mutex);
			pthread_exit (NULL);
		}

		/* Get the next one to make. We leave it on the list until it
		   is created so the main thread doesn't add it again while we
		   are creating it. */
		info = g_queue_peek_head ((GQueue *)&thumbnails_to_make);
		currently_thumbnailing = info;
		current_orig_mtime = info->original_file_mtime;
		/*********************************
		 * MUTEX UNLOCKED
		 *********************************/

#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Unlocking mutex\n");
#endif
		pthread_mutex_unlock (&thumbnails_mutex);

		time (&current_time);

		/* Don't try to create a thumbnail if the file was modified recently.
		   This prevents constant re-thumbnailing of changing files. */ 
		if (current_time < current_orig_mtime + THUMBNAIL_CREATION_DELAY_SECS &&
		    current_time >= current_orig_mtime) {
#ifdef DEBUG_THUMBNAILS
			g_message ("(Thumbnail Thread) Skipping: %s\n",
				   info->image_uri);
#endif
			/* Reschedule thumbnailing via a change notification */
			g_timeout_add_seconds (1, thumbnail_thread_notify_file_changed,
				       g_strdup (info->image_uri));
 			continue;
		}

		/* Create the thumbnail. */
#ifdef DEBUG_THUMBNAILS
		g_message ("(Thumbnail Thread) Creating thumbnail: %s\n",
			   info->image_uri);
#endif

		pixbuf = gnome_desktop_thumbnail_factory_generate_thumbnail (thumbnail_factory,
									     info->image_uri,
									     info->mime_type);

		if (pixbuf) {
			gnome_desktop_thumbnail_factory_save_thumbnail (thumbnail_factory,
									pixbuf,
									info->image_uri,
									current_orig_mtime);
			g_object_unref (pixbuf);
		} else {
			gnome_desktop_thumbnail_factory_create_failed_thumbnail (thumbnail_factory, 
										 info->image_uri,
										 current_orig_mtime);
		}
		/* We need to call nautilus_file_changed(), but I don't think that is
		   thread safe. So add an idle handler and do it from the main loop. */
		g_idle_add_full (G_PRIORITY_HIGH_IDLE,
				 thumbnail_thread_notify_file_changed,
				 g_strdup (info->image_uri), NULL);
	}
}
static void
supports_port_ready_cb (MMPlugin *plugin,
                        GAsyncResult *result,
                        SupportsInfo *info)
{
    MMPluginSupportsResult support_result;
    GError *error = NULL;

    /* Get supports check results */
    support_result = mm_plugin_supports_port_finish (plugin,
                                                     result,
                                                     &error);
    if (error) {
        mm_warn ("(%s): (%s) error when checking support: '%s'",
                 mm_plugin_get_name (plugin),
                 info->name,
                 error->message);
        g_error_free (error);
    }

    switch (support_result) {
    case MM_PLUGIN_SUPPORTS_PORT_SUPPORTED:
        /* Found a best plugin */
        info->best_plugin = plugin;

        if (info->suggested_plugin &&
            info->suggested_plugin != plugin) {
            /* The last plugin we tried said it supported this port, but it
             * doesn't correspond with the one we're being suggested. */
            g_warn_if_reached ();
        }

        mm_dbg ("(%s): (%s) found best plugin for port",
                mm_plugin_get_name (info->best_plugin),
                info->name);
        info->current = NULL;

        /* Schedule checking support, which will end the operation */
        info->source_id = g_idle_add ((GSourceFunc)find_port_support_idle,
                                      info);
        break;

    case MM_PLUGIN_SUPPORTS_PORT_UNSUPPORTED:
        if (info->suggested_plugin) {
            if (info->suggested_plugin == plugin) {
                /* If the plugin that just completed the support check claims
                 * not to support this port, but this plugin is clearly the
                 * right plugin since it claimed this port's physical modem,
                 * just drop the port.
                 */
                mm_dbg ("(%s/%s): ignoring port unsupported by physical modem's plugin",
                        info->subsys,
                        info->name);
                info->best_plugin = NULL;
                info->current = NULL;
            } else {
                /* The last plugin we tried is NOT the one we got suggested, so
                 * directly check support with the suggested plugin. If we
                 * already checked its support, it won't be checked again. */
                info->current = g_slist_find (info->current,
                                              info->suggested_plugin);
            }
        } else {
            /* If the plugin knows it doesn't support the modem, just keep on
             * checking the next plugin.
             */
            info->current = g_slist_next (info->current);
        }
        info->source_id = g_idle_add ((GSourceFunc)find_port_support_idle,
                                      info);
        break;

    case MM_PLUGIN_SUPPORTS_PORT_DEFER:
        /* Try with the suggested one after being deferred */
        if (info->suggested_plugin) {
            mm_dbg ("(%s): (%s) deferring support check, suggested: %s",
                    mm_plugin_get_name (MM_PLUGIN (info->current->data)),
                    info->name,
                    mm_plugin_get_name (MM_PLUGIN (info->suggested_plugin)));
            info->current = g_slist_find (info->current,
                                          info->suggested_plugin);
        } else {
            mm_dbg ("(%s): (%s) deferring support check",
                    mm_plugin_get_name (MM_PLUGIN (info->current->data)),
                    info->name);
        }
        /* Schedule checking support */
        info->source_id = g_timeout_add_seconds (SUPPORTS_DEFER_TIMEOUT_SECS,
                                                 (GSourceFunc)find_port_support_idle,
                                                 info);
        break;

    case MM_PLUGIN_SUPPORTS_PORT_DEFER_UNTIL_SUGGESTED:
        /* If we arrived here and we already have a plugin suggested, use it */
        if (info->suggested_plugin) {
            mm_dbg ("(%s): (%s) task completed, got suggested plugin",
                    mm_plugin_get_name (info->suggested_plugin),
                    info->name);
            /* Schedule checking support, which will end the operation */
            info->best_plugin = info->suggested_plugin;
            info->current = NULL;
            info->source_id = g_idle_add ((GSourceFunc)find_port_support_idle,
                                          info);
        } else {
            /* We are deferred until a suggested plugin is given. If last supports task
             * of a given device is finished without finding a best plugin, this task
             * will get finished reporting unsupported. */
            mm_dbg ("(%s) deferring support check until result suggested",
                    info->name);
            info->defer_until_suggested = TRUE;
        }
        break;
    }
}
Example #6
0
GST_END_TEST
GST_START_TEST (check_emit_encoded_media)
{
  guint bus_watch_id1, bus_watch_id2;
  GstBus *srcbus, *testbus;
  GstCaps *caps;

  GST_INFO ("Running test check_push_buffer");

  loop = g_main_loop_new (NULL, FALSE);

  /* Create source pipeline */
  src_pipeline = gst_pipeline_new ("src-pipeline");
  uridecodebin = gst_element_factory_make ("uridecodebin", NULL);
  appsink = gst_element_factory_make ("appsink", NULL);

  srcbus = gst_pipeline_get_bus (GST_PIPELINE (src_pipeline));

  bus_watch_id1 = gst_bus_add_watch (srcbus, gst_bus_async_signal_func, NULL);
  g_signal_connect (srcbus, "message", G_CALLBACK (bus_msg_cb), src_pipeline);
  g_object_unref (srcbus);

  gst_bin_add_many (GST_BIN (src_pipeline), uridecodebin, appsink, NULL);

  caps = gst_caps_new_any ();
  g_object_set (G_OBJECT (uridecodebin), "uri", VIDEO_PATH, "caps", caps, NULL);
  gst_caps_unref (caps);

  g_signal_connect (G_OBJECT (uridecodebin), "pad-added", G_CALLBACK (link_pad),
      appsink);

  g_object_set (appsink, "emit-signals", TRUE, NULL);
  g_signal_connect (appsink, "new-sample", G_CALLBACK (post_recv_sample), NULL);
  g_signal_connect (appsink, "eos", G_CALLBACK (appsink_eos_cb), NULL);

  /* Create test pipeline */
  test_pipeline = gst_pipeline_new ("test-pipeline");
  httpep = gst_element_factory_make ("httppostendpoint", NULL);
  g_object_set (httpep, "use-encoded-media", TRUE, NULL);

  testbus = gst_pipeline_get_bus (GST_PIPELINE (test_pipeline));

  bus_watch_id2 = gst_bus_add_watch (testbus, gst_bus_async_signal_func, NULL);
  g_signal_connect (testbus, "message", G_CALLBACK (bus_msg_cb), test_pipeline);
  g_object_unref (testbus);

  gst_bin_add (GST_BIN (test_pipeline), httpep);
  g_signal_connect (G_OBJECT (httpep), "eos", G_CALLBACK (http_eos_cb), NULL);

  /* Set pipeline to start state */
  gst_element_set_state (test_pipeline, GST_STATE_PLAYING);

  g_object_get (G_OBJECT (httpep), "http-method", &method, NULL);
  GST_INFO ("Http end point configured as %d", method);

  mark_point ();

  g_timeout_add_seconds (WAIT_TIMEOUT, timer_cb, NULL);

  g_main_loop_run (loop);

  mark_point ();

  GST_DEBUG ("Main loop stopped");

  GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (src_pipeline),
      GST_DEBUG_GRAPH_SHOW_ALL, "src_after_main_loop");

  GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (test_pipeline),
      GST_DEBUG_GRAPH_SHOW_ALL, "test_after_main_loop");

  gst_element_set_state (src_pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (src_pipeline));

  gst_element_set_state (test_pipeline, GST_STATE_NULL);
  gst_object_unref (GST_OBJECT (test_pipeline));

  g_source_remove (bus_watch_id1);
  g_source_remove (bus_watch_id2);
  g_main_loop_unref (loop);
}
Example #7
0
void mega_notify_client_timer_start(MEGAExt *mega_ext)
{
    g_debug("Starting timer");
    g_timeout_add_seconds(1, mega_notify_client_on_timer, mega_ext);
}
Example #8
0
static gboolean
presence_chooser_scroll_event_cb (EmpathyPresenceChooser *chooser,
				  GdkEventScroll        *event,
				  gpointer               user_data)
{
	EmpathyPresenceChooserPriv *priv;
	GList                     *list, *l;
	const gchar               *current_status;
	StateAndStatus            *sas;
	gboolean                   match;

	priv = GET_PRIV (chooser);

	switch (event->direction) {
	case GDK_SCROLL_UP:
		break;
	case GDK_SCROLL_DOWN:
		break;
	default:
		return FALSE;
	}

	current_status = gtk_label_get_text (GTK_LABEL (priv->label));

	/* Get the list of presets, which in this context means all the items
	 * without a trailing "...".
	 */
	list = presence_chooser_get_presets (chooser);
	sas = NULL;
	match = FALSE;
	for (l = list; l; l = l->next) {
		sas = l->data;

		if (sas->state == priv->last_state &&
		    strcmp (sas->status, current_status) == 0) {
			sas = NULL;
			match = TRUE;
			if (event->direction == GDK_SCROLL_UP) {
				if (l->prev) {
					sas = l->prev->data;
				}
			}
			else if (event->direction == GDK_SCROLL_DOWN) {
				if (l->next) {
					sas = l->next->data;
				}
			}
			break;
		}

		sas = NULL;
	}

	if (sas) {
		presence_chooser_reset_scroll_timeout (chooser);

		priv->scroll_status = g_strdup (sas->status);
		priv->scroll_state = sas->state;

		priv->scroll_timeout_id =
			g_timeout_add_seconds (1,
					       (GSourceFunc) presence_chooser_scroll_timeout_cb,
					       chooser);

		presence_chooser_flash_stop (chooser, sas->state);
		gtk_label_set_text (GTK_LABEL (priv->label), sas->status);	
	}
	else if (!match) {
		const gchar *status;
		/* If we didn't get any match at all, it means the last state
		 * was a custom one. Just switch to the first one.
		 */
		status = empathy_presence_get_default_message (states[0]);

		presence_chooser_reset_scroll_timeout (chooser);
		empathy_idle_set_presence (priv->idle, states[0], status);
	}

	g_list_foreach (list, (GFunc) g_free, NULL);
	g_list_free (list);

	return TRUE;
}
Example #9
0
static void
daemon_constructed (GObject *_object)
{
  Daemon *daemon = DAEMON (_object);
  CockpitManager *manager;
  CockpitNetwork *network = NULL;
  CockpitResourceMonitor *monitor;
  CockpitRealms *realms;
  CockpitServices *services;
  CockpitJournal *journal;
  CockpitAccounts *accounts;
  CockpitStorageManager *storage_manager;
  CockpitObjectSkeleton *object = NULL;

  g_assert (_daemon_instance == NULL);
  _daemon_instance = daemon;

  daemon->system_bus_proxy = g_dbus_proxy_new_sync (daemon->connection, G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
                                                    NULL, "org.freedesktop.DBus",
                                                    "/org/freedesktop/DBus",
                                                    "org.freedesktop.DBus", NULL, NULL);
  g_assert (daemon->system_bus_proxy != NULL);

  daemon->object_manager = g_dbus_object_manager_server_new ("/com/redhat/Cockpit");

  /* /com/redhat/Cockpit/Manager */
  manager = manager_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Manager");
  cockpit_object_skeleton_set_manager (object, manager);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (manager);
  g_object_unref (object);

  /* /com/redhat/Cockpit/Network */
  network = network_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Network");
  cockpit_object_skeleton_set_network (object, network);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_clear_object (&network);
  g_clear_object (&object);

  /* /com/redhat/Cockpit/CpuMonitor */
  monitor = cpu_monitor_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/CpuMonitor");
  cockpit_object_skeleton_set_resource_monitor (object, monitor);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (monitor);
  g_object_unref (object);

  /* /com/redhat/Cockpit/MemoryMonitor */
  monitor = memory_monitor_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/MemoryMonitor");
  cockpit_object_skeleton_set_resource_monitor (object, monitor);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (monitor);
  g_object_unref (object);

  /* /com/redhat/Cockpit/NetworkMonitor */
  monitor = network_monitor_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/NetworkMonitor");
  cockpit_object_skeleton_set_resource_monitor (object, monitor);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (monitor);
  g_object_unref (object);

  /* /com/redhat/Cockpit/DiskIOMonitor */
  monitor = disk_io_monitor_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/DiskIOMonitor");
  cockpit_object_skeleton_set_resource_monitor (object, monitor);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (monitor);
  g_object_unref (object);

  /* /com/redhat/Cockpit/Realms */
  realms = realms_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Realms");
  cockpit_object_skeleton_set_realms (object, realms);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (realms);
  g_object_unref (object);

  /* /com/redhat/Cockpit/Services */
  services = services_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Services");
  cockpit_object_skeleton_set_services (object, services);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (services);
  g_object_unref (object);

  /* /com/redhat/Cockpit/Journal */
  journal = journal_new ();
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Journal");
  cockpit_object_skeleton_set_journal (object, journal);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (journal);

  /* /com/redhat/Cockpit/Accounts */
  accounts = accounts_new ();
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Accounts");
  cockpit_object_skeleton_set_accounts (object, accounts);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (accounts);

  g_object_unref (object);

  /* /com/redhat/Cockpit/Storage/Manager */
  storage_manager = storage_manager_new (daemon);
  object = cockpit_object_skeleton_new ("/com/redhat/Cockpit/Storage/Manager");
  cockpit_object_skeleton_set_storage_manager (object, storage_manager);
  g_dbus_object_manager_server_export (daemon->object_manager, G_DBUS_OBJECT_SKELETON (object));
  g_object_unref (storage_manager);
  g_object_unref (object);

  daemon->storage_provider = storage_provider_new (daemon);

  /* Export the ObjectManager */
  g_dbus_object_manager_server_set_connection (daemon->object_manager, daemon->connection);

  daemon->tick_timeout_id = g_timeout_add_seconds (1, on_timeout, daemon);

  if (G_OBJECT_CLASS (daemon_parent_class)->constructed != NULL)
    G_OBJECT_CLASS (daemon_parent_class)->constructed (_object);
}
Example #10
0
static void prv_server_unavailable_cb(GUPnPControlPoint *cp,
				      GUPnPDeviceProxy *proxy,
				      gpointer user_data)
{
	dlr_upnp_t *upnp = user_data;
	const char *udn;
	dlr_device_t *device;
	const gchar *ip_address;
	unsigned int i;
	dlr_device_context_t *context;
	gboolean subscribed;
	gboolean under_construction = FALSE;
	prv_device_new_ct_t *priv_t;
	gboolean construction_ctx = FALSE;
	const dleyna_task_queue_key_t *queue_id;

	DLEYNA_LOG_DEBUG("Enter");

	udn = gupnp_device_info_get_udn((GUPnPDeviceInfo *)proxy);

	ip_address = gupnp_context_get_host_ip(
		gupnp_control_point_get_context(cp));

	if (!udn || !ip_address)
		goto on_error;

	DLEYNA_LOG_DEBUG("UDN %s", udn);
	DLEYNA_LOG_DEBUG("IP Address %s", ip_address);

	device = g_hash_table_lookup(upnp->server_udn_map, udn);

	if (!device) {
		priv_t = g_hash_table_lookup(upnp->server_uc_map, udn);

		if (priv_t) {
			device = priv_t->device;
			under_construction = TRUE;
		}
	}

	if (!device) {
		DLEYNA_LOG_WARNING("Device not found. Ignoring");
		goto on_error;
	}

	for (i = 0; i < device->contexts->len; ++i) {
		context = g_ptr_array_index(device->contexts, i);
		if (!strcmp(context->ip_address, ip_address))
			break;
	}

	if (i < device->contexts->len) {
		subscribed = (context->subscribed_av || context->subscribed_cm);

		if (under_construction)
			construction_ctx = !strcmp(context->ip_address,
						   priv_t->ip_address);

		(void) g_ptr_array_remove_index(device->contexts, i);

		if (device->contexts->len == 0) {
			if (!under_construction) {
				DLEYNA_LOG_DEBUG(
					"Last Context lost. Delete device");

				upnp->lost_server(device->path);
				g_hash_table_remove(upnp->server_udn_map, udn);
			} else {
				DLEYNA_LOG_WARNING(
				       "Device under construction. Cancelling");

				dleyna_task_processor_cancel_queue(
							priv_t->queue_id);
			}
		} else if (under_construction && construction_ctx) {
			DLEYNA_LOG_WARNING(
				"Device under construction. Switching context");

			/* Cancel previous contruction task chain */
			g_hash_table_remove(priv_t->upnp->server_uc_map,
					    priv_t->udn);
			dleyna_task_queue_set_finally(
						priv_t->queue_id,
						prv_device_context_switch_end);
			dleyna_task_processor_cancel_queue(priv_t->queue_id);

			/* Create a new construction task chain */
			context = dlr_device_get_context(device);
			queue_id = prv_create_device_queue(&priv_t);
			prv_update_device_context(priv_t, upnp, udn, device,
						  context->ip_address,
						  queue_id);

			/* Start tasks from current construction step */
			dlr_device_construct(device, context, upnp->connection,
					     upnp->interface_info, queue_id);
		} else if (subscribed && !device->timeout_id) {
			DLEYNA_LOG_DEBUG("Subscribe on new context");

			device->timeout_id = g_timeout_add_seconds(1,
					prv_subscribe_to_service_changes,
					device);
		}
	}

on_error:

	return;
}
Example #11
0
void
app_init (int argc, char **argv)
{
  static gboolean nosplash = FALSE;
  static gboolean nonew = FALSE;
  static gboolean use_integrated_ui = TRUE;
  static gboolean credits = FALSE;
  static gboolean version = FALSE;
  static gboolean verbose = FALSE;
  static gboolean log_to_stderr = FALSE;
#ifdef HAVE_GNOME
  GnomeClient *client;
#endif
  static char *export_file_name = NULL;
  static char *export_file_format = NULL;
  static char *size = NULL;
  static char *show_layers = NULL;
  gboolean made_conversions = FALSE;
  GSList *files = NULL;
  static const gchar **filenames = NULL;
  int i = 0;

  gchar *export_format_string = 
     /* Translators:  The argument is a list of options, not to be translated */
    g_strdup_printf(_("Select the filter/format out of: %s"),
		    "cgm, dia, dxf, eps, eps-builtin, " EPS_PANGO
		    "fig, mp, plt, hpgl, png ("
#  if defined(HAVE_LIBPNG) && defined(HAVE_LIBART)
		    "png-libart, "
#  endif
#  ifdef HAVE_CAIRO
		    "cairo-png, cairo-alpha-png, "
#  endif
		    /* we always have pixbuf but don't know exactly all it's *few* save formats */
		    "pixbuf-png), jpg, "
		    "shape, svg, tex (pgf-tex, pstricks-tex), " WMF
		    "wpg");

  GOptionContext *context = NULL;
  static GOptionEntry options[] =
  {
    {"export", 'e', 0, G_OPTION_ARG_FILENAME, NULL /* &export_file_name */,
     N_("Export loaded file and exit"), N_("OUTPUT")},
    {"filter",'t', 0, G_OPTION_ARG_STRING, NULL /* &export_file_format */,
     NULL /* &export_format_string */, N_("TYPE") },
    {"size", 's', 0, G_OPTION_ARG_STRING, NULL,
     N_("Export graphics size"), N_("WxH")},
    {"show-layers", 'L', 0, G_OPTION_ARG_STRING, NULL,
     N_("Show only specified layers (e.g. when exporting). Can be either the layer name or a range of layer numbers (X-Y)"),
     N_("LAYER,LAYER,...")},
    {"nosplash", 'n', 0, G_OPTION_ARG_NONE, &nosplash,
     N_("Don't show the splash screen"), NULL },
    {"nonew", 'n', 0, G_OPTION_ARG_NONE, &nonew,
     N_("Don't create an empty diagram"), NULL },
    {"classic", '\0', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &use_integrated_ui,
     N_("Start classic user interface (no diagrams in tabs)"), NULL },
    {"log-to-stderr", 'l', 0, G_OPTION_ARG_NONE, &log_to_stderr,
     N_("Send error messages to stderr instead of showing dialogs."), NULL },
    {"input-directory", 'I', 0, G_OPTION_ARG_CALLBACK, _check_option_input_directory,
     N_("Directory containing input files"), N_("DIRECTORY")},
    {"output-directory", 'O', 0, G_OPTION_ARG_CALLBACK, _check_option_output_directory,
     N_("Directory containing output files"), N_("DIRECTORY")},
    {"credits", 'c', 0, G_OPTION_ARG_NONE, &credits,
     N_("Display credits list and exit"), NULL },
    {"verbose", 0, 0, G_OPTION_ARG_NONE, &verbose,
     N_("Generate verbose output"), NULL },
    {"version", 'v', 0, G_OPTION_ARG_NONE, &version,
     N_("Display version and exit"), NULL },
    { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, NULL /* &filenames */,
      NULL, NULL },
    { NULL }
  };
  
  /* for users of app_init() the default is interactive */
  dia_is_interactive = TRUE;

  options[0].arg_data = &export_file_name;
  options[1].arg_data = &export_file_format;
  options[1].description = export_format_string;
  options[2].arg_data = &size;
  options[3].arg_data = &show_layers;
  g_assert (strcmp (options[13].long_name, G_OPTION_REMAINING) == 0);
  options[13].arg_data = (void*)&filenames;

  argv0 = (argc > 0) ? argv[0] : "(none)";

#if GTK_CHECK_VERSION(2,24,0)
  /* ... use setlocale directly? */
#else
  gtk_set_locale();
#endif
  setlocale(LC_NUMERIC, "C");
  _setup_textdomains ();

  context = g_option_context_new(_("[FILE...]"));
  g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE);
#ifndef HAVE_GNOME
  /* avoid to add it a second time */
  g_option_context_add_group (context, gtk_get_option_group (FALSE));
#endif
  if (argv) {
    GError *error = NULL;

    if (!g_option_context_parse (context, &argc, &argv, &error)) {
      if (error) { /* IMO !error here is a bug upstream, triggered e.g. with --gdk-debug=updates */
	g_print ("%s", error->message);
	g_error_free (error);
      } else {
	g_print (_("Invalid option?"));
      }

      g_option_context_free(context);
      exit(1);
    }
    /* second level check of command line options, existance of input files etc. */
    if (filenames) {
      while (filenames[i] != NULL) {
	gchar *filename; 
	gchar *testpath;	  

	if (g_str_has_prefix (filenames[i], "file://")) {
	  filename = g_filename_from_uri (filenames[i], NULL, NULL);
	  if (!g_utf8_validate(filename, -1, NULL)) {
	    gchar *tfn = filename;
	    filename = g_filename_to_utf8(filename, -1, NULL, NULL, NULL);
	    g_free(tfn);
	  }
	} else
	  filename = g_filename_to_utf8 (filenames[i], -1, NULL, NULL, NULL);

	if (!filename) {
	  g_print (_("Filename conversion failed: %s\n"), filenames[i]);
	  continue;
	}

	if (g_path_is_absolute(filename))
	  testpath = filename;
	else
	  testpath = g_build_filename(input_directory ? input_directory : ".", filename, NULL);

	/* we still have a problem here, if GLib's file name encoding would not be utf-8 */
	if (g_file_test (testpath, G_FILE_TEST_IS_REGULAR))
	  files = g_slist_append(files, filename);
	else {
	  g_print (_("Missing input: %s\n"), filename);
	  g_free (filename);
	}
	if (filename != testpath)
	  g_free (testpath);
	++i;
      }
    }
    /* given some files to output, we are not starting up the UI */
    if (export_file_name || export_file_format || size)
      dia_is_interactive = FALSE;

  }

  if (argv && dia_is_interactive && !version) {
#ifdef HAVE_GNOME
    GnomeProgram *program =
      gnome_program_init (PACKAGE, VERSION, LIBGNOMEUI_MODULE,
			  argc, argv,
			  /* haven't found a quick way to pass GOption here */
			  GNOME_PARAM_GOPTION_CONTEXT, context,
			  GNOME_PROGRAM_STANDARD_PROPERTIES,
			  GNOME_PARAM_NONE);
    client = gnome_master_client();
    if(client == NULL) {
      g_warning(_("Can't connect to session manager!\n"));
    }
    else {
      g_signal_connect(G_OBJECT (client), "save_yourself",
		       G_CALLBACK (save_state), NULL);
      g_signal_connect(G_OBJECT (client), "die",
		       G_CALLBACK (session_die), NULL);
    }

    /* This smaller icon is 48x48, standard Gnome size */
    /* gnome_window_icon_set_default_from_file (GNOME_ICONDIR"/dia_gnome_icon.png");*/

#else
#  ifdef G_THREADS_ENABLED
    g_thread_init (NULL);
#  endif
    gtk_init(&argc, &argv);
#endif
  }
  else {
#ifdef G_THREADS_ENABLED
    g_thread_init (NULL);
#endif
    g_type_init();
    /*
     * On Windows there is no command line without display so that gtk_init is harmless. 
     * On X11 we need gtk_init_check() to avoid exit() just because there is no display 
     * running outside of X11.
     */
    if (!gtk_init_check(&argc, &argv))
      dia_log_message ("Running without display");
  }

  /* done with option parsing, don't leak */
  g_free(export_format_string);
  
  if (version) {
    gchar *ver_utf8;
    gchar *ver_locale;
#if (defined __TIME__) && (defined __DATE__)
    /* TRANSLATOR: 2nd and 3rd %s are time and date respectively. */
    ver_utf8 = g_strdup_printf(_("Dia version %s, compiled %s %s\n"), VERSION, __TIME__, __DATE__);
#else
    ver_utf8 = g_strdup_printf(_("Dia version %s\n"), VERSION);
#endif
    ver_locale = g_locale_from_utf8(ver_utf8, -1, NULL, NULL, NULL);
    printf("%s\n", ver_locale);
    g_free(ver_locale);
    g_free(ver_utf8);
    if (verbose)
      dump_dependencies();
    exit(0);
  }

  if (!dia_is_interactive)
    log_to_stderr = TRUE;

  libdia_init (   (dia_is_interactive ? DIA_INTERACTIVE : 0)
	       | (log_to_stderr ? DIA_MESSAGE_STDERR : 0)
	       | (verbose ? DIA_VERBOSE : 0) );

  print_credits(credits);

  if (dia_is_interactive) {
    create_user_dirs();

    if (!nosplash)
      app_splash_init("");

    /* Init cursors: */
    default_cursor = gdk_cursor_new(GDK_LEFT_PTR);
    ddisplay_set_all_cursor(default_cursor);
  }

  dia_register_plugins();
  dia_register_builtin_plugin(internal_plugin_init);

  load_all_sheets();     /* new mechanism */

  dia_log_message ("object defaults");
  {
    DiaContext *ctx = dia_context_new (_("Object Defaults"));
    dia_object_defaults_load (NULL, TRUE /* prefs.object_defaults_create_lazy */, ctx);
    dia_context_release (ctx);
  }
  debug_break();

  if (object_get_type("Standard - Box") == NULL) {
    message_error(_("Couldn't find standard objects when looking for "
		  "object-libs; exiting...\n"));
    g_critical( _("Couldn't find standard objects when looking for "
	    "object-libs in '%s'; exiting...\n"), dia_get_lib_directory("dia"));
    exit(1);
  }

  persistence_load();

  /** Must load prefs after persistence */
  prefs_init();

  if (dia_is_interactive) {

    /* further initialization *before* reading files */  
    active_tool = create_modify_tool();

    dia_log_message ("ui creation");
    if (use_integrated_ui) {
      create_integrated_ui();
    } else {
      create_toolbox();
      /* for the integrated ui case it is integrated */
      persistence_register_window_create("layer_window",
				         (NullaryFunc*)&layer_dialog_create);
    }
      
    /*fill recent file menu */
    recent_file_history_init();

    /* Set up autosave to check every 5 minutes */
    g_timeout_add_seconds(5*60, autosave_check_autosave, NULL);

#if 0 /* do we really open these automatically in the next session? */
    persistence_register_window_create("diagram_tree", 
                                       &diagram_tree_show);
#endif
    persistence_register_window_create("sheets_main_dialog",
				       (NullaryFunc*)&sheets_dialog_create);

    /* In current setup, we can't find the autosaved files. */
    /*autosave_restore_documents();*/

  }

  dia_log_message ("diagrams");
  made_conversions = handle_all_diagrams(files, export_file_name,
					 export_file_format, size, show_layers,
					 input_directory, output_directory);
					 
  if (dia_is_interactive && files == NULL && !nonew) {
    if (use_integrated_ui) {
      GList * list;
    
      file_new_callback(NULL);  
      list = dia_open_diagrams();
      if (list) {
        Diagram * diagram = list->data;
        diagram_update_extents(diagram);
        diagram->is_default = TRUE;
      }
    } else {
      gchar *filename = g_filename_from_utf8(_("Diagram1.dia"), -1, NULL, NULL, NULL);
      Diagram *diagram = new_diagram (filename);
      g_free(filename);
    
      if (diagram != NULL) {
        diagram_update_extents(diagram);
        diagram->is_default = TRUE;
        /* I think this is done in diagram_init() with a call to 
         * layer_dialog_update_diagram_list() */
        layer_dialog_set_diagram(diagram);
        new_display(diagram); 
      }
    }
  }
  g_slist_free(files);
  if (made_conversions) exit(0);

  dynobj_refresh_init();
  dia_log_message ("initialized");
}
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *err = NULL;
	guint signal;

	set_version();

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (g_option_context_parse(context, &argc, &argv, &err) == FALSE) {
		if (err != NULL) {
			g_printerr("%s\n", err->message);
			g_error_free(err);
		} else
			g_printerr("An unknown error occurred\n");

		exit(EXIT_FAILURE);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(EXIT_SUCCESS);
	}

	signal = setup_signalfd();
	if (!signal)
		return EXIT_FAILURE;

	if (option_dbg || option_mgmt_dbg)
		__btd_log_init("*", 0);
	else
		__btd_log_init(NULL, 0);

	if (!set_capabilities()) {
		__btd_log_cleanup();
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	quit_timeout = g_timeout_add_seconds(STARTUP_GRACE_SECONDS,
							quit_eventloop, NULL);
	if (quit_timeout == 0) {
		error("Failed to init startup timeout");
		__btd_log_cleanup();
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	if (!bt_bluetooth_start(option_index, option_mgmt_dbg, adapter_ready)) {
		__btd_log_cleanup();
		g_source_remove(quit_timeout);
		g_source_remove(signal);
		return EXIT_FAILURE;
	}

	/* Use params: mtu = 0, flags = 0 */
	start_sdp_server(0, 0);

	DBG("Entering main loop");

	event_loop = g_main_loop_new(NULL, FALSE);

	g_main_loop_run(event_loop);

	g_source_remove(signal);

	if (quit_timeout > 0)
		g_source_remove(quit_timeout);

	cleanup_services();

	stop_sdp_server();
	bt_bluetooth_cleanup();
	g_main_loop_unref(event_loop);

	/* If no adapter was initialized, hal_ipc is NULL */
	if (hal_ipc) {
		ipc_unregister(hal_ipc, HAL_SERVICE_ID_CORE);
		ipc_cleanup(hal_ipc);
	}

	info("Exit");

	__btd_log_cleanup();

	free(config_vendor);
	free(config_model);
	free(config_name);
	free(config_serial);
	free(config_fw_rev);
	free(config_hw_rev);

	return EXIT_SUCCESS;
}
Example #13
0
static int
constructor(Plugin *p, char **fp)
{
    ENTER;

    batt *b;
    p->priv = b = g_new0(batt, 1);
    p->pwid = gtk_event_box_new();
    GTK_WIDGET_SET_FLAGS( p->pwid, GTK_NO_WINDOW );
    gtk_container_set_border_width( GTK_CONTAINER(p->pwid), 1 );

    b->drawingArea = gtk_drawing_area_new();
    gtk_widget_add_events( b->drawingArea, GDK_BUTTON_PRESS_MASK );

    gtk_container_add( (GtkContainer*)p->pwid, b->drawingArea );

    if ((b->orientation = p->panel->orientation) == ORIENT_HORIZ) {
        b->height = b->length = 20;
        b->thickness = b->width = 8;
    }
    else {
        b->height = b->thickness = 8;
        b->length = b->width = 20;
    }
    gtk_widget_set_size_request(b->drawingArea, b->width, b->height);

    gtk_widget_show(b->drawingArea);

    b->bg = gdk_gc_new(p->panel->topgwin->window);
    b->gc1 = gdk_gc_new(p->panel->topgwin->window);
    b->gc2 = gdk_gc_new(p->panel->topgwin->window);

    g_signal_connect (G_OBJECT (b->drawingArea), "button_press_event",
            G_CALLBACK(buttonPressEvent), (gpointer) p);
    g_signal_connect (G_OBJECT (b->drawingArea),"configure_event",
          G_CALLBACK (configureEvent), (gpointer) b);
    g_signal_connect (G_OBJECT (b->drawingArea), "expose_event",
          G_CALLBACK (exposeEvent), (gpointer) b);

    sem_init(&(b->alarmProcessLock), 0, 1);

    b->alarmCommand = b->backgroundColor = b->chargingColor1 = b->chargingColor2
            = b->dischargingColor1 = b->dischargingColor2 = NULL;

    /* Set default values for integers */
    b->alarmTime = 5;
    b->requestedBorder = 1;
    b->numSamples = b->rateSamplesSum = b->wasCharging = 0;

    b->rateSamples = (unsigned int *) malloc(sizeof(int) * MAX_SAMPLES);

    line s;
    s.len = 256;

    if (fp) {

        /* Apply options */
        while (lxpanel_get_line(fp, &s) != LINE_BLOCK_END) {
            if (s.type == LINE_NONE) {
                ERR( "batt: illegal token %s\n", s.str);
                goto error;
            }
            if (s.type == LINE_VAR) {
                if (!g_ascii_strcasecmp(s.t[0], "HideIfNoBattery"))
                    b->hide_if_no_battery = atoi(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "AlarmCommand"))
                    b->alarmCommand = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "BackgroundColor"))
                    b->backgroundColor = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "ChargingColor1"))
                    b->chargingColor1 = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "ChargingColor2"))
                    b->chargingColor2 = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "DischargingColor1"))
                    b->dischargingColor1 = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "DischargingColor2"))
                    b->dischargingColor2 = g_strdup(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "AlarmTime"))
                    b->alarmTime = atoi(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "BorderWidth"))
                    b->requestedBorder = atoi(s.t[1]);
                else if (!g_ascii_strcasecmp(s.t[0], "Size")) {
                    b->thickness = MAX(1, atoi(s.t[1]));
                    if (b->orientation == ORIENT_HORIZ)
                        b->width = b->thickness;
                    else
                        b->height = b->thickness;
                    gtk_widget_set_size_request(b->drawingArea, b->width,
                            b->height);
                }
                else {
                    ERR( "batt: unknown var %s\n", s.t[0]);
                    continue;
                }
            }
            else {
                ERR( "batt: illegal in this context %s\n", s.str);
                goto error;
            }
        }

    }

    /* Make sure the border value is acceptable */
    b->border = MIN(MAX(0, b->requestedBorder),
            (MIN(b->length, b->thickness) - 1) / 2);

    /* Apply more default options */
    if (! b->alarmCommand)
        b->alarmCommand = g_strdup("xmessage Battery low");
    if (! b->backgroundColor)
        b->backgroundColor = g_strdup("black");
    if (! b->chargingColor1)
        b->chargingColor1 = g_strdup("#28f200");
    if (! b->chargingColor2)
        b->chargingColor2 = g_strdup("#22cc00");
    if (! b->dischargingColor1)
        b->dischargingColor1 = g_strdup("#ffee00");
    if (! b->dischargingColor2)
        b->dischargingColor2 = g_strdup("#d9ca00");

    gdk_color_parse(b->backgroundColor, &b->background);
    gdk_color_parse(b->chargingColor1, &b->charging1);
    gdk_color_parse(b->chargingColor2, &b->charging2);
    gdk_color_parse(b->dischargingColor1, &b->discharging1);
    gdk_color_parse(b->dischargingColor2, &b->discharging2);
    gdk_colormap_alloc_color(gdk_drawable_get_colormap(
            p->panel->topgwin->window), &b->background, FALSE, TRUE);
    gdk_colormap_alloc_color(gdk_drawable_get_colormap(
            p->panel->topgwin->window), &b->charging1, FALSE, TRUE);
    gdk_colormap_alloc_color(gdk_drawable_get_colormap(
            p->panel->topgwin->window), &b->charging2, FALSE, TRUE);
    gdk_colormap_alloc_color(gdk_drawable_get_colormap(
            p->panel->topgwin->window), &b->discharging1, FALSE, TRUE);
    gdk_colormap_alloc_color(gdk_drawable_get_colormap(
            p->panel->topgwin->window), &b->discharging2, FALSE, TRUE);
    gdk_gc_set_foreground(b->bg, &b->background);

    check_batteries( b );   /* get available batteries */

    /* Start the update loop */
#if GTK_CHECK_VERSION( 2, 14, 0 )
    b->timer = g_timeout_add_seconds( 3, (GSourceFunc) update_timout, (gpointer) b);
#else
    b->timer = g_timeout_add( 3000,
            (GSourceFunc) update_timout, (gpointer) b);
#endif
    RET(TRUE);

error:
    destructor( p );
    RET(FALSE);
}
Example #14
0
int main (int argc, char *argv[])
{

    char* arg_list[] = {
        "mplayer",
        /* argv[0], the name of the program. */
        "../data/Bleepie - Summer Forever.oga",
        NULL
        /* The argument list must end with a NULL.*/
    };
    /*
    boost::thread z (
                        boost::bind(&spawn, arg_list)
                    );
    */
    spawn ("mplayer", arg_list);

    GtkWidget *button      = NULL;
    GtkWidget *win         = NULL;
    GtkWidget *vbox        = NULL;
    GtkWidget *hbox        = NULL;
    GtkWidget *label       = NULL;
    GtkWidget *separ       = NULL;
    GtkWidget *image_buton = NULL;
    GtkWidget *imbox       = NULL;
    GtkWidget *wheel       = NULL;

    /* Initialize GTK+ */
    g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, (GLogFunc) gtk_false, NULL);
    gtk_init (&argc, &argv);
    g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL);

    /* Create the main window */
    //create the main window
    win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    //gtk_window_set_default_size((GtkWindow*)win,350,350);
    /* When the window is given the "delete-event" signal (this is given
     * by the window manager, usually by the "close" option, or on the
     * titlebar), we ask it to call the delete_event () function
     * as defined above. The data passed to the callback
     * function is NULL and is ignored in the callback function. */
    g_signal_connect (win, "delete-event",
                      G_CALLBACK (delete_event), NULL);
    //when receiving the destroy signal quit the app
    g_signal_connect (win, "destroy", G_CALLBACK (delete_event), NULL);

    gtk_container_set_border_width (GTK_CONTAINER (win), 10);
    gtk_window_set_title (GTK_WINDOW (win), "| - Alfa Bomb - Venam - |");
    gtk_window_set_position (GTK_WINDOW (win), GTK_WIN_POS_CENTER);
    gtk_widget_realize (win);


    ///vbox
    /* Create some boxes with buttons */
    vbox = gtk_vbox_new (FALSE,0);
    //insert it into the win
    gtk_container_add (GTK_CONTAINER (win), vbox);

    ///label
    //add a label to vbox
    /* create a new label. */
    label = gtk_label_new ("Alfa Bomb");

    /* Align the label to the left side.  We'll discuss this function and
    * others in the section on Widget Attributes. */
    gtk_misc_set_alignment (GTK_MISC (label), 0, 1);
    gtk_misc_set_padding(GTK_MISC (label),75,10);

    /* Pack the label into the vertical box (vbox box1).  Remember that
    * widgets added to a vbox will be packed one on top of the other in
    * order. */
    gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);

    ///hbox
    //horizontal box here that is inside the vbox
    hbox = gtk_hbox_new (FALSE,0);
    //gtk_container_add (GTK_CONTAINER (vbox), hbox);
    gtk_box_pack_start(GTK_BOX (vbox), hbox,FALSE, FALSE, 0);
    //spin
    wheel = gtk_spin_button_new_with_range(1,50,1);
    gtk_box_pack_start(GTK_BOX (hbox), wheel, FALSE, FALSE, 0);


    GtkWidget * texta;
    texta =gtk_entry_new();
    gtk_entry_set_text((GtkEntry*)texta,"8-number");
    gtk_box_pack_start (GTK_BOX (hbox),texta , TRUE, TRUE, 0); //box,child,expand,fill,padding




    ///hbox
    //horizontal box here that is inside the vbox
    hbox = gtk_hbox_new (TRUE,10);
    //gtk_container_add (GTK_CONTAINER (vbox), hbox);
    gtk_box_pack_end(GTK_BOX (vbox), hbox,TRUE, TRUE, 0);

    ///2 buttons at the bottom inside hbox
    button = gtk_button_new_from_stock( GTK_STOCK_CLOSE);
    g_signal_connect(button, "clicked", G_CALLBACK (delete_event), NULL);
    gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); //box,child,expand,fill,padding

    ///label
    //add a label to vbox
    /* create a new label. */
    char str[10];
    std::ostringstream o;
    o << sms_sent;
    label = gtk_label_new (  o.str().c_str() );
    guint blah = g_timeout_add_seconds (1, update_label, (gpointer)label );
    /* Align the label to the left side.  We'll discuss this function and
     * others in the section on Widget Attributes. */
    gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
    gtk_misc_set_padding(GTK_MISC (label),0,0);

    //g_signal_connect (vbox, "", gtk_main_quit, NULL);

    /* Pack the label into the vertical box (vbox box1).  Remember that
    * widgets added to a vbox will be packed one on top of the other in
    * order. */
    gtk_box_pack_end (GTK_BOX (hbox), label, FALSE, FALSE, 0);


    button = gtk_button_new_with_label ("About");
    g_signal_connect (button, "clicked", G_CALLBACK(about_this), (gpointer) win);
    gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); //box,child,expand,fill,padding


    ///WHEEL AND BOMB
    hbox = gtk_hbox_new(TRUE,0);
    gtk_box_pack_start(GTK_BOX (vbox), hbox,FALSE, FALSE, 0);

    ///image button
    image_buton = gtk_button_new();
    /* Connect the "clicked" signal of the button to our callback */
    GtkWidget* thevars[4] = {texta,wheel,win,image_buton};
    g_signal_connect (image_buton, "released",
                      G_CALLBACK (callback_entry), thevars);
    /* This calls our box creating function , the box is inserted inside the button*/
    gtk_button_set_label((GtkButton*)image_buton, "BOMB!");
    //imbox = xpm_label_box ("data/emblem-danger.png","");
    //gtk_container_add (GTK_CONTAINER (image_buton), imbox);
    //gtk_container_border_width (GTK_CONTAINER(image_buton), 0);
    gtk_box_pack_start (GTK_BOX (hbox), image_buton, TRUE, TRUE, 0);


    ///Separator
    /* Creates a separator, we'll learn more about these later,
     * but they are quite simple. */
    separ = gtk_hseparator_new ();
    /* Pack the separator into the vbox. Remember each of these
     * widgets is being packed into a vbox, so they'll be stacked
     * vertically. */
    gtk_box_pack_start (GTK_BOX (vbox), separ, FALSE, FALSE, 5);



    /* Enter the main loop */
    gtk_widget_show_all (win);
    gtk_main ();

}
Example #15
0
int __connman_technology_enable(enum connman_service_type type, DBusMessage *msg)
{
	struct connman_technology *technology;
	GSList *list;
	int err = 0;
	int ret = -ENODEV;
	DBusMessage *reply;

	DBG("type %d enable", type);

	technology = technology_find(type);
	if (technology == NULL) {
		err = -ENXIO;
		goto done;
	}

	if (technology->pending_reply != NULL) {
		err = -EBUSY;
		goto done;
	}

	if (msg != NULL) {
		/*
		 * This is a bit of a trick. When msg is not NULL it means
		 * thats technology_enable was invoked from the manager API. Hence we save
		 * the state here.
		 */
		technology->enable_persistent = TRUE;
		save_state(technology);
	}

	__connman_rfkill_block(technology->type, FALSE);

	/*
	 * An empty device list means that devices in the technology
	 * were rfkill blocked. The unblock above will enable the devs.
	 */
	if (technology->device_list == NULL)
		return 0;

	for (list = technology->device_list; list; list = list->next) {
		struct connman_device *device = list->data;

		err = __connman_device_enable(device);
		/*
		 * err = 0 : Device was enabled right away.
		 * If atleast one device gets enabled, we consider
		 * the technology to be enabled.
		 */
		if (err == 0)
			ret = 0;
	}

done:
	if (ret == 0) {
		if (msg != NULL)
			g_dbus_send_reply(connection, msg, DBUS_TYPE_INVALID);
		return ret;
	}

	if (msg != NULL) {
		if (err == -EINPROGRESS) {
			technology->pending_reply = dbus_message_ref(msg);
			technology->pending_timeout = g_timeout_add_seconds(10,
					technology_pending_reply, technology);
		} else {
			reply = __connman_error_failed(msg, -err);
			if (reply != NULL)
				g_dbus_send_message(connection, reply);
		}
	}

	return err;
}
static void
_source_notification_added_cb (MexNotificationSource *source,
                               MexNotification       *notification,
                               MexNotificationArea   *area)
{
    MexNotificationAreaPrivate *priv = GET_PRIVATE (area);
    ClutterActor *actor;
    ClutterActor *last_top_actor;
    ClutterAnimation *animation;

    actor = _make_notification_actor (notification);

    g_hash_table_insert (priv->notification_to_actor,
                         notification,
                         actor);

    clutter_container_add_actor (CLUTTER_CONTAINER (area),
                                 actor);
    mx_stack_child_set_x_fill (MX_STACK (area), actor, FALSE);
    mx_stack_child_set_y_fill (MX_STACK (area), actor, FALSE);
    mx_stack_child_set_x_align (MX_STACK (area), actor, MX_ALIGN_MIDDLE);
    mx_stack_child_set_y_align (MX_STACK (area), actor, MX_ALIGN_MIDDLE);

    /* Get the last notification since we want to fade that out */
    last_top_actor = g_queue_peek_head (priv->stack);

    g_queue_push_head (priv->stack, actor);

    clutter_container_raise_child (CLUTTER_CONTAINER (area),
                                   actor,
                                   last_top_actor);



    /* Fade out old notification */
    if (last_top_actor)
    {
        clutter_actor_animate (last_top_actor,
                               CLUTTER_EASE_OUT_QUAD,
                               350,
                               "opacity", 0x00,
                               NULL);
    }

    clutter_actor_set_opacity (actor, 0);
    animation = clutter_actor_animate (actor,
                                       CLUTTER_EASE_OUT_QUAD,
                                       350,
                                       "opacity", 0xff,
                                       NULL);

    /* Delay new notification fade in if we had an old one */
    if (last_top_actor)
    {
        ClutterTimeline *timeline;

        timeline = clutter_animation_get_timeline (animation);

        clutter_timeline_set_delay (timeline, 450);
    }

    g_object_set_data (G_OBJECT (actor),
                       "notification-area",
                       area);
    g_object_set_data (G_OBJECT (actor),
                       "notification",
                       notification);

    if (notification->duration > 0)
    {
        guint timeout_id =
            g_timeout_add_seconds (notification->duration,
                                   (GSourceFunc)_notification_timeout_cb,
                                   actor);

        g_hash_table_insert (priv->notification_to_timeout_id,
                             notification,
                             GINT_TO_POINTER (timeout_id));
    }
}
static void
dun_start (NmaBtDevice *self)
{
	NmaBtDevicePrivate *priv = NMA_BT_DEVICE_GET_PRIVATE (self);
	gboolean have_mm = FALSE, have_mm1 = TRUE;

	g_message ("%s: starting DUN device discovery...", __func__);

	_set_status (self, _("Detecting phone configuration..."));

	/* ModemManager stuff */
	priv->mm_proxy = dbus_g_proxy_new_for_name (priv->bus,
	                                            MM_SERVICE,
	                                            MM_PATH,
	                                            MM_INTERFACE);
	g_assert (priv->mm_proxy);
	have_mm = _name_has_owner (priv->bus, MM_SERVICE);

	dbus_g_object_register_marshaller (g_cclosure_marshal_VOID__BOXED,
	                                   G_TYPE_NONE,
	                                   G_TYPE_BOXED,
	                                   G_TYPE_INVALID);
	dbus_g_proxy_add_signal (priv->mm_proxy, "DeviceAdded",
	                         DBUS_TYPE_G_OBJECT_PATH, G_TYPE_INVALID);
	dbus_g_proxy_connect_signal (priv->mm_proxy, "DeviceAdded",
								 G_CALLBACK (modem_added), self,
								 NULL);

	dbus_g_proxy_add_signal (priv->mm_proxy, "DeviceRemoved",
	                         DBUS_TYPE_G_OBJECT_PATH, G_TYPE_INVALID);
	dbus_g_proxy_connect_signal (priv->mm_proxy, "DeviceRemoved",
								 G_CALLBACK (modem_removed), self,
								 NULL);

#if WITH_MODEM_MANAGER_1
	/* ModemManager1 stuff */
	{
		priv->dbus_connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL);
		if (priv->dbus_connection) {
			priv->modem_manager_1 = mm_manager_new_sync (priv->dbus_connection,
			                                             G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE,
			                                             NULL,
			                                             NULL);
			if (priv->modem_manager_1) {
				g_signal_connect (priv->modem_manager_1,
				                  "object-added",
				                  G_CALLBACK (modem_object_added),
				                  self);
				g_signal_connect (priv->modem_manager_1,
				                  "object-removed",
				                  G_CALLBACK (modem_object_removed),
				                  self);
			}
		}

		have_mm1 = !!priv->modem_manager_1;
	}
#endif

	/* Ensure at least one of ModemManager or ModemManager1 are around */
	if (!have_mm && !have_mm1) {
		dun_error (self, __func__, NULL, _("ModemManager is not running"));
		return;
	}

	/* Bluez */
	priv->dun_proxy = dbus_g_proxy_new_for_name (priv->bus,
	                                             BLUEZ_SERVICE,
	                                             priv->object_path,
	                                             BLUEZ_SERIAL_INTERFACE);
	g_assert (priv->dun_proxy);

	priv->dun_timeout_id = g_timeout_add_seconds (45, dun_timeout_cb, self);

	g_message ("%s: calling Connect...", __func__);

	/* Watch for BT device property changes */
	dbus_g_object_register_marshaller (_nma_marshal_VOID__STRING_BOXED,
	                                   G_TYPE_NONE,
	                                   G_TYPE_STRING, G_TYPE_VALUE,
	                                   G_TYPE_INVALID);
	dbus_g_proxy_add_signal (priv->dun_proxy, "PropertyChanged",
	                         G_TYPE_STRING, G_TYPE_VALUE, G_TYPE_INVALID);
	dbus_g_proxy_connect_signal (priv->dun_proxy, "PropertyChanged",
	                             G_CALLBACK (dun_property_changed), self, NULL);

	/* Request a connection to the device and get the port */
	dbus_g_proxy_begin_call_with_timeout (priv->dun_proxy, "Connect",
	                                      dun_connect_cb,
	                                      self,
	                                      NULL,
	                                      20000,
	                                      G_TYPE_STRING, "dun",
	                                      G_TYPE_INVALID);

	g_message ("%s: waiting for Connect success...", __func__);
}
Example #18
0
int
main (int argc, gchar ** argv)
{
  GError *err = NULL;
  GOptionContext *ctx;
  GESPipeline *pipeline;
  GESTimeline *timeline;
  GESTrack *tracka, *trackv;
  GESLayer *layer1, *layer2;
  GESUriClip *src;
  GMainLoop *mainloop;

  gint inpoint = 0, duration = 10;
  gboolean mute = FALSE;
  gchar *audiofile = NULL;
  GOptionEntry options[] = {
    {"inpoint", 'i', 0, G_OPTION_ARG_INT, &inpoint,
        "in-point in the file (in seconds, default:0s)", "seconds"},
    {"duration", 'd', 0, G_OPTION_ARG_INT, &duration,
        "duration to use from the file (in seconds, default:10s)", "seconds"},
    {"mute", 'm', 0, G_OPTION_ARG_NONE, &mute,
        "Whether to mute the audio from the file",},
    {"audiofile", 'a', 0, G_OPTION_ARG_FILENAME, &audiofile,
          "Use this audiofile instead of the original audio from the file",
        "audiofile"},
    {NULL}
  };

  ctx =
      g_option_context_new
      ("- Plays an video file with sound (origin/muted/replaced)");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());

  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing %s\n", err->message);
    exit (1);
  }

  if (argc == 1) {
    g_print ("%s", g_option_context_get_help (ctx, TRUE, NULL));
    exit (0);
  }
  g_option_context_free (ctx);

  ges_init ();

  /* Create an Audio/Video pipeline with two layers */
  pipeline = ges_pipeline_new ();

  timeline = ges_timeline_new ();

  tracka = GES_TRACK (ges_audio_track_new ());
  trackv = GES_TRACK (ges_video_track_new ());

  layer1 = ges_layer_new ();
  layer2 = ges_layer_new ();
  g_object_set (layer2, "priority", 1, NULL);

  if (!ges_timeline_add_layer (timeline, layer1) ||
      !ges_timeline_add_layer (timeline, layer2) ||
      !ges_timeline_add_track (timeline, tracka) ||
      !ges_timeline_add_track (timeline, trackv) ||
      !ges_pipeline_set_timeline (pipeline, timeline))
    return -1;

  if (1) {
    gchar *uri = gst_filename_to_uri (argv[1], NULL);
    /* Add the main audio/video file */
    src = ges_uri_clip_new (uri);
    g_free (uri);
    g_object_set (src, "start", 0, "in-point", inpoint * GST_SECOND,
        "duration", duration * GST_SECOND, "mute", mute, NULL);
    ges_layer_add_clip (layer1, GES_CLIP (src));
  }

  /* Play the pipeline */
  gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);
  mainloop = g_main_loop_new (NULL, FALSE);
  g_timeout_add_seconds (duration + 1, (GSourceFunc) g_main_loop_quit,
      mainloop);
  g_main_loop_run (mainloop);

  return 0;
}
int main(int argc, char *argv[]) {
  CustomData data;
  GstStateChangeReturn ret;
  GstBus *bus;
  
  /* Initialize GTK */
  gtk_init (&argc, &argv);
  
  /* Initialize GStreamer */
  gst_init (&argc, &argv);
  
  /* Initialize our data structure */
  memset (&data, 0, sizeof (data));
  data.duration = GST_CLOCK_TIME_NONE;
  
  /* Create the elements */
  data.playbin = gst_element_factory_make ("playbin", "playbin");
   
  if (!data.playbin) {
    g_printerr ("Not all elements could be created.\n");
    return -1;
  }
  
  /* Set the URI to play */
  g_object_set (data.playbin, "uri", "http://docs.gstreamer.com/media/sintel_trailer-480p.webm", NULL);
  
  /* Connect to interesting signals in playbin */
  g_signal_connect (G_OBJECT (data.playbin), "video-tags-changed", (GCallback) tags_cb, &data);
  g_signal_connect (G_OBJECT (data.playbin), "audio-tags-changed", (GCallback) tags_cb, &data);
  g_signal_connect (G_OBJECT (data.playbin), "text-tags-changed", (GCallback) tags_cb, &data);
  
  /* Create the GUI */
  create_ui (&data);
  
  /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
  bus = gst_element_get_bus (data.playbin);
  gst_bus_add_signal_watch (bus);
  g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data);
  g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, &data);
  g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, &data);
  g_signal_connect (G_OBJECT (bus), "message::application", (GCallback)application_cb, &data);
  gst_object_unref (bus);
  
  /* Start playing */
  ret = gst_element_set_state (data.playbin, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr ("Unable to set the pipeline to the playing state.\n");
    gst_object_unref (data.playbin);
    return -1;
  }
  
  /* Register a function that GLib will call every second */
  g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data);
  
  /* Start the GTK main loop. We will not regain control until gtk_main_quit is called. */
  gtk_main ();
  
  /* Free resources */
  gst_element_set_state (data.playbin, GST_STATE_NULL);
  gst_object_unref (data.playbin);
  return 0;
}
Example #20
0
File: main.c Project: hannenz/busy
int main(int argc, char **argv){
	GMainLoop *main_loop;
	GSocketService *service;
	GInetAddress *iaddr;
	GSocketAddress *saddr;
	AppData *app_data;
	GError *error = NULL;

	// Init
	g_set_prgname(argv[0]);
	g_mem_set_vtable(glib_mem_profiler_table);
	g_type_init();

	// Start the daemon
	start_daemon(g_get_prgname(), LOG_LOCAL0);
	syslog(LOG_NOTICE, "-----------------------------------\n");
	syslog(LOG_NOTICE, "Daemon has been started\n");


//	atexit(cleanup);

	// Initialize App Data structire
	app_data = g_slice_new0(AppData);
	app_data->queue = g_queue_new();
	app_data->hosts = NULL;
	app_data->running_backups = NULL;

	// For global access to app_data
	app_data_aux_ptr = app_data;

	// Read configuration
	if (!read_config(app_data)){
		syslog(LOG_ERR, "Failed to read config file \"%s\"", CONFIG_FILE);
		exit(-1);
	}

	// If no hosts configured in config file, try reading from MySQL

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_NOTICE, "No hosts configured in /etc/busy/busy.conf, now reading hosts from MySQL");
		app_data->hosts = db_read_hosts(app_data->mysql);
	}

	if (g_list_length(app_data->hosts) == 0){
		syslog(LOG_ERR, "Absolutely no hosts configured! Please configure at least one host either in %s or use the Web frontend", CONFIG_FILE);
		//~ syslog(LOG_ERR, "I won't waste any more cpu time now and exit");
		//~ exit(0);
	}
	else {
		GList *p;
		for (p = app_data->hosts; p != NULL; p = p->next){
			Host *host = p->data;
			host_dump(host);
			syslog(LOG_NOTICE, "%s %f", host_get_name(host), host_get_max_age(host));
		}
	}

	// Setup listener for incoming TCP (localhost port 4000)
	service = g_socket_service_new();
	iaddr = g_inet_address_new_from_string("127.0.0.1");
	saddr = g_inet_socket_address_new(iaddr, 4000);
	g_socket_listener_add_address(G_SOCKET_LISTENER(service), saddr, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, NULL, NULL, &error);
	g_object_unref(iaddr);
	g_object_unref(saddr);
	g_socket_service_start(service);
	g_signal_connect(service, "incoming", (GCallback)on_incoming, app_data);

	// Call wakeup and archive function once
	wakeup(app_data);
	do_archive(app_data);

	// Check preiodically for backups, queue and archives,
	g_timeout_add_seconds(WAKEUP_INTERVAL, (GSourceFunc)wakeup, app_data);
	g_timeout_add_seconds(10, (GSourceFunc)do_backup, app_data);
	g_timeout_add_seconds(6 * 3600, (GSourceFunc)do_archive, app_data);

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

	return (EXIT_SUCCESS);
}
static void
update_finish (WeatherInfo *info, gpointer data)
{
    static int gw_fault_counter = 0;
#ifdef HAVE_LIBNOTIFY
    char *message, *detail;
#endif
    char *s;
    MateWeatherApplet *gw_applet = (MateWeatherApplet *)data;
    gint nxtSunEvent;
    const gchar *icon_name;

    /* Update timer */
    if (gw_applet->timeout_tag > 0)
        g_source_remove(gw_applet->timeout_tag);
    if (gw_applet->mateweather_pref.update_enabled)
    {
	gw_applet->timeout_tag =
		g_timeout_add_seconds (
                       gw_applet->mateweather_pref.update_interval,
                        timeout_cb, gw_applet);

        nxtSunEvent = weather_info_next_sun_event(gw_applet->mateweather_info);
        if (nxtSunEvent >= 0)
            gw_applet->suncalc_timeout_tag =
                        g_timeout_add_seconds (nxtSunEvent,
                                suncalc_timeout_cb, gw_applet);
    }

    if ((TRUE == weather_info_is_valid (info)) ||
	     (gw_fault_counter >= MAX_CONSECUTIVE_FAULTS))
    {
	    gw_fault_counter = 0;
            icon_name = weather_info_get_icon_name (gw_applet->mateweather_info);
            gtk_image_set_from_icon_name (GTK_IMAGE(gw_applet->image), 
                                          icon_name, GTK_ICON_SIZE_BUTTON);
	      
	    gtk_label_set_text (GTK_LABEL (gw_applet->label), 
	        		weather_info_get_temp_summary(
					gw_applet->mateweather_info));
	    
	    s = weather_info_get_weather_summary (gw_applet->mateweather_info);
	    gtk_widget_set_tooltip_text (GTK_WIDGET (gw_applet->applet), s);
	    g_free (s);

	    /* Update dialog -- if one is present */
	    if (gw_applet->details_dialog) {
	    	mateweather_dialog_update (MATEWEATHER_DIALOG (gw_applet->details_dialog));
	    }

	    /* update applet */
	    place_widgets(gw_applet);

#ifdef HAVE_LIBNOTIFY
        if (gw_applet->mateweather_pref.show_notifications)
        {
		    NotifyNotification *n;
	            
		    /* Show notifications if possible */
	            if (!notify_is_initted ())
	                notify_init (_("Weather Forecast"));

		    if (notify_is_initted ())
		    {
			 GError *error = NULL;
                         const char *icon;
			 
	           	 /* Show notification */
	           	 message = g_strdup_printf ("%s: %s",
					 weather_info_get_location_name (info),
					 weather_info_get_sky (info));
	           	 detail = g_strdup_printf (
					 _("City: %s\nSky: %s\nTemperature: %s"),
					 weather_info_get_location_name (info),
					 weather_info_get_sky (info),
					 weather_info_get_temp_summary (info));

			 icon = weather_info_get_icon_name (gw_applet->mateweather_info);
			 if (icon == NULL)
				 icon = "stock-unknown";
	           	 
			 n = notify_notification_new (message, detail, icon);
	
		   	 notify_notification_show (n, &error);
			 if (error)
			 {
				 g_warning ("%s", error->message);
				 g_error_free (error);
			 }
		   	     
		   	 g_free (message);
		   	 g_free (detail);
		    }
        }
#endif
    }
    else
    {
	    /* there has been an error during retrival
	     * just update the fault counter
	     */
	    gw_fault_counter++;
    }
}
int main(int argc, char **argv)
{
    GOptionContext *options;
    GError *error = NULL;

    options = g_option_context_new(NULL);
    g_option_context_add_main_entries(options, entries, NULL);
    if (!g_option_context_parse(options, &argc, &argv, &error)) {
        g_print("Failed to parse options: %s\n", error->message);
        return 1;
    }

    if (disable_audio && disable_video) {
        g_print("Audio and video disabled. Nothing to do.\n");
        return 0;
    }

    /* PREPARE FOR RECEIVING */

    OwrPayload *receive_payload;

    owr_init(NULL);

    bus = owr_bus_new();
    owr_bus_set_message_callback(bus, (OwrBusMessageCallback) bus_message_print_callback,
        message_origin_name_func, NULL);

    if (!print_messages) {
        g_object_set(bus, "message-type-mask", OWR_MESSAGE_TYPE_ERROR, NULL);
    }

    owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(owr_window_registry_get()));

    recv_transport_agent = owr_transport_agent_new(FALSE);
    g_assert(OWR_IS_TRANSPORT_AGENT(recv_transport_agent));
    owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(recv_transport_agent));

    owr_transport_agent_set_local_port_range(recv_transport_agent, 5120, 5127);
    if (!remote_addr)
        owr_transport_agent_add_local_address(recv_transport_agent, "127.0.0.1");
    else if (local_addr)
        owr_transport_agent_add_local_address(recv_transport_agent, local_addr);

    // SEND
    send_transport_agent = owr_transport_agent_new(TRUE);
    g_assert(OWR_IS_TRANSPORT_AGENT(send_transport_agent));
    owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(send_transport_agent));

    owr_transport_agent_set_local_port_range(send_transport_agent, 5120, 5129);
    if (!remote_addr)
        owr_transport_agent_add_local_address(send_transport_agent, "127.0.0.1");

    if (!disable_video) {
        recv_session_video = owr_media_session_new(FALSE);
        owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(recv_session_video));
        send_session_video = owr_media_session_new(TRUE);
        owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(send_session_video));
    }
    if (!disable_audio) {
        recv_session_audio = owr_media_session_new(FALSE);
        owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(recv_session_audio));
        send_session_audio = owr_media_session_new(TRUE);
        owr_bus_add_message_origin(bus, OWR_MESSAGE_ORIGIN(send_session_audio));
    }

    if (!disable_video) {
        g_signal_connect(recv_session_video, "on-new-candidate", G_CALLBACK(got_candidate), send_session_video);
        g_signal_connect(send_session_video, "on-new-candidate", G_CALLBACK(got_candidate), recv_session_video);
        if (remote_addr) {
            g_signal_connect(recv_session_video, "on-candidate-gathering-done", G_CALLBACK(gathering_done), send_session_video);
            g_signal_connect(send_session_video, "on-candidate-gathering-done", G_CALLBACK(gathering_done), recv_session_video);
	    owr_session_set_local_port(OWR_SESSION(send_session_video), OWR_COMPONENT_TYPE_RTP, 5120);
	    owr_session_set_local_port(OWR_SESSION(send_session_video), OWR_COMPONENT_TYPE_RTCP, 5121);
	    owr_session_set_local_port(OWR_SESSION(recv_session_video), OWR_COMPONENT_TYPE_RTP, 5122);
	    owr_session_set_local_port(OWR_SESSION(recv_session_video), OWR_COMPONENT_TYPE_RTCP, 5123);
        }
    }
    if (!disable_audio) {
        g_signal_connect(recv_session_audio, "on-new-candidate", G_CALLBACK(got_candidate), send_session_audio);
        g_signal_connect(send_session_audio, "on-new-candidate", G_CALLBACK(got_candidate), recv_session_audio);
        if (remote_addr) {
            g_signal_connect(recv_session_audio, "on-candidate-gathering-done", G_CALLBACK(gathering_done), send_session_audio);
            g_signal_connect(send_session_audio, "on-candidate-gathering-done", G_CALLBACK(gathering_done), recv_session_audio);
	    owr_session_set_local_port(OWR_SESSION(send_session_audio), OWR_COMPONENT_TYPE_RTP, 5124);
	    owr_session_set_local_port(OWR_SESSION(send_session_audio), OWR_COMPONENT_TYPE_RTCP, 5125);
	    owr_session_set_local_port(OWR_SESSION(recv_session_audio), OWR_COMPONENT_TYPE_RTP, 5126);
	    owr_session_set_local_port(OWR_SESSION(recv_session_audio), OWR_COMPONENT_TYPE_RTCP, 5127);
        }
    }

    // VIDEO
    if (!disable_video) {
        g_signal_connect(recv_session_video, "on-incoming-source", G_CALLBACK(got_remote_source), NULL);

        receive_payload = owr_video_payload_new(OWR_CODEC_TYPE_VP8, 103, 90000, TRUE, FALSE);
        g_object_set(receive_payload, "rtx-payload-type", 123, NULL);
        if (adaptation)
            g_object_set(receive_payload, "adaptation", TRUE, NULL);

        owr_media_session_add_receive_payload(recv_session_video, receive_payload);
    }

    // AUDIO
    if (!disable_audio) {
        g_signal_connect(recv_session_audio, "on-incoming-source", G_CALLBACK(got_remote_source), NULL);

        receive_payload = owr_audio_payload_new(OWR_CODEC_TYPE_OPUS, 100, 48000, 1);
        owr_media_session_add_receive_payload(recv_session_audio, receive_payload);
    }

    /* PREPARE FOR SENDING */

    if (!uri) {
        owr_get_capture_sources(
                (!disable_video ? OWR_MEDIA_TYPE_VIDEO : 0) | (!disable_audio ? OWR_MEDIA_TYPE_AUDIO : 0),
                got_sources, NULL);
    } else {
        uri_source_agent = owr_uri_source_agent_new(uri);
        g_signal_connect(uri_source_agent, "on-new-source", G_CALLBACK(on_new_source), NULL);
        owr_uri_source_agent_play(uri_source_agent);
    }

    g_timeout_add_seconds(10, (GSourceFunc)dump_cb, NULL);

    owr_run();

    g_free(remote_addr);
    g_free(uri);

    return 0;
}
int
main (int argc, char **argv)
{
  GOptionEntry options[] = {
    {"effects", 'e', 0, G_OPTION_ARG_STRING, &opt_effects,
        "Effects to use (comma-separated list of element names)", NULL},
    {NULL}
  };
  GOptionContext *ctx;
  GError *err = NULL;
  GMainLoop *loop;
  GstElement *src, *sink;
  gchar **effect_names, **e;

  ctx = g_option_context_new ("");
  g_option_context_add_main_entries (ctx, options, NULL);
  g_option_context_add_group (ctx, gst_init_get_option_group ());
  if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
    g_print ("Error initializing: %s\n", err->message);
    return 1;
  }
  g_option_context_free (ctx);

  if (opt_effects != NULL)
    effect_names = g_strsplit (opt_effects, ",", -1);
  else
    effect_names = g_strsplit (DEFAULT_EFFECTS, ",", -1);

  for (e = effect_names; e != NULL && *e != NULL; ++e) {
    GstElement *el;

    el = gst_element_factory_make (*e, NULL);
    if (el) {
      g_print ("Adding effect '%s'\n", *e);
      g_queue_push_tail (&effects, el);
    }
  }

  pipeline = gst_pipeline_new ("pipeline");

  src = gst_element_factory_make ("videotestsrc", NULL);
  g_object_set (src, "is-live", TRUE, NULL);

  blockpad = gst_element_get_static_pad (src, "src");

  conv_before = gst_element_factory_make ("videoconvert", NULL);

  cur_effect = g_queue_pop_head (&effects);

  conv_after = gst_element_factory_make ("videoconvert", NULL);

  sink = gst_element_factory_make ("ximagesink", NULL);

  gst_bin_add_many (GST_BIN (pipeline), src, conv_before, cur_effect,
      conv_after, sink, NULL);

  gst_element_link_many (src, conv_before, cur_effect, conv_after,
      sink, NULL);

  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  loop = g_main_loop_new (NULL, FALSE);

  gst_bus_add_watch (GST_ELEMENT_BUS (pipeline), bus_cb, loop);

  g_timeout_add_seconds (1, timeout_cb, loop);

  g_main_loop_run (loop);

  gst_element_set_state (pipeline, GST_STATE_NULL);
  gst_object_unref (pipeline);

  return 0;
}
Example #24
0
bool loop(int argc, char** argv) {

	char home[256]; //NEED TO MAKE THIS DYNAMIC
	strcpy(home, getenv("HOME"));

	//parse the config file
	settings.parse_config(strcat(home, config_file));
	//load the controls into list
	ElementList list(settings.card);
	list_ptr = &list;
	//reorder the controls to the order specified in the config file
	settings.reorder_list(&list);

	//set the scale
	list.set_scale((Element::scale_t)settings.scaling);
	//set the auto_mute
	list.set_auto_mute(settings.auto_mute);
	
	//initialize gtk
	gtk_init(&argc, &argv);

	//set up the tray_slider that goes in the tray
	if (settings.enable_tray_icon){
		GtkWidget *tray_frame;
		tray_frame = gtk_alignment_new(0.5,0.0,0,0);
		settings.tray_slider = new retro_slider;
		settings.set_tray_slider(&list);
		settings.apply_to_tray_slider(settings.tray_slider);
		if (list.num_elems > 0){
			settings.tray_slider->init(tray_frame, (void*)settings.tray_control, &Element::get_callback, &Element::set_callback, (settings.tray_control->values > 1));
		} else {
			settings.tray_control = NULL;
		}

		//set up the small window that holds the tray_slider
		settings.slider_window = gtk_window_new (GTK_WINDOW_POPUP);
		gtk_window_set_resizable(GTK_WINDOW(settings.slider_window), false);
		gtk_window_set_decorated(GTK_WINDOW(settings.slider_window), false);
		gtk_window_set_skip_taskbar_hint(GTK_WINDOW(settings.slider_window), true);
		gtk_window_set_skip_pager_hint(GTK_WINDOW(settings.slider_window), true);
		gtk_widget_set_usize(settings.slider_window, settings.tray_slider->width, settings.tray_slider->height);
		//don't want accidental closure of the slider window to destroy the window
		g_signal_connect(settings.slider_window, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL);
		//want the widow to go away when it loses focus
		g_signal_connect(settings.slider_window, "focus-out-event", G_CALLBACK (gtk_widget_hide), NULL);
		gtk_container_add( GTK_CONTAINER(settings.slider_window), tray_frame );
		//we want it hidden by default, but it must be shown at least once or else scrolling over the icon will cause a hang
		gtk_widget_show_all(settings.slider_window);
		gtk_widget_hide_all(settings.slider_window);
		
			
		//set up tray icon
#if GTK_CHECK_VERSION(2,16,0)
		settings.tray_icon = gtk_status_icon_new();
		gtk_status_icon_set_from_file(settings.tray_icon, VOL_MUTED_IMAGE);
#else
		settings.tray_icon = GTK_WIDGET(egg_tray_icon_new("Retrovol Tray Icon"));
		//set the background color
		bool enable_tray_icon_background_color = settings.enable_tray_icon_background_color; 
		GdkColor bg_color;
		char bg_color_str[8];
		if (cmdline_enable_bg_color){
			enable_tray_icon_background_color = true;
			strcpy(bg_color_str, cmdline_bg_color);
		} else if (settings.enable_tray_icon_background_color){
			settings.nftoh(settings.tray_icon_background_color, bg_color_str);
		}
		if (enable_tray_icon_background_color){
			if (gdk_color_parse(bg_color_str, &bg_color)){
				GtkStyle *style = gtk_style_copy(gtk_widget_get_style(settings.tray_icon));
				style->bg[GTK_STATE_NORMAL] = bg_color;
				gtk_widget_set_style(settings.tray_icon, style);
			} else {
				fprintf(stderr, _("Error:  Failed to set background color to %s\n"), bg_color_str);
			}
		}
		//set up the images
		settings.tray_icon_image = gtk_image_new();
		gtk_container_add( GTK_CONTAINER(settings.tray_icon), settings.tray_icon_image );
		gtk_image_set_from_file(GTK_IMAGE(settings.tray_icon_image), VOL_MEDIUM_IMAGE);
		//set the event mask
		gtk_widget_set_events (settings.tray_icon, GDK_BUTTON_PRESS_MASK | GDK_SCROLL_MASK);
#endif

		//signals
		g_signal_connect(G_OBJECT(settings.tray_icon), "button_press_event", G_CALLBACK (&tray_button_press_event_callback), settings.slider_window);
		if (settings.tray_control){
			g_signal_connect(G_OBJECT(settings.tray_icon), "scroll_event", G_CALLBACK (&retro_slider::scroll_event_callback), settings.tray_slider);
		}

#if GTK_CHECK_VERSION(2,16,0)
		//make icon visible
		gtk_status_icon_set_visible(settings.tray_icon, true);
#else
		//handle situations where the icon's window dies, such as due to the tray itself exiting
		g_signal_connect(G_OBJECT(settings.tray_icon), "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL);

		//make icon visible
		gtk_widget_show_all(settings.tray_icon);
#endif

		//set up the popup menu (the function checks if it should actually do anything)
		set_menu();

	}
	


	//set up the window
	settings.main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	//gtk_window_set_position(GTK_WINDOW(settings.main_window), GTK_WIN_POS_CENTER);
	gtk_window_set_default_size(GTK_WINDOW(settings.main_window), settings.window_width, settings.window_height);
	gtk_window_set_title(GTK_WINDOW(settings.main_window), "Retrovol");
	restore_posdim();
	g_signal_connect(settings.main_window, "configure-event", G_CALLBACK (save_posdim), NULL);
	
	//if the tray icon is enabled, we want the window to hide rather than closing
	if (settings.enable_tray_icon){
		g_signal_connect(settings.main_window, "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL);
	}

	//make the over_box, which will hold stuff like the menu, status bar, and the actual content in the middle
	GtkWidget *over_box;
	over_box = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(settings.main_window), over_box);

	//define the menu
	GtkItemFactoryEntry menu_items_1[] = {
		{ (gchar*)_("/_File"),           NULL,              NULL,                      0, (gchar*)"<Branch>" },
		{ (gchar*)_("/File/_Configure"), (gchar*)"<CTRL>C", G_CALLBACK(configure),     0, (gchar*)"<StockItem>", GTK_STOCK_EXECUTE },
		{ (gchar*)_("/File/_Quit"),      (gchar*)"<CTRL>Q", G_CALLBACK(close_window),  0, (gchar*)"<StockItem>", GTK_STOCK_QUIT },
	};
	gint nmenu_items_1 = sizeof (menu_items_1) / sizeof (menu_items_1[0]);
	
	GtkItemFactoryEntry menu_items_2[] = {
		{ (gchar*)_("/_File"),           NULL,              NULL,                      0, (gchar*)"<Branch>" },
		{ (gchar*)_("/File/_Configure"), (gchar*)"<CTRL>C", G_CALLBACK(configure),     0, (gchar*)"<StockItem>", GTK_STOCK_EXECUTE },
		{ (gchar*)_("/File/_Exit completely"),      (gchar*)"<CTRL>E", G_CALLBACK(gtk_main_quit),  0, (gchar*)"<StockItem>", GTK_STOCK_QUIT },
		{ (gchar*)_("/File/_Quit"),      (gchar*)"<CTRL>Q", G_CALLBACK(close_window),  0, (gchar*)"<StockItem>", GTK_STOCK_QUIT },
	};
	gint nmenu_items_2 = sizeof (menu_items_2) / sizeof (menu_items_2[0]);

	GtkItemFactoryEntry *menu_items;
	gint nmenu_items;
	//if the tray menu is enabled, don't have the "Exit" entry in the main menu
	if (settings.enable_tray_menu){
		menu_items = menu_items_1;
		nmenu_items = nmenu_items_1;
	} else {
		menu_items = menu_items_2;
		nmenu_items = nmenu_items_2;
	}

	//build the menu
	GtkWidget *menubar;
	menubar = get_menubar_menu(settings.main_window, menu_items, nmenu_items, "<RetrovolMain>");
	gtk_box_pack_start(GTK_BOX(over_box), menubar, FALSE, TRUE, 0);


	//use a scrolled window
	GtkWidget *scrolled_window;
	scrolled_window = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy((GtkScrolledWindow*)scrolled_window, GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_container_add(GTK_CONTAINER(over_box), scrolled_window);
	
	//put the stuff into a viewport manually, so we can specify that it should have no shadow
	GtkWidget *viewport;
	viewport = gtk_viewport_new(NULL, NULL);
	gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
	gtk_container_add(GTK_CONTAINER(scrolled_window), viewport);
	
			
	//and create an Hbox to hold all the stuff
	GtkWidget *hbox;
	if (settings.vertical){
		hbox = gtk_hbox_new(TRUE, 2);
		gtk_container_add(GTK_CONTAINER(viewport), hbox);
	} else {
		hbox = gtk_vbox_new(TRUE, 2);
		gtk_container_add(GTK_CONTAINER(viewport), hbox);
	}
			
	//add the sliders
	retro_slider *sliders = new retro_slider[list.num_items];
	
	for(int i=0; i<list.num_items; i++){
		//use a vbox w/ slider on top and label on bottom
		GtkWidget *vbox;
		if (settings.vertical){
			vbox = gtk_vbox_new(FALSE, 2);
		} else {
			vbox = gtk_hbox_new(FALSE, 2);
		}
		gtk_box_pack_start(GTK_BOX(hbox), vbox, false, false, 0);
		
		if (strcmp(list.items[i]->type, "INTEGER") == 0){
			//integers need sliders
			//the rslider pseudo-widget likes to be inside a container, lets use a GtkAlignment
			GtkWidget *frame;
			if (settings.vertical){
				frame = gtk_alignment_new(0.5,0.0,0,0);
				gtk_box_pack_start(GTK_BOX(vbox), frame, false, false, 0);
			} else {
				frame = gtk_alignment_new(0.0,0.5,0,0);
				gtk_box_pack_end(GTK_BOX(vbox), frame, false, false, 0);
			}
			//make the slider and associate with a control
			settings.apply_to_slider(&sliders[i]);
			sliders[i].init(frame, (void*)list.items[i], &Element::get_callback, &Element::set_callback, (list.items[i]->values > 1));
		
		} else if (strcmp(list.items[i]->type, "BOOLEAN") == 0){
			//booleans need checkboxes
			GtkWidget *alignment;
			if (settings.vertical){
				alignment = gtk_alignment_new(0.5,1.0,0,0);
				gtk_box_pack_start(GTK_BOX(vbox), alignment, true, true, 0);
			} else {
				alignment = gtk_alignment_new(1.0,0.5,0,0);
				gtk_box_pack_end(GTK_BOX(vbox), alignment, true, true, 0);
			}
			GtkWidget *chkbx;
			chkbx = gtk_check_button_new();
			//set it to the current state
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkbx), (bool)list.items[i]->get());
			//bind to the toggle_checkbox function
			Element* ptr = list.items[i];
			g_signal_connect(GTK_TOGGLE_BUTTON(chkbx), "toggled", G_CALLBACK (toggle_checkbox), ptr);
			g_signal_connect_after(GTK_TOGGLE_BUTTON(chkbx), "expose-event", G_CALLBACK (refresh_checkbox), ptr);
			gtk_container_add(GTK_CONTAINER(alignment), chkbx);
		} else if (strcmp(list.items[i]->type, "ENUMERATED") == 0){
			GtkWidget *alignment;
			if (settings.vertical){
				alignment = gtk_alignment_new(0.5,0.5,0,0);
				gtk_box_pack_start(GTK_BOX(vbox), alignment, true, true, 0);
			} else {
				alignment = gtk_alignment_new(1.0,0.5,0,0);
				gtk_box_pack_end(GTK_BOX(vbox), alignment, true, true, 0);
			}
			//insert a combobox with the different options
			GtkWidget *combo_box;
			combo_box=gtk_combo_box_new_text();
			for(unsigned int n=0; n<list.items[i]->number_of_enums; n++){
				gtk_combo_box_append_text(GTK_COMBO_BOX(combo_box), list.items[i]->enums[n]);
			}
			gtk_combo_box_set_active(GTK_COMBO_BOX(combo_box), list.items[i]->get());
			//bind to the change_combo_box function
			g_signal_connect(GTK_COMBO_BOX(combo_box), "changed", G_CALLBACK (change_combo_box), list.items[i]);
			gtk_container_add(GTK_CONTAINER(alignment), combo_box);
		}
		
		//add a checkbox for sliders that are muteable
		if (list.items[i]->switch_id >= 0){
			GtkWidget *alignment;
			if (settings.vertical){
				alignment = gtk_alignment_new(0.5,1.0,0,0);
				gtk_box_pack_start(GTK_BOX(vbox), alignment, true, true, 0);
			} else {
				alignment = gtk_alignment_new(1.0,0.5,0,0);
				gtk_box_pack_end(GTK_BOX(vbox), alignment, true, true, 0);
			}
			GtkWidget *chkbx;
			chkbx = gtk_check_button_new();
			//set it to the current state
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chkbx), (bool)list.elems[list.items[i]->switch_id].get());
			//bind to the toggle_checkbox function
			g_signal_connect(GTK_TOGGLE_BUTTON(chkbx), "toggled", G_CALLBACK (toggle_checkbox), &(list.elems[list.items[i]->switch_id]));
			g_signal_connect_after(GTK_TOGGLE_BUTTON(chkbx), "expose-event", G_CALLBACK (refresh_checkbox), &(list.elems[list.items[i]->switch_id]));
			
			gtk_container_add(GTK_CONTAINER(alignment), chkbx);
		}
		
		//display the name of the control
		GtkWidget *alignment;
		char wrapped[256];
		if (settings.vertical){
			alignment = gtk_alignment_new(0.5,1.0,0,0);
			gtk_box_pack_end(GTK_BOX(vbox), alignment, false, false, 0);
			word_wrap(wrapped, list.items[i]->short_name);
		} else {
			alignment = gtk_alignment_new(1.0,0.5,0,0);
			gtk_box_pack_start(GTK_BOX(vbox), alignment, false, false, 0);
			strcpy(wrapped, list.items[i]->short_name);
		}
		GtkWidget *label;
		label = gtk_label_new(wrapped);
		gtk_container_add(GTK_CONTAINER(alignment), label);
	}
	
	//finish the window stuff
	if (!start_hidden){ gtk_widget_show_all(settings.main_window); }
	g_signal_connect(settings.main_window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
	

	//add some periodic refreshment to keep the icon and window up-to-date
	#if GTK_CHECK_VERSION(2,14,0)
		int timeout = g_timeout_add_seconds(1, update, NULL);
	#else
		//this is less efficient than g_timeout_add_seconds()
		int timeout = g_timeout_add(1000, update, NULL);
	#endif
	
	//finished with gtk setup
	gtk_main();

	//stop the timeout
	g_source_remove(timeout);
	
	//have the window shown again if it was open before we restarted
	if (settings.resume_main){
		settings.resume_main = false;
		start_hidden = false;
	} else {
		start_hidden = true;
	}

	return(settings.restart);
}
Example #25
0
void run_client( pcat_client c, pcat_point p )
{
    gchar *argv[ 2 ] = {
        c->program_name,
        NULL
    };
    size_t additional_env_vars = 1;
    size_t total_env_slots = c->space.num_knobs + additional_env_vars + 1;
    gchar **child_env =
        (gchar **)g_malloc( total_env_slots * sizeof( child_env[0] ) );
    for( size_t i = 0; i < c->space.num_knobs; i++ )
    {
        size_t buffer_size = 1000; /* way too big? */
        child_env[i] = g_malloc( buffer_size );
        pcat_knob k = &get_space( c )->knobs[i];
        printf( "%s\n", k->name );
        switch( k->kind )
        {
            case PCAT_KNOBK_DISCRETE:
                g_snprintf( child_env[i], (gulong)buffer_size, "%s%s=%"PRIi64,
                            PCAT_ENV_VAR_VALUE_PREFIX, k->name, p[i].d );
                break;
            case PCAT_KNOBK_CONTINUOUS:
                g_snprintf( child_env[i], (gulong)buffer_size, "%s%s=%lf",
                            PCAT_ENV_VAR_VALUE_PREFIX, k->name, p[i].c );
                break;
            case PCAT_KNOBK_UNORDERED:
                g_message( "---> Don't really know what to do about " );
                break;
            default:
                g_message( "---> Wrong kind of knob" );
                break;
        }
    }
    child_env[ c->space.num_knobs ] = PCAT_SENSOR_READINGS_FILENAME "=blam";
    child_env[ c->space.num_knobs + 1 ] = NULL;
    // playing_env_dump();
    
    int chld_std_out_fd, chld_std_err_fd;
    GError *err = NULL;
    data_bucket_ b;
    b.out_done = FALSE;
    b.err_done = FALSE;
    b.child_done = FALSE;
    gchar *result_regex_str = "PCAT_CLIENT_((?<res>SUCCESS)|FAILURE[[:space:]]*\\=[[:space:]]*(?<fcode>[^[:space:]]*))";
    gchar *val_regex_str = PCAT_CLIENT_REPORT_PREFIX "(?<var_name>[[:alpha:]][[:alnum:]_]*)[[:space:]]*\\:[[:space:]]*(?<type_val>REAL|STRING|INTEGRAL)[[:space:]]*\\=[[:space:]]*(?<value>[^[:space:]]*)";
    b.result_regex = g_regex_new( result_regex_str, 0 /* compile flags */, 0 /* match flags*/, &err );
    if( err != NULL )
    {
        printf( "blah: %s\n", err->message );
        abort();
    }
    b.val_regex    = g_regex_new( val_regex_str, 0 /* compile flags */, 0 /* match flags*/, &err );
    b.main_loop = g_main_loop_new( NULL, FALSE );
    gboolean spawn_worked = g_spawn_async_with_pipes(
        NULL, /* const gchar *working_directory */
        argv,
        child_env,
        G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
        /* GSpawnFlags flags */
        /* G_SPAWN_LEAVE_DESCRIPTORS_OPEN */
        /* G_SPAWN_SEARCH_PATH */
        /* G_SPAWN_STDOUT_TO_DEV_NULL */
        /* G_SPAWN_STDERR_TO_DEV_NULL */
        /* G_SPAWN_CHILD_INHERITS_STDIN */
        /* G_SPAWN_FILE_AND_ARGV_ZERO */
        NULL, /* GSpawnChildSetupFunc child_setup */
        NULL, /* gpointer user_data */
        &b.child_pid,
        NULL, /* gint *standard_input */
        &chld_std_out_fd,
        &chld_std_err_fd,
        &err );

    if( !spawn_worked )
    {
        // error!
    }

    b.child_eid = g_child_watch_add( b.child_pid, handle_client_exit, &b );

    /* Create channels that will be used to read data from pipes. */
#ifdef G_OS_WIN32
    b.out_source = g_io_channel_win32_new_fd( chld_std_out_fd );
    b.err_source = g_io_channel_win32_new_fd( chld_std_err_fd );
#else
    b.out_source = g_io_channel_unix_new( chld_std_out_fd );
    b.err_source = g_io_channel_unix_new( chld_std_err_fd );
#endif

    b.out_eid = g_io_add_watch( b.out_source, G_IO_IN | G_IO_HUP, (GIOFunc)child_out_handler, &b );
    b.err_eid = g_io_add_watch( b.err_source, G_IO_IN | G_IO_HUP, (GIOFunc)child_out_handler, &b );
    // these too
    // G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
    // G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP | G_IO_NVAL,

    b.timeout_eid = g_timeout_add_seconds( 10, timeout_func, &b );

    g_main_loop_run( b.main_loop );
    g_message( "Done running client\n" );
    g_io_channel_unref( b.out_source );
    g_io_channel_unref( b.err_source );
    g_main_loop_unref( b.main_loop );
    g_regex_unref( b.val_regex );
    g_regex_unref( b.result_regex );
    for( size_t i = 0; i < c->space.num_knobs; i++ )
    {
        g_free( child_env[i] );
    }
    g_free( child_env );
}
Example #26
0
int
main(int argc, char **argv)
{
  GMainLoop *loop;
  GstRTSPServer *server;
  GstRTSPMediaMapping *mapping;
  GstRTSPCamMediaFactory *factory;
  GstRTSPUrl *local_url;
  GOptionContext *ctx;
  GOptionGroup *gst_group;
  gboolean res;
  GError *error = NULL;

  g_type_init ();
  g_thread_init (NULL);

  ctx = g_option_context_new ("rtsp://host:port/path");
  g_option_context_add_main_entries (ctx, option_entries, NULL);
  gst_group = gst_init_get_option_group ();
  g_option_context_add_group (ctx, gst_group);
  res = g_option_context_parse (ctx, &argc, &argv, &error);
  g_option_context_free (ctx);

  gst_init (&argc, &argv);

  if (!res) {
    g_printerr ("command line error: %s\n", error->message);
    g_error_free (error);

    return 1;
  }

  if (gst_rtsp_url_parse (argc != 2 ? "rtsp://127.0.0.1:8554/test" : argv[1], &local_url) != GST_RTSP_OK) {
    g_printerr ("invalid rtsp url\n");

    return 1;
  }

  loop = g_main_loop_new (NULL, FALSE);

  server = gst_rtsp_server_new ();

  factory = gst_rtsp_cam_media_factory_new ();
  g_object_set (factory, "video-device", video_device,
      "video", !no_video,
      "video-width", video_width,
      "video-height", video_height,
      "video-codec", video_codec,
      "video-framerate", fps_n, fps_d,
      "audio", !no_audio,
      "audio-device", audio_device,
      "audio-codec", audio_codec,
      NULL);

  gst_rtsp_media_factory_set_shared (GST_RTSP_MEDIA_FACTORY (factory), TRUE);
  mapping = gst_rtsp_server_get_media_mapping (server);
  gst_rtsp_media_mapping_add_factory (mapping, local_url->abspath,
      GST_RTSP_MEDIA_FACTORY (factory));
  g_object_unref (mapping);

  gst_rtsp_url_free (local_url);

  gst_rtsp_server_attach (server, NULL);

  g_timeout_add_seconds (5, (GSourceFunc) timeout, server);
  /* start serving */
  g_main_loop_run (loop);

  return 0;
}
Example #27
0
void cm_gdata_update_contacts_update_timer(void)
{
    if(timer_query_contacts != 0)
        g_source_remove(timer_query_contacts);
    timer_query_contacts = g_timeout_add_seconds(cm_gdata_config.max_cache_age, (GSourceFunc)cm_gdata_update_contacts_cache, NULL);
}
Example #28
0
static void
tweet_window_constructed (GObject *gobject)
{
  TweetWindow *window = TWEET_WINDOW (gobject);
  TweetWindowPrivate *priv = window->priv;
  ClutterActor *stage;
  ClutterActor *view;
  ClutterActor *img;
  ClutterColor stage_color = { 0, 0, 0, 255 };

  stage = gtk_clutter_embed_get_stage (GTK_CLUTTER_EMBED (priv->canvas));
  clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);

  view = tweet_status_view_new (priv->status_model);
  g_signal_connect (view,
                    "button-press-event", G_CALLBACK (on_status_view_button_press),
                    window);
  g_signal_connect (view,
                    "button-release-event", G_CALLBACK (on_status_view_button_release),
                    window);
  priv->scroll = tidy_finger_scroll_new (TIDY_FINGER_SCROLL_MODE_KINETIC);
  clutter_container_add_actor (CLUTTER_CONTAINER (priv->scroll), view);
  clutter_actor_show (view);
  clutter_actor_set_reactive (view, TRUE);
  priv->status_view = view;

  clutter_actor_set_size (priv->scroll, CANVAS_WIDTH, CANVAS_HEIGHT);
  clutter_actor_set_position (priv->scroll, CANVAS_PADDING, CANVAS_PADDING);
  clutter_container_add_actor (CLUTTER_CONTAINER (stage), priv->scroll);
  clutter_actor_set_reactive (priv->scroll, TRUE);
  clutter_actor_show (priv->scroll);

  img = tweet_texture_new_from_stock (GTK_WIDGET (window),
                                      GTK_STOCK_REFRESH,
                                      GTK_ICON_SIZE_DIALOG);
  if (!img)
    g_warning ("Unable to load the `%s' stock icon", GTK_STOCK_REFRESH);

  priv->spinner = tweet_spinner_new ();
  tweet_spinner_set_image (TWEET_SPINNER (priv->spinner), img);
  clutter_container_add_actor (CLUTTER_CONTAINER (stage), priv->spinner);
  clutter_actor_set_size (priv->spinner, 128, 128);
  clutter_actor_set_anchor_point (priv->spinner, 64, 64);
  clutter_actor_set_position (priv->spinner,
                              WINDOW_WIDTH / 2,
                              CANVAS_HEIGHT / 2);
  clutter_actor_show (priv->spinner);
  tweet_spinner_start (TWEET_SPINNER (priv->spinner));
  tweet_actor_animate (priv->spinner, TWEET_LINEAR, 500,
                       "opacity", tweet_interval_new (G_TYPE_UCHAR, 0, 127),
                       NULL);

  clutter_actor_show (stage);
  gtk_widget_show (GTK_WIDGET (window));

  twitter_client_get_user_timeline (priv->client, NULL, 0, NULL);

  priv->refresh_id =
    g_timeout_add_seconds (tweet_config_get_refresh_time (priv->config),
                           refresh_timeout,
                           window);
}
Example #29
0
gboolean
main_loop (gpointer data)
{
  gint status;
  gint tmp, winner;
  gchar *str = NULL;

  status = gnibbles_move_worms ();
  gnibbles_scoreboard_update (scoreboard);

  if (status == VICTORY) {
    end_game (TRUE);
    winner = gnibbles_get_winner ();

    if (winner == -1)
      return FALSE;

    str = g_strdup_printf (_("Game over! The game has been won by %s!"),
                             names[winner]);
#ifdef GGZ_CLIENT
    add_chat_text (str);
#endif
    g_free (str);

    if (keyboard_id) {
      g_signal_handler_disconnect (G_OBJECT (stage), keyboard_id);
      keyboard_id = 0;
    }
    if (main_id) {
      g_source_remove (main_id);
      main_id = 0;
    }
    if (add_bonus_id)
      g_source_remove (add_bonus_id);

    add_bonus_id = 0;

    animate_end_game ();
    gnibbles_log_score (window);

    return FALSE;
  }

  if (status == GAMEOVER) {

    if (keyboard_id) {
      g_signal_handler_disconnect (G_OBJECT (stage), keyboard_id);
      keyboard_id = 0;
    }
    main_id = 0;
    if (add_bonus_id)
      g_source_remove (add_bonus_id);

    add_bonus_id = 0;

    animate_end_game ();
    gnibbles_log_score (window);

    return FALSE;
  }

  if (status == NEWROUND) {
#ifdef GGZ_CLIENT
    if (ggz_network_mode) {
      end_game (TRUE);
      add_chat_text (_("The game is over."));
      return FALSE;
    }
#endif

    if (keyboard_id) {
      g_signal_handler_disconnect (G_OBJECT (stage), keyboard_id);
      keyboard_id = 0;
    }
    if (add_bonus_id)
      g_source_remove (add_bonus_id);

    if (main_id) {
      g_source_remove (main_id);
      main_id = 0;
    }
    add_bonus_id = 0;

    animate_end_game ();
    restart_id = g_timeout_add_seconds (1, (GSourceFunc) restart_game, NULL);

    return FALSE;
  }

  if (boni->numleft == 0) {
    if (restart_id)
      return TRUE;

    if (keyboard_id)
      g_signal_handler_disconnect (G_OBJECT (stage), keyboard_id);

    keyboard_id = 0;

    if (add_bonus_id)
      g_source_remove (add_bonus_id);

    add_bonus_id = 0;
    if (main_id) {
      g_source_remove (main_id);
      main_id = 0;
    }
    if ((current_level < MAXLEVEL) && (!properties->random
                                       || ggz_network_mode)) {
      current_level++;
    } else if (properties->random && !ggz_network_mode) {
      tmp = rand () % MAXLEVEL + 1;
      while (tmp == current_level)
        tmp = rand () % MAXLEVEL + 1;
      current_level = tmp;
    }
    animate_end_game ();
    restart_id = g_timeout_add_seconds (1, (GSourceFunc) restart_game, NULL);
    return FALSE;
  }

  return TRUE;
}
/**
 * facq_pipeline_monitor_attach:
 * @mon: A #FacqPipelineMonitor object.
 *
 * Attaches the timeout source to the main thread, so the internal callback
 * function can start to check for new messages, in the #FacqPipelineMonitor
 * object.
 * You don't need to call this function, this function is called in #FacqStream.
 */
void facq_pipeline_monitor_attach(FacqPipelineMonitor *mon)
{
	g_return_if_fail(FACQ_IS_PIPELINE_MONITOR(mon));
	mon->priv->source_id = 
		g_timeout_add_seconds(1,facq_pipeline_monitor_timeout_func,mon);
}