Пример #1
0
void
CDMCallbackProxy::KeyStatusChanged(const nsCString& aSessionId,
                                   const nsTArray<uint8_t>& aKeyId,
                                   GMPMediaKeyStatus aStatus)
{
  MOZ_ASSERT(mProxy->IsOnGMPThread());

  bool keyStatusesChange = false;
  {
    CDMCaps::AutoLock caps(mProxy->Capabilites());
    keyStatusesChange = caps.SetKeyStatus(aKeyId,
                                          NS_ConvertUTF8toUTF16(aSessionId),
                                          aStatus);
  }
  if (keyStatusesChange) {
    nsCOMPtr<nsIRunnable> task;
    task = NewRunnableMethod<nsString>(mProxy,
                                       &CDMProxy::OnKeyStatusesChange,
                                       NS_ConvertUTF8toUTF16(aSessionId));
    NS_DispatchToMainThread(task);
  }
}
Пример #2
0
nsresult
MediaSourceDecoder::SetCDMProxy(CDMProxy* aProxy)
{
  nsresult rv = MediaDecoder::SetCDMProxy(aProxy);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = mReader->SetCDMProxy(aProxy);
  NS_ENSURE_SUCCESS(rv, rv);

  if (aProxy) {
    // The sub readers can't decrypt EME content until they have a CDMProxy,
    // and the CDMProxy knows the capabilities of the CDM. The MediaSourceReader
    // remains in "waiting for resources" state until then. We need to kick the
    // reader out of waiting if the CDM gets added with known capabilities.
    CDMCaps::AutoLock caps(aProxy->Capabilites());
    if (!caps.AreCapsKnown()) {
      nsCOMPtr<nsIRunnable> task(
        NS_NewRunnableMethod(this, &MediaDecoder::NotifyWaitingForResourcesStatusChanged));
      caps.CallOnMainThreadWhenCapsAvailable(task);
    }
  }
  return NS_OK;
}
/* static */
already_AddRefed<PlatformDecoderModule>
PlatformDecoderModule::CreateCDMWrapper(CDMProxy* aProxy)
{
  bool cdmDecodesAudio;
  bool cdmDecodesVideo;
  {
    CDMCaps::AutoLock caps(aProxy->Capabilites());
    cdmDecodesAudio = caps.CanDecryptAndDecodeAudio();
    cdmDecodesVideo = caps.CanDecryptAndDecodeVideo();
  }

  // We always create a default PDM in order to decode
  // non-encrypted tracks.
  nsRefPtr<PlatformDecoderModule> pdm = Create();
  if (!pdm) {
    return nullptr;
  }

  nsRefPtr<PlatformDecoderModule> emepdm(
    new EMEDecoderModule(aProxy, pdm, cdmDecodesAudio, cdmDecodesVideo));
  return emepdm.forget();
}
Пример #4
0
int main(){
	initscr();
	start_color();
	colorContent();
	printw("What's your name?\n");
	scanw("%s",pName);
	printw("Wow, %s? That's a really gay name.", pName);
	noecho();
	while((ch=getch()) != 'q' && health > 0){
		varReset();
		erase();
		if(pInput(ch)==1)
			hunger--;
		checks();
		checkMath();
		caps();
		drawMap();
	}
	erase();
	attron(COLOR_PAIR(6));
	printw("GAME OVER");
	getch();
	printw("\n");
	attron(COLOR_PAIR(4));
	if(ch=='q'){
		printw("\nYou quit.");
	}
	else if(health==0){
		printw("\nYou died.");
	}
	printw("\nPress 'q' to exit.");
	while((ch=getch())!='q'){
		attron(COLOR_PAIR(6));
		mvprintw(3,0,"Press 'q' to exit.");
	}
	endwin();
	return 0;
}
Пример #5
0
static void irc_001(ir_parseline_t *ipl)
{
  char *tptr;

  ioutput(OUT_S|OUT_L, COLOR_NO_COLOR, "Server welcome: %s", ipl->line);
  update_server_welcome(ipl->line);

  /* update server name */
  mydelete(gnetwork->curserveractualname);
  gnetwork->curserveractualname = getpart(ipl->line + 1, 1);

  /* update nick */
  mydelete(gnetwork->user_nick);
  mydelete(gnetwork->caps_nick);
  gnetwork->user_nick = mystrdup(ipl->part[2]);
  gnetwork->caps_nick = mystrdup(ipl->part[2]);
  caps(gnetwork->caps_nick);
  gnetwork->nick_number = 0;
  gnetwork->next_restrict = gdata.curtime + gdata.restrictsend_delay;
  ++(gdata.needsclear);

  tptr = get_user_modes();
  if (tptr && tptr[0]) {
    writeserver(WRITESERVER_NOW, "MODE %s %s",
                gnetwork->user_nick, tptr);
  }

  /* server connected raw command */
  for (tptr = irlist_get_head(&(gnetwork->server_connected_raw));
       tptr;
       tptr = irlist_get_next(tptr)) {
    writeserver(WRITESERVER_NORMAL, "%s", tptr);
  }

  /* nickserv */
  identify_needed(0);
}
Пример #6
0
void
CDMCallbackProxy::SessionClosed(const nsCString& aSessionId)
{
  MOZ_ASSERT(mProxy->IsOnGMPThread());

  bool keyStatusesChange = false;
  {
    CDMCaps::AutoLock caps(mProxy->Capabilites());
    keyStatusesChange = caps.RemoveKeysForSession(NS_ConvertUTF8toUTF16(aSessionId));
  }
  if (keyStatusesChange) {
    nsCOMPtr<nsIRunnable> task;
    task = NewRunnableMethod<nsString>(mProxy,
      &CDMProxy::OnKeyStatusesChange,
      NS_ConvertUTF8toUTF16(aSessionId));
    NS_DispatchToMainThread(task);
  }

  nsCOMPtr<nsIRunnable> task;
  task = NewRunnableMethod<nsString>(mProxy,
                                     &CDMProxy::OnSessionClosed,
                                     NS_ConvertUTF8toUTF16(aSessionId));
  NS_DispatchToMainThread(task);
}
Пример #7
0
MediaPlayer::Capabilities MediaPlayer::capabilities()
{
    MediaPlayer::Capabilities caps( 0 );

    if ( m_gst_audio_volume )
        caps |= MediaPlayer::CapChangeVolume;

    if ( m_pitchPlugin )
        caps |= MediaPlayer::CapChangePitch;

    if ( m_gst_audio_tempo )
        caps |= MediaPlayer::CapChangeTempo;

    // This element is not precreated (as it is rarely needed)
    GstElement * splitter = gst_element_factory_make("audiokaraoke", "karaoketest" );

    if ( splitter )
    {
        g_object_unref( splitter );
        caps |= MediaPlayer::CapVoiceRemoval;
    }

    return caps;
}
static void proc_sync_set_req(struct mcap_mcl *mcl, uint8_t *cmd, uint32_t len)
{
	mcap_md_sync_set_req *req;
	uint32_t sched_btclock, cur_btclock;
	uint16_t btres;
	uint8_t update;
	uint64_t timestamp;
	struct sync_set_data *set_data;
	int phase2_delay, ind_freq, when;

	if (len != sizeof(mcap_md_sync_set_req)) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	req = (mcap_md_sync_set_req *) cmd;
	sched_btclock = ntohl(req->btclock);
	update = req->timestui;
	timestamp = ntoh64(req->timestst);

	if (sched_btclock != MCAP_BTCLOCK_IMMEDIATE &&
			!valid_btclock(sched_btclock)) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (update > 1) {
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (!mcl->csp->remote_caps) {
		/* Remote side did not ask our capabilities yet */
		send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE, 0, 0, 0);
		return;
	}

	if (!caps(mcl)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return;
	}

	if (!read_btclock_retry(mcl, &cur_btclock, &btres)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return;
	}

	if (sched_btclock == MCAP_BTCLOCK_IMMEDIATE)
		phase2_delay = 0;
	else {
		phase2_delay = btdiff(cur_btclock, sched_btclock);

		if (phase2_delay < 0) {
			/* can not reset in the past tense */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}

		/* Convert to miliseconds */
		phase2_delay = bt2ms(phase2_delay);

		if (phase2_delay > 61*1000) {
			/* More than 60 seconds in the future */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		} else if (phase2_delay < caps(mcl)->latency / 1000) {
			/* Too fast for us to do in time */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}
	}

	if (update) {
		/* Indication frequency: required accuracy divided by ours */
		/* Converted to milisseconds */
		ind_freq = (1000 * mcl->csp->rem_req_acc) / caps(mcl)->ts_acc;

		if (ind_freq < MAX(caps(mcl)->latency * 2 / 1000, 100)) {
			/* Too frequent, we can't handle */
			send_sync_set_rsp(mcl, MCAP_INVALID_PARAM_VALUE,
						0, 0, 0);
			return;
		}

		DBG("CSP: indication every %dms", ind_freq);
	} else
		ind_freq = 0;

	if (mcl->csp->ind_timer) {
		/* Old indications are no longer sent */
		g_source_remove(mcl->csp->ind_timer);
		mcl->csp->ind_timer = 0;
	}

	if (!mcl->csp->set_data)
		mcl->csp->set_data = g_new0(struct sync_set_data, 1);

	set_data = (struct sync_set_data *) mcl->csp->set_data;

	set_data->update = update;
	set_data->sched_btclock = sched_btclock;
	set_data->timestamp = timestamp;
	set_data->ind_freq = ind_freq;
	set_data->role = get_btrole(mcl);

	/* TODO is there some way to schedule a call based directly on
	 * a BT clock value, instead of this estimation that uses
	 * the SO clock? */

	if (phase2_delay > 0) {
		when = phase2_delay + caps(mcl)->syncleadtime_ms;
		mcl->csp->set_timer = g_timeout_add(when,
						proc_sync_set_req_phase2,
						mcl);
	} else
		proc_sync_set_req_phase2(mcl);

	/* First indication is immediate */
	if (update)
		sync_send_indication(mcl);
}
static gboolean proc_sync_set_req_phase2(gpointer user_data)
{
	struct mcap_mcl *mcl;
	struct sync_set_data *data;
	uint8_t update;
	uint32_t sched_btclock;
	uint64_t new_tmstamp;
	int ind_freq;
	int role;
	uint32_t btclock;
	uint64_t tmstamp;
	struct timespec base_time;
	uint16_t tmstampacc;
	gboolean reset;
	int delay;

	if (!user_data)
		return FALSE;

	mcl = user_data;

	if (!mcl->csp->set_data)
		return FALSE;

	data = mcl->csp->set_data;
	update = data->update;
	sched_btclock = data->sched_btclock;
	new_tmstamp = data->timestamp;
	ind_freq = data->ind_freq;
	role = data->role;

	if (!caps(mcl)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return FALSE;
	}

	if (!get_all_clocks(mcl, &btclock, &base_time, &tmstamp)) {
		send_sync_set_rsp(mcl, MCAP_UNSPECIFIED_ERROR, 0, 0, 0);
		return FALSE;
	}

	if (get_btrole(mcl) != role) {
		send_sync_set_rsp(mcl, MCAP_INVALID_OPERATION, 0, 0, 0);
		return FALSE;
	}

	reset = (new_tmstamp != MCAP_TMSTAMP_DONTSET);

	if (reset) {
		if (sched_btclock != MCAP_BTCLOCK_IMMEDIATE) {
			delay = bt2us(btdiff(sched_btclock, btclock));
			if (delay >= 0 || ((new_tmstamp - delay) > 0)) {
				new_tmstamp += delay;
				DBG("CSP: reset w/ delay %dus, compensated",
									delay);
			} else
				DBG("CSP: reset w/ delay %dus, uncompensated",
									delay);
		}

		reset_tmstamp(mcl->csp, &base_time, new_tmstamp);
		tmstamp = new_tmstamp;
	}

	tmstampacc = caps(mcl)->latency + caps(mcl)->ts_acc;

	if (mcl->csp->ind_timer) {
		g_source_remove(mcl->csp->ind_timer);
		mcl->csp->ind_timer = 0;
	}

	if (update) {
		int when = ind_freq + caps(mcl)->syncleadtime_ms;
		mcl->csp->ind_timer = g_timeout_add(when,
						sync_send_indication,
						mcl);
	}

	send_sync_set_rsp(mcl, MCAP_SUCCESS, btclock, tmstamp, tmstampacc);

	/* First indication after set is immediate */
	if (update)
		sync_send_indication(mcl);

	return FALSE;
}
SynapticsTouchpad::SynapticsTouchpad(Display *display, int deviceId): XlibTouchpad(display, deviceId),
    m_resX(1), m_resY(1)
{
    m_capsAtom.intern(m_connection, SYNAPTICS_PROP_CAPABILITIES);
    m_touchpadOffAtom.intern(m_connection, SYNAPTICS_PROP_OFF);
    XcbAtom resolutionAtom(m_connection, SYNAPTICS_PROP_RESOLUTION);
    XcbAtom edgesAtom(m_connection, SYNAPTICS_PROP_EDGES);

    loadSupportedProperties(synapticsProperties);

    m_toRadians.append("CircScrollDelta");

    PropertyInfo edges(m_display, m_deviceId, edgesAtom, 0);
    if (edges.i && edges.nitems == 4) {
        int w = qAbs(edges.i[1] - edges.i[0]);
        int h = qAbs(edges.i[3] - edges.i[2]);
        m_resX = w / 90;
        m_resY = h / 50;
        qDebug() << "Width: " << w << " height: " << h;
        qDebug() << "Approx. resX: " << m_resX << " resY: " << m_resY;
    }

    PropertyInfo resolution(m_display, m_deviceId, resolutionAtom, 0);
    if (resolution.i && resolution.nitems == 2 &&
        resolution.i[0] > 1 && resolution.i[1] > 1)
    {
        m_resY = qMin(static_cast<unsigned long>(resolution.i[0]),
                static_cast<unsigned long>(INT_MAX));
        m_resX = qMin(static_cast<unsigned long>(resolution.i[1]),
                static_cast<unsigned long>(INT_MAX));
        qDebug() << "Touchpad resolution: x: " << m_resX << " y: " << m_resY;
    }

    m_scaleByResX.append("HorizScrollDelta");
    m_scaleByResY.append("VertScrollDelta");
    m_scaleByResX.append("MaxTapMove");
    m_scaleByResY.append("MaxTapMove");

    m_resX = qMax(10, m_resX);
    m_resY = qMax(10, m_resY);
    qDebug() << "Final resolution x:" << m_resX << " y:" << m_resY;
    m_negate["HorizScrollDelta"] = "InvertHorizScroll";
    m_negate["VertScrollDelta"] = "InvertVertScroll";
    m_supported.append(m_negate.values());
    m_supported.append("Coasting");

    PropertyInfo caps(m_display, m_deviceId, m_capsAtom.atom(), 0);
    if (!caps.b) {
        return;
    }

    enum TouchpadCapabilitiy
    {
        TouchpadHasLeftButton,
        TouchpadHasMiddleButton,
        TouchpadHasRightButton,
        TouchpadTwoFingerDetect,
        TouchpadThreeFingerDetect,
        TouchpadPressureDetect,
        TouchpadPalmDetect,
        TouchpadCapsCount
    };

    QVector<bool> cap(TouchpadCapsCount, false);
    qCopy(caps.b, caps.b + qMin(cap.size(), static_cast<int>(caps.nitems)),
          cap.begin());

    if (!cap[TouchpadTwoFingerDetect]) {
        m_supported.removeAll("HorizTwoFingerScroll");
        m_supported.removeAll("VertTwoFingerScroll");
        m_supported.removeAll("TwoFingerTapButton");
    }

    if (!cap[TouchpadThreeFingerDetect]) {
        m_supported.removeAll("ThreeFingerTapButton");
    }

    if (!cap[TouchpadPressureDetect]) {
        m_supported.removeAll("FingerHigh");
        m_supported.removeAll("FingerLow");

        m_supported.removeAll("PalmMinZ");
        m_supported.removeAll("PressureMotionMinZ");
        m_supported.removeAll("PressureMotionMinFactor");
        m_supported.removeAll("PressureMotionMaxZ");
        m_supported.removeAll("PressureMotionMaxFactor");
        m_supported.removeAll("EmulateTwoFingerMinZ");
    }

    if (!cap[TouchpadPalmDetect]) {
        m_supported.removeAll("PalmDetect");
        m_supported.removeAll("PalmMinWidth");
        m_supported.removeAll("PalmMinZ");
        m_supported.removeAll("EmulateTwoFingerMinW");
    }

    for (QMap<QString, QString>::Iterator i = m_negate.begin();
         i != m_negate.end(); ++i)
    {
        if (!m_supported.contains(i.key())) {
            m_supported.removeAll(i.value());
        }
    }

    m_paramList = synapticsProperties;
}
Пример #11
0
SkImageCacherator::CachedFormat SkImage_Lazy::chooseCacheFormat(SkColorSpace* dstColorSpace,
                                                                const GrCaps* grCaps) const {
    SkColorSpace* cs = fInfo.colorSpace();
    if (!cs || !dstColorSpace) {
        return kLegacy_CachedFormat;
    }

    CacheCaps caps(grCaps);
    switch (fInfo.colorType()) {
        case kUnknown_SkColorType:
        case kAlpha_8_SkColorType:
        case kRGB_565_SkColorType:
        case kARGB_4444_SkColorType:
        case kRGB_888x_SkColorType:
        case kRGBA_1010102_SkColorType:
        case kRGB_101010x_SkColorType:
            // We don't support color space on these formats, so always decode in legacy mode:
            // TODO: Ask the codec to decode these to something else (at least sRGB 8888)?
            return kLegacy_CachedFormat;

        case kGray_8_SkColorType:
            // TODO: What do we do with grayscale sources that have strange color spaces attached?
            // The codecs and color space xform don't handle this correctly (yet), so drop it on
            // the floor. (Also, inflating by a factor of 8 is going to be unfortunate).
            // As it is, we don't directly support sRGB grayscale, so ask the codec to convert
            // it for us. This bypasses some really sketchy code GrUploadPixmapToTexture.
            if (cs->gammaCloseToSRGB() && caps.supportsSRGB()) {
                return kSRGB8888_CachedFormat;
            } else {
                return kLegacy_CachedFormat;
            }

        case kRGBA_8888_SkColorType:
            if (cs->gammaCloseToSRGB()) {
                if (caps.supportsSRGB()) {
                    return kSRGB8888_CachedFormat;
                } else if (caps.supportsHalfFloat()) {
                    return kLinearF16_CachedFormat;
                } else {
                    return kLegacy_CachedFormat;
                }
            } else {
                if (caps.supportsHalfFloat()) {
                    return kLinearF16_CachedFormat;
                } else if (caps.supportsSRGB()) {
                    return kSRGB8888_CachedFormat;
                } else {
                    return kLegacy_CachedFormat;
                }
            }

        case kBGRA_8888_SkColorType:
            // Odd case. sBGRA isn't a real thing, so we may not have this texturable.
            if (caps.supportsSBGR()) {
                if (cs->gammaCloseToSRGB()) {
                    return kSBGR8888_CachedFormat;
                } else if (caps.supportsHalfFloat()) {
                    return kLinearF16_CachedFormat;
                } else if (caps.supportsSRGB()) {
                    return kSRGB8888_CachedFormat;
                } else {
                    // sBGRA support without sRGBA is highly unlikely (impossible?) Nevertheless.
                    return kLegacy_CachedFormat;
                }
            } else {
                if (cs->gammaCloseToSRGB()) {
                    if (caps.supportsSRGB()) {
                        return kSRGB8888_CachedFormat;
                    } else if (caps.supportsHalfFloat()) {
                        return kLinearF16_CachedFormat;
                    } else {
                        return kLegacy_CachedFormat;
                    }
                } else {
                    if (caps.supportsHalfFloat()) {
                        return kLinearF16_CachedFormat;
                    } else if (caps.supportsSRGB()) {
                        return kSRGB8888_CachedFormat;
                    } else {
                        return kLegacy_CachedFormat;
                    }
                }
            }

        case kRGBA_F16_SkColorType:
            if (caps.supportsHalfFloat()) {
                return kLinearF16_CachedFormat;
            } else if (caps.supportsSRGB()) {
                return kSRGB8888_CachedFormat;
            } else {
                return kLegacy_CachedFormat;
            }
    }
    SkDEBUGFAIL("Unreachable");
    return kLegacy_CachedFormat;
}
Пример #12
0
GeneralTab::GeneralTab(const QString &device, v4l2 &fd, int n, QWidget *parent) :
	QGridLayout(parent),
	v4l2(fd),
	m_row(0),
	m_col(0),
	m_cols(n),
	m_audioInput(NULL),
	m_tvStandard(NULL),
	m_videoPreset(NULL),
	m_freq(NULL),
	m_vidCapFormats(NULL),
	m_frameSize(NULL),
	m_vidOutFormats(NULL)
{
	setSpacing(3);

	setSizeConstraint(QLayout::SetMinimumSize);

	if (querycap(m_querycap)) {
		addLabel("Device:");
		addLabel(device + (useWrapper() ? " (wrapped)" : ""), Qt::AlignLeft);

		addLabel("Driver:");
		addLabel((char *)m_querycap.driver, Qt::AlignLeft);

		addLabel("Card:");
		addLabel((char *)m_querycap.card, Qt::AlignLeft);

		addLabel("Bus:");
		addLabel((char *)m_querycap.bus_info, Qt::AlignLeft);
	}

	g_tuner(m_tuner);

	v4l2_standard vs;
	if (enum_std(vs, true)) {
		addLabel("TV Standard");
		m_tvStandard = new QComboBox(parent);
		do {
			m_tvStandard->addItem((char *)vs.name);
		} while (enum_std(vs));
		addWidget(m_tvStandard);
		connect(m_tvStandard, SIGNAL(activated(int)), SLOT(standardChanged(int)));
		updateStandard();
	}

	v4l2_dv_enum_preset preset;
	if (enum_dv_preset(preset, true)) {
		addLabel("Video Preset");
		m_videoPreset = new QComboBox(parent);
		do {
			m_videoPreset->addItem((char *)preset.name);
		} while (enum_dv_preset(preset));
		addWidget(m_videoPreset);
		connect(m_videoPreset, SIGNAL(activated(int)), SLOT(presetChanged(int)));
		updatePreset();
	}

	v4l2_input vin;
	if (enum_input(vin, true)) {
		addLabel("Input");
		m_videoInput = new QComboBox(parent);
		do {
			m_videoInput->addItem((char *)vin.name);
		} while (enum_input(vin));
		addWidget(m_videoInput);
		connect(m_videoInput, SIGNAL(activated(int)), SLOT(inputChanged(int)));
		updateVideoInput();
	}

	v4l2_output vout;
	if (enum_output(vout, true)) {
		addLabel("Output");
		m_videoOutput = new QComboBox(parent);
		do {
			m_videoOutput->addItem((char *)vout.name);
		} while (enum_output(vout));
		addWidget(m_videoOutput);
		connect(m_videoOutput, SIGNAL(activated(int)), SLOT(outputChanged(int)));
		updateVideoOutput();
	}

	v4l2_audio vaudio;
	if (enum_audio(vaudio, true)) {
		addLabel("Input Audio");
		m_audioInput = new QComboBox(parent);
		do {
			m_audioInput->addItem((char *)vaudio.name);
		} while (enum_audio(vaudio));
		addWidget(m_audioInput);
		connect(m_audioInput, SIGNAL(activated(int)), SLOT(inputAudioChanged(int)));
		updateAudioInput();
	}

	v4l2_audioout vaudout;
	if (enum_audout(vaudout, true)) {
		addLabel("Output Audio");
		m_audioOutput = new QComboBox(parent);
		do {
			m_audioOutput->addItem((char *)vaudout.name);
		} while (enum_audout(vaudout));
		addWidget(m_audioOutput);
		connect(m_audioOutput, SIGNAL(activated(int)), SLOT(outputAudioChanged(int)));
		updateAudioOutput();
	}

	if (m_tuner.type) {
		m_freq = new QSpinBox(parent);
		m_freq->setMinimum(m_tuner.rangelow);
		m_freq->setMaximum(m_tuner.rangehigh);
		m_freq->setWhatsThis(QString("Frequency\nLow: %1\nHigh: %2")
				.arg(m_tuner.rangelow).arg(m_tuner.rangehigh));
		connect(m_freq, SIGNAL(valueChanged(int)), SLOT(freqChanged(int)));
		updateFreq();
		addLabel("Frequency");
		addWidget(m_freq);

		addLabel("Frequency Table");
		m_freqTable = new QComboBox(parent);
		for (int i = 0; v4l2_channel_lists[i].name; i++) {
			m_freqTable->addItem(v4l2_channel_lists[i].name);
		}
		addWidget(m_freqTable);
		connect(m_freqTable, SIGNAL(activated(int)), SLOT(freqTableChanged(int)));

		addLabel("Channels");
		m_freqChannel = new QComboBox(parent);
		m_freqChannel->setSizeAdjustPolicy(QComboBox::AdjustToContents);
		addWidget(m_freqChannel);
		connect(m_freqChannel, SIGNAL(activated(int)), SLOT(freqChannelChanged(int)));
		updateFreqChannel();
	}

	v4l2_fmtdesc fmt;
	addLabel("Capture Image Formats");
	m_vidCapFormats = new QComboBox(parent);
	if (enum_fmt_cap(fmt, true)) {
		do {
			m_vidCapFormats->addItem(pixfmt2s(fmt.pixelformat) +
					" - " + (const char *)fmt.description);
		} while (enum_fmt_cap(fmt));
	}
	addWidget(m_vidCapFormats);
	connect(m_vidCapFormats, SIGNAL(activated(int)), SLOT(vidCapFormatChanged(int)));

	addLabel("Frame Width");
	m_frameWidth = new QSpinBox(parent);
	addWidget(m_frameWidth);
	connect(m_frameWidth, SIGNAL(editingFinished()), SLOT(frameWidthChanged()));
	addLabel("Frame Height");
	m_frameHeight = new QSpinBox(parent);
	addWidget(m_frameHeight);
	connect(m_frameHeight, SIGNAL(editingFinished()), SLOT(frameHeightChanged()));

	addLabel("Frame Size");
	m_frameSize = new QComboBox(parent);
	m_frameSize->setSizeAdjustPolicy(QComboBox::AdjustToContents);
	addWidget(m_frameSize);
	connect(m_frameSize, SIGNAL(activated(int)), SLOT(frameSizeChanged(int)));

	addLabel("Frame Interval");
	m_frameInterval = new QComboBox(parent);
	m_frameInterval->setSizeAdjustPolicy(QComboBox::AdjustToContents);
	addWidget(m_frameInterval);
	connect(m_frameInterval, SIGNAL(activated(int)), SLOT(frameIntervalChanged(int)));

	updateVidCapFormat();

	if (caps() & V4L2_CAP_VIDEO_OUTPUT) {
		addLabel("Output Image Formats");
		m_vidOutFormats = new QComboBox(parent);
		if (enum_fmt_out(fmt, true)) {
			do {
				m_vidOutFormats->addItem(pixfmt2s(fmt.pixelformat) +
						" - " + (const char *)fmt.description);
			} while (enum_fmt_out(fmt));
		}
		addWidget(m_vidOutFormats);
		connect(m_vidOutFormats, SIGNAL(activated(int)), SLOT(vidOutFormatChanged(int)));
	}

	addLabel("Capture Method");
	m_capMethods = new QComboBox(parent);
	if (m_querycap.capabilities & V4L2_CAP_STREAMING) {
		v4l2_requestbuffers reqbuf;

		// Yuck. The videobuf framework does not accept a count of 0.
		// This is out-of-spec, but it means that the only way to test which
		// method is supported is to give it a non-zero count. But non-videobuf
		// drivers like uvc do not allow e.g. S_FMT calls after a REQBUFS call
		// with non-zero counts unless there is a REQBUFS call with count == 0
		// in between. This is actual proper behavior, although somewhat
		// unexpected. So the only way at the moment to do this that works
		// everywhere is to call REQBUFS with a count of 1, and then again with
		// a count of 0.
		if (reqbufs_user_cap(reqbuf, 1)) {
			m_capMethods->addItem("User pointer I/O", QVariant(methodUser));
			reqbufs_user_cap(reqbuf, 0);
		}
		if (reqbufs_mmap_cap(reqbuf, 1)) {
			m_capMethods->addItem("Memory mapped I/O", QVariant(methodMmap));
			reqbufs_mmap_cap(reqbuf, 0);
		}
	}
	if (m_querycap.capabilities & V4L2_CAP_READWRITE) {
		m_capMethods->addItem("read()", QVariant(methodRead));
	}
	addWidget(m_capMethods);

	QGridLayout::addWidget(new QWidget(parent), rowCount(), 0, 1, n);
	setRowStretch(rowCount() - 1, 1);
}
Пример #13
0
int main(int argc, char **argv) {
	unsigned pid = 0;
	int i;

	// handle CTRL-C
	signal (SIGINT, my_handler);
	signal (SIGTERM, my_handler);

	for (i = 1; i < argc; i++) {
		// default options
		if (strcmp(argv[i], "--help") == 0 ||
		    strcmp(argv[i], "-?") == 0) {
			usage();
			return 0;
		}
		else if (strcmp(argv[i], "--version") == 0) {
			printf("firemon version %s\n\n", VERSION);
			return 0;
		}
		
		// options without a pid argument
		else if (strcmp(argv[i], "--top") == 0) {
			top(); // never to return
		}
		else if (strcmp(argv[i], "--list") == 0) {
			list();
			return 0;
		}
		else if (strcmp(argv[i], "--netstats") == 0) {
			struct stat s;
			if (getuid() != 0 && stat("/proc/sys/kernel/grsecurity", &s) == 0) {
				fprintf(stderr, "Error: this feature is not available on Grsecurity systems\n");
				exit(1);
			}	

			netstats();
			return 0;
		}


		// cumulative options with or without a pid argument
		else if (strcmp(argv[i], "--x11") == 0) {
			arg_x11 = 1;
		}
		else if (strcmp(argv[i], "--cgroup") == 0) {
			arg_cgroup = 1;
		}
		else if (strcmp(argv[i], "--cpu") == 0) {
			arg_cpu = 1;
		}
		else if (strcmp(argv[i], "--seccomp") == 0) {
			arg_seccomp = 1;
		}
		else if (strcmp(argv[i], "--caps") == 0) {
			arg_caps = 1;
		}
		else if (strcmp(argv[i], "--tree") == 0) {
			arg_tree = 1;
		}
		else if (strcmp(argv[i], "--interface") == 0) {
			arg_interface = 1;
		}
		else if (strcmp(argv[i], "--route") == 0) {
			arg_route = 1;
		}
		else if (strcmp(argv[i], "--arp") == 0) {
			arg_arp = 1;
		}

		else if (strncmp(argv[i], "--name=", 7) == 0) {
			char *name = argv[i] + 7;
			if (name2pid(name, (pid_t *) &pid)) {
				fprintf(stderr, "Error: cannot find sandbox %s\n", name);
				return 1;
			}
		}
		
		// etc
		else if (strcmp(argv[i], "--nowrap") == 0)
			arg_nowrap = 1;
		
		// invalid option
		else if (*argv[i] == '-') {
			fprintf(stderr, "Error: invalid option\n");		
			return 1;
		}
		
		// PID argument
		else {
			// this should be a pid number
			char *ptr = argv[i];
			while (*ptr != '\0') {
				if (!isdigit(*ptr)) {
					fprintf(stderr, "Error: not a valid PID number\n");
					exit(1);
				}
				ptr++;
			}

			sscanf(argv[i], "%u", &pid);
			break;
		}
	}

	if (arg_tree)
		tree((pid_t) pid);
	if (arg_interface)
		interface((pid_t) pid);
	if (arg_route)
		route((pid_t) pid);
	if (arg_arp)
		arp((pid_t) pid);
	if (arg_seccomp)
		seccomp((pid_t) pid);
	if (arg_caps)
		caps((pid_t) pid);
	if (arg_cpu)
		cpu((pid_t) pid);
	if (arg_cgroup)
		cgroup((pid_t) pid);
	if (arg_x11)
		x11((pid_t) pid);
	
	if (!arg_route && !arg_arp && !arg_interface && !arg_tree && !arg_caps && !arg_seccomp && !arg_x11)
		procevent((pid_t) pid); // never to return
		
	return 0;
}
Пример #14
0
void mlayer(void)
{
   static char command[COMMANDLEN+2];
   static double undoFit[NA], undoFitUnc[NA];

   /* Process command */
      while (queryString("mlayer% ", command, COMMANDLEN + 2) == NULL);
      caps(command);

      /* Spawn a command */
      if (strcmp(command, "!") == 0 || strcmp(command, "!!") == 0) {
         bang(command);

      /* Print current directory */
      } else if (strcmp(command, "PWD") == 0) {
         puts(currentDir);

      /* Change current directory */
      } else if (strcmp(command, "CD") == 0) {
         cd(command);

      /* Help */
      } else if (strcmp(command, "?") == 0
		 || strcmp(command, "HE") == 0
		 || strcmp(command, "HELP") == 0) {
         help(command + (*command == '?' ? 1 : 2));

      /* Value of vacuum QCSQ */
      } else if (strcmp(command, "QCV") == 0 || strcmp(command, "VQC") == 0) {
         setVQCSQ(tqcsq);

      /* Value of vacuum linear absorption coefficient */
      } else if (strcmp(command, "MUV") == 0 || strcmp(command, "VMU") == 0) {
         setVMU(tmu);

      /* Wavelength */
      } else if (strcmp(command, "WL") == 0) {
	 double v = lambda;
         if (setWavelength(&lambda)==0 && lambda != v) {
	   /* May need to recalculate Q for the new wavelength */
	   if (theta_offset != 0. && loaded) loadData(infile); 
	 }

      /* Theta offset */
      } else if (strcmp(command, "TO") == 0) {
	 double v = theta_offset;
	 if (setThetaoffset(&theta_offset)==0 && theta_offset != v) {
	   /* May need to recalculate Q for the new theta offset */
	   if (loaded) loadData(infile); 
	 }

      /* Number of layers */
      } else if (
         strcmp(command, "NTL") == 0 ||
         strcmp(command, "NML") == 0 ||
         strcmp(command, "NBL") == 0
      ) switch (command[1]) {
         case 'T':
            setNLayer(&ntlayer);
            break;
         case 'M':
            setNLayer(&nmlayer);
            break;
         case 'B':
            setNLayer(&nblayer);
            break;

      /* Add or remove layers */
      } else if (
         strcmp(command, "ATL") == 0 ||
         strcmp(command, "AML") == 0 ||
         strcmp(command, "ABL") == 0 ||
         strcmp(command, "RTL") == 0 ||
         strcmp(command, "RML") == 0 ||
         strcmp(command, "RBL") == 0
      ) {
         modifyLayers(command);

      /* Copy layer */
      } else if (strcmp(command, "CL") == 0) {
         copyLayer(command);

      /* Maximum number of layers used to simulate rough interface */
      } else if (
         strcmp(command, "NR") == 0 &&
         !setNRough(&nrough)
      ) {
         /* Generate interface profile */
         if (nrough < 3) nrough = 11;
         if (*proftyp == 'H')
            gentanh(nrough, zint, rufint);
         else
            generf(nrough, zint, rufint);

      /* Specify error function or hyperbolic tangent profile */
      } else if (strcmp(command, "PR") == 0) {
         setProfile(proftyp, PROFTYPLEN + 2);

      /* Number of layers in multilayer */
      } else if (strcmp(command, "NMR") == 0) {
         setNrepeat(&nrepeat);

      /* Range of Q to be scanned */
      } else if (strcmp(command, "QL") == 0) {
         setQrange(&qmin, &qmax);

      /* Number of points scanned */
      } else if (strcmp(command, "NP") == 0) {
         setNpnts();

      /* File for input data */
      } else if (strcmp(command, "IF") == 0) {
         setFilename(infile, INFILELEN + 2);

      /* File for output data */
      } else if (strcmp(command, "OF") == 0) {
         setFilename(outfile, OUTFILELEN + 2);

      /* File for parameters */
      } else if (strcmp(command, "PF") == 0) {
         setFilename(parfile, PARFILELEN + 2);

      /* Delta lambda */
      } else if (strcmp(command, "DL") == 0) {
         setLamdel(&lamdel);

      /* Delta theta */
      } else if (strcmp(command, "DT") == 0) {
         setThedel(&thedel);

      /* Beam intensity */
      } else if (strcmp(command, "BI") == 0) {
         setBeamIntens(&bmintns, &Dbmintns);

      /* Background intensity */
      } else if (strcmp(command, "BK") == 0) {
         setBackground(&bki, &Dbki);

      /* Verify parameters by printing out */
      } else if (
         strncmp(command, "TVE", 3) == 0 ||
         strncmp(command, "MVE", 3) == 0 ||
         strncmp(command, "BVE", 3) == 0 ||
         strncmp(command, "VE", 2) == 0
      ) {
         printLayers(command);

      /* Get data from file */
      } else if (strcmp(command, "GD") == 0) {
         loadData(infile);

      /* Edit constraints */
      } else if (strcmp(command, "EC") == 0) {
         constrainFunc newmodule;

         newmodule = newConstraints(constrainScript, constrainModule);
         if (newmodule != NULL) Constrain = newmodule;

      /* Reload constrain module */
      } else if (strcmp(command, "LC") == 0) {
         Constrain = loadConstrain(constrainModule);

      /* Unload constrain module */
      } else if (strcmp(command, "ULC") == 0) {
         Constrain = loadConstrain(NULL);

      /* Load parameters from parameter file */
      } else if (strncmp(command, "LP", 2) == 0) {
         loadParms(command, &npnts, parfile, constrainScript, constrainModule);

      /* Save parameters to parameter file */
      } else if (strcmp(command, "SP") == 0) {
         parms(tqcsq, mqcsq, bqcsq, tqcmsq, mqcmsq, bqcmsq, td, md, bd,
               trough, mrough, brough, tmu, mmu, bmu,
               MAXLAY, &lambda, &lamdel, &thedel, &theta_offset,
               &ntlayer, &nmlayer, &nblayer, &nrepeat, &qmin, &qmax, &npnts,
               infile, outfile,
               &bmintns, &bki, listA, &mfit, NA, &nrough, proftyp,
               DA, constrainScript, parfile, TRUE);

      /* List data and fit */
      } else if (strcmp(command, "LID") == 0) {
         listData();

      /* Generate logarithm of bare (unconvoluted) reflectivity */
      } else if (strcmp(command, "GR") == 0 || strcmp(command, "SA") == 0) {
         genReflect(command);

      /* Generate and display layer profile used for roughness */
      } else if (strcmp(command, "GLP") == 0) {
         genProfile();

      /* Save layer profile to OUTFILE */
      } else if (
         strcmp(command, "SLP") == 0 ||
         strcmp(command, "SSP") == 0
      ) {
         saveProfile(command);

      /* Save values in XTEMP and YTEMP to OUTFILE */
      } else if (strcmp(command, "SV") == 0) {
         saveTemps(outfile);

      /* Calculate derivative of reflectivity or spin asymmetry with respect
         to a fit parameter or save a fit to disk file */
      } else if (
         strcmp(command, "RD") == 0 ||
         strcmp(command, "RSD") == 0 ||
         strcmp(command, "SRF") == 0 ||
         strcmp(command, "SRSF") == 0
      ) {
         printDerivs(command);

      /* Turn off all varied parameters */
      } else if (strcmp(command, "VANONE") == 0) {
         clearLista(listA);

      /* Specify which parameters are to be varied in the reflectivity fit */
      } else if (strncmp(command, "VA", 2) == 0) {
         varyParm(command);

      /* Calculate chi-squared */
      } else if (strcmp(command, "CSR") == 0 || strcmp(command, "CSRS") == 0) {
         printChiSq(command);

      /* Fit five-layer reflectivity */
      } else if (strncmp(command, "FR", 2) == 0) {
         register int n;

         for (n = 0; n < NA; n++) {
            undoFit[n] = A[n];
            undoFitUnc[n] = DA[n];
         }
         fitReflec(command);

      /* Undo last fit */
      } else if (strcmp(command, "UF") == 0) {
         register int n;

         for (n = 0; n < NA; n++) {
            A[n] = undoFit[n];
            DA[n] = undoFitUnc[n];
         }

      /* Exit */
      } else if (strcmp(command, "EX") == 0) {
         parms(tqcsq, mqcsq, bqcsq, tqcmsq, mqcmsq, bqcmsq, td, md, bd,
               trough, mrough, brough, tmu, mmu, bmu,
               MAXLAY, &lambda, &lamdel, &thedel, &theta_offset,
               &ntlayer, &nmlayer, &nblayer, &nrepeat, &qmin, &qmax, &npnts,
               infile, outfile,
               &bmintns, &bki, listA, &mfit, NA, &nrough, proftyp,
               DA, constrainScript, parfile, TRUE);
         exit(0);

      /* Exit without saving changes */
      } else if (strcmp(command, "QU") == 0 || strcmp(command, "QUIT") == 0) {
         exit(0);

      /***** Start new ************** */

      /* Plot reflectivity on screen */
      } else if (strncmp(command, "PRF", 3) == 0) {
         plotfit(command);

      /* Plot profile on screen */
      } else if (strcmp(command, "PLP") == 0) {
      /* Generate profile */
         plotprofile(command);

      /* Send data to other processes. */
      } else if (strcmp(command, "SEND") == 0) {
	ipc_send(command);

      /* Receive data to other processes. */
      } else if (strcmp(command, "RECV") == 0) {
	ipc_recv(command);

      /* Plot movie of reflectivity change from fit */
      } else if (strncmp(command, "MVF", 3) == 0) {
         fitMovie(command, undoFit);

      /* Plot general movie from data file on screen */
      } else if (strncmp(command, "MVX", 3) == 0) {
         arbitraryMovie(command);

      /* Plot movie of parameter on screen */
      } else if (strncmp(command, "MV", 2) == 0) {
         oneParmMovie(command);

      /* Update constraints */
      } else if (strcmp(command, "UC") == 0) {
         genshift(a, TRUE);
         /* constrain(a); */
         (*Constrain)(FALSE, a, ntlayer, nmlayer, nrepeat, nblayer);
         genshift(a, FALSE);

      /* Enter critical Q squared */
      /* or */
      /* Top length absorption coefficient */
      /* or */
      /* Thicknesses of top layers */
      /* or */
      /* Roughnesses of top layers */

      } else {
         static char *paramcom[] = {"QC", "MU", "D", "RO"};
         static double  *top[] = { tqcsq,  tmu,  td,  trough};
         static double  *mid[] = { mqcsq,  mmu,  md,  mrough};
         static double  *bot[] = { bqcsq,  bmu,  bd,  brough};
         static double *Dtop[] = {Dtqcsq, Dtmu, Dtd, Dtrough};
         static double *Dmid[] = {Dmqcsq, Dmmu, Dmd, Dmrough};
         static double *Dbot[] = {Dbqcsq, Dbmu, Dbd, Dbrough};
         static int (*store[])(int, double *, double *) = {
            setQCSQ, setMU, setD, setRO
         };
         int param, code = -1;

         for (param = 0; param < sizeof(paramcom) / sizeof(paramcom[0]); param++) {
            code = fetchLayParam(command, paramcom[param], top[param],
               mid[param], bot[param], Dtop[param], Dmid[param], Dbot[param],
               store[param]);
            if (code > -1) break;
         }
         if (code == -1)
            ERROR("/** Unrecognized command: %s **/\n", command);
      }
}
Пример #15
0
nsresult
EMEH264Decoder::GmpInput(MP4Sample* aSample)
{
  MOZ_ASSERT(IsOnGMPThread());

  nsAutoPtr<MP4Sample> sample(aSample);
  if (!mGMP) {
    mCallback->Error();
    return NS_ERROR_FAILURE;
  }

  if (sample->crypto.valid) {
    CDMCaps::AutoLock caps(mProxy->Capabilites());
    MOZ_ASSERT(caps.CanDecryptAndDecodeVideo());
    const auto& keyid = sample->crypto.key;
    if (!caps.IsKeyUsable(keyid)) {
      nsRefPtr<nsIRunnable> task(new DeliverSample(this, sample.forget()));
      caps.CallWhenKeyUsable(keyid, task, mGMPThread);
      return NS_OK;
    }
  }


  mLastStreamOffset = sample->byte_offset;

  GMPVideoFrame* ftmp = nullptr;
  GMPErr err = mHost->CreateFrame(kGMPEncodedVideoFrame, &ftmp);
  if (GMP_FAILED(err)) {
    mCallback->Error();
    return NS_ERROR_FAILURE;
  }

  gmp::GMPVideoEncodedFrameImpl* frame = static_cast<gmp::GMPVideoEncodedFrameImpl*>(ftmp);
  err = frame->CreateEmptyFrame(sample->size);
  if (GMP_FAILED(err)) {
    mCallback->Error();
    return NS_ERROR_FAILURE;
  }

  memcpy(frame->Buffer(), sample->data, frame->Size());

  frame->SetEncodedWidth(mConfig.display_width);
  frame->SetEncodedHeight(mConfig.display_height);
  frame->SetTimeStamp(sample->composition_timestamp);
  frame->SetCompleteFrame(true);
  frame->SetDuration(sample->duration);
  if (sample->crypto.valid) {
    frame->InitCrypto(sample->crypto);
  }
  frame->SetFrameType(sample->is_sync_point ? kGMPKeyFrame : kGMPDeltaFrame);
  frame->SetBufferType(GMP_BufferLength32);

  nsTArray<uint8_t> info; // No codec specific per-frame info to pass.
  nsresult rv = mGMP->Decode(frame, false, info, 0);
  if (NS_FAILED(rv)) {
    mCallback->Error();
    return rv;
  }

  return NS_OK;
}
Пример #16
0
bool AudioDeviceElement::setState(AkElement::ElementState state)
{
    AkElement::ElementState curState = this->state();

    switch (curState) {
    case AkElement::ElementStateNull: {
        switch (state) {
        case AkElement::ElementStatePaused: {
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = true;
                this->m_readFramesLoop = true;
                this->m_readFramesLoopResult = QtConcurrent::run(&this->m_threadPool,
                                                                 this->readFramesLoop,
                                                                 this);
            }

            return AkElement::setState(state);
        }
        case AkElement::ElementStatePlaying: {
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = false;
                this->m_readFramesLoop = true;
                this->m_readFramesLoopResult = QtConcurrent::run(&this->m_threadPool,
                                                                 this->readFramesLoop,
                                                                 this);
            } else if (this->m_device != DUMMY_OUTPUT_DEVICE
                       && this->m_outputs.contains(this->m_device)) {
                QString device = this->m_device;
                AkAudioCaps caps(this->m_caps);
                this->m_mutex.lock();
                this->m_convert->setProperty("caps", caps.toString());
                this->m_mutex.unlock();

                this->m_mutexLib.lock();
                auto isInit = this->m_audioDevice->init(device, caps);
                this->m_mutexLib.unlock();

                if (!isInit)
                    return false;
            }

            return AkElement::setState(state);
        }
        case AkElement::ElementStateNull:
            break;
        }

        break;
    }
    case AkElement::ElementStatePaused: {
        switch (state) {
        case AkElement::ElementStateNull:
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = false;
                this->m_readFramesLoop = false;
                this->m_readFramesLoopResult.waitForFinished();
            } else if (this->m_device != DUMMY_OUTPUT_DEVICE
                       && this->m_outputs.contains(this->m_device)) {
                this->m_mutexLib.lock();
                this->m_audioDevice->uninit();
                this->m_mutexLib.unlock();
            }

            return AkElement::setState(state);
        case AkElement::ElementStatePlaying:
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = false;
            } else if (this->m_device != DUMMY_OUTPUT_DEVICE
                       && this->m_outputs.contains(this->m_device)) {
                QString device = this->m_device;
                AkAudioCaps caps(this->m_caps);
                this->m_mutex.lock();
                this->m_convert->setProperty("caps", caps.toString());
                this->m_mutex.unlock();

                this->m_mutexLib.lock();
                auto isInit = this->m_audioDevice->init(device, caps);
                this->m_mutexLib.unlock();

                if (!isInit)
                    return false;
            }

            return AkElement::setState(state);
        case AkElement::ElementStatePaused:
            break;
        }

        break;
    }
    case AkElement::ElementStatePlaying: {
        switch (state) {
        case AkElement::ElementStateNull:
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = false;
                this->m_readFramesLoop = false;
                this->m_readFramesLoopResult.waitForFinished();
            } else if (this->m_device != DUMMY_OUTPUT_DEVICE
                       && this->m_outputs.contains(this->m_device)) {
                this->m_mutexLib.lock();
                this->m_audioDevice->uninit();
                this->m_mutexLib.unlock();
            }

            return AkElement::setState(state);
        case AkElement::ElementStatePaused:
            if (this->m_inputs.contains(this->m_device)) {
                this->m_pause = true;
            } else if (this->m_device != DUMMY_OUTPUT_DEVICE
                       && this->m_outputs.contains(this->m_device)) {
                this->m_mutexLib.lock();
                this->m_audioDevice->uninit();
                this->m_mutexLib.unlock();
            }

            return AkElement::setState(state);
        case AkElement::ElementStatePlaying:
            break;
        }

        break;
    }
    }

    return false;
}
Пример #17
0
void magblocks4(void)
{
   static char command[COMMANDLEN + 2];
   static double undoFit[NA], undoFitUnc[NA];
   int npnts, j;
   double qmax, qmin;

   /* Process command */
      while (queryString("magblocks4% ", command, COMMANDLEN + 2) == NULL);
      caps(command);

      /* Spawn a command */
      if (strcmp(command, "!") == 0 || strcmp(command, "!!") == 0) {
        bang(command);

      /* Print current directory */
      } else if (strcmp(command, "PWD") == 0) {
         puts(currentDir);

      /* Change current directory */
      } else if (strcmp(command, "CD") == 0) {
         cd(command);
         
      /* Help */
      } else if (
         strcmp(command, "?") == 0 ||
         strcmp(command, "HE") == 0
      ) {
         help(command + (*command == '?' ? 1 : 2));

      /* Value of vacuum QCSQ */
      } else if (
         strcmp(command, "QCV") == 0 ||
         strcmp(command, "VQC") == 0
      ) {
         setVQCSQ(qcsq);

      /* Vacuum QCMSQ */
      } else if (
         strcmp(command, "QMV") == 0 ||
         strcmp(command, "VQM") == 0
      ) {
         setVMQCSQ(qcmsq);

      /* Value of vacuum linear absorption coefficient */
      } else if (
         strcmp(command, "MUV") == 0 ||
         strcmp(command, "VMU") == 0
      ) {
         setVMU(mu);

      /* Enter critical Q squared */
      } else if (strncmp(command, "QC", 2) == 0) {
         setQCSQ(command + 2, qcsq, Dqcsq);

      /* Top magnetic critical Q squared */
      } else if (strncmp(command, "QM", 2) == 0) {
         setMQCSQ(command + 2, qcmsq, Dqcmsq);

      /* Top length absorption coefficient */
      } else if (strncmp(command, "MU", 2) == 0) {
         setMU(command + 2, mu, Dmu);

      /* Thicknesses of magnetic layers */
      } else if (strncmp(command, "DM", 2) == 0) {
         setDM(command + 2, dm, Ddm);

      /* Delta lambda */
      } else if (strcmp(command, "DL") == 0) {
         setLamdel(&lamdel);

      /* Delta theta */
      } else if (strcmp(command, "DT") == 0) {
         setThedel(&thedel);

      /* Enter chemical thickness */
      } else if (command[0] == 'D') {
         setD(command + 1, d, Dd);

      /* Chemical roughnesses */
      } else if (strncmp(command, "RO", 2) == 0) {
         setRO(command + 2, rough, Drough);

      /* Magnetic roughnesses of layers */
      } else if (strncmp(command, "RM", 2) == 0) {
         setMRO(command + 2, mrough, Dmrough);

      /* Theta angle of average moment in layer */
      } else if (strncmp(command, "TH", 2) == 0) {
         setTHE(command + 2, the, Dthe);

      /* Wavelength */
      } else if (strcmp(command, "WL") == 0) {
         setWavelength(&lambda);

      /* Guide angle */
      } else if (strcmp(command, "EPS") == 0) {
         setGuideangle(&aguide);

      /* Number of layers */
      } else if (strcmp(command, "NL") == 0) {
         if (!setNlayer(&nlayer))
         /* Bug found Wed Jun  7 10:38:45 EDT 2000 by KOD */
         /* since it starts at 0, correction for vacuum forces zero */
         for (j = 1; j <= nlayer; j++)
            /* Set all absorptions to non-zero values */
            if (mu[j] < *mu) mu[j] = *mu + 1.e-20;

      /* Add or remove layers */
      } else if (strcmp(command, "AL") == 0 || strcmp(command, "RL") == 0) {
         modifyLayers(command);

      /* Copy layer */
      } else if (strcmp(command, "CL") == 0) {
         copyLayer(command);

      /* Make superlattice */
      } else if (strcmp(command, "SL") == 0) {
         superLayer(command);

      /* Maximum number of layers used to simulate rough interface */
      } else if (strcmp(command, "NR") == 0) {
         if (!setNrough(&nrough)) {
            /* Generate interface profile */
            if (nrough < 3) nrough = 11;
            if (proftyp[0] == 'H')
               gentanh(nrough, zint, rufint);
            else
               generf(nrough, zint, rufint);
         }

      /* Specify error function or hyperbolic tangent profile */
      } else if (strcmp(command, "PR") == 0) {
         setProfile(proftyp, PROFTYPLEN + 2);

      /* Range of Q to be scanned */
      } else if (strcmp(command, "QL") == 0) {
         if (!setQrange(&qmin, &qmax)) {
            qmina = qmin;
            qmaxa = qmax;
            qminb = qmin;
            qmaxb = qmax;
            qminc = qmin;
            qmaxc = qmax;
            qmind = qmin;
            qmaxd = qmax;
         }

      /* Number of points scanned */
      } else if (strcmp(command, "NP") == 0) {
         if (!setNpnts(&npnts)) {
            npntsa = npnts;
            npntsb = npnts;
            npntsc = npnts;
            npntsd = npnts;
         }

      /* File for input data */
      } else if (strcmp(command, "IF") == 0) {
         setFilename(infile, INFILELEN + 2);

      /* File for output data */
      } else if (strcmp(command, "OF") == 0) {
         setFilename(outfile, OUTFILELEN + 2);

      /* File for parameters */
      } else if (strcmp(command, "PF") == 0) {
         setFilename(parfile, PARFILELEN + 2);

      /* Polarization state */
      } else if (strcmp(command, "PS") == 0) {
         setPolstat(polstat, POLSTATLEN + 2);

      /* Beam intensity */
      } else if (strcmp(command, "BI") == 0) {
         setBeamIntens(&bmintns, &Dbmintns);

      /* Background intensity */
      } else if (strcmp(command, "BK") == 0) {
         setBackground(&bki, &Dbki);

      /* Verify parameters by printing out */
      } else if (strncmp(command, "VE", 2) == 0) {
         printLayers(command);

      /* Get data from file */
      } else if (strcmp(command, "GD") == 0) {
         loadData(infile, xspin);

      /* Edit constraints */
      } else if (strcmp(command, "EC") == 0) {
         constrainFunc newmodule;

         newmodule = newConstraints(constrainScript, constrainModule);
         if (newmodule != NULL) Constrain = newmodule;

      /* Reload constrain module */
      } else if (strcmp(command, "LC") == 0) {
         Constrain = loadConstrain(constrainModule);

      /* Unload constrain module */
      } else if (strcmp(command, "ULC") == 0) {
         Constrain = loadConstrain(NULL);

      /* Load parameters from parameter file */
      } else if (strncmp(command, "LP", 2) == 0) {
         loadParms(command, parfile, constrainScript, constrainModule);

      /* Save parameters to parameter file */
      } else if (strcmp(command, "SP") == 0) {
         parms(qcsq, qcmsq, d, dm, rough, mrough, mu, the,
               MAXLAY, &lambda, &lamdel, &thedel, &aguide,
              &nlayer, &qmina, &qmaxa, &npntsa,
              &qminb, &qmaxb, &npntsb, &qminc, &qmaxc, &npntsc,
              &qmind, &qmaxd, &npntsd,
               infile, outfile,
              &bmintns, &bki, listA, &mfit, NA, &nrough, proftyp,
               polstat, DA, constrainScript, parfile, TRUE);

      /* List data and fit */
      } else if (strcmp(command, "LID") == 0) {
         listData();

      /* Generate logarithm of bare (unconvoluted) reflectivity */
      /* or generate reflected amplitude */
      } else if (strcmp(command,"GR") == 0 || strcmp(command, "GA") == 0) {
         genReflect(command);

      /* Generate and display layer profile */
      } else if (
         strcmp(command, "GLP") == 0 ||
         strncmp(command, "SLP", 3) == 0
      ) {
         genProfile(command);

      /* Save values in Q4X and YFIT to OUTFILE */
      } else if (strcmp(command, "SV") == 0) {
         saveTemps(outfile, xspin, y4x, n4x, FALSE);

      /* Save values in Q4X and YFITA to OUTFILE */
      } else if (strcmp(command, "SVA") == 0) {
         saveTemps(outfile, xspin, yfita, n4x, TRUE);

      /* Calculate derivative of reflectivity or spin asymmetry with respect */
      /* to a fit parameter or save a fit to disk file */
      } else if (
         strcmp(command, "RD") == 0 ||
         strcmp(command, "SRF") == 0
      ) {
         printDerivs(command, npnts);

      /* Turn off all varied parameters */
      } else if (strcmp(command, "VANONE") == 0) {
         clearLista(listA);

      /* Specify which parameters are to be varied in the reflectivity fit */
      } else if (strncmp(command, "VA", 2) == 0) {
         varyParm(command);

      /* Calculate chi-squared */
      } else if (
         strcmp(command, "CSR") == 0 ||
         strcmp(command, "CS") == 0
      ) {
         calcChiSq(command);

      /* Fit reflectivity */
      } else if (strncmp(command, "FR", 2) == 0) {
         for (j = 0; j < NA; j++) {
            undoFit[j] = A[j];
            undoFitUnc[j] = DA[j];
         }
         fitReflec(command);

      /* Undo last fit */
      } else if (strcmp(command, "UF") == 0) {
         for (j = 0; j < NA; j++) {
            A[j] = undoFit[j];
            DA[j] = undoFitUnc[j];
         }

      /* Exit */
      } else if (
         strcmp(command, "EX") == 0 ||
         strcmp(command, "EXS") == 0
      ) {
         parms(qcsq, qcmsq, d, dm, rough, mrough, mu, the,
               MAXLAY, &lambda, &lamdel, &thedel, &aguide,
              &nlayer, &qmina, &qmaxa, &npntsa,
              &qminb, &qmaxb, &npntsb, &qminc, &qmaxc, &npntsc,
              &qmind, &qmaxd, &npntsd,
               infile, outfile,
              &bmintns, &bki, listA, &mfit, NA, &nrough, proftyp,
               polstat, DA, constrainScript, parfile, TRUE);
         /* Print elapsed CPU time */
         if (strcmp(command, "EXS") == 0) system("ps");
         exit(0);

      /* Exit without saving changes */
      } else if (strcmp(command, "QU") == 0 || strcmp(command, "QUIT") == 0) {
         exit(0);

      /* Plot reflectivity on screen */
      } else if (strncmp(command, "PRF", 3) == 0) {
         plotfit(command, xspin);

      /* Plot profile on screen */
      } else if (strncmp(command, "PLP", 3) == 0) {
         plotprofile(command, xspin);

      /* Plot movie of reflectivity change from fit */
      } else if (strncmp(command, "MVF", 3) == 0) {
         fitMovie(command, xspin, undoFit);

      /* Plot general movie from data file on screen */
      } else if (strncmp(command, "MVX", 3) == 0) {
         arbitraryMovie(command, xspin);

      /* Plot movie of parameter on screen */
      } else if (strncmp(command, "MV", 2) == 0) {
         oneParmMovie(command, xspin);

      /* Update constraints */
      } else if (strcmp(command, "UC") == 0) {
         genshift(a, TRUE);
         /* constrain(a); */
         (*Constrain)(FALSE, a, nlayer);
         genshift(a, FALSE);

      /* Determine number of points required for resolution extension */
      } else if (strcmp(command, "RE") == 0) {
         calcExtend(xspin);

#if 0 /* Dead code --- shadowed by "CD" command earlier */
      /* Convolute input raw data set with instrumental resolution */
      } else if (strcmp(command, "CD") == 0) {
         calcConvolve(polstat);
#endif

      /* Send data to other processes. */
      } else if (strcmp(command, "SEND") == 0) {
	ipc_send(command);

      /* Receive data to other processes. */
      } else if (strcmp(command, "RECV") == 0) {
	ipc_recv(command);

      /* Faulty input */
      } else
         ERROR("/** Unrecognized command **/");
}
Пример #18
0
std::vector<symbol> connection::desired_capabilities() const {
    value caps(pn_connection_remote_desired_capabilities(pn_object()));
    return get_multiple<std::vector<symbol> >(caps);
}
Пример #19
0
static void ir_parseline2(ir_parseline_t *ipl)
{
  channel_t *ch;
  char *nick;
  char *part3a;
  char *t;
  unsigned int i;

  caps(ipl->part[1]);

  /* NOTICE nick */
  if (!strcmp(ipl->part[1], "NOTICE")) {
    if (gnetwork->caps_nick && ipl->part[2]) {
      if (!strcmp(caps(ipl->part[2]), gnetwork->caps_nick)) {
        /* nickserv */
        identify_check(ipl->line);
#ifdef USE_RUBY
        if (do_myruby_notice(ipl->line) == 0)
#endif /* USE_RUBY */
          privmsgparse(0, 0, ipl->line);
      }
    }
  }

  /* PRIVMSG */
  if (!strcmp(ipl->part[1], "PRIVMSG")) {
#ifndef WITHOUT_BLOWFISH
    char *line2;

    line2 = test_fish_message(ipl->line, ipl->part[2], ipl->part[3], ipl->part[4]);
    if (line2) {
#ifdef USE_RUBY
      if (do_myruby_privmsg(line2) == 0)
#endif /* USE_RUBY */
        privmsgparse(1, 1, line2);
      mydelete(line2);
    } else {
#endif /* WITHOUT_BLOWFISH */
#ifdef USE_RUBY
      if (do_myruby_privmsg(ipl->line) == 0)
#endif /* USE_RUBY */
        privmsgparse(1, 0, ipl->line);
#ifndef WITHOUT_BLOWFISH
    }
#endif /* WITHOUT_BLOWFISH */
  }

  /* :server 001  xxxx :welcome.... */
  if ( !strcmp(ipl->part[1], "001") ) {
    irc_001(ipl);
    return;
  }

  /* :server 005 xxxx aaa bbb=x ccc=y :are supported... */
  if ( !strcmp(ipl->part[1], "005") ) {
    irc_005(ipl);
    return;
  }

  /* :server 401 botnick usernick :No such nick/channel */
  if ( !strcmp(ipl->part[1], "401") ) {
    if (ipl->part[2] && ipl->part[3]) {
      if (!strcmp(ipl->part[2], "*")) {
        lost_nick(ipl->part[3]);
      }
    }
    return;
  }

  /* :server 433 old new :Nickname is already in use. */
  if ( !strcmp(ipl->part[1], "433") ) {
    if (ipl->part[2] && ipl->part[3]) {
      if (!strcmp(ipl->part[2], "*")) {
        ioutput(OUT_S|OUT_L, COLOR_NO_COLOR,
                "Nickname %s already in use on %s, trying %s%u",
                ipl->part[3],
                gnetwork->name,
                get_config_nick(),
                gnetwork->nick_number);

        /* generate new nick and retry */
        writeserver(WRITESERVER_NORMAL, "NICK %s%u",
                    get_config_nick(),
                    (gnetwork->nick_number)++);
      }
    }
    return;
  }

  /* :server 470 botnick #channel :(you are banned) transfering you to #newchannel */
  if ( !strcmp(ipl->part[1], "470") ) {
    if (ipl->part[2] && ipl->part[3]) {
      outerror(OUTERROR_TYPE_WARN_LOUD,
               "channel on %s: %s", gnetwork->name, strstr(ipl->line, "470"));
      for (ch = irlist_get_head(&(gnetwork->channels));
           ch;
           ch = irlist_get_next(ch)) {
        if (strcmp(caps(ipl->part[2]), gnetwork->caps_nick))
             continue;
        if (strcmp(caps(ipl->part[3]), ch->name))
             continue;
        ch->flags |= CHAN_KICKED;
      }
    }
    return;
  }

  /* names list for a channel */
  /* :server 353 our_nick = #channel :nick @nick +nick nick */
  if ( !strcmp(ipl->part[1], "353") ) {
    if (ipl->part[2] && ipl->part[3] && ipl->part[5]) {
      caps(ipl->part[4]);

      for (ch = irlist_get_head(&(gnetwork->channels));
           ch;
           ch = irlist_get_next(ch)) {
        if (strcmp(ipl->part[4], ch->name) != 0)
          continue;
        for (i=0; (t = getpart(ipl->line, 6+i)); ++i) {
          addtomemberlist(ch, i == 0 ? t+1 : t);
          mydelete(t);
        }
        return;
      }
      ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR,
              "Got name data for %s which is not a known channel on %s!",
              ipl->part[4], gnetwork->name);
      writeserver(WRITESERVER_NORMAL, "PART %s", ipl->part[4]);
    }
    return;
  }

  if (gnetwork->lastping != 0) {
    if (strcmp(ipl->part[1], "PONG") == 0) {
      lag_message();
      return;
    }
  }

#if PING_SRVR
  /* server ping */
  if (strncmp(ipl->line, "PING :", 6) == 0) {
    if (gdata.debug > 0)
      ioutput(OUT_S, COLOR_NO_COLOR,
              "Server Ping on %s: %s",
              gnetwork->name, ipl->line);
    writeserver(WRITESERVER_NOW, "PO%s", ipl->line+2);
    return;
  }
#endif

  /* QUIT */
  if (strcmp(ipl->part[1], "QUIT") == 0) {
    if (gnetwork->caps_nick) {
      nick = ir_get_nickarg(ipl->line);
      if (!strcmp(caps(nick), gnetwork->caps_nick)) {
        /* we quit? */
        outerror(OUTERROR_TYPE_WARN_LOUD,
                 "Forced quit on %s: %s", gnetwork->name, ipl->line);
        close_server();
        clean_send_buffers();
        /* do not reconnect */
        gnetwork->serverstatus = SERVERSTATUS_EXIT;
      } else {
        /* someone else quit */
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          removefrommemberlist(ch, nick);
        }
        reverify_restrictsend();
      }
      mydelete(nick);
    }
    return;
  }

  /* MODE #channel +x ... */
  if (strcmp(ipl->part[1], "MODE") == 0) {
    if (ipl->part[2] && ipl->part[3]) {
      /* find channel */
      for (ch = irlist_get_head(&(gnetwork->channels)); ch; ch = irlist_get_next(ch)) {
        char *ptr;
        unsigned int plus;
        unsigned int part;
        unsigned int ii;

        if (strcasecmp(ch->name, ipl->part[2]) != 0)
          continue;

        plus = 0;
        part = 4;
        for (ptr = ipl->part[3]; *ptr; ++ptr) {
          if (*ptr == '+') {
            plus = 1;
          } else if (*ptr == '-') {
            plus = 0;
          } else {
            for (ii = 0; (ii < MAX_PREFIX && gnetwork->prefixes[ii].p_mode); ++ii) {
              if (*ptr == gnetwork->prefixes[ii].p_mode) {
                /* found a nick mode */
                nick = getpart(ipl->line, ++part);
                if (nick) {
                  if (nick[strlen(nick)-1] == IRCCTCP) {
                    nick[strlen(nick)-1] = '\0';
                  }
                  if (plus == 0) {
                    if (strcasecmp(nick, get_config_nick()) == 0) {
                      identify_needed(0);
                    }
                  }
                  changeinmemberlist_mode(ch, nick,
                                          gnetwork->prefixes[ii].p_symbol,
                                          plus);
                  mydelete(nick);
                }
                break;
              }
            }
            for (ii = 0; (ii < MAX_CHANMODES && gnetwork->chanmodes[ii]); ++ii) {
              if (*ptr == gnetwork->chanmodes[ii]) {
                /* found a channel mode that has an argument */
                ++part;
                break;
              }
            }
          }
        }
        return;
      }
      if (strcasecmp(ipl->part[2], get_config_nick()) == 0) {
        if (ipl->part[3][0] == '-') {
          identify_needed(0);
        }
      }
    }
    return;
  }

  if (ipl->part[2] && ipl->part[2][0] == ':') {
    part3a = ipl->part[2] + 1;
  } else {
    part3a = ipl->part[2];
  }

  /* JOIN */
  if (strcmp(ipl->part[1], "JOIN") == 0) {
    if (gnetwork->caps_nick && part3a) {
      caps(part3a);
      nick = ir_get_nickarg(ipl->line);
      if (!strcmp(caps(nick), gnetwork->caps_nick)) {
        /* we joined */
        /* clear now, we have succesfully logged in */
        gnetwork->serverconnectbackoff = 0;
        ioutput(OUT_S|OUT_L|OUT_D, COLOR_NO_COLOR,
                "Joined %s on %s", part3a, gnetwork->name);

        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          if (strcmp(part3a, ch->name) != 0)
            continue;

          ch->flags |= CHAN_ONCHAN;
          ch->lastjoin = gdata.curtime;
          ch->nextann = gdata.curtime + gdata.waitafterjoin;
          ch->nextmsg = gdata.curtime + gdata.waitafterjoin;
          if (ch->joinmsg) {
            writeserver(WRITESERVER_NOW, "PRIVMSG %s :%s", ch->name, ch->joinmsg);
          }
          gnetwork->botstatus = BOTSTATUS_JOINED;
          start_sends();
          mydelete(nick);
          return;
        }
      } else {
        /* someone else joined */
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          if (strcmp(part3a, ch->name) != 0)
            continue;

          addtomemberlist(ch, nick);
          mydelete(nick);
          return;
        }
      }
      ir_unknown_channel(part3a);
      mydelete(nick);
    }
    return;
  }

  /* PART */
  if (strcmp(ipl->part[1], "PART") == 0) {
    if (gnetwork->caps_nick && part3a) {
      nick = ir_get_nickarg(ipl->line);
      if (!strcmp(caps(nick), gnetwork->caps_nick)) {
        /* we left? */
        mydelete(nick);
        return;
      } else {
        /* someone else left */
        caps(part3a);
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          if (strcmp(part3a, ch->name) != 0)
            continue;

          removefrommemberlist(ch, nick);
          mydelete(nick);
          reverify_restrictsend();
          return;
        }
      }
      ir_unknown_channel(part3a);
      mydelete(nick);
    }
    return;
  }

  /* NICK */
  if (strcmp(ipl->part[1], "NICK") == 0) {
    if (gnetwork->caps_nick && part3a) {
      nick = ir_get_nickarg(ipl->line);
      if (!strcmp(caps(nick), gnetwork->caps_nick)) {
        /* we changed, update nick */
        mydelete(gnetwork->user_nick);
        mydelete(gnetwork->caps_nick);
        gnetwork->user_nick = mystrdup(part3a);
        gnetwork->caps_nick = mystrdup(part3a);
        caps(gnetwork->caps_nick);
        gnetwork->nick_number = 0;
        ++(gdata.needsclear);
        identify_needed(0);
      } else {
        /* someone else has a new nick */
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          changeinmemberlist_nick(ch, nick, part3a);
        }
        user_changed_nick(nick, part3a);
      }
      mydelete(nick);
    }
    return;
  }

  /* KICK */
  if (strcmp(ipl->part[1], "KICK") == 0) {
    if (gnetwork->caps_nick && part3a && ipl->part[3]) {
      caps(part3a);
      if (!strcmp(caps(ipl->part[3]), gnetwork->caps_nick)) {
        /* we were kicked */
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          if (strcmp(part3a, ch->name) != 0)
            continue;

          if (gdata.noautorejoin) {
            outerror(OUTERROR_TYPE_WARN_LOUD,
                     "Kicked on %s: %s", gnetwork->name, ipl->line);
            ch->flags |= CHAN_KICKED;
            clearmemberlist(ch);
            reverify_restrictsend();
          } else {
            outerror(OUTERROR_TYPE_WARN_LOUD,
                     "Kicked on %s, Rejoining: %s", gnetwork->name, ipl->line);
            ch->flags &= ~CHAN_ONCHAN;
            joinchannel(ch);
          }
        }
      } else {
        /* someone else was kicked */
        for (ch = irlist_get_head(&(gnetwork->channels));
             ch;
             ch = irlist_get_next(ch)) {
          if (strcmp(part3a, ch->name) != 0)
            continue;

          removefrommemberlist(ch, ipl->part[3]);
          reverify_restrictsend();
          return;
        }
      }
    }
    return;
  }

  /* ERROR :Closing Link */
  if (strncmp(ipl->line, "ERROR :Closing Link", strlen("ERROR :Closing Link")) == 0) {
    if (gdata.exiting) {
      gnetwork->recentsent = 0;
      return;
    }
    ioutput(OUT_S|OUT_L|OUT_D, COLOR_RED,
            "Server Closed Connection on %s: %s",
            gnetwork->name, ipl->line);
    close_server();
    return;
  }
}
Пример #20
0
void parsedccchat(dccchat_t *chat,
                  char* line)
{
  char *linec;
  userinput ui;
  unsigned int count;
  unsigned int found;
  
  updatecontext();
  
  linec = mystrdup(line);
  caps(linec);
  
  chat->con.lastcontact = gdata.curtime;
  
  switch (chat->status)
    {
    case DCCCHAT_AUTHENTICATING:
      found = dcc_host_password(chat, line);
      if (found == 1)
        {
          ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
                  "DCC CHAT Correct password");
          
          chat->status = DCCCHAT_CONNECTED;
          
          writedccchat(chat,0," \n");
          writedccchat(chat,0,"Entering DCC Chat Admin Interface\n");
          writedccchat(chat,0,"For Help type \"help\"\n");
          
          if (chat->level >= ADMIN_LEVEL_FULL)
            {
          count = irlist_size(&gdata.msglog);
          writedccchat(chat, 0, "** You have %u %s in the message log%s\n",
                       count,
                       count != 1 ? "messages" : "message",
                       count ? ", use MSGREAD to read them" : "");
          writedccchat(chat,0," \n");
            }
        }
      else
        {
          ioutput(OUT_S|OUT_L|OUT_D, COLOR_MAGENTA,
                  "DCC CHAT: Incorrect password");
          
          writedccchat(chat,0,"Incorrect Password\n");
          count_badip(&(chat->con.remote));
          shutdowndccchat(chat,1);
          /* caller deletes */
        }
      break;
      
    case DCCCHAT_CONNECTED:
      if (gdata.debug > 11)
        {
          ioutput(OUT_S, COLOR_CYAN, ">DCC>: %s", line);
        }
      u_fillwith_dcc(&ui,chat,line);
      u_parseit(&ui);
      break;
      
    case DCCCHAT_UNUSED:
    case DCCCHAT_LISTENING:
    case DCCCHAT_CONNECTING:
    default:
      outerror(OUTERROR_TYPE_WARN_LOUD,
               "Unexpected dccchat state %u", chat->status);
      break;
    }
  
  mydelete(linec);
}
Пример #21
0
void QLCChannel_Test::copy()
{
    QLCChannel* channel = new QLCChannel();
    QVERIFY(channel->capabilities().size() == 0);

    channel->setName("Foobar");
    channel->setGroup(QLCChannel::Tilt);
    channel->setControlByte(QLCChannel::ControlByte(3));
    channel->setColour(QLCChannel::Yellow);

    QLCCapability* cap1 = new QLCCapability(10, 19, "10-19");
    QVERIFY(channel->addCapability(cap1) == true);

    QLCCapability* cap2 = new QLCCapability(50, 59, "50-59");
    QVERIFY(channel->addCapability(cap2) == true);

    QLCCapability* cap3 = new QLCCapability(40, 49, "40-49");
    QVERIFY(channel->addCapability(cap3) == true);

    QLCCapability* cap4 = new QLCCapability(0, 9, "0-9");
    QVERIFY(channel->addCapability(cap4) == true);

    QLCCapability* cap5 = new QLCCapability(200, 209, "200-209");
    QVERIFY(channel->addCapability(cap5) == true);

    QLCCapability* cap6 = new QLCCapability(30, 39, "30-39");
    QVERIFY(channel->addCapability(cap6) == true);

    QLCCapability* cap7 = new QLCCapability(26, 29, "26-29");
    QVERIFY(channel->addCapability(cap7) == true);

    QLCCapability* cap8 = new QLCCapability(20, 25, "20-25");
    QVERIFY(channel->addCapability(cap8) == true);

    /* Create a copy of the original channel */
    QLCChannel* copy = new QLCChannel(channel);

    QVERIFY(copy->name() == "Foobar");
    QVERIFY(copy->group() == QLCChannel::Tilt);
    QVERIFY(copy->controlByte() == QLCChannel::ControlByte(3));
    QVERIFY(copy->colour() == QLCChannel::Yellow);

    /* Verify that the capabilities in the copied channel are also
       copies i.e. their pointers are not the same as the originals. */
    QList <QLCCapability*> caps(copy->capabilities());
    QVERIFY(caps.size() == 8);
    QVERIFY(caps.at(0) != cap1);
    QVERIFY(caps.at(0)->name() == cap1->name());
    QVERIFY(caps.at(0)->min() == cap1->min());
    QVERIFY(caps.at(0)->max() == cap1->max());

    QVERIFY(caps.at(1) != cap2);
    QVERIFY(caps.at(1)->name() == cap2->name());
    QVERIFY(caps.at(1)->min() == cap2->min());
    QVERIFY(caps.at(1)->max() == cap2->max());

    QVERIFY(caps.at(2) != cap3);
    QVERIFY(caps.at(2)->name() == cap3->name());
    QVERIFY(caps.at(2)->min() == cap3->min());
    QVERIFY(caps.at(2)->max() == cap3->max());

    QVERIFY(caps.at(3) != cap4);
    QVERIFY(caps.at(3)->name() == cap4->name());
    QVERIFY(caps.at(3)->min() == cap4->min());
    QVERIFY(caps.at(3)->max() == cap4->max());

    QVERIFY(caps.at(4) != cap5);
    QVERIFY(caps.at(4)->name() == cap5->name());
    QVERIFY(caps.at(4)->min() == cap5->min());
    QVERIFY(caps.at(4)->max() == cap5->max());

    QVERIFY(caps.at(5) != cap6);
    QVERIFY(caps.at(5)->name() == cap6->name());
    QVERIFY(caps.at(5)->min() == cap6->min());
    QVERIFY(caps.at(5)->max() == cap6->max());

    QVERIFY(caps.at(6) != cap7);
    QVERIFY(caps.at(6)->name() == cap7->name());
    QVERIFY(caps.at(6)->min() == cap7->min());
    QVERIFY(caps.at(6)->max() == cap7->max());

    QVERIFY(caps.at(7) != cap8);
    QVERIFY(caps.at(7)->name() == cap8->name());
    QVERIFY(caps.at(7)->min() == cap8->min());
    QVERIFY(caps.at(7)->max() == cap8->max());
}
Пример #22
0
void
putref(int n, char **tvec)
{
	char *s, *tx;
	char buf1[BUFSIZ], buf2[50];
	int nauth = 0, i, lastype = 0, cch, macro = 0, la;
	int lauth = 0, ltitle = 0, lother = 0;

	fprintf(fo, ".]-%c", sep);
	for (i = 0; i < n; i++) {
		s = tvec[i];
		if (*s == 0)
			continue;
		if (control(s[0])) {
			if (lastype && macro)
				fprintf(fo, "..%c", sep);
			if (control(s[1])) {
				cch = s[2];
				tx = s+3;
				macro = 1;
			}
			else {
				cch = s[1];
				tx = s+2;
				macro = 0;
			}
		}
		else {
			cch = lastype;
			tx = s;
		}
#if EBUG
		fprintf(stderr, "smallcaps %s cch %c\n",smallcaps, cch);
#endif
		if (mindex(smallcaps, cch))
			tx = caps(tx, buf1);
#if EBUG
		fprintf(stderr, " s %o tx %o %s\n",s,tx,tx);
#endif
		if (!control(s[0])) {	/* append to previous item */
			if (lastype != 0) {
				if (macro)
					fprintf(fo, "%s%c", tx, sep);
				else
					fprintf(fo, ".as [%c \" %s%c",lastype,tx,sep);
				if (lastype == 'T')
					ltitle = (mindex(".;,?", last(tx))!=0);
				if (lastype == 'A')
					lauth = last(tx) == '.';
			}
			continue;
		}
		if (mindex("XYZ[]", cch)) {	/* skip these */
			lastype = 0;
			continue;
		}
		else {
			if (cch == 'A') {
				if (nauth < authrev)
					tx = revauth(tx, buf2);
				if (nauth++ == 0)
					if (macro)
						fprintf(fo,
						".de [%c%c%s%c",cch,sep,tx,sep);
					else
						fprintf(fo,
						".ds [%c%s%c", cch,tx,sep);
				else {
					la = (tvec[i+1][1]!='A');
					fprintf(fo, ".as [A \"");
					if (la == 0 || nauth != 2)
						fprintf(fo, ",");
					if (la)
						fprintf(fo,"%s", 
						mindex(smallcaps, 'A') ? " \\s-2AND\\s+2" : " and");
					fprintf(fo, "%s%c", tx, sep);
				}
				lauth = last(tx) == '.';
			}
			else {
				if (macro)
					fprintf(fo,
						".de [%c%c%s%c",cch,sep,tx,sep);
				else
					fprintf(fo, ".ds [%c%s%c",cch,tx, sep);
			}
		}
		if (cch == 'P')
			fprintf(fo, ".nr [P %d%c", mindex(s, '-')!=0, sep);
		lastype = cch;
		if (cch == 'T')
			ltitle = (mindex(".;,?", last(tx)) != 0);
		if (cch == 'O')
			lother = (mindex(".;,?", last(tx)) != 0);
	}
	if (lastype && macro)
		fprintf(fo, "..%c", sep);
	fprintf(fo, ".nr [T %d%c", ltitle, sep);
	fprintf(fo, ".nr [A %d%c", lauth, sep);
	fprintf(fo, ".nr [O %d%c", lother, sep);
	fprintf(fo, ".][ %s%c", class(n, tvec), '\n');
}
Пример #23
0
int main(int iArgC, char *cArgV[])
{
#ifdef __GLIBCXX__
	// Set a better exception handler
	std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
#endif

	// Disable stdin/printf/etc. sync for a speed boost
	std::ios_base::sync_with_stdio(false);

	// Declare the supported options.
	po::options_description poActions("Actions");
	poActions.add_options()
		("info,i",
			"display information about the map, including attributes/metadata")

		("print,p", po::value<int>(),
			"print the given layer in ASCII")

		("render,r", po::value<std::string>(),
			"render the map to the given .png file")
	;

	po::options_description poOptions("Options");
	poOptions.add_options()
		("type,t", po::value<std::string>(),
			"specify the map type (default is autodetect)")
		("graphics,g", po::value<std::string>(),
			"filename storing game graphics (required with --render)")
		("script,s",
			"format output suitable for script parsing")
		("force,f",
			"force open even if the map is not in the given format")
		("list-types",
			"list supported file types")
	;

	po::options_description poHidden("Hidden parameters");
	poHidden.add_options()
		("map", "map file to manipulate")
		("help", "produce help message")
	;

	po::options_description poVisible("");
	poVisible.add(poActions).add(poOptions);

	po::options_description poComplete("Parameters");
	poComplete.add(poActions).add(poOptions).add(poHidden);
	po::variables_map mpArgs;

	std::string strFilename, strType;
	std::map<gm::ImagePurpose, gm::Map::GraphicsFilename> manualGfx;

	bool bScript = false; // show output suitable for script parsing?
	bool bForceOpen = false; // open anyway even if map not in given format?
	int iRet = RET_OK;
	try {
		po::parsed_options pa = po::parse_command_line(iArgC, cArgV, poComplete);

		// Parse the global command line options
		for (auto& i : pa.options) {
			if (i.string_key.empty()) {
				// If we've already got an map filename, complain that a second one
				// was given (probably a typo.)
				if (!strFilename.empty()) {
					std::cerr << "Error: unexpected extra parameter (multiple map "
						"filenames given?!)" << std::endl;
					return 1;
				}
				assert(i.value.size() > 0);  // can't have no values with no name!
				strFilename = i.value[0];
			} else if (i.string_key.compare("help") == 0) {
				std::cout <<
					"Copyright (C) 2010-2015 Adam Nielsen <*****@*****.**>\n"
					"This program comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
					"and you are welcome to change and redistribute it under certain conditions;\n"
					"see <http://www.gnu.org/licenses/> for details.\n"
					"\n"
					"Utility to manipulate map files used by games to store data files.\n"
					"Build date " __DATE__ " " __TIME__ << "\n"
					"\n"
					"Usage: gamemap <map> <action> [action...]\n" << poVisible << "\n"
					<< std::endl;
				return RET_OK;
			} else if (
				(i.string_key.compare("t") == 0) ||
				(i.string_key.compare("type") == 0)
			) {
				strType = i.value[0];
			} else if (
				(i.string_key.compare("g") == 0) ||
				(i.string_key.compare("graphics") == 0)
			) {
				std::string purpose, temp;
				gm::Map::GraphicsFilename gf;
				bool a = split(i.value[0], '=', &purpose, &temp);
				bool b = split(temp, ':', &gf.type, &gf.filename);
				if (!a || !b) {
					std::cerr << "Malformed -g/--graphics parameter.  Must be of the "
						"form purpose=type:filename.\n"
						"Use --help or --list-types for details." << std::endl;
					return RET_BADARGS;
				}
				bool found = false;
				for (unsigned int i = 0; i < (unsigned int)gm::ImagePurpose::ImagePurposeCount; i++) {
					gm::ImagePurpose p = (gm::ImagePurpose)i;
					if (purpose.compare(toString(p)) == 0) {
						manualGfx[p] = gf;
						found = true;
					}
				}
				if (!found) {
					std::cerr << "No match for tileset purpose: " << purpose << "\n"
						<< "Use --list-types for details." << std::endl;
					return RET_BADARGS;
				}
			} else if (
				(i.string_key.compare("s") == 0) ||
				(i.string_key.compare("script") == 0)
			) {
				bScript = true;
			} else if (
				(i.string_key.compare("f") == 0) ||
				(i.string_key.compare("force") == 0)
			) {
				bForceOpen = true;
			} else if (
				(i.string_key.compare("list-types") == 0)
			) {
				std::cout << "Tileset purposes: (--graphics purpose=type:file)\n";
				for (unsigned int i = 0; i < (unsigned int)gm::ImagePurpose::ImagePurposeCount; i++) {
					gm::ImagePurpose p = (gm::ImagePurpose)i;
					std::cout << "  " << toString(p) << "\n";
				}

				std::cout << "\nTileset types: (--graphics purpose=type:file)\n";
				for (auto& tilesetType : gg::TilesetManager::formats()) {
					std::string code = tilesetType->code();
					std::cout << "  " << code;
					int len = code.length();
					if (len < 20) std::cout << std::string(20-code.length(), ' ');
					std::cout << ' ' << tilesetType->friendlyName();
					auto ext = tilesetType->fileExtensions();
					if (ext.size()) {
						auto i = ext.begin();
						std::cout << " (*." << *i;
						for (i++; i != ext.end(); i++) {
							std::cout << "; *." << *i;
						}
						std::cout << ")";
					}
					std::cout << '\n';
				}

				std::cout << "\nMap types: (--type)\n";
				for (auto& mapType : gm::MapManager::formats()) {
					std::string code = mapType->code();
					std::cout << "  " << code;
					int len = code.length();
					if (len < 20) std::cout << std::string(20 - code.length(), ' ');
					std::cout << ' ' << mapType->friendlyName();
					auto ext = mapType->fileExtensions();
					if (ext.size()) {
						auto i = ext.begin();
						std::cout << " (*." << *i;
						for (i++; i != ext.end(); i++) {
							std::cout << "; *." << *i;
						}
						std::cout << ")";
					}
					std::cout << '\n';
				}

				return RET_OK;
			}
		}

		if (strFilename.empty()) {
			std::cerr << "Error: no game map filename given" << std::endl;
			return RET_BADARGS;
		}
		std::cout << "Opening " << strFilename << " as type "
			<< (strType.empty() ? "<autodetect>" : strType) << std::endl;

		std::unique_ptr<stream::inout> content;
		try {
			content = std::make_unique<stream::file>(strFilename, false);
		} catch (const stream::open_error& e) {
			std::cerr << "Error opening " << strFilename << ": " << e.what()
				<< std::endl;
			return RET_SHOWSTOPPER;
		}

		gm::MapManager::handler_t mapType;
		if (strType.empty()) {
			// Need to autodetect the file format.
			for (auto& mapTestType : gm::MapManager::formats()) {
				gm::MapType::Certainty cert = mapTestType->isInstance(*content);
				switch (cert) {
					case gm::MapType::Certainty::DefinitelyNo:
						// Don't print anything (TODO: Maybe unless verbose?)
						break;
					case gm::MapType::Certainty::Unsure:
						std::cout << "File could be a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						// If we haven't found a match already, use this one
						if (!mapType) mapType = mapTestType;
						break;
					case gm::MapType::Certainty::PossiblyYes:
						std::cout << "File is likely to be a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						// Take this one as it's better than an uncertain match
						mapType = mapTestType;
						break;
					case gm::MapType::Certainty::DefinitelyYes:
						std::cout << "File is definitely a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						mapType = mapTestType;
						// Don't bother checking any other formats if we got a 100% match
						goto finishTesting;
				}
				if (cert != gm::MapType::Certainty::DefinitelyNo) {
					// We got a possible match, see if it requires any suppdata
					auto suppList = mapTestType->getRequiredSupps(*content, strFilename);
					if (suppList.size() > 0) {
						// It has suppdata, see if it's present
						std::cout << "  * This format requires supplemental files..." << std::endl;
						bool bSuppOK = true;
						for (auto& i : suppList) {
							try {
								auto suppStream = std::make_unique<stream::file>(i.second, false);
							} catch (const stream::open_error&) {
								bSuppOK = false;
								std::cout << "  * Could not find/open " << i.second
									<< ", map is probably not "
									<< mapTestType->code() << std::endl;
								break;
							}
						}
						if (bSuppOK) {
							// All supp files opened ok
							std::cout << "  * All supp files present, map is likely "
								<< mapTestType->code() << std::endl;
							// Set this as the most likely format
							mapType = mapTestType;
						}
					}
				}
			}
finishTesting:
			if (!mapType) {
				std::cerr << "Unable to automatically determine the file type.  Use "
					"the --type option to manually specify the file format." << std::endl;
				return RET_BE_MORE_SPECIFIC;
			}
		} else {
			mapType = gm::MapManager::byCode(strType);
			if (!mapType) {
				std::cerr << "Unknown file type given to -t/--type: " << strType
					<< std::endl;
				return RET_BADARGS;
			}
		}

		assert(mapType != NULL);

		// Check to see if the file is actually in this format
		if (!mapType->isInstance(*content)) {
			if (bForceOpen) {
				std::cerr << "Warning: " << strFilename << " is not a "
					<< mapType->friendlyName() << ", open forced." << std::endl;
			} else {
				std::cerr << "Invalid format: " << strFilename << " is not a "
					<< mapType->friendlyName() << "\n"
					<< "Use the -f option to try anyway." << std::endl;
				return RET_BE_MORE_SPECIFIC;
			}
		}

		// See if the format requires any supplemental files
		camoto::SuppData suppData;
		for (auto& i : mapType->getRequiredSupps(*content, strFilename)) {
			try {
				std::cerr << "Opening supplemental file " << i.second << std::endl;
				suppData[i.first] = std::make_unique<stream::file>(i.second, false);
			} catch (const stream::open_error& e) {
				std::cerr << "Error opening supplemental file " << i.second << ": "
					<< e.what() << std::endl;
				// Continue anyway in case the file is optional
			}
		}

		// Open the map file
		std::shared_ptr<gm::Map> pMap = mapType->open(std::move(content), suppData);
		assert(pMap);

		// File type of inserted files defaults to empty, which means 'generic file'
		std::string strLastFiletype;

		// Run through the actions on the command line
		for (auto& i : pa.options) {
			if (i.string_key.compare("info") == 0) {
				listAttributes(pMap.get(), bScript);

				std::cout << (bScript ? "gfx_filename_count=" : "Number of graphics filenames: ")
					<< pMap->graphicsFilenames().size() << "\n";
				int fileNum = 0;
				for (auto& a : pMap->graphicsFilenames()) {
					if (bScript) {
						std::cout << "gfx_file" << fileNum << "_name=" << a.second.filename << "\n";
						std::cout << "gfx_file" << fileNum << "_type=" << a.second.type << "\n";
						std::cout << "gfx_file" << fileNum << "_purpose=" << (unsigned int)a.first << "\n";
					} else {
						std::cout << "Graphics file " << fileNum+1 << ": " << a.second.filename
							<< " [";
						switch (a.first) {
							case gm::ImagePurpose::GenericTileset1:    std::cout << "Generic tileset 1"; break;
							case gm::ImagePurpose::BackgroundImage:    std::cout << "Background image"; break;
							case gm::ImagePurpose::BackgroundTileset1: std::cout << "Background tileset 1"; break;
							case gm::ImagePurpose::BackgroundTileset2: std::cout << "Background tileset 2"; break;
							case gm::ImagePurpose::ForegroundTileset1: std::cout << "Foreground tileset 1"; break;
							case gm::ImagePurpose::ForegroundTileset2: std::cout << "Foreground tileset 2"; break;
							case gm::ImagePurpose::SpriteTileset1:     std::cout << "Sprite tileset 1"; break;
							case gm::ImagePurpose::FontTileset1:       std::cout << "Font tileset 1"; break;
							case gm::ImagePurpose::FontTileset2:       std::cout << "Font tileset 2"; break;
							default:
								std::cout << "Unknown purpose <fix this>";
								break;
						}
						std::cout << " of type " << a.second.type << "]\n";
					}
					fileNum++;
				}

				std::cout << (bScript ? "map_type=" : "Map type: ");
				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					std::cout << (bScript ? "2d" : "2D grid-based") << "\n";
#define CAP(o, c, v)        " " __STRING(c) << ((v & o::Caps::c) ? '+' : '-')
#define MAP2D_CAP(c)        CAP(gm::Map2D,        c, mapCaps)
#define MAP2D_LAYER_CAP(c)  CAP(gm::Map2D::Layer, c, layerCaps)

					auto mapCaps = map2d->caps();
					if (bScript) {
						std::cout << "map_caps=" << (unsigned int)mapCaps << "\n";
					} else {
						std::cout << "Map capabilities:"
							<< MAP2D_CAP(HasViewport)
							<< MAP2D_CAP(HasMapSize)
							<< MAP2D_CAP(SetMapSize)
							<< MAP2D_CAP(HasTileSize)
							<< MAP2D_CAP(SetTileSize)
							<< MAP2D_CAP(AddPaths)
							<< "\n"
						;
					}
					auto mapTileSize = map2d->tileSize();
					std::cout << (bScript ? "tile_width=" : "Tile size: ") << mapTileSize.x
						<< (bScript ? "\ntile_height=" : "x") << mapTileSize.y << "\n";

					auto mapSize = map2d->mapSize();
					std::cout
						<< (bScript ? "map_width=" : "Map size: ") << mapSize.x
						<< (bScript ? "\nmap_height=" : "x") << mapSize.y
						<< (bScript ? "" : " tiles")
						<< "\n";

					if (mapCaps & gm::Map2D::Caps::HasViewport) {
						auto vp = map2d->viewport();
						std::cout << (bScript ? "viewport_width=" : "Viewport size: ")
							<< vp.x
							<< (bScript ? "\nviewport_height=" : "x") << vp.y
							<< (bScript ? "" : " pixels") << "\n";
					}

					unsigned int layerCount = map2d->layers().size();
					std::cout << (bScript ? "layercount=" : "Layer count: ")
						<< layerCount << "\n";
					unsigned int layerIndex = 0;
					for (auto& layer : map2d->layers()) {
						std::string prefix;
						if (bScript) {
							std::stringstream ss;
							ss << "layer" << layerIndex << '_';
							prefix = ss.str();
							std::cout << prefix << "name=" << layer->title() << "\n";
						} else {
							prefix = "  ";
							std::cout << "Layer " << layerIndex + 1 << ": \"" << layer->title()
								<< "\"\n";
						}
						auto layerCaps = layer->caps();
						if (bScript) std::cout << prefix << "caps="
							<< (unsigned int)layerCaps << "\n";
						else std::cout << prefix << "Capabilities:"
							<< MAP2D_LAYER_CAP(HasOwnSize)
							<< MAP2D_LAYER_CAP(SetOwnSize)
							<< MAP2D_LAYER_CAP(HasOwnTileSize)
							<< MAP2D_LAYER_CAP(SetOwnTileSize)
							<< MAP2D_LAYER_CAP(HasPalette)
							<< MAP2D_LAYER_CAP(UseImageDims)
							<< "\n"
						;

						gg::Point layerTileSize;
						bool layerTileSame;
						if (layerCaps & gm::Map2D::Layer::Caps::HasOwnTileSize) {
							layerTileSize = layer->tileSize();
							layerTileSame = false;
						} else {
							layerTileSize = mapTileSize;
							layerTileSame = true;
						}
						std::cout << prefix << (bScript ? "tile_width=" : "Tile size: ")
							<< layerTileSize.x;
						if (bScript) std::cout << "\n" << prefix << "tile_height=";
						else std::cout << "x";
						std::cout << layerTileSize.y;
						if (layerTileSame && (!bScript)) {
							std::cout << " (same as map)";
						}
						std::cout << "\n";

						gg::Point layerSize;
						bool layerSame;
						if (layerCaps & gm::Map2D::Layer::Caps::HasOwnSize) {
							layerSize = layer->layerSize();
							layerSame = false;
						} else {
							// Convert from map tilesize to layer tilesize, leaving final
							// pixel dimensions unchanged
							layerSize.x = mapSize.x * mapTileSize.x / layerTileSize.x;
							layerSize.y = mapSize.y * mapTileSize.y / layerTileSize.y;
							layerSame = true;
						}
						std::cout << prefix << (bScript ? "width=" : "Layer size: ")
							<< layerSize.x;
						if (bScript) std::cout << "\n" << prefix << "height=";
						else std::cout << "x";
						std::cout << layerSize.y;
						if (layerSame && (!bScript)) {
							std::cout << " (same as map)";
						}
						std::cout << "\n";

						layerIndex++;
					}

				} else {
					std::cout << (bScript ? "unknown" : "Unknown!  Fix this!") << "\n";
				}

			} else if (i.string_key.compare("print") == 0) {
				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					unsigned int targetLayer = strtoul(i.value[0].c_str(), NULL, 10);
					if (targetLayer == 0) {
						std::cerr << "Invalid layer index passed to --print.  Use --info "
							"to list layers in this map." << std::endl;
						iRet = RET_BADARGS;
						continue;
					}
					if (targetLayer > map2d->layers().size()) {
						std::cerr << "Invalid layer index passed to --print.  Use --info "
							"to list layers in this map." << std::endl;
						iRet = RET_BADARGS;
						continue;
					}

					auto layer = map2d->layers().at(targetLayer - 1);
					// If this fails, the map format returned a null pointer for the layer
					assert(layer);

					// Figure out the layer size
					gg::Point layerSize, tileSize;
					getLayerDims(*map2d, *layer, &layerSize, &tileSize);

					auto items = layer->items();
					auto t = items.begin();
					unsigned int numItems = items.size();
					if (t != items.end()) {
						for (unsigned int y = 0; y < layerSize.y; y++) {
							for (unsigned int x = 0; x < layerSize.x; x++) {
								for (unsigned int i = 0; i < numItems; i++) {
									if ((t->pos.x == x) && (t->pos.y == y)) break;
									t++;
									if (t == items.end()) t = items.begin();
								}
								if ((t->pos.x != x) || (t->pos.y != y)) {
									// Grid position with no tile!
									std::cout << "     ";
								} else {
									std::cout << std::hex << std::setw(4)
										<< (unsigned int)t->code << ' ';
								}
							}
							std::cout << "\n";
						}
					} else {
						std::cout << "Layer is empty!" << std::endl;
					}

				} else {
					std::cerr << "Support for printing this map type has not yet "
						"been implemented!" << std::endl;
				}

			} else if (i.string_key.compare("render") == 0) {
				// Don't need to check i.value[0], program_options does that for us

				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					gm::TilesetCollection allTilesets;

					for (auto& a : manualGfx) {
						if (!bScript) {
							std::cout << "Loading " << a.second.type << " from "
								<< a.second.filename << std::endl;
						}
						allTilesets[a.first] = openTileset(a.second.filename, a.second.type);
					}

					for (auto& a : pMap->graphicsFilenames()) {
						if (allTilesets.find(a.first) == allTilesets.end()) {
							if (a.second.filename.empty()) {
								std::cerr << toString(a.first) << " is required, and must "
									"be specified manually with --graphics." << std::endl;
								iRet = RET_BADARGS;
							} else {
								// This tileset hasn't been specified on the command line, but the
								// map format handler has given us a filename, so open the file
								// suggested from the map.
								allTilesets[a.first] = openTileset(a.second.filename, a.second.type);
							}
						} else {
							if (!a.second.filename.empty()) {
								std::cout << toString(a.first) << " overridden on command-line\n";
							}
						}
					}

					if (allTilesets.empty()) {
						std::cerr << "No tilesets were loaded, map cannot be rendered.  "
							"Use --graphics to specify a tileset." << std::endl;
						iRet = RET_BADARGS;
					} else {
						map2dToPng(*map2d, allTilesets, i.value[0]);
					}
				} else {
					std::cerr << PROGNAME ": Rendering this type of map is not yet "
						"implemented." << std::endl;
					return RET_SHOWSTOPPER;
				}

			// Ignore --type/-t
			} else if (i.string_key.compare("type") == 0) {
			} else if (i.string_key.compare("t") == 0) {
			// Ignore --script/-s
			} else if (i.string_key.compare("script") == 0) {
			} else if (i.string_key.compare("s") == 0) {
			// Ignore --force/-f
			} else if (i.string_key.compare("force") == 0) {
			} else if (i.string_key.compare("f") == 0) {

			}
		} // for (all command line elements)
		//pMap->flush();
	} catch (const po::error& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< "  Use --help for help." << std::endl;
		return RET_BADARGS;
	} catch (const stream::error& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< "  Use --help for help." << std::endl;
		return RET_SHOWSTOPPER;
	}

	return iRet;
}
Пример #24
0
static int drop_privs(bool klogd, bool auditd) {
    // Tricky, if ro.build.type is "eng" then this is true because of the
    // side effect that ro.debuggable == 1 as well, else it is false.
    bool eng =
        __android_logger_property_get_bool("ro.build.type", BOOL_DEFAULT_FALSE);

    struct sched_param param;
    memset(&param, 0, sizeof(param));

    if (set_sched_policy(0, SP_BACKGROUND) < 0) {
        android::prdebug("failed to set background scheduling policy");
        if (!eng) return -1;
    }

    if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
        android::prdebug("failed to set batch scheduler");
        if (!eng) return -1;
    }

    if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
        android::prdebug("failed to set background cgroup");
        if (!eng) return -1;
    }

    if (!eng && (prctl(PR_SET_DUMPABLE, 0) < 0)) {
        android::prdebug("failed to clear PR_SET_DUMPABLE");
        return -1;
    }

    if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
        android::prdebug("failed to set PR_SET_KEEPCAPS");
        if (!eng) return -1;
    }

    std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(),
                                                             cap_free);
    if (cap_clear(caps.get()) < 0) return -1;
    cap_value_t cap_value[] = { CAP_SETGID,  // must be first for below
                                klogd ? CAP_SYSLOG : CAP_SETGID,
                                auditd ? CAP_AUDIT_CONTROL : CAP_SETGID };
    if (cap_set_flag(caps.get(), CAP_PERMITTED, arraysize(cap_value), cap_value,
                     CAP_SET) < 0) {
        return -1;
    }
    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, arraysize(cap_value), cap_value,
                     CAP_SET) < 0) {
        return -1;
    }
    if (cap_set_proc(caps.get()) < 0) {
        android::prdebug(
            "failed to set CAP_SETGID, CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)",
            errno);
        if (!eng) return -1;
    }

    gid_t groups[] = { AID_READPROC };

    if (setgroups(arraysize(groups), groups) == -1) {
        android::prdebug("failed to set AID_READPROC groups");
        if (!eng) return -1;
    }

    if (setgid(AID_LOGD) != 0) {
        android::prdebug("failed to set AID_LOGD gid");
        if (!eng) return -1;
    }

    if (setuid(AID_LOGD) != 0) {
        android::prdebug("failed to set AID_LOGD uid");
        if (!eng) return -1;
    }

    if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, cap_value, CAP_CLEAR) < 0) {
        return -1;
    }
    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, cap_value, CAP_CLEAR) < 0) {
        return -1;
    }
    if (cap_set_proc(caps.get()) < 0) {
        android::prdebug("failed to clear CAP_SETGID (%d)", errno);
        if (!eng) return -1;
    }

    return 0;
}
Пример #25
0
bool IsVideoPad(GstPad * inPad)
{
    ScopedObject<GstCaps> caps(gst_pad_get_caps(inPad));
    std::string capsName = Caps::GetName(caps.get());
    return NULL != g_strrstr(capsName.c_str(), "video");
}