Exemplo n.º 1
0
static GstFlowReturn
gst_mxf_mux_create_metadata (GstMXFMux * mux)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GSList *l;
  GArray *tmp;

  GST_DEBUG_OBJECT (mux, "Creating MXF metadata");

  for (l = mux->collect->data; l; l = l->next) {
    GstMXFMuxPad *cpad = l->data;
    GstCaps *caps;

    if (!cpad || !cpad->descriptor)
      return GST_FLOW_ERROR;

    caps = gst_pad_get_current_caps (cpad->collect.pad);
    if (!caps)
      return GST_FLOW_ERROR;

    if (cpad->writer->update_descriptor)
      cpad->writer->update_descriptor (cpad->descriptor,
          caps, cpad->mapping_data, cpad->collect.buffer);
    gst_caps_unref (caps);
  }

  /* Preface */
  mux->preface =
      (MXFMetadataPreface *) g_object_new (MXF_TYPE_METADATA_PREFACE, NULL);
  mxf_uuid_init (&MXF_METADATA_BASE (mux->preface)->instance_uid,
      mux->metadata);
  g_hash_table_insert (mux->metadata,
      &MXF_METADATA_BASE (mux->preface)->instance_uid, mux->preface);
  mux->metadata_list = g_list_prepend (mux->metadata_list, mux->preface);

  mxf_timestamp_set_now (&mux->preface->last_modified_date);
  mux->preface->version = 258;
  mux->preface->object_model_version = 1;

  mxf_op_set_generalized (&mux->preface->operational_pattern, MXF_OP_1a, TRUE,
      TRUE, FALSE);

  tmp = g_array_new (FALSE, FALSE, sizeof (MXFUL));
  for (l = mux->collect->data; l; l = l->next) {
    GstMXFMuxPad *cpad = l->data;
    guint i;
    gboolean found = FALSE;

    if (!cpad || !cpad->descriptor ||
        mxf_ul_is_zero (&cpad->descriptor->essence_container))
      return GST_FLOW_ERROR;

    for (i = 0; i < tmp->len; i++) {
      if (mxf_ul_is_equal (&cpad->descriptor->essence_container,
              &g_array_index (tmp, MXFUL, i))) {
        found = TRUE;
        break;
      }
    }

    if (found)
      continue;

    g_array_append_val (tmp, cpad->descriptor->essence_container);
  }
  mux->preface->n_essence_containers = tmp->len;
  mux->preface->essence_containers = (MXFUL *) g_array_free (tmp, FALSE);

  /* This will later be used as UID for the material package */
  mxf_uuid_init (&mux->preface->primary_package_uid, mux->metadata);

  /* Identifications */
  {
    MXFMetadataIdentification *identification;
    static const guint8 gst_uid[] = {
      0xe5, 0xde, 0xcd, 0x04, 0x24, 0x90, 0x69, 0x18,
      0x8a, 0xc9, 0xb5, 0xd7, 0x02, 0x58, 0x46, 0x78
    };
    guint major, minor, micro, nano;

    mux->preface->n_identifications = 1;
    mux->preface->identifications = g_new0 (MXFMetadataIdentification *, 1);
    identification = mux->preface->identifications[0] =
        (MXFMetadataIdentification *)
        g_object_new (MXF_TYPE_METADATA_IDENTIFICATION, NULL);

    mxf_uuid_init (&MXF_METADATA_BASE (identification)->instance_uid,
        mux->metadata);
    g_hash_table_insert (mux->metadata,
        &MXF_METADATA_BASE (identification)->instance_uid, identification);
    mux->metadata_list = g_list_prepend (mux->metadata_list, identification);

    mxf_uuid_init (&identification->this_generation_uid, NULL);

    identification->company_name = g_strdup ("GStreamer");
    identification->product_name = g_strdup ("GStreamer Multimedia Framework");

    gst_version (&major, &minor, &micro, &nano);
    identification->product_version.major = major;
    identification->product_version.minor = minor;
    identification->product_version.patch = micro;
    identification->product_version.build = nano;
    identification->product_version.release =
        (nano == 0) ? 1 : (nano == 1) ? 2 : 4;

    identification->version_string =
        g_strdup_printf ("%u.%u.%u.%u", major, minor, micro, nano);
    memcpy (&identification->product_uid, &gst_uid, 16);

    memcpy (&identification->modification_date,
        &mux->preface->last_modified_date, sizeof (MXFTimestamp));
    memcpy (&identification->toolkit_version, &identification->product_version,
        sizeof (MXFProductVersion));

#ifdef HAVE_SYS_UTSNAME_H
    {
      struct utsname sys_details;

      if (uname (&sys_details) == 0) {
        identification->platform = g_strdup_printf ("%s %s %s",
            sys_details.sysname, sys_details.release, sys_details.machine);
      }
    }
#endif

#if defined(G_OS_WIN32)
    if (identification->platform == NULL)
      identification->platform = g_strdup ("Microsoft Windows");
#elif defined(G_OS_BEOS)
    if (identification->platform == NULL)
      identification->platform = g_strdup ("BEOS");
#elif defined(G_OS_UNIX)
    if (identification->platform == NULL)
      identification->platform = g_strdup ("Unix");
#endif
  }

  /* Content storage */
  {
    MXFMetadataContentStorage *cstorage;
    guint i;

    cstorage = mux->preface->content_storage = (MXFMetadataContentStorage *)
        g_object_new (MXF_TYPE_METADATA_CONTENT_STORAGE, NULL);
    mxf_uuid_init (&MXF_METADATA_BASE (cstorage)->instance_uid, mux->metadata);
    g_hash_table_insert (mux->metadata,
        &MXF_METADATA_BASE (cstorage)->instance_uid, cstorage);
    mux->metadata_list = g_list_prepend (mux->metadata_list, cstorage);

    cstorage->n_packages = 2;
    cstorage->packages = g_new0 (MXFMetadataGenericPackage *, 2);

    /* Source package */
    {
      MXFMetadataSourcePackage *p;

      cstorage->packages[1] = (MXFMetadataGenericPackage *)
          g_object_new (MXF_TYPE_METADATA_SOURCE_PACKAGE, NULL);
      mxf_uuid_init (&MXF_METADATA_BASE (cstorage->packages[1])->instance_uid,
          mux->metadata);
      g_hash_table_insert (mux->metadata,
          &MXF_METADATA_BASE (cstorage->packages[1])->instance_uid,
          cstorage->packages[1]);
      mux->metadata_list =
          g_list_prepend (mux->metadata_list, cstorage->packages[1]);
      p = (MXFMetadataSourcePackage *) cstorage->packages[1];

      mxf_umid_init (&p->parent.package_uid);
      p->parent.name = g_strdup ("Source package");
      memcpy (&p->parent.package_creation_date,
          &mux->preface->last_modified_date, sizeof (MXFTimestamp));
      memcpy (&p->parent.package_modified_date,
          &mux->preface->last_modified_date, sizeof (MXFTimestamp));

      p->parent.n_tracks = g_slist_length (mux->collect->data);
      p->parent.tracks = g_new0 (MXFMetadataTrack *, p->parent.n_tracks);

      if (p->parent.n_tracks > 1) {
        MXFMetadataMultipleDescriptor *d;

        p->descriptor = (MXFMetadataGenericDescriptor *)
            g_object_new (MXF_TYPE_METADATA_MULTIPLE_DESCRIPTOR, NULL);
        d = (MXFMetadataMultipleDescriptor *) p->descriptor;
        d->n_sub_descriptors = p->parent.n_tracks;
        d->sub_descriptors =
            g_new0 (MXFMetadataGenericDescriptor *, p->parent.n_tracks);

        mxf_uuid_init (&MXF_METADATA_BASE (d)->instance_uid, mux->metadata);
        g_hash_table_insert (mux->metadata,
            &MXF_METADATA_BASE (d)->instance_uid, d);
        mux->metadata_list = g_list_prepend (mux->metadata_list, d);
      }

      /* Tracks */
      {
        guint n = 0;

        /* Essence tracks */
        for (l = mux->collect->data; l; l = l->next) {
          GstMXFMuxPad *cpad = l->data;
          MXFMetadataTimelineTrack *track;
          MXFMetadataSequence *sequence;
          MXFMetadataSourceClip *clip;
          GstCaps *caps;

          p->parent.tracks[n] = (MXFMetadataTrack *)
              g_object_new (MXF_TYPE_METADATA_TIMELINE_TRACK, NULL);
          track = (MXFMetadataTimelineTrack *) p->parent.tracks[n];
          mxf_uuid_init (&MXF_METADATA_BASE (track)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (track)->instance_uid, track);
          mux->metadata_list = g_list_prepend (mux->metadata_list, track);

          caps = gst_pad_get_current_caps (cpad->collect.pad);
          track->parent.track_id = n + 1;
          track->parent.track_number =
              cpad->writer->get_track_number_template (cpad->descriptor,
              caps, cpad->mapping_data);

          cpad->writer->get_edit_rate (cpad->descriptor,
              caps, cpad->mapping_data,
              cpad->collect.buffer, p, track, &track->edit_rate);
          gst_caps_unref (caps);

          sequence = track->parent.sequence = (MXFMetadataSequence *)
              g_object_new (MXF_TYPE_METADATA_SEQUENCE, NULL);
          mxf_uuid_init (&MXF_METADATA_BASE (sequence)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (sequence)->instance_uid, sequence);
          mux->metadata_list = g_list_prepend (mux->metadata_list, sequence);

          memcpy (&sequence->data_definition, &cpad->writer->data_definition,
              16);

          sequence->n_structural_components = 1;
          sequence->structural_components =
              g_new0 (MXFMetadataStructuralComponent *, 1);

          clip = (MXFMetadataSourceClip *)
              g_object_new (MXF_TYPE_METADATA_SOURCE_CLIP, NULL);
          sequence->structural_components[0] =
              (MXFMetadataStructuralComponent *) clip;
          mxf_uuid_init (&MXF_METADATA_BASE (clip)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (clip)->instance_uid, clip);
          mux->metadata_list = g_list_prepend (mux->metadata_list, clip);

          memcpy (&clip->parent.data_definition, &sequence->data_definition,
              16);
          clip->start_position = 0;

          cpad->source_package = p;
          cpad->source_track = track;
          cpad->descriptor->linked_track_id = n + 1;
          if (p->parent.n_tracks == 1) {
            p->descriptor = (MXFMetadataGenericDescriptor *) cpad->descriptor;
          } else {
            MXF_METADATA_MULTIPLE_DESCRIPTOR (p->
                descriptor)->sub_descriptors[n] =
                (MXFMetadataGenericDescriptor *) cpad->descriptor;
          }

          n++;
        }
      }
    }

    /* Material package */
    {
      MXFMetadataMaterialPackage *p;
      MXFFraction min_edit_rate = { 0, 0 };
      gdouble min_edit_rate_d = G_MAXDOUBLE;

      cstorage->packages[0] = (MXFMetadataGenericPackage *)
          g_object_new (MXF_TYPE_METADATA_MATERIAL_PACKAGE, NULL);
      memcpy (&MXF_METADATA_BASE (cstorage->packages[0])->instance_uid,
          &mux->preface->primary_package_uid, 16);
      g_hash_table_insert (mux->metadata,
          &MXF_METADATA_BASE (cstorage->packages[0])->instance_uid,
          cstorage->packages[0]);
      mux->metadata_list =
          g_list_prepend (mux->metadata_list, cstorage->packages[0]);
      p = (MXFMetadataMaterialPackage *) cstorage->packages[0];

      mxf_umid_init (&p->package_uid);
      p->name = g_strdup ("Material package");
      memcpy (&p->package_creation_date, &mux->preface->last_modified_date,
          sizeof (MXFTimestamp));
      memcpy (&p->package_modified_date, &mux->preface->last_modified_date,
          sizeof (MXFTimestamp));

      p->n_tracks = g_slist_length (mux->collect->data) + 1;
      p->tracks = g_new0 (MXFMetadataTrack *, p->n_tracks);

      /* Tracks */
      {
        guint n;

        n = 1;
        /* Essence tracks */
        for (l = mux->collect->data; l; l = l->next) {
          GstMXFMuxPad *cpad = l->data;
          GstCaps *caps;
          MXFMetadataSourcePackage *source_package;
          MXFMetadataTimelineTrack *track, *source_track;
          MXFMetadataSequence *sequence;
          MXFMetadataSourceClip *clip;

          source_package = MXF_METADATA_SOURCE_PACKAGE (cstorage->packages[1]);
          source_track =
              MXF_METADATA_TIMELINE_TRACK (source_package->parent.tracks[n -
                  1]);

          p->tracks[n] = (MXFMetadataTrack *)
              g_object_new (MXF_TYPE_METADATA_TIMELINE_TRACK, NULL);
          track = (MXFMetadataTimelineTrack *) p->tracks[n];
          mxf_uuid_init (&MXF_METADATA_BASE (track)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (track)->instance_uid, track);
          mux->metadata_list = g_list_prepend (mux->metadata_list, track);

          track->parent.track_id = n + 1;
          track->parent.track_number = 0;

          caps = gst_pad_get_current_caps (cpad->collect.pad);
          cpad->writer->get_edit_rate (cpad->descriptor,
              caps, cpad->mapping_data,
              cpad->collect.buffer, source_package, source_track,
              &track->edit_rate);
          gst_caps_unref (caps);

          if (track->edit_rate.n != source_track->edit_rate.n ||
              track->edit_rate.d != source_track->edit_rate.d) {
            memcpy (&source_track->edit_rate, &track->edit_rate,
                sizeof (MXFFraction));
          }

          if (track->edit_rate.d <= 0 || track->edit_rate.n <= 0) {
            GST_ERROR_OBJECT (mux, "Invalid edit rate");
            return GST_FLOW_ERROR;
          }

          if (min_edit_rate_d >
              ((gdouble) track->edit_rate.n) / ((gdouble) track->edit_rate.d)) {
            min_edit_rate_d =
                ((gdouble) track->edit_rate.n) / ((gdouble) track->edit_rate.d);
            memcpy (&min_edit_rate, &track->edit_rate, sizeof (MXFFraction));
          }

          sequence = track->parent.sequence = (MXFMetadataSequence *)
              g_object_new (MXF_TYPE_METADATA_SEQUENCE, NULL);
          mxf_uuid_init (&MXF_METADATA_BASE (sequence)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (sequence)->instance_uid, sequence);
          mux->metadata_list = g_list_prepend (mux->metadata_list, sequence);

          memcpy (&sequence->data_definition, &cpad->writer->data_definition,
              16);
          sequence->n_structural_components = 1;
          sequence->structural_components =
              g_new0 (MXFMetadataStructuralComponent *, 1);

          clip = (MXFMetadataSourceClip *)
              g_object_new (MXF_TYPE_METADATA_SOURCE_CLIP, NULL);
          sequence->structural_components[0] =
              (MXFMetadataStructuralComponent *) clip;
          mxf_uuid_init (&MXF_METADATA_BASE (clip)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (clip)->instance_uid, clip);
          mux->metadata_list = g_list_prepend (mux->metadata_list, clip);

          memcpy (&clip->parent.data_definition, &sequence->data_definition,
              16);
          clip->start_position = 0;

          memcpy (&clip->source_package_id, &cstorage->packages[1]->package_uid,
              32);
          clip->source_track_id = n;

          n++;
        }

        n = 0;
        /* Timecode track */
        {
          MXFMetadataTimelineTrack *track;
          MXFMetadataSequence *sequence;
          MXFMetadataTimecodeComponent *component;

          p->tracks[n] = (MXFMetadataTrack *)
              g_object_new (MXF_TYPE_METADATA_TIMELINE_TRACK, NULL);
          track = (MXFMetadataTimelineTrack *) p->tracks[n];
          mxf_uuid_init (&MXF_METADATA_BASE (track)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (track)->instance_uid, track);
          mux->metadata_list = g_list_prepend (mux->metadata_list, track);

          track->parent.track_id = n + 1;
          track->parent.track_number = 0;
          track->parent.track_name = g_strdup ("Timecode track");
          /* FIXME: Is this correct? */
          memcpy (&track->edit_rate, &min_edit_rate, sizeof (MXFFraction));

          sequence = track->parent.sequence = (MXFMetadataSequence *)
              g_object_new (MXF_TYPE_METADATA_SEQUENCE, NULL);
          mxf_uuid_init (&MXF_METADATA_BASE (sequence)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (sequence)->instance_uid, sequence);
          mux->metadata_list = g_list_prepend (mux->metadata_list, sequence);

          memcpy (&sequence->data_definition,
              mxf_metadata_track_identifier_get
              (MXF_METADATA_TRACK_TIMECODE_12M_INACTIVE), 16);

          sequence->n_structural_components = 1;
          sequence->structural_components =
              g_new0 (MXFMetadataStructuralComponent *, 1);

          component = (MXFMetadataTimecodeComponent *)
              g_object_new (MXF_TYPE_METADATA_TIMECODE_COMPONENT, NULL);
          sequence->structural_components[0] =
              (MXFMetadataStructuralComponent *) component;
          mxf_uuid_init (&MXF_METADATA_BASE (component)->instance_uid,
              mux->metadata);
          g_hash_table_insert (mux->metadata,
              &MXF_METADATA_BASE (component)->instance_uid, component);
          mux->metadata_list = g_list_prepend (mux->metadata_list, component);

          memcpy (&component->parent.data_definition,
              &sequence->data_definition, 16);

          component->start_timecode = 0;
          if (track->edit_rate.d == 0)
            component->rounded_timecode_base = 1;
          else
            component->rounded_timecode_base =
                (((gdouble) track->edit_rate.n) /
                ((gdouble) track->edit_rate.d) + 0.5);
          /* TODO: drop frame */
        }

        memcpy (&mux->min_edit_rate, &min_edit_rate, sizeof (MXFFraction));
      }
    }

    for (i = 0; i < cstorage->packages[1]->n_tracks; i++) {
      MXFMetadataTrack *track = cstorage->packages[1]->tracks[i];
      guint j;
      guint32 templ;
      guint8 n_type, n;

      if ((track->track_number & 0x00ff00ff) != 0)
        continue;

      templ = track->track_number;
      n_type = 0;

      for (j = 0; j < cstorage->packages[1]->n_tracks; j++) {
        MXFMetadataTrack *tmp = cstorage->packages[1]->tracks[j];

        if (tmp->track_number == templ) {
          n_type++;
        }
      }

      n = 0;
      for (j = 0; j < cstorage->packages[1]->n_tracks; j++) {
        MXFMetadataTrack *tmp = cstorage->packages[1]->tracks[j];

        if (tmp->track_number == templ) {
          n++;
          tmp->track_number |= (n_type << 16) | (n);
        }
      }
    }

    cstorage->n_essence_container_data = 1;
    cstorage->essence_container_data =
        g_new0 (MXFMetadataEssenceContainerData *, 1);
    cstorage->essence_container_data[0] = (MXFMetadataEssenceContainerData *)
        g_object_new (MXF_TYPE_METADATA_ESSENCE_CONTAINER_DATA, NULL);
    mxf_uuid_init (&MXF_METADATA_BASE (cstorage->essence_container_data[0])->
        instance_uid, mux->metadata);
    g_hash_table_insert (mux->metadata,
        &MXF_METADATA_BASE (cstorage->essence_container_data[0])->instance_uid,
        cstorage->essence_container_data[0]);
    mux->metadata_list =
        g_list_prepend (mux->metadata_list,
        cstorage->essence_container_data[0]);

    cstorage->essence_container_data[0]->linked_package =
        MXF_METADATA_SOURCE_PACKAGE (cstorage->packages[1]);
    cstorage->essence_container_data[0]->index_sid = 0;
    cstorage->essence_container_data[0]->body_sid = 1;
  }
void viewer_manager_specific_scan_response_hlr(GSList *bss_info_list)
{
	hidden_ap_data_t *hidden_ap_data = NULL;
	const char *ssid = view_ime_hidden_popup_get_ssid(ug_app_state->hidden_ap_popup);
	wlan_security_mode_type_t sec_mode;
	if (!ssid) {
		return;
	}
	INFO_LOG(UG_NAME_RESP, "Specific scan complete response received for AP[%s]", ssid);
	int ap_count = g_slist_length(bss_info_list);
	net_wifi_connection_info_t *bss_info = NULL;

	if (ap_count == 1) {
		bss_info = g_slist_nth_data(bss_info_list, 0);
		if (!bss_info || g_strcmp0(ssid, bss_info->essid)) {
			INFO_LOG(UG_NAME_RESP, "Fatal: Bss info is NULL OR response received for wrong ssid. ", ssid);
			/* Bss info not available or Response recieved for wrong ssid */
			ap_count = 0;
		} else {
			sec_mode = bss_info->security_info.sec_mode;
		}
	}

	if (ap_count == 1) {
		/* Only if there is one AP found then we need Users further action */
		switch (sec_mode) {
		case WLAN_SEC_MODE_NONE:
			INFO_LOG(UG_NAME_NORMAL, "One AP item with ssid[%s] found. Its security is Open.", ssid);
			/* This is an Open AP. Ask for confirmation to connect. */
			hidden_ap_data = g_try_new0(hidden_ap_data_t, 1);

			popup_btn_info_t popup_btn_data;
			memset(&popup_btn_data, 0, sizeof(popup_btn_data));
			popup_btn_data.info_txt = "Wi-Fi network detected. Connect?";
			popup_btn_data.btn1_cb = hidden_ap_connect_ok_cb;
			popup_btn_data.btn2_cb = hidden_ap_connect_cacel_cb;
			hidden_ap_data->sec_mode = WLAN_SEC_MODE_NONE;
			hidden_ap_data->ssid = g_strdup(ssid);
			popup_btn_data.btn2_data = popup_btn_data.btn1_data = hidden_ap_data;
			popup_btn_data.btn1_txt = sc(PACKAGE, I18N_TYPE_Connect);
			popup_btn_data.btn2_txt = sc(PACKAGE, I18N_TYPE_Cancel);
			hidden_ap_data->confirmation_popup = common_utils_show_info_popup(ug_app_state->win_main, &popup_btn_data);
			break;
		case WLAN_SEC_MODE_IEEE8021X:
			INFO_LOG(UG_NAME_NORMAL, "One AP item with ssid[%s] found. Its security is EAP.", ssid);
			/* This is a EAP secured AP. Ask for confirmation to connect. */
			Evas_Object* navi_frame = viewer_manager_get_naviframe();
			wifi_device_info_t device_info;
			if (navi_frame == NULL) {
				ERROR_LOG(UG_NAME_NORMAL, "Failed : get naviframe");
				return;
			}
			memset(&device_info, 0, sizeof(device_info));
			device_info.security_mode = sec_mode;
			device_info.ssid = (char *)ssid;

			ug_app_state->eap_view = create_eap_connect(ug_app_state->win_main, navi_frame, PACKAGE, &device_info, eap_view_close_cb);
			break;
		case WLAN_SEC_MODE_WEP:
		case WLAN_SEC_MODE_WPA_PSK:
		case WLAN_SEC_MODE_WPA2_PSK:
			INFO_LOG(UG_NAME_NORMAL, "One AP item with ssid[%s] found. Its security is %d", ssid, sec_mode);
			/* This is a WEP/WPA/WPA-2 secured AP. Ask for confirmation to connect. */
			hidden_ap_data = g_try_new0(hidden_ap_data_t, 1);
			pswd_popup_create_req_data_t	popup_info;
			hidden_ap_data->sec_mode = sec_mode;
			hidden_ap_data->ssid = g_strdup(ssid);
			popup_info.title = bss_info->essid;
			popup_info.ok_cb = hidden_ap_connect_ok_cb;
			popup_info.cancel_cb = hidden_ap_connect_cacel_cb;
			popup_info.show_wps_btn = FALSE;
			popup_info.wps_btn_cb = NULL;
			popup_info.cb_data = hidden_ap_data;
			INFO_LOG(UG_NAME_NORMAL, "Going to create a popup. ug_app_state = 0x%x", ug_app_state);
			ug_app_state->passpopup = common_pswd_popup_create(ug_app_state->win_main, PACKAGE, &popup_info);
			INFO_LOG(UG_NAME_NORMAL, "After create a popup");
			if (ug_app_state->passpopup == NULL) {
				INFO_LOG(UG_NAME_ERR, "pass popup create failed !");
			}
			break;
		default:
			INFO_LOG(UG_NAME_NORMAL, "Unkown security mode: %d", sec_mode);
			break;
		}
	} else if (ap_count == 0) {
		INFO_LOG(UG_NAME_NORMAL, "No AP item with ssid[%s] found", ssid);
		char *disp_msg = g_strdup_printf("Unable to find %s", ssid);
		common_utils_show_info_ok_popup(ug_app_state->win_main, PACKAGE, disp_msg);
		g_free(disp_msg);
	} else {
		INFO_LOG(UG_NAME_NORMAL, "More than one AP items with ssid[%s] found", ssid);
	}

	/* If the hidden AP found on first and second scan OR not found even after first and second scan then delete the popup */
	view_hidden_ap_popup_destroy(ug_app_state->hidden_ap_popup);
	ug_app_state->hidden_ap_popup = NULL;
	return;
}
Exemplo n.º 3
0
static int init(struct sr_output *o)
{
	struct context *ctx;
	struct sr_probe *probe;
	GSList *l;
	GVariant *gvar;
	int num_probes;
	time_t t;

	if (!o)
		return SR_ERR_ARG;

	if (!o->sdi)
		return SR_ERR_ARG;

	ctx = g_try_malloc0(sizeof(struct context));
	o->internal = ctx;

	/* Get the number of probes, and the unitsize. */
	for (l = o->sdi->probes; l; l = l->next) {
		probe = l->data;
		if (probe->type != SR_PROBE_LOGIC)
			continue;
		if (!probe->enabled)
			continue;
		ctx->num_enabled_probes++;
	}

	ctx->unitsize = (ctx->num_enabled_probes + 7) / 8;

	num_probes = g_slist_length(o->sdi->probes);

	if (sr_config_get(o->sdi->driver, o->sdi, NULL, SR_CONF_SAMPLERATE,
			&gvar) == SR_OK) {
		ctx->samplerate = g_variant_get_uint64(gvar);
		g_variant_unref(gvar);
	} else
		ctx->samplerate = 0;

	ctx->separator = ',';
	ctx->header = g_string_sized_new(512);

	t = time(NULL);

	/* Some metadata */
	g_string_append_printf(ctx->header, "; CSV, generated by %s on %s",
			       PACKAGE_STRING, ctime(&t));
	g_string_append_printf(ctx->header, "; Samplerate: %"PRIu64"\n",
			       ctx->samplerate);

	/* Columns / channels */
	g_string_append_printf(ctx->header, "; Channels (%d/%d):",
			       ctx->num_enabled_probes, num_probes);
	for (l = o->sdi->probes; l; l = l->next) {
		probe = l->data;
		if (probe->type != SR_PROBE_LOGIC)
			continue;
		if (!probe->enabled)
			continue;
		g_string_append_printf(ctx->header, " %s,", probe->name);
	}
	if (o->sdi->probes)
		/* Drop last separator. */
		g_string_truncate(ctx->header, ctx->header->len - 1);
	g_string_append_printf(ctx->header, "\n");

	return SR_OK;
}
Exemplo n.º 4
0
static void pk_backend_install_packages_thread(PkBackendJob *job, GVariant *params, gpointer user_data) {
	gchar *dest_dir_name, **pkg_tokens, **pkg_ids;
	guint i;
	gdouble percent_step;
	GSList *repo, *install_list = NULL, *l;
	sqlite3_stmt *pkglist_stmt = NULL, *collection_stmt = NULL;
    PkBitfield transaction_flags = 0;
	PkInfoEnum ret;
	PkBackendKatjaJobData *job_data = pk_backend_job_get_user_data(job);

	g_variant_get(params, "(t^a&s)", &transaction_flags, &pkg_ids);
	pk_backend_job_set_status(job, PK_STATUS_ENUM_DEP_RESOLVE);

	if ((sqlite3_prepare_v2(job_data->db,
							"SELECT summary, cat FROM pkglist NATURAL JOIN repos "
							"WHERE name LIKE @name AND ver LIKE @ver AND arch LIKE @arch AND repo LIKE @repo",
							-1,
							&pkglist_stmt,
							NULL) != SQLITE_OK) ||
		(sqlite3_prepare_v2(job_data->db,
						   "SELECT (c.collection_pkg || ';' || p.ver || ';' || p.arch || ';' || r.repo), p.summary, "
						   "p.full_name, p.ext FROM collections AS c "
						   "JOIN pkglist AS p ON c.collection_pkg = p.name "
						   "JOIN repos AS r ON p.repo_order = r.repo_order "
						   "WHERE c.name LIKE @name AND r.repo LIKE @repo",
						   -1,
						   &collection_stmt,
						   NULL) != SQLITE_OK)) {
		pk_backend_job_error_code(job, PK_ERROR_ENUM_CANNOT_GET_FILELIST, "%s", sqlite3_errmsg(job_data->db));
		goto out;
	}

	for (i = 0; pkg_ids[i]; i++) {
		pkg_tokens = pk_package_id_split(pkg_ids[i]);
		sqlite3_bind_text(pkglist_stmt, 1, pkg_tokens[PK_PACKAGE_ID_NAME], -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(pkglist_stmt, 2, pkg_tokens[PK_PACKAGE_ID_VERSION], -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(pkglist_stmt, 3, pkg_tokens[PK_PACKAGE_ID_ARCH], -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(pkglist_stmt, 4, pkg_tokens[PK_PACKAGE_ID_DATA], -1, SQLITE_TRANSIENT);

		if (sqlite3_step(pkglist_stmt) == SQLITE_ROW) {

			/* If it isn't a collection */
			if (g_strcmp0((gchar *) sqlite3_column_text(pkglist_stmt, 1), "collections")) {
				if (pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) {
					pk_backend_job_package(job, PK_INFO_ENUM_INSTALLING,
										   pkg_ids[i],
										   (gchar *) sqlite3_column_text(pkglist_stmt, 0));
				} else {
					install_list = g_slist_append(install_list, g_strdup(pkg_ids[i]));
				}
			} else {
				sqlite3_bind_text(collection_stmt, 1, pkg_tokens[PK_PACKAGE_ID_NAME], -1, SQLITE_TRANSIENT);
				sqlite3_bind_text(collection_stmt, 2, pkg_tokens[PK_PACKAGE_ID_DATA], -1, SQLITE_TRANSIENT);

				while (sqlite3_step(collection_stmt) == SQLITE_ROW) {
					ret = katja_pkg_is_installed((gchar *) sqlite3_column_text(collection_stmt, 2));
					if ((ret == PK_INFO_ENUM_INSTALLING) || (ret == PK_INFO_ENUM_UPDATING)) {
						if ((pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) &&
							!g_strcmp0((gchar *) sqlite3_column_text(collection_stmt, 3), "obsolete")) {
							/* TODO: Don't just skip obsolete packages but remove them */
						} else if (pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) {
							pk_backend_job_package(job, ret,
												   (gchar *) sqlite3_column_text(collection_stmt, 0),
												   (gchar *) sqlite3_column_text(collection_stmt, 1));
						} else {
							install_list = g_slist_append(install_list,
														  g_strdup((gchar *) sqlite3_column_text(collection_stmt, 0)));
						}
					}
				}

				sqlite3_clear_bindings(collection_stmt);
				sqlite3_reset(collection_stmt);
			}
		}

		sqlite3_clear_bindings(pkglist_stmt);
		sqlite3_reset(pkglist_stmt);
		g_strfreev(pkg_tokens);
	}

	if (install_list && !pk_bitfield_contain(transaction_flags, PK_TRANSACTION_FLAG_ENUM_SIMULATE)) {
		/* / 2 means total percentage for installing and for downloading */
		percent_step = 100.0 / g_slist_length(install_list) / 2;

		/* Download the packages */
		pk_backend_job_set_status(job, PK_STATUS_ENUM_DOWNLOAD);
		dest_dir_name = g_build_filename(LOCALSTATEDIR, "cache", "PackageKit", "downloads", NULL);
		for (l = install_list, i = 0; l; l = g_slist_next(l), i++) {
			pk_backend_job_set_percentage(job, percent_step * i);
			pkg_tokens = pk_package_id_split(l->data);
			repo = g_slist_find_custom(repos, pkg_tokens[PK_PACKAGE_ID_DATA], katja_cmp_repo);

			if (repo)
				katja_pkgtools_download(KATJA_PKGTOOLS(repo->data), job,
										dest_dir_name,
										pkg_tokens[PK_PACKAGE_ID_NAME]);
			g_strfreev(pkg_tokens);
		}
		g_free(dest_dir_name);

		/* Install the packages */
		pk_backend_job_set_status(job, PK_STATUS_ENUM_INSTALL);
		for (l = install_list; l; l = g_slist_next(l), i++) {
			pk_backend_job_set_percentage(job, percent_step * i);
			pkg_tokens = pk_package_id_split(l->data);
			repo = g_slist_find_custom(repos, pkg_tokens[PK_PACKAGE_ID_DATA], katja_cmp_repo);

			if (repo)
				katja_pkgtools_install(KATJA_PKGTOOLS(repo->data), job, pkg_tokens[PK_PACKAGE_ID_NAME]);
			g_strfreev(pkg_tokens);
		}
	}
	g_slist_free_full(install_list, g_free);

out:
	sqlite3_finalize(pkglist_stmt);
	sqlite3_finalize(collection_stmt);

	pk_backend_job_finished (job);
}
Exemplo n.º 5
0
/**
 * 填充群组数据(grpinf)到数据集(model)指定位置(iter).
 * @param model model
 * @param iter iter
 * @param grpinf class GroupInfo
 */
void palTreeModelFillFromGroupInfo(GtkTreeModel *model,
                                   GtkTreeIter *iter,
                                   const GroupInfo *grpinf,
                                   const char* font) {
  GtkIconTheme *theme;
  GdkPixbuf *cpixbuf, *opixbuf= nullptr;
  PangoAttrList *attrs;
  PangoAttribute *attr;
  gchar *info, *extra;
  PalInfo *pal;
  GError* error = nullptr;

  /* 创建图标 */
  theme = gtk_icon_theme_get_default();
  if (grpinf->type == GROUP_BELONG_TYPE_REGULAR) {
    pal = static_cast<PalInfo *>(grpinf->member->data);
    auto file = iptux_erase_filename_suffix(pal->iconfile);
    cpixbuf = gtk_icon_theme_load_icon(theme, file, MAX_ICONSIZE,
                                       GtkIconLookupFlags(0), &error);
    if(cpixbuf == nullptr) {
      LOG_WARN("gtk_icon_theme_load_icon failed: [%d] %s", error->code, error->message);
      g_error_free(error);
      error = nullptr;
    } else {
      opixbuf = GDK_PIXBUF(g_object_ref(cpixbuf));
    }
    g_free(file);
  } else {
    cpixbuf = gtk_icon_theme_load_icon(theme, "tip-hide", MAX_ICONSIZE,
                                       GtkIconLookupFlags(0), NULL);
    opixbuf = gtk_icon_theme_load_icon(theme, "tip-show", MAX_ICONSIZE,
                                       GtkIconLookupFlags(0), NULL);
  }

  /* 创建主信息 */
  if (grpinf->type == GROUP_BELONG_TYPE_REGULAR) {
    char ipstr[INET_ADDRSTRLEN];
    pal = static_cast<PalInfo *>(grpinf->member->data);
    inet_ntop(AF_INET, &pal->ipv4, ipstr, INET_ADDRSTRLEN);
    info = g_strdup_printf("%s\n%s", pal->name, ipstr);
  } else
    info = g_strdup(grpinf->name);

  /* 创建扩展信息 */
  if (grpinf->type == GROUP_BELONG_TYPE_REGULAR)
    extra = NULL;
  else
    extra = g_strdup_printf("(%u)", g_slist_length(grpinf->member));

  /* 创建字体风格 */
  attrs = pango_attr_list_new();
  if (grpinf->type == GROUP_BELONG_TYPE_REGULAR) {
    auto dspt = pango_font_description_from_string(font);
    attr = pango_attr_font_desc_new(dspt);
    pango_attr_list_insert(attrs, attr);
    pango_font_description_free(dspt);
  } else {
    attr = pango_attr_size_new(8192);
    pango_attr_list_insert(attrs, attr);
    attr = pango_attr_style_new(PANGO_STYLE_ITALIC);
    pango_attr_list_insert(attrs, attr);
    attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
    pango_attr_list_insert(attrs, attr);
  }

  /* 设置相应的数据 */
  gtk_tree_store_set(GTK_TREE_STORE(model), iter,
                     PalTreeModelColumn ::CLOSED_EXPANDER, cpixbuf,
                     PalTreeModelColumn ::OPEN_EXPANDER, opixbuf,
                     PalTreeModelColumn ::INFO, info,
                     PalTreeModelColumn ::EXTRAS, extra,
                     PalTreeModelColumn ::STYLE, attrs,
                     PalTreeModelColumn ::COLOR, &color,
                     PalTreeModelColumn ::DATA, grpinf,
                     -1);

  /* 释放资源 */
  if (cpixbuf) g_object_unref(cpixbuf);
  if (opixbuf) g_object_unref(opixbuf);
  g_free(info);
  g_free(extra);
  pango_attr_list_unref(attrs);
}
Exemplo n.º 6
0
int TestRunner::windowCount()
{
    // +1 -> including the main view
    return g_slist_length(webViewList) + 1;
}
void process_incoming_invite(struct sipe_core_private *sipe_private,
			     struct sipmsg *msg)
{
	gchar *newTag;
	const gchar *oldHeader;
	gchar *newHeader;
	gboolean is_multiparty = FALSE;
	gboolean was_multiparty = TRUE;
	gboolean just_joined = FALSE;
	gchar *from;
	const gchar *callid         = sipmsg_find_header(msg, "Call-ID");
	const gchar *roster_manager = sipmsg_find_header(msg, "Roster-Manager");
	const gchar *end_points_hdr = sipmsg_find_header(msg, "EndPoints");
	const gchar *trig_invite    = sipmsg_find_header(msg, "TriggeredInvite");
	const gchar *content_type   = sipmsg_find_header(msg, "Content-Type");
	const gchar *subject        = sipmsg_find_header(msg, "Subject");
	GSList *end_points = NULL;
	struct sip_session *session;
	struct sip_dialog *dialog;
	const gchar *ms_text_format;
	gboolean dont_delay = FALSE;

#ifdef HAVE_VV
	if (g_str_has_prefix(content_type, "multipart/alternative")) {
		sipe_mime_parts_foreach(content_type, msg->body, sipe_invite_mime_cb, msg);
		/* Reload Content-Type to get type of the selected message part */
		content_type = sipmsg_find_header(msg, "Content-Type");
	}
#endif

	if (g_str_has_prefix(content_type, "multipart/mixed")) {
		sipe_mime_parts_foreach(content_type, msg->body, sipe_invite_mime_mixed_cb, msg);
		/* Reload Content-Type to get type of the selected message part */
		content_type = sipmsg_find_header(msg, "Content-Type");
	}

	/* Lync 2010 file transfer */
	if (g_str_has_prefix(content_type, "application/ms-filetransfer+xml")) {
		sip_transport_response(sipe_private, msg, 488, "Not Acceptable Here", NULL);
		return;
	}

	/* Invitation to join conference */
	if (g_str_has_prefix(content_type, "application/ms-conf-invite+xml")) {
		process_incoming_invite_conf(sipe_private, msg);
		return;
	}

#ifdef HAVE_VV
	/* Invitation to audio call */
	if (msg->body && strstr(msg->body, "m=audio")) {
		process_incoming_invite_call(sipe_private, msg);
		return;
	}
#endif

	/* Only accept text invitations */
	if (msg->body && !(strstr(msg->body, "m=message") || strstr(msg->body, "m=x-ms-message"))) {
		sip_transport_response(sipe_private, msg, 501, "Not implemented", NULL);
		return;
	}

	// TODO There *must* be a better way to clean up the To header to add a tag...
	SIPE_DEBUG_INFO_NOFORMAT("Adding a Tag to the To Header on Invite Request...");
	oldHeader = sipmsg_find_header(msg, "To");
	newTag = gentag();
	newHeader = g_strdup_printf("%s;tag=%s", oldHeader, newTag);
	g_free(newTag);
	sipmsg_remove_header_now(msg, "To");
	sipmsg_add_header_now(msg, "To", newHeader);
	g_free(newHeader);

	if (end_points_hdr) {
		end_points = sipmsg_parse_endpoints_header(end_points_hdr);

		if (g_slist_length(end_points) > 2) {
			is_multiparty = TRUE;
		}
	}
	if (trig_invite && !g_ascii_strcasecmp(trig_invite, "TRUE")) {
		is_multiparty = TRUE;
	}

	/* Multiparty session */
	session = sipe_session_find_chat_by_callid(sipe_private, callid);
	if (is_multiparty) {

		if (session) {
			if (session->chat_session) {
				/* Update roster manager for existing multiparty session */
				if (roster_manager)
					sipe_chat_set_roster_manager(session, roster_manager);

			} else {
				gchar *chat_title = sipe_chat_get_name();

				/* Convert IM session to multiparty session */
				g_free(session->with);
				session->with = NULL;
				was_multiparty = FALSE;
				session->chat_session = sipe_chat_create_session(SIPE_CHAT_TYPE_MULTIPARTY,
										 roster_manager,
										 chat_title);

				g_free(chat_title);
			}
		} else {
			/* New multiparty session */
			session = sipe_session_add_chat(sipe_private,
							NULL,
							TRUE,
							roster_manager);
		}

		/* Create chat */
		if (!session->chat_session->backend) {
			gchar *self = sip_uri_self(sipe_private);
			session->chat_session->backend = sipe_backend_chat_create(SIPE_CORE_PUBLIC,
										  session->chat_session,
										  session->chat_session->title,
										  self);
			g_free(self);
		}
	}

	/* IM session */
	from = parse_from(sipmsg_find_header(msg, "From"));
	if (!session)
		session = sipe_session_find_or_add_im(sipe_private, from);

	/* session is now initialized */
	g_free(session->callid);
	session->callid = g_strdup(callid);

	if (is_multiparty && end_points) {
		gchar *to = parse_from(sipmsg_find_header(msg, "To"));
		GSList *entry = end_points;
		while (entry) {
			struct sipendpoint *end_point = entry->data;
			entry = entry->next;

			if (!g_ascii_strcasecmp(from, end_point->contact) ||
			    !g_ascii_strcasecmp(to,   end_point->contact))
				continue;

			dialog = sipe_dialog_find(session, end_point->contact);
			if (dialog) {
				g_free(dialog->theirepid);
				dialog->theirepid = end_point->epid;
				end_point->epid = NULL;
			} else {
				dialog = sipe_dialog_add(session);

				dialog->callid = g_strdup(session->callid);
				dialog->with = end_point->contact;
				end_point->contact = NULL;
				dialog->theirepid = end_point->epid;
				end_point->epid = NULL;

				just_joined = TRUE;

				/* send triggered INVITE */
				sipe_im_invite(sipe_private, session, dialog->with, NULL, NULL, NULL, TRUE);
			}
		}
		g_free(to);
	}

	if (end_points) {
		GSList *entry = end_points;
		while (entry) {
			struct sipendpoint *end_point = entry->data;
			entry = entry->next;
			g_free(end_point->contact);
			g_free(end_point->epid);
			g_free(end_point);
		}
		g_slist_free(end_points);
	}

	dialog = sipe_dialog_find(session, from);
	if (dialog) {
		sipe_im_cancel_dangling(sipe_private, session, dialog, from,
					sipe_im_reenqueue_unconfirmed);
		/* dialog is no longer valid */
	} else {
		just_joined = TRUE;
	}

	dialog = sipe_dialog_add(session);
	dialog->with = g_strdup(from);
	dialog->callid = g_strdup(session->callid);
	dialog->is_established = TRUE;
	sipe_dialog_parse(dialog, msg, FALSE);

	if (is_multiparty && !was_multiparty) {
		/* add current IM counterparty to chat */
		sipe_backend_chat_add(session->chat_session->backend,
				      sipe_dialog_first(session)->with,
				      FALSE);
	}

	/* add inviting party to chat */
	if (just_joined && session->chat_session) {
		sipe_backend_chat_add(session->chat_session->backend,
				      from,
				      TRUE);
	}

	if (!is_multiparty && subject)
		sipe_im_topic(sipe_private, session, subject);

	/* ms-text-format: text/plain; charset=UTF-8;msgr=WAAtAE0...DIADQAKAA0ACgA;ms-body=SGk= */

	/* This used only in 2005 official client, not 2007 or Reuters.
	   Disabled for most cases as interfering with audit of messages which only is applied to regular MESSAGEs.
	   Only enabled for 2005 multiparty chats as otherwise the first message got lost completely.
	*/
	/* also enabled for 2005 file transfer. Didn't work otherwise. */
	ms_text_format = sipmsg_find_header(msg, "ms-text-format");
	if (is_multiparty ||
	    (ms_text_format && g_str_has_prefix(ms_text_format, "text/x-msmsgsinvite")) )
	{
		if (ms_text_format) {
			if (g_str_has_prefix(ms_text_format, "text/x-msmsgsinvite"))
			{
				dont_delay = TRUE;
			}
			else if (g_str_has_prefix(ms_text_format, "text/plain") || g_str_has_prefix(ms_text_format, "text/html"))
			{
				/* please do not optimize logic inside as this code may be re-enabled for other cases */
				gchar *html = get_html_message(ms_text_format, NULL);
				if (html) {
					if (is_multiparty) {
						sipe_backend_chat_message(SIPE_CORE_PUBLIC,
									  session->chat_session->backend,
									  from,
									  0,
									  html);
					} else {
						sipe_backend_im_message(SIPE_CORE_PUBLIC,
									from,
									html);
					}
					g_free(html);
					sipmsg_add_header(msg, "Supported", "ms-text-format"); /* accepts received message */
					dont_delay = TRUE;
				}
			}
		}
	}

	g_free(from);

	sipmsg_add_header(msg, "Supported", "com.microsoft.rtc-multiparty");

	if (dont_delay || !SIPE_CORE_PRIVATE_FLAG_IS(MPOP)) {
		send_invite_response(sipe_private, msg);
	} else {
		delayed_invite_response(sipe_private, msg, session->callid);
	}
}
Exemplo n.º 8
0
/** the cairo people say that we shouldn't do this - oh well */
cairo_path_t *
asCCairoPath(USER_OBJECT_ s_path)
{
	cairo_path_t *path;
	cairo_path_data_t *element;
	GSList *data = NULL, *cur;
	gint i,j;
	
	/* init path structure */
	path = (cairo_path_t*)R_alloc(1, sizeof(cairo_path_t));
	
	/* set status code */
	path->status = CAIRO_STATUS_SUCCESS;
	
	/* for each path element, create points according to type and store in list */
	for (i = 0; i < GET_LENGTH(s_path); i++) {
		USER_OBJECT_ s_element = VECTOR_ELT(s_path, i);
		int points = 0, len;
		cairo_path_data_type_t type = asCInteger(getAttrib(s_element, install("type")));
		/* how many points do we need for this type of element? */
		switch(type) {
			case CAIRO_PATH_MOVE_TO:
			case CAIRO_PATH_LINE_TO:
				points = 1;
			break;
			case CAIRO_PATH_CURVE_TO:
				points = 3;
			break;
			case CAIRO_PATH_CLOSE_PATH:
				points = 0;
			break;
			default:
				PROBLEM "Converting Cairo path: did not understand type %d", type
				ERROR;
		}
		len = points + 1; /* have to include header */
		element = (cairo_path_data_t*)R_alloc(len, sizeof(cairo_path_data_t));
		/* define header element */
		element[0].header.type = type;
		element[0].header.length = len;
		data = g_slist_append(data, &element[0]); /* add header to list */
		for (j = 1; j < len; j++) { /* define points */
			element[j].point.x = INTEGER_DATA(s_element)[2*j];
			element[j].point.y = INTEGER_DATA(s_element)[2*j+1];
			data = g_slist_append(data, &element[j]); /* add point to list */
		}
	}
	
	/* initialize the path's data array */
	path->num_data = g_slist_length(data);
	path->data = (cairo_path_data_t*)R_alloc(path->num_data, sizeof(cairo_path_data_t));
	
	/* copy list into array */
	cur = data;
	for(i = 0; i < path->num_data; i++) {
		path->data[i] = ((cairo_path_data_t*)cur->data)[0];
		cur = g_slist_next(cur);
	}

	return(path);	
}
Exemplo n.º 9
0
const gchar* archive_create(const char* archive_name, GSList* files,
			COMPRESS_METHOD method, ARCHIVE_FORMAT format) {
	struct archive* arch;
	struct archive_entry* entry;
	char* buf = NULL;
	ssize_t len;
	int fd;
	struct stat st;
	struct file_info* file;
	gchar* filename = NULL;
	gchar* msg = NULL;

#ifndef _TEST
	gint num = 0;
	gint total = g_slist_length (files);
#endif

	g_return_val_if_fail(files != NULL, "No files for archiving");

	debug_print("File: %s\n", archive_name);
	arch = archive_write_new();
	switch (method) {
		case ZIP:
			if (archive_write_set_compression_gzip(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
		case BZIP2:
			if (archive_write_set_compression_bzip2(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
#if NEW_ARCHIVE_API
		case COMPRESS:
			if (archive_write_set_compression_compress(arch) != ARCHIVE_OK)
    			        return archive_error_string(arch);
			break;
#endif
		case NO_COMPRESS:
			if (archive_write_set_compression_none(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
	}
	switch (format) {
		case TAR:
			if (archive_write_set_format_ustar(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
		case SHAR:
			if (archive_write_set_format_shar(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
		case PAX:
			if (archive_write_set_format_pax(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
		case CPIO:
			if (archive_write_set_format_cpio(arch) != ARCHIVE_OK)
				return archive_error_string(arch);
			break;
		case NO_FORMAT:
			return "Missing archive format";
	}
	if (archive_write_open_file(arch, archive_name) != ARCHIVE_OK)
		return archive_error_string(arch);

	while (files && ! stop_action) {
#ifndef _TEST
		set_progress_print_all(num++, total, 30);
#endif
		file = (struct file_info *) files->data;
		if (!file)
			continue;
		filename = get_full_path(file);
		/* libarchive will crash if instructed to add archive to it self */
		if (g_utf8_collate(archive_name, filename) == 0) {
			buf = NULL;
			buf = g_strdup_printf(
						"%s: Not dumping to %s", archive_name, filename);
			g_warning("%s\n", buf);
#ifndef _TEST
			debug_print("%s\n", buf);
#endif
			g_free(buf);
		}
		else {
#ifndef _TEST
			debug_print("Adding: %s\n", filename);
			msg = g_strdup_printf("%s", filename);
			set_progress_file_label(msg);
			g_free(msg);
#endif
			entry = archive_entry_new();
			lstat(filename, &st);
			if ((fd = open(filename, O_RDONLY)) == -1) {
				perror("open file");
			}
			else {
				archive_entry_copy_stat(entry, &st);
				archive_entry_set_pathname(entry, filename);
				if (S_ISLNK(st.st_mode)) {
					buf = NULL;
					buf = malloc(PATH_MAX + 1);
					if ((len = readlink(filename, buf, PATH_MAX)) < 0)
						perror("error in readlink");
					else
						buf[len] = '\0';
					archive_entry_set_symlink(entry, buf);
					g_free(buf);
					archive_entry_set_size(entry, 0);
					archive_write_header(arch, entry);
				}
				else {
					if (archive_write_header(arch, entry) != ARCHIVE_OK)
						g_warning("%s", archive_error_string(arch));
					buf = NULL;
					buf = malloc(READ_BLOCK_SIZE);
					len = read(fd, buf, READ_BLOCK_SIZE);
					while (len > 0) {
						if (archive_write_data(arch, buf, len) == -1)
							g_warning("%s", archive_error_string(arch));
						memset(buf, 0, READ_BLOCK_SIZE);
						len = read(fd, buf, READ_BLOCK_SIZE);
					}
					g_free(buf);
				}
				close(fd);
				archive_entry_free(entry);
			}
		}
		g_free(filename);
		files = g_slist_next(files);
	}
#ifndef _TEST
	if (stop_action)
		unlink(archive_name);
	stop_action = FALSE;
#endif
	archive_write_close(arch);
	archive_write_finish(arch);
	return NULL;
}
Exemplo n.º 10
0
void
parse_args( int argc, char** argv )
{
	int i;
	GSList* alist;
	GSList* ap;
	int n;

	alist = 0;
	for( i = 1; i < argc; i++ )
		if(      !strcmp(argv[i], "-h") || !strcmp(argv[i], "--help") )
		{
			printf("%s", usage);
			exit(0);
		}
		else if( !strcmp(argv[i], "-v") || !strcmp(argv[i], "--version") )
		{
			printf(KPABE_VERSION, "-enc");
			exit(0);
		}
		else if( !strcmp(argv[i], "-k") || !strcmp(argv[i], "--keep-input-file") )
		{
			keep = 1;
		}
		else if( !strcmp(argv[i], "-o") || !strcmp(argv[i], "--output") )
		{
			if( ++i >= argc )
				die(usage);
			else
				out_file = argv[i];
		}
		else if( !strcmp(argv[i], "-d") || !strcmp(argv[i], "--deterministic") )
		{
			pbc_random_set_deterministic(0);
		}
		else if( !pub_file )
		{
			pub_file = argv[i];
		}
		else if( !in_file )
		{
			in_file = argv[i];
		}
		else
		{
			parse_attribute(&alist, argv[i]);
		}

	if( !pub_file || !in_file || !alist )
		die(usage);

	if( !out_file )
		out_file = g_strdup_printf("%s.kpabe", in_file);

	alist = g_slist_sort(alist, comp_string);
	n = g_slist_length(alist);

	attrs = malloc((n + 1) * sizeof(char*));

	i = 0;
	for( ap = alist; ap; ap = ap->next )
		attrs[i++] = ap->data;
	attrs[i] = 0;
}
Exemplo n.º 11
0
static gint
evil_timeout (gpointer data)
{
  int i;
  int n_windows;
  int len;
  int create_count;
  int destroy_count;
  
  len = g_slist_length (evil_windows);  
  
  if (len > 35)
    {
      create_count = 2;
      destroy_count = 5;
    }
  else
    {
      create_count = 5;
      destroy_count = 5;
    }

  /* Create some windows */
  n_windows = g_random_int_range (0, create_count);
  
  i = 0;
  while (i < n_windows)
    {
      GtkWidget *w;
      GtkWidget *c;
      int t;
      GtkWidget *parent;
      
      w = gtk_window_new (GTK_WINDOW_TOPLEVEL);

      gtk_window_move (GTK_WINDOW (w),
                       g_random_int_range (0,
                                           gdk_screen_width ()),
                       g_random_int_range (0,
                                           gdk_screen_height ()));

      parent = NULL;
      
      /* set transient for random window (may create all kinds of weird cycles) */
      if (len > 0)
        {
          t = g_random_int_range (- (len / 3), len);
          if (t >= 0)
            {
              parent = g_slist_nth_data (evil_windows, t);
              
              if (parent != NULL)
                gtk_window_set_transient_for (GTK_WINDOW (w), GTK_WINDOW (parent));
            }
        }
      
      if (parent != NULL)
        c = gtk_button_new_with_label ("Evil Transient!");
      else
        c = gtk_button_new_with_label ("Evil Window!");
      gtk_container_add (GTK_CONTAINER (w), c);
      
      gtk_widget_show_all (w);
      
      evil_windows = g_slist_prepend (evil_windows, w);
      
      ++i;
    }

  /* Destroy some windows */
  if (len > destroy_count)
    {
      n_windows = g_random_int_range (0, destroy_count);
      i = 0;
      while (i < n_windows)
        {
          GtkWidget *w;
          
          w = g_slist_nth_data (evil_windows,
                                g_random_int_range (0, len));
          if (w)
            {
              --len;
              evil_windows = g_slist_remove (evil_windows, w);
              gtk_widget_destroy (w);
            }
          
          ++i;
        }
    }
  
  return TRUE;
}
Exemplo n.º 12
0
gboolean
kms_sdp_message_context_has_groups (SdpMessageContext * ctx)
{
  return g_slist_length (ctx->groups) > 0;
}
Exemplo n.º 13
0
void command_main_loop(int argc, char **argv)
{
gint n, status, num_tokens;
gchar *inp, *out, *ext, *tmp, *line, *base, **buff;
gboolean exit=FALSE;
GSList *list, *files, *item, *structures;
struct file_pak *inp_pak, *out_pak;
struct model_pak *model;

if (argc < 2)
  printf("gdis> Commandline interface. Enter ? for help.\n");

/* command line */
do
  {
/* if additional keywords - process as single command line */
  if (argc > 1)
    {
/* convert options into single string for processing */
    buff = g_malloc(argc*sizeof(gchar *));
    for (n=1 ; n<argc ; n++)
      *(buff+n-1) = g_strdup(argv[n]);
    *(buff+argc-1) = NULL;
    line = g_strjoinv(" ", buff);
    g_strfreev(buff);
    exit = TRUE;
    }
  else
    {
/* standard repeating prompt */
    printf("gdis> ");
    line = file_read_line(stdin);
    }

/* quit primitive */
  if (g_ascii_strncasecmp("qu", line, 2) == 0 ||
      g_ascii_strncasecmp("ex", line, 2) == 0)
    exit=TRUE;

/* test primitive */
  if (g_ascii_strncasecmp("te", line, 2) == 0)
    {
    buff = tokenize(line, &num_tokens);
    for (n=1 ; n<num_tokens ; n++)
      test_run(*(buff+n));
    g_strfreev(buff);
    }

/* copy primitive */
  if (g_ascii_strncasecmp("co", line, 2) == 0 || g_ascii_strncasecmp("cp", line, 2) == 0)
    {
    buff = tokenize(line, &num_tokens);

    if (num_tokens > 2)
      {

      out_pak = get_file_info(*(buff+2), BY_EXTENSION);
      if (!out_pak)
        {
        printf("Error: unrecognized output filetype.\n");
        break;
        }
      if (!out_pak->write_file)
        {
        printf("Error: write method for this filetype does not exist.\n");
        break;
        }

/* FIXME! - this is all wrong - should be no dependence on sysenv.cwd for path */
/* since this falls over with something like prompt:>gdis cp /tmp/gok.sot /tmp/dest/gok.meta */
      ext = file_extension_get(*(buff+2));
      files = file_dir_list_pattern(sysenv.cwd, *(buff+1));
      for (list=files ; list ; list=g_slist_next(list))
        {
        inp_pak = get_file_info(list->data, BY_EXTENSION);

        inp = g_build_filename(sysenv.cwd, list->data, NULL);

/* FIXME - changed to correct a problem with Florian's metadata store */
//        base = parse_strip(list->data);
        base = g_strdup(list->data);

        if (inp_pak)
          {
          if (inp_pak->read_file)
            {
            model = model_new();

            status = inp_pak->read_file(inp, model);

            structures = g_slist_find(sysenv.mal, model);

#if DEBUG_COMMAND_MAIN_LOOP
printf("Items loaded = %d [status = %d]\n", g_slist_length(structures), status);
#endif

            if (g_slist_length(structures) > 1)
              {
/* multiple output for input files that contain more than one structure */
              n = 1;
              for (item=structures ; item ; item=g_slist_next(item))
                {
                model = item->data;

                tmp = g_strdup_printf("%s_%d.%s", base, n, ext);
                out = g_build_filename(sysenv.cwd, tmp, NULL);

                status = out_pak->write_file(out, model);

#if DEBUG_COMMAND_MAIN_LOOP
printf("a [%s] -> [%s]\n", inp, out);
#endif
                g_free(out);
                g_free(tmp);
                model_free(model);
                n++;
                }
              }
            else
              {
              tmp = g_strdup_printf("%s.%s", base, ext);

              out = g_build_filename(sysenv.cwd, tmp, NULL);
              g_free(tmp);

              status = out_pak->write_file(out, model);

#if DEBUG_COMMAND_MAIN_LOOP
printf("b [%s] -> [%s]\n", inp, out);
#endif
              g_free(out);
              model_free(model);
              }
            }
          else
            printf("Error: read method for this filetype does not exist.\n");
          }
        else
          {
          printf("Error: unrecognized input filetype.\n");
          }
        g_free(base);
        g_free(inp);
        }


/* CURRENT hack */
if (!files)
  {
/* FIXME */

  }




      g_free(ext);

      free_slist(files);
      }
    else
      printf("Error: insufficient tokens for <copy> command\n");

    g_strfreev(buff);
    }

  if (g_ascii_strncasecmp("ls", line, 2) == 0)
    {
    buff = tokenize(line, &num_tokens);

    if (num_tokens > 1)
      files = file_dir_list_pattern(sysenv.cwd, *(buff+1));
    else
      files = file_dir_list(sysenv.cwd, FALSE);

    for (list=files ; list ; list=g_slist_next(list))
      {
      printf("%s\n", (gchar *) list->data);
      }

    g_strfreev(buff);
    }

  if (g_ascii_strncasecmp("cd", line, 2) == 0)
    {
    buff = tokenize(line, &num_tokens);

    if (num_tokens > 1)
      {
      inp = g_build_path(DIR_SEP, sysenv.cwd, *(buff+1), NULL);
      set_path(inp);
      g_free(inp);
      }

    printf("%s\n", sysenv.cwd);

    g_strfreev(buff);
    }

  if (g_ascii_strncasecmp("pwd", line, 3) == 0)
    {
    printf("%s\n", sysenv.cwd);
    }

  if (g_ascii_strncasecmp("?", line, 1) == 0 || g_ascii_strncasecmp("h", line, 1) == 0)
    {
    printf("GDIS v%4.2f available commands\n\n", VERSION);

    printf("cd <destination>\n");
    printf("    - changes to target directory\n");

    printf("pwd\n");
    printf("    - prints the current working directory\n");

    printf("ls\n");
    printf("    - lists the files in the current working directory\n");

    printf("copy <source> <destination>\n");
    printf("    - convert between filetypes, based on extension (wildcards allowed)\n");
    printf("quit\n");
    printf("    - exit program\n");
    }

/* done -> next line */
  g_free(line);
  }
while (!exit);
}
Exemplo n.º 14
0
void fpi_imgdev_image_captured(struct fp_img_dev *imgdev, struct fp_img *img)
{
	struct fp_print_data *print;
	int r;
	fp_dbg("");

	if (imgdev->action_state != IMG_ACQUIRE_STATE_AWAIT_IMAGE) {
		fp_dbg("ignoring due to current state %d", imgdev->action_state);
		return;
	}

	if (imgdev->action_result) {
		fp_dbg("not overwriting existing action result");
		return;
	}

	r = sanitize_image(imgdev, &img);
	if (r < 0) {
		imgdev->action_result = r;
		fp_img_free(img);
		goto next_state;
	}

	fp_img_standardize(img);
	imgdev->acquire_img = img;
	if (imgdev->action != IMG_ACTION_CAPTURE) {
		r = fpi_img_to_print_data(imgdev, img, &print);
		if (r < 0) {
			fp_dbg("image to print data conversion error: %d", r);
			imgdev->action_result = FP_ENROLL_RETRY;
			goto next_state;
		} else if (img->minutiae->num < MIN_ACCEPTABLE_MINUTIAE) {
			fp_dbg("not enough minutiae, %d/%d", img->minutiae->num,
				MIN_ACCEPTABLE_MINUTIAE);
			fp_print_data_free(print);
			/* depends on FP_ENROLL_RETRY == FP_VERIFY_RETRY */
			imgdev->action_result = FP_ENROLL_RETRY;
			goto next_state;
		}
	}

	imgdev->acquire_data = print;
	switch (imgdev->action) {
	case IMG_ACTION_ENROLL:
		if (!imgdev->enroll_data) {
			imgdev->enroll_data = fpi_print_data_new(imgdev->dev);
		}
		BUG_ON(g_slist_length(print->prints) != 1);
		/* Move print data from acquire data into enroll_data */
		imgdev->enroll_data->prints =
			g_slist_prepend(imgdev->enroll_data->prints, print->prints->data);
		print->prints = g_slist_remove(print->prints, print->prints->data);

		fp_print_data_free(imgdev->acquire_data);
		imgdev->acquire_data = NULL;
		imgdev->enroll_stage++;
		if (imgdev->enroll_stage == imgdev->dev->nr_enroll_stages)
			imgdev->action_result = FP_ENROLL_COMPLETE;
		else
			imgdev->action_result = FP_ENROLL_PASS;
		break;
	case IMG_ACTION_VERIFY:
		verify_process_img(imgdev);
		break;
	case IMG_ACTION_IDENTIFY:
		identify_process_img(imgdev);
		break;
	case IMG_ACTION_CAPTURE:
		imgdev->action_result = FP_CAPTURE_COMPLETE;
		break;
	default:
		BUG();
		break;
	}

next_state:
	imgdev->action_state = IMG_ACQUIRE_STATE_AWAIT_FINGER_OFF;
	dev_change_state(imgdev, IMGDEV_STATE_AWAIT_FINGER_OFF);
}
Exemplo n.º 15
0
bool window_has_accel(GtkWindow* toplevel)
{
  return g_slist_length(gtk_accel_groups_from_object(G_OBJECT(toplevel))) != 0;
}
Exemplo n.º 16
0
static GError*
_cache_load_from_ns(struct meta1_prefixes_set_s *m1ps, const gchar *ns_name,
		const gchar *local_url, GArray **updated_prefixes, gboolean *meta0_ok)
{
	struct addr_info_s local_ai;
	GError *err = NULL;
	GSList *l, *m0_list = NULL;
	guint idx = rand();
	gboolean done = FALSE;

	EXTRA_ASSERT(m1ps != NULL);

	if (!ns_name || !local_url) {
		GRID_TRACE("META1 prefix set not configured to be reloaded from a namespace");
		return NULL;
	}

	memset(&local_ai, 0, sizeof(local_ai));
	grid_string_to_addrinfo(local_url, &local_ai);

	/* Get the META0 address */
	err = conscience_get_services (ns_name, NAME_SRVTYPE_META0, FALSE, &m0_list);
	if (err != NULL) {
		g_prefix_error(&err, "META0 locate error : ");
		return err;
	}

	if (!m0_list)
		return NEWERROR(0, "No META0 available in the namespace");;

	/* Get the prefixes list */
	guint max = g_slist_length(m0_list);
	guint nb_retry = 0;
	while (nb_retry < max) {
		struct service_info_s *si;

		l = g_slist_nth(m0_list, idx%max);
		if (!(si = l->data)) {
			nb_retry++;
			idx++;
			continue;
		}

		err = _cache_load_from_m0(m1ps, ns_name, &local_ai,
				&(si->addr), updated_prefixes, meta0_ok);
		if (!err) {
			done = TRUE;
			break;
		}

		GRID_WARN("M0 cache loading error : (%d) %s", err->code, err->message);
		if (!CODE_IS_NETWORK_ERROR(err->code))
			break;

		g_clear_error(&err);
		nb_retry++;
		idx++;
	}

	g_slist_foreach(m0_list, service_info_gclean, NULL);
	g_slist_free(m0_list);
	if (!err && !done)
		err = NEWERROR(0, "No META0 replied");
	return err;
}
Exemplo n.º 17
0
void SludgeProjectManager::on_add_file_clicked()
{
	GtkWidget *dialog;
	GtkFileFilter *filter, *slufilter, *sldfilter, *trafilter;

	dialog = gtk_file_chooser_dialog_new("Add file to SLUDGE project",
				      NULL,
				      GTK_FILE_CHOOSER_ACTION_OPEN,
				      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
				      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
				      NULL);

	filter = gtk_file_filter_new();
	gtk_file_filter_set_name(filter, "SLU/SLD/TRA files");
	gtk_file_filter_add_pattern(filter, "*.[sS][lL][uU]");
	gtk_file_filter_add_pattern(filter, "*.[sS][lL][dD]");
	gtk_file_filter_add_pattern(filter, "*.[tT][rR][aA]");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filter);

	slufilter = gtk_file_filter_new();
	gtk_file_filter_set_name(slufilter, "SLUDGE scripts (*.slu)");
	gtk_file_filter_add_pattern(slufilter, "*.[sS][lL][uU]");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), slufilter);

	sldfilter = gtk_file_filter_new();
	gtk_file_filter_set_name(sldfilter, "SLUDGE constant definition files (*.sld)");
	gtk_file_filter_add_pattern(sldfilter, "*.[sS][lL][dD]");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), sldfilter);

	trafilter = gtk_file_filter_new();
	gtk_file_filter_set_name(trafilter, "SLUDGE translation files (*.tra)");
	gtk_file_filter_add_pattern(trafilter, "*.[tT][rR][aA]");
	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), trafilter);

	gtk_file_chooser_set_filter(GTK_FILE_CHOOSER (dialog), filter);

	gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER (dialog), TRUE);

	if (currentFolder[0] != 0)
	{
		gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER (dialog), currentFolder);
	}

	if (gtk_dialog_run(GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
	{
		GSList *filenames;
		char *filename;
		filenames = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER (dialog));

		for (int j = 0; j < g_slist_length(filenames); j++) {
			filename = (char *) g_slist_nth(filenames, j)->data;
			flipBackslashes(&filename);

			getSourceDirFromName(currentFilename);
			addFileToProject(filename, sourceDirectory, fileList, &fileListNum);
			setFileChanged();
		
			g_free(filename);
		}
		g_slist_free(filenames);
	}
	gtk_widget_destroy(dialog);

	listChanged(FILE_TREEVIEW);
}
int LayoutTestController::windowCount()
{
    // +1 -> including the main view
    return g_slist_length(webViewList) + 1;
}
Exemplo n.º 19
0
void
sp_align_distribute_v_clicked (GtkWidget *widget, const gchar *layout)
{
	SPDesktop *desktop;
	SPSelection *selection;
	const GSList *slist, *l;
	struct _SPBBoxSort *bbs;
	int len, pos;
	unsigned int changed;

	desktop = SP_ACTIVE_DESKTOP;
	if (!desktop) return;

	selection = SP_DT_SELECTION (desktop);
	slist = sp_selection_item_list (selection);
	if (!slist) return;
	if (!slist->next) return;

	len = g_slist_length ((GSList *) slist);
	bbs = g_new (struct _SPBBoxSort, len);
	pos = 0;
	for (l = slist; l != NULL; l = l->next) {
		bbs[pos].item = SP_ITEM (l->data);
		sp_item_bbox_desktop (bbs[pos].item, &bbs[pos].bbox);
		bbs[pos].anchor = 0.5 * layout[0] * bbs[pos].bbox.y0 + 0.5 * layout[1] * bbs[pos].bbox.y1;
		pos += 1;
	}

	qsort (bbs, len, sizeof (struct _SPBBoxSort), sp_align_bbox_sort);

	changed = FALSE;

	if (!layout[2]) {
		float dist, step;
		int i;
		dist = bbs[len - 1].anchor - bbs[0].anchor;
		step = dist / (len - 1);
		for (i = 0; i < len; i++) {
			float pos;
			pos = bbs[0].anchor + i * step;
			if (!NR_DF_TEST_CLOSE (pos, bbs[i].anchor, 1e-6)) {
				sp_item_move_rel (bbs[i].item, 0.0, pos - bbs[i].anchor);
				changed = TRUE;
			}
		}
	} else {
		/* Damn I am not sure, how to order them initially (Lauris) */
		float dist, span, step, pos;
		int i;
		dist = bbs[len - 1].bbox.y1 - bbs[0].bbox.y0;
		span = 0;
		for (i = 0; i < len; i++) span += (bbs[i].bbox.y1 - bbs[i].bbox.y0);
		step = (dist - span) / (len - 1);
		pos = bbs[0].bbox.y0;
		for (i = 0; i < len; i++) {
			if (!NR_DF_TEST_CLOSE (pos, bbs[i].bbox.y0, 1e-6)) {
				sp_item_move_rel (bbs[i].item, 0.0, pos - bbs[i].bbox.y0);
				changed = TRUE;
			}
			pos += (bbs[i].bbox.y1 - bbs[i].bbox.y0);
			pos += step;
		}
	}

	g_free (bbs);

	if (changed) {
		sp_selection_changed (selection);
		sp_document_done (SP_DT_DOCUMENT (desktop));
	}
}
Exemplo n.º 20
0
/**
 * @brief Parse the entity string and resolve all static light sources. Sources which
 * are very close to each other are merged. Their colors are blended according
 * to their light value (intensity).
 */
void R_LoadBspLights(r_bsp_model_t *bsp) {
	vec3_t origin, color;
	vec_t radius;

	memset(&r_bsp_light_state, 0, sizeof(r_bsp_light_state));

	const r_bsp_light_state_t *s = &r_bsp_light_state;

	R_ResolveBspLightParameters();

	// iterate the world surfaces for surface lights
	const r_bsp_surface_t *surf = bsp->surfaces;

	for (uint16_t i = 0; i < bsp->num_surfaces; i++, surf++) {

		// light-emitting surfaces are of course lights
		if ((surf->texinfo->flags & SURF_LIGHT) && surf->texinfo->value) {
			VectorMA(surf->center, 1.0, surf->normal, origin);

			radius = sqrt(surf->texinfo->light * sqrt(surf->area) * BSP_LIGHT_SURFACE_RADIUS_SCALE);

			R_AddBspLight(bsp, origin, surf->texinfo->emissive, radius * s->brightness);
		}
	}
	
	// parse the entity string for point lights
	const char *ents = Cm_EntityString();

	VectorClear(origin);

	radius = BSP_LIGHT_POINT_DEFAULT_RADIUS * s->brightness;
	VectorSet(color, 1.0, 1.0, 1.0);

	char class_name[MAX_QPATH];
	_Bool entity = false, light = false;

	while (true) {

		const char *c = ParseToken(&ents);

		if (!strlen(c)) {
			break;
		}

		if (*c == '{') {
			entity = true;
		}

		if (!entity) { // skip any whitespace between ents
			continue;
		}

		if (*c == '}') {
			entity = false;

			if (light) { // add it
				R_AddBspLight(bsp, origin, color, radius * BSP_LIGHT_POINT_RADIUS_SCALE);

				radius = BSP_LIGHT_POINT_DEFAULT_RADIUS;
				VectorSet(color, 1.0, 1.0, 1.0);

				light = false;
			}
		}

		if (!g_strcmp0(c, "classname")) {

			c = ParseToken(&ents);
			g_strlcpy(class_name, c, sizeof(class_name));

			if (!strncmp(c, "light", 5)) { // light, light_spot, etc..
				light = true;
			}

			continue;
		}

		if (!g_strcmp0(c, "origin")) {
			sscanf(ParseToken(&ents), "%f %f %f", &origin[0], &origin[1], &origin[2]);
			continue;
		}

		if (!g_strcmp0(c, "light")) {
			radius = atof(ParseToken(&ents)) * s->brightness;
			continue;
		}

		if (!g_strcmp0(c, "_color")) {
			sscanf(ParseToken(&ents), "%f %f %f", &color[0], &color[1], &color[2]);
			ColorFilter(color, color, s->brightness, s->saturation, s->contrast);
			continue;
		}
	}

	// allocate the lights array and copy them in
	bsp->num_bsp_lights = g_slist_length(r_bsp_light_state.lights);
	bsp->bsp_lights = Mem_LinkMalloc(sizeof(r_bsp_light_t) * bsp->num_bsp_lights, bsp);

	GSList *e = r_bsp_light_state.lights;
	r_bsp_light_t *bl = bsp->bsp_lights;
	while (e) {
		*bl++ = *((r_bsp_light_t *) e->data);
		e = e->next;
	}

	// reset state
	g_slist_free_full(r_bsp_light_state.lights, Mem_Free);
	r_bsp_light_state.lights = NULL;

	Com_Debug(DEBUG_RENDERER, "Loaded %d bsp lights\n", bsp->num_bsp_lights);
}
Exemplo n.º 21
0
void
sp_selected_path_combine(SPDesktop *desktop)
{
    Inkscape::Selection *selection = sp_desktop_selection(desktop);
    SPDocument *doc = sp_desktop_document(desktop);
    
    if (g_slist_length((GSList *) selection->itemList()) < 1) {
        sp_desktop_message_stack(desktop)->flash(Inkscape::WARNING_MESSAGE, _("Select <b>object(s)</b> to combine."));
        return;
    }

    desktop->messageStack()->flash(Inkscape::IMMEDIATE_MESSAGE, _("Combining paths..."));
    // set "busy" cursor
    desktop->setWaitingCursor();

    GSList *items = g_slist_copy((GSList *) selection->itemList());

    items = sp_degroup_list (items); // descend into any groups in selection

    GSList *to_paths = NULL;
    for (GSList *i = items; i != NULL; i = i->next) {
        SPItem *item = (SPItem *) i->data;
        if (!SP_IS_PATH(item) && !SP_IS_GROUP(item))
            to_paths = g_slist_prepend(to_paths, item);
    }
    GSList *converted = NULL;
    bool did = sp_item_list_to_curves(to_paths, &items, &converted);
    g_slist_free(to_paths);
    for (GSList *i = converted; i != NULL; i = i->next)
        items = g_slist_prepend(items, doc->getObjectByRepr((Inkscape::XML::Node*)(i->data)));

    items = sp_degroup_list (items); // converting to path may have added more groups, descend again

    items = g_slist_sort(items, (GCompareFunc) sp_item_repr_compare_position);
    items = g_slist_reverse(items);

    // remember the position, id, transform and style of the topmost path, they will be assigned to the combined one
    gint position = 0;
    char const *id = NULL;
    char const *transform = NULL;
    gchar *style = NULL;
    gchar *path_effect = NULL;

    SPCurve* curve = 0;
    SPItem *first = NULL;
    Inkscape::XML::Node *parent = NULL; 

    if (did) {
        selection->clear();
    }

    for (GSList *i = items; i != NULL; i = i->next) {  // going from top to bottom

        SPItem *item = (SPItem *) i->data;
        if (!SP_IS_PATH(item))
            continue;

        if (!did) {
            selection->clear();
            did = true;
        }

        SPCurve *c = sp_path_get_curve_for_edit(SP_PATH(item));
        if (first == NULL) {  // this is the topmost path
            first = item;
            parent = SP_OBJECT_REPR(first)->parent();
            position = SP_OBJECT_REPR(first)->position();
            id = SP_OBJECT_REPR(first)->attribute("id");
            transform = SP_OBJECT_REPR(first)->attribute("transform");
            // FIXME: merge styles of combined objects instead of using the first one's style
            style = g_strdup(SP_OBJECT_REPR(first)->attribute("style"));
            path_effect = g_strdup(SP_OBJECT_REPR(first)->attribute("inkscape:path-effect"));
            //c->transform(item->transform);
            curve = c;
        } else {
            c->transform(item->getRelativeTransform(SP_OBJECT(first)));
            curve->append(c, false);
            c->unref();
        }

        // unless this is the topmost object,
        if (item != first) {
            // reduce position only if the same parent
            if (SP_OBJECT_REPR(item)->parent() == parent)
                position--;
            // delete the object for real, so that its clones can take appropriate action
            SP_OBJECT(item)->deleteObject();
        }
    }

    g_slist_free(items);

    if (did) {
        SP_OBJECT(first)->deleteObject(false);
        // delete the topmost.

        Inkscape::XML::Document *xml_doc = sp_document_repr_doc(desktop->doc());
        Inkscape::XML::Node *repr = xml_doc->createElement("svg:path");

        // restore id, transform, path effect, and style
        repr->setAttribute("id", id);
        if (transform) repr->setAttribute("transform", transform);
        repr->setAttribute("style", style);
        g_free(style);

        repr->setAttribute("inkscape:path-effect", path_effect);
        g_free(path_effect);

        // set path data corresponding to new curve
        gchar *dstring = sp_svg_write_path(curve->get_pathvector());
        curve->unref();
        if (path_effect)
            repr->setAttribute("inkscape:original-d", dstring);
        else
            repr->setAttribute("d", dstring);
        g_free(dstring);

        // add the new group to the parent of the topmost
        parent->appendChild(repr);

        // move to the position of the topmost, reduced by the number of deleted items
        repr->setPosition(position > 0 ? position : 0);

        sp_document_done(sp_desktop_document(desktop), SP_VERB_SELECTION_COMBINE, 
                         _("Combine"));

        selection->set(repr);

        Inkscape::GC::release(repr);

    } else {
        sp_desktop_message_stack(desktop)->flash(Inkscape::ERROR_MESSAGE, _("<b>No path(s)</b> to combine in the selection."));
    }

    desktop->clearWaitingCursor();
}
Exemplo n.º 22
0
/* insert_chunk function will recalculate the free_chunk_list, the data_size,
   the end_of_file, and the data_gathered as appropriate.
   It will also insert the data chunk that is coming in the right
   place of the file in memory.
   HINTS:
   file->data_gathered 	contains the real data gathered independently
	 		from the file length
   file->file_length 	contains the length of the file in memory, i.e.,
			the last offset captured. In most cases, the real
			file length would be different.
*/
static void
insert_chunk(active_file   *file, export_object_entry_t *entry, const smb_eo_t *eo_info)
{
        guint           nfreechunks = g_slist_length(file->free_chunk_list);
	guint		i;
        free_chunk      *current_free_chunk;
        free_chunk      *new_free_chunk;
	guint64 	chunk_offset=eo_info->smb_file_offset;
	guint64 	chunk_length=eo_info->payload_len;
        guint64         chunk_end_offset = chunk_offset+chunk_length-1;
	/* Size of file in memory */
        guint64         calculated_size = chunk_offset+chunk_length;
	gpointer	dest_memory_addr;

	/* Let's recalculate the file length and data gathered */
	if (file->data_gathered==0 && nfreechunks==0) {
		/* If this is the first entry for this file, we first
		   create an initial free chunk */
                new_free_chunk=g_malloc(sizeof(free_chunk));
                new_free_chunk->start_offset=0;
		new_free_chunk->end_offset=MAX(file->file_length,chunk_end_offset+1)-1;
		file->free_chunk_list=NULL;
		file->free_chunk_list=g_slist_append(file->free_chunk_list,new_free_chunk);
		nfreechunks+=1;
	} else {
		if (chunk_end_offset > file->file_length-1) {
                	new_free_chunk=g_malloc(sizeof(free_chunk));
                	new_free_chunk->start_offset=file->file_length;
			new_free_chunk->end_offset=chunk_end_offset;
			file->free_chunk_list=g_slist_append(file->free_chunk_list,new_free_chunk);
			nfreechunks+=1;
			}
	}
	file->file_length = MAX(file->file_length,chunk_end_offset+1);

        for (i=0;i<nfreechunks;i++) {
                current_free_chunk = g_slist_nth_data(file->free_chunk_list,i);
                if (chunk_offset <= current_free_chunk->start_offset ) {
                        if (chunk_end_offset >= current_free_chunk->start_offset) {
                                if (chunk_end_offset < current_free_chunk->end_offset) {
                                        file->data_gathered+=
                                                (chunk_end_offset-current_free_chunk->start_offset+1);
                                        current_free_chunk->start_offset=chunk_end_offset+1;
                                } else {
                                        file->data_gathered+=
                                                (current_free_chunk->end_offset-current_free_chunk->start_offset+1);
                                        file->free_chunk_list =
                                                g_slist_remove(file->free_chunk_list,current_free_chunk);
					nfreechunks-=1;
					if (nfreechunks==0) { /* The free chunk list is empty */
						g_slist_free(file->free_chunk_list);
						file->free_chunk_list=NULL;
						break;
					}
                                }
                        } else {
                                break;
                        }
                } else {
			if (chunk_offset <= current_free_chunk->end_offset) {
                                if (chunk_end_offset < current_free_chunk->end_offset) {
                                        new_free_chunk=g_malloc(sizeof(free_chunk));
                                        new_free_chunk->start_offset=chunk_end_offset+1;
                                        new_free_chunk->end_offset=current_free_chunk->end_offset;
                                        current_free_chunk->end_offset=chunk_offset-1;
                                        file->free_chunk_list =
                                                g_slist_insert(file->free_chunk_list,new_free_chunk,i+1);
                                        file->data_gathered+=chunk_length;
                                } else {
                                        file->data_gathered+=current_free_chunk->end_offset-chunk_offset+1;
                                        current_free_chunk->end_offset=chunk_offset-1;
                                }
                        }
                }
        }

	/* Now, let's insert the data chunk into memory
	   ...first, we shall be able to allocate the memory */
	if (!entry->payload_data) {
		/* This is a New file */
		if (calculated_size > G_MAXSIZE) {
			/*
			 * The argument to g_try_malloc() is
			 * a gsize, the maximum value of which is
			 * G_MAXSIZE.  If the calculated size is
			 * bigger than that, we just say the attempt
			 * to allocate memory failed.
			 */
			entry->payload_data=NULL;
		} else {
			entry->payload_data = g_try_malloc((gsize)calculated_size);
			entry->payload_len=calculated_size;
		}
		if (!entry->payload_data) {
			/* Memory error */
			file->is_out_of_memory=TRUE;
		}
	} else {
		/* This is an existing file in memory */
		if (calculated_size > (guint64) entry->payload_len &&
		    !file->is_out_of_memory) {
			/* We need more memory */
			if (calculated_size > G_MAXSIZE) {
				/*
				 * As for g_try_malloc(), so for
				 * g_try_realloc().
				 */
				dest_memory_addr=NULL;
			} else {
				dest_memory_addr=g_try_realloc(
					entry->payload_data,
					(gsize)calculated_size);
			}
			if(!dest_memory_addr) {
				/* Memory error */
				file->is_out_of_memory=TRUE;
				/* We don't have memory for this file.
				   Free the current file content from memory */
				g_free(entry->payload_data);
				entry->payload_data=NULL;
				entry->payload_len=0;
			} else {
				entry->payload_data=dest_memory_addr;
				entry->payload_len=calculated_size;
			}
		}
	}
	/* ...then, put the chunk of the file in the right place */
	if(!file->is_out_of_memory) {
		dest_memory_addr=entry->payload_data+chunk_offset;
		g_memmove(dest_memory_addr,eo_info->payload_data,eo_info->payload_len);
	}
}
Exemplo n.º 23
0
static PyObject *Decoder_register(PyObject *self, PyObject *args,
		PyObject *kwargs)
{
	struct srd_decoder_inst *di;
	struct srd_pd_output *pdo;
	PyObject *py_new_output_id;
	PyTypeObject *meta_type_py;
	const GVariantType *meta_type_gv;
	int output_type;
	char *proto_id, *meta_name, *meta_descr;
	char *keywords[] = {"output_type", "proto_id", "meta", NULL};

	meta_type_py = NULL;
	meta_type_gv = NULL;
	meta_name = meta_descr = NULL;

	if (!(di = srd_inst_find_by_obj(NULL, self))) {
		PyErr_SetString(PyExc_Exception, "decoder instance not found");
		return NULL;
	}

	/* Default to instance id, which defaults to class id. */
	proto_id = di->inst_id;
	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|s(Oss)", keywords,
			&output_type, &proto_id,
			&meta_type_py, &meta_name, &meta_descr)) {
		/* Let Python raise this exception. */
		return NULL;
	}

	/* Check if the meta value's type is supported. */
	if (output_type == SRD_OUTPUT_META) {
		if (meta_type_py == &PyLong_Type)
			meta_type_gv = G_VARIANT_TYPE_INT64;
		else if (meta_type_py == &PyFloat_Type)
			meta_type_gv = G_VARIANT_TYPE_DOUBLE;
		else {
			PyErr_Format(PyExc_TypeError, "Unsupported type.");
			return NULL;
		}
	}

	srd_dbg("Instance %s creating new output type %d for %s.",
		di->inst_id, output_type, proto_id);

	pdo = g_malloc(sizeof(struct srd_pd_output));

	/* pdo_id is just a simple index, nothing is deleted from this list anyway. */
	pdo->pdo_id = g_slist_length(di->pd_output);
	pdo->output_type = output_type;
	pdo->di = di;
	pdo->proto_id = g_strdup(proto_id);

	if (output_type == SRD_OUTPUT_META) {
		pdo->meta_type = meta_type_gv;
		pdo->meta_name = g_strdup(meta_name);
		pdo->meta_descr = g_strdup(meta_descr);
	}

	di->pd_output = g_slist_append(di->pd_output, pdo);
	py_new_output_id = Py_BuildValue("i", pdo->pdo_id);

	return py_new_output_id;
}
Exemplo n.º 24
0
static void
gimp_thumb_box_create_thumbnails (GimpThumbBox *box,
                                  gboolean      force)
{
  Gimp           *gimp     = box->context->gimp;
  GimpProgress   *progress = GIMP_PROGRESS (box);
  GimpFileDialog *dialog   = NULL;
  GtkWidget      *toplevel;
  GSList         *list;
  gint            n_uris;
  gint            i;

  if (gimp->config->thumbnail_size == GIMP_THUMBNAIL_SIZE_NONE)
    return;

  toplevel = gtk_widget_get_toplevel (GTK_WIDGET (box));

  if (GIMP_IS_FILE_DIALOG (toplevel))
    dialog = GIMP_FILE_DIALOG (toplevel);

  gimp_set_busy (gimp);

  if (dialog)
    gimp_file_dialog_set_sensitive (dialog, FALSE);
  else
    gtk_widget_set_sensitive (toplevel, FALSE);

  if (box->uris)
    {
      gtk_widget_hide (box->info);
      gtk_widget_show (box->progress);
    }

  n_uris = g_slist_length (box->uris);

  if (n_uris > 1)
    {
      gchar *str;

      gimp_progress_start (GIMP_PROGRESS (box), "", TRUE);

      progress = gimp_sub_progress_new (GIMP_PROGRESS (box));

      gimp_sub_progress_set_step (GIMP_SUB_PROGRESS (progress), 0, n_uris);

      for (list = box->uris->next, i = 1;
           list;
           list = g_slist_next (list), i++)
        {
          str = g_strdup_printf (_("Thumbnail %d of %d"), i, n_uris);
          gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), str);
          g_free (str);

          gimp_progress_set_value (progress, 0.0);

          while (gtk_events_pending ())
            gtk_main_iteration ();

          gimp_thumb_box_create_thumbnail (box,
                                           list->data,
                                           gimp->config->thumbnail_size,
                                           force,
                                           progress);

          if (dialog && dialog->canceled)
            goto canceled;

          gimp_sub_progress_set_step (GIMP_SUB_PROGRESS (progress), i, n_uris);
        }

      str = g_strdup_printf (_("Thumbnail %d of %d"), n_uris, n_uris);
      gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), str);
      g_free (str);

      gimp_progress_set_value (progress, 0.0);

      while (gtk_events_pending ())
        gtk_main_iteration ();
    }

  if (box->uris)
    {
      gimp_thumb_box_create_thumbnail (box,
                                       box->uris->data,
                                       gimp->config->thumbnail_size,
                                       force,
                                       progress);

      gimp_progress_set_value (progress, 1.0);
    }

 canceled:

  if (n_uris > 1)
    {
      g_object_unref (progress);

      gimp_progress_end (GIMP_PROGRESS (box));
      gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), "");
    }

  if (box->uris)
    {
      gtk_widget_hide (box->progress);
      gtk_widget_show (box->info);
    }

  if (dialog)
    gimp_file_dialog_set_sensitive (dialog, TRUE);
  else
    gtk_widget_set_sensitive (toplevel, TRUE);

  gimp_unset_busy (gimp);
}
Exemplo n.º 25
0
void 
matedialog_entry (MateDialogData *data, MateDialogEntryData *entry_data)
{
  GtkBuilder *builder = NULL;
  GtkWidget *dialog;
  GObject *text;
  GSList *entries = NULL; 
  GSList *tmp;
  GObject *vbox;
  
  builder = matedialog_util_load_ui_file ("matedialog_entry_dialog", NULL);

  if (builder == NULL) {
    data->exit_code = matedialog_util_return_exit_code (MATEDIALOG_ERROR);
    return;
  }
	
  gtk_builder_connect_signals (builder, NULL);
	
  dialog = GTK_WIDGET (gtk_builder_get_object (builder, "matedialog_entry_dialog"));
	
  g_signal_connect (G_OBJECT (dialog), "response",
                    G_CALLBACK (matedialog_entry_dialog_response), data);

  if (data->dialog_title)
    gtk_window_set_title (GTK_WINDOW (dialog), data->dialog_title);
	
  matedialog_util_set_window_icon (dialog, data->window_icon, MATEDIALOG_IMAGE_FULLPATH ("matedialog-entry.png"));

  if (data->width > -1 || data->height > -1)
    gtk_window_set_default_size (GTK_WINDOW (dialog), data->width, data->height);

  text = gtk_builder_get_object (builder, "matedialog_entry_text");

  if (entry_data->dialog_text)
    gtk_label_set_text_with_mnemonic (GTK_LABEL (text), g_strcompress (entry_data->dialog_text));
  
  vbox = gtk_builder_get_object (builder, "vbox4");
  
  matedialog_entry_fill_entries(&entries, entry_data->data);
  
  n_entries = g_slist_length (entries);

  if (n_entries > 1) {
    #if GTK_CHECK_VERSION(2,24,0)
      entry = gtk_combo_box_text_new_with_entry ();
    #else
      entry = gtk_combo_box_entry_new_text ();
    #endif

    for (tmp = entries; tmp; tmp = tmp->next) {
      #if GTK_CHECK_VERSION(2,24,0)
        gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (entry), tmp->data);
      #else
        gtk_combo_box_append_text (GTK_COMBO_BOX (entry), tmp->data);
      #endif
    }

    if (entry_data->entry_text) {
      #if GTK_CHECK_VERSION(2,24,0)
        gtk_combo_box_text_prepend_text (GTK_COMBO_BOX_TEXT (entry), entry_data->entry_text);
      #else
        gtk_combo_box_prepend_text (GTK_COMBO_BOX (entry), entry_data->entry_text);
      #endif
      gtk_combo_box_set_active (GTK_COMBO_BOX (entry), 0);
    }

    g_signal_connect (gtk_bin_get_child (GTK_BIN (entry)), "activate",
                      G_CALLBACK (matedialog_entry_combo_activate_default),
                      GTK_WINDOW (dialog));
  } else {
    entry = gtk_entry_new();

    gtk_entry_set_activates_default (GTK_ENTRY (entry), TRUE);
    
    if (entry_data->entry_text)
      gtk_entry_set_text (GTK_ENTRY (entry), entry_data->entry_text);

    if (entry_data->hide_text)
      g_object_set (G_OBJECT (entry), "visibility", FALSE, NULL);
  }

  gtk_widget_show (entry);

  gtk_box_pack_end (GTK_BOX (vbox), entry, FALSE, FALSE, 0);

  gtk_label_set_mnemonic_widget (GTK_LABEL (text), entry);

  g_object_unref (builder);

  matedialog_util_show_dialog (dialog);

  if(data->timeout_delay > 0) {
    g_timeout_add_seconds (data->timeout_delay, (GSourceFunc) matedialog_util_timeout_handle, NULL);
  }

  gtk_main ();
}
Exemplo n.º 26
0
  void NiceConnection::getCandidate(uint stream_id, uint component_id, const std::string &foundation) {
    GSList* lcands = nice_agent_get_local_candidates(agent_, stream_id, component_id);
    // We only want to get the new candidates
    int listLength = g_slist_length(lcands);
    ELOG_DEBUG("List length %u, candsDelivered %u", listLength, candsDelivered_);
    if (candsDelivered_ <= g_slist_length(lcands)){
      lcands = g_slist_nth(lcands, (candsDelivered_));
    }
    ELOG_DEBUG("getCandidate %u", g_slist_length(lcands));
    for (GSList* iterator = lcands; iterator; iterator = iterator->next) {
      ELOG_DEBUG("Candidate");
      char address[NICE_ADDRESS_STRING_LEN], baseAddress[NICE_ADDRESS_STRING_LEN];
      NiceCandidate *cand = (NiceCandidate*) iterator->data;
      nice_address_to_string(&cand->addr, address);
      nice_address_to_string(&cand->base_addr, baseAddress);
      candsDelivered_++;
      if (strstr(address, ":") != NULL) { // We ignore IPv6 candidates at this point
        continue;
      }
      CandidateInfo cand_info;
      cand_info.componentId = cand->component_id;
      cand_info.foundation = cand->foundation;
      cand_info.priority = cand->priority;
      cand_info.hostAddress = std::string(address);
      cand_info.hostPort = nice_address_get_port(&cand->addr);
      cand_info.mediaType = mediaType;

      /*
       *   NICE_CANDIDATE_TYPE_HOST,
       *    NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
       *    NICE_CANDIDATE_TYPE_PEER_REFLEXIVE,
       *    NICE_CANDIDATE_TYPE_RELAYED,
       */
      switch (cand->type) {
        case NICE_CANDIDATE_TYPE_HOST:
          cand_info.hostType = HOST;
          break;
        case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE:
          cand_info.hostType = SRFLX;
          cand_info.rAddress = std::string(baseAddress);
          cand_info.rPort = nice_address_get_port(&cand->base_addr);
          break;
        case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE:
          cand_info.hostType = PRFLX;
          break;
        case NICE_CANDIDATE_TYPE_RELAYED:
          char turnAddres[NICE_ADDRESS_STRING_LEN];
          ELOG_DEBUG("TURN LOCAL CANDIDATE");
          nice_address_to_string(&cand->turn->server,turnAddres);
          ELOG_DEBUG("address %s", address);
          ELOG_DEBUG("baseAddress %s", baseAddress);
          ELOG_DEBUG("stream_id %u", cand->stream_id);
          ELOG_DEBUG("priority %u", cand->priority);
          ELOG_DEBUG("TURN ADDRESS %s", turnAddres);

          cand_info.hostType = RELAY;
          cand_info.rAddress = std::string(baseAddress);
          cand_info.rPort = nice_address_get_port(&cand->base_addr);
          break;
        default:
          break;
      }
      cand_info.netProtocol = "udp";
      cand_info.transProtocol = std::string(*transportName.get());
      cand_info.username = ufrag_;
      cand_info.password = upass_;
      //localCandidates->push_back(cand_info);
      this->getNiceListener()->onCandidate(cand_info, this);
    }
    // for nice_agent_get_local_candidates,  the caller owns the returned GSList as well as the candidates contained within it.
    // let's free everything in the list, as well as the list.
    g_slist_free_full(lcands, (GDestroyNotify)&nice_candidate_free);

  }
Exemplo n.º 27
0
static gboolean
role_plot_can_add (GogObject const *parent)
{
	GogChart *chart = GOG_CHART (parent);
	return (chart->axis_set & (1 << GOG_AXIS_Z)) == 0 || g_slist_length (chart->plots) == 0;
}
Exemplo n.º 28
0
void MainWindow::on_actionScan_triggered()
{
	QString s;
	int num_devices, pos;
	struct sr_device *device;
	char *di_num_probes, *str;
	struct sr_samplerates *samplerates;
	const static float mult[] = { 2.f, 2.5f, 2.f };

	statusBar()->showMessage(tr("Scanning for logic analyzers..."), 2000);

	sr_device_scan();
	devices = sr_device_list();
	num_devices = g_slist_length(devices);

	ui->comboBoxLA->clear();
	for (int i = 0; i < num_devices; ++i) {
		device = (struct sr_device *)g_slist_nth_data(devices, i);
		ui->comboBoxLA->addItem(device->plugin->name); /* TODO: Full name */
	}

	if (num_devices == 0) {
		s = tr("No supported logic analyzer found.");
		statusBar()->showMessage(s, 2000);
		return;
	} else if (num_devices == 1) {
		s = tr("Found supported logic analyzer: ");
		s.append(device->plugin->name);
		statusBar()->showMessage(s, 2000);
	} else {
		/* TODO: Allow user to select one of the devices. */
		s = tr("Found multiple logic analyzers: ");
		for (int i = 0; i < num_devices; ++i) {
			device = (struct sr_device *)g_slist_nth_data(devices, i);
			s.append(device->plugin->name);
			if (i != num_devices - 1)
				s.append(", ");
		}
		statusBar()->showMessage(s, 2000);
		return;
	}

	device = (struct sr_device *)g_slist_nth_data(devices, 0 /* opt_device */);

	setCurrentLA(0 /* TODO */);

	di_num_probes = (char *)device->plugin->get_device_info(
			device->plugin_index, SR_DI_NUM_PROBES);
	if (di_num_probes != NULL) {
		setNumChannels(GPOINTER_TO_INT(di_num_probes));
	} else {
		setNumChannels(8); /* FIXME: Error handling. */
	}

	ui->comboBoxLA->clear();
	ui->comboBoxLA->addItem(device->plugin->name); /* TODO: Full name */

	s = QString(tr("Channels: %1")).arg(getNumChannels());
	ui->labelChannels->setText(s);

	samplerates = (struct sr_samplerates *)device->plugin->get_device_info(
		      device->plugin_index, SR_DI_SAMPLERATES);
	if (!samplerates) {
		/* TODO: Error handling. */
	}

	/* Populate the combobox with supported samplerates. */
	ui->comboBoxSampleRate->clear();
	if (!samplerates) {
		ui->comboBoxSampleRate->addItem("No samplerate");
		ui->comboBoxSampleRate->setEnabled(false);
	} else if (samplerates->list != NULL) {
		for (int i = 0; samplerates->list[i]; ++i) {
			str = sr_samplerate_string(samplerates->list[i]);
			s = QString(str);
			free(str);
			ui->comboBoxSampleRate->insertItem(0, s,
				QVariant::fromValue(samplerates->list[i]));
		}
		ui->comboBoxSampleRate->setEnabled(true);
	} else {
		pos = 0;
		for (uint64_t r = samplerates->low; r <= samplerates->high; ) {
			str = sr_samplerate_string(r);
			s = QString(str);
			free(str);
			ui->comboBoxSampleRate->insertItem(0, s,
						QVariant::fromValue(r));
			r *= mult[pos++];
			pos %= 3;
		}
		ui->comboBoxSampleRate->setEnabled(true);
	}
	ui->comboBoxSampleRate->setCurrentIndex(0);

	/* FIXME */
	ui->comboBoxNumSamples->clear();
	ui->comboBoxNumSamples->addItem("100", 100); /* For testing... */
	ui->comboBoxNumSamples->addItem("3000000", 3000000);
	ui->comboBoxNumSamples->addItem("2000000", 2000000);
	ui->comboBoxNumSamples->addItem("1000000", 1000000);

	ui->comboBoxNumSamples->setEditable(true);

	if (getCurrentLA() >= 0)
		setupDockWidgets();

	/* Enable all relevant fields now (i.e. make them non-gray). */
	ui->comboBoxNumSamples->setEnabled(true);
	ui->labelChannels->setEnabled(true);
	ui->action_Get_samples->setEnabled(true);
}
Exemplo n.º 29
0
t_agent_client *
register_with_agent(	t_agent	*agent,		 /* Agent to register with    */
			int	*am_mask	 /* Messages accepted	      */
#ifdef DEBUG
		,	char	*name		 /* For debugging!!!	      */
#endif
					)
/*
 * Register with the given agent. A new client will be created
 * with a distinct input queue onto which all agent status
 * messages will be duplicated.
 * In addition a new file descriptor for the output queue
 * will be created for sending messages to the agent.
 * The am_mask is a list of every message ID that the client
 * should be sent, terminated with NULL. If this is the only
 * value given then no messages will ever be sent to the client
 * registering.
 */
{
	t_agent_client	*client;
	int		cell;			 /* Cell in 'mask' array      */

	if(!agent)				 /* Agent doesn't exist?      */
	{
		E("Client called to register with NULL agent");
		return NULL;			 /* Nothing to do!	      */
	}

	client = NEW(t_agent_client);

	if(!client)
	{
		E("Failed to create new client");
		return NULL;
	}

	client->agent = agent;
	client->op_am_q = agent->ip_am_q;
	client->ip_am_q = NO_AM_Q;

#ifdef DEBUG
	client->name = name;
#endif

	client->ip_am_q = new_am_q();

	if(client->ip_am_q == NO_AM_Q)
	{
		E("Failed to initialise client due to msg Q failure");
		D(7, "INFO: agent = [%s]", agent->name);
		del_client(client);
		return NULL;
	}

	/*
	 * Compile the message mask.  For every message in the list,
	 * set the appropriate messsage ID in the mask to TRUE
	 */

	for(cell = 0; cell < am_enums; cell++)	 /* Default all masks to FALSE*/
		client->mask[cell] = FALSE;

	while(*am_mask)				 /* For each ID in the list ..*/
	{
#ifdef PARANOID
		if(*am_mask > am_enums)		 /* Sanity (range check)      */
		{
			E("mask value [%d] > MAX [%d]",
				*am_mask, am_enums);
		}
		else
#endif
			client->mask[(*am_mask) - 1] = TRUE;/* Set to true    */
		am_mask++;
	}

	/* --- Append the client to the agent's master list of clients --- */ 

	WAITLOCK(agent->lck);
	agent->clients = g_slist_append(agent->clients, client);
	D(7, "[%s] is client %d of agent [%s]", name, g_slist_length(agent->clients)-1, agent->name);
	UNLOCK(agent->lck);

	return client;
}						 /* register_with_agent()     */
GtkTextBuffer *gtk_text_buffer_duplicate(GtkTextBuffer *source_buffer)
{
	// Local variables
	gchar				*conversion_buffer;			// Used when converting between unicode character types
	GtkTextIter			end_iter;
	GtkTextIter			end_iter_minus_one;
	gint				end_offset;
	gint				i;
	guint				loop_counter;
	GtkTextIter 		loop_iter;
	GtkTextBuffer		*new_text_buffer;
	guint				num_tags;
	GtkTextIter			source_buffer_end;
	GtkTextIter			source_buffer_start;
	gint				start_offset;
	GSList				*tag_list;
	GtkTextTag			*tag_ptr;
	gunichar			temp_char;
	GString				*temp_gstring;


	// Validate the tags in the source buffer
	text_layer_dialog_validate_buffer_tag_quantity(GTK_TEXT_BUFFER(source_buffer));

	// Initialise various things
	temp_gstring = g_string_new(NULL);

	// Create a new text buffer
	new_text_buffer = gtk_text_buffer_new(get_text_tags_table());

	// Get the bounds of the source buffer
	gtk_text_buffer_get_bounds(GTK_TEXT_BUFFER(source_buffer), &source_buffer_start, &source_buffer_end);
	gtk_text_iter_order(&source_buffer_start, &source_buffer_end);

	// Scan through the source text buffer one character at a time, getting the character and the tags that apply to it
	start_offset = gtk_text_iter_get_offset(&source_buffer_start);
	end_offset = gtk_text_iter_get_offset(&source_buffer_end);
	for (i = 0; i < end_offset; i++)
	{
		// Copy one character from the source text buffer to the new destination text buffer
		gtk_text_buffer_get_iter_at_offset(GTK_TEXT_BUFFER(source_buffer), &loop_iter, i);
		temp_char = gtk_text_iter_get_char(&loop_iter);
		conversion_buffer = g_ucs4_to_utf8(&temp_char, 1, NULL, NULL, NULL);
		if (NULL == conversion_buffer)
		{
			g_string_printf(temp_gstring, "%s ED441: %s", _("Error"), _("Could not convert unicode character from ucs4 to utf8."));
			display_warning(temp_gstring->str);
			continue;
		}

		// Validate the retrieved character
		if (TRUE != g_unichar_validate(temp_char))
		{
			// Something other than a unicode character was retrieved
			g_string_printf(temp_gstring, "%s ED442: %s", _("Error"), _("Invalid unicode character found in text."));
			display_warning(temp_gstring->str);
			continue;
		}
		gtk_text_buffer_insert_at_cursor(GTK_TEXT_BUFFER(new_text_buffer), conversion_buffer, -1);
		g_free(conversion_buffer);

		// Copy the tags from the character in the source buffer to the new character in the destination buffer
		tag_list = gtk_text_iter_get_tags(&loop_iter);
		num_tags = g_slist_length(tag_list);
		gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(new_text_buffer), &end_iter);
		end_iter_minus_one = end_iter;
		gtk_text_iter_backward_char(&end_iter_minus_one);
		for (loop_counter = 0; loop_counter < num_tags; loop_counter++)
		{
			// Copy each tag from the source text buffer to the destination one
			tag_ptr = g_slist_nth_data(tag_list, loop_counter);
			gtk_text_buffer_apply_tag(GTK_TEXT_BUFFER(new_text_buffer), tag_ptr, &end_iter_minus_one, &end_iter);
		}
		g_slist_free(tag_list);
	}
	g_string_free(temp_gstring, TRUE);

	// Validate the tags in the duplicated buffer
	text_layer_dialog_validate_buffer_tag_quantity(GTK_TEXT_BUFFER(new_text_buffer));

	// Return the duplicated text buffer
	return new_text_buffer;
}