Exemplo n.º 1
0
int8_t set_motor_levels(int16_t motor_speed_level,
		uint16_t motor_direction_level)
{
	motor_levels.speed_channel_level = motor_speed_level;
	motor_levels.direction_channel_level = motor_direction_level;
	motor_timestamp = get_current_time();

	if (motor_speed_level == MOTOR_LEVEL_BRAKE)
	{
		start_braking();
	}
	else if (motor_speed_level > 0) // if want to go forward
	{
		// if already going forward or stopped
		if ((motor_direction == MOTOR_DIRECTION_FORWARD) || (motor_direction
				== MOTOR_DIRECTION_STOPPED))
		{
			set_speed_motor_pwm_level(motor_speed_level);
			motor_state = MOTOR_STATE_ACTIVE;
			set_motor_direction(MOTOR_DIRECTION_FORWARD);
		}
		else // if trying to change directions
		{
			start_brake_coasting();
			post_error(ERR_MOTOR_FAULT);
		}
	}
	else if (motor_speed_level < 0) // if want to go backward
	{
		if ((motor_direction == MOTOR_DIRECTION_REVERSE) || (motor_direction
				== MOTOR_DIRECTION_STOPPED))
		{
			set_speed_motor_pwm_level(motor_speed_level);
			motor_state = MOTOR_STATE_ACTIVE;
			set_motor_direction(MOTOR_DIRECTION_REVERSE);
		}
		else // if trying to changed directions
		{
			start_brake_coasting();
			post_error(ERR_MOTOR_FAULT);
		}
	}
	else // if stopping, but not changing directions, then just coast
	{
		set_speed_motor_pwm_level(motor_speed_level);
		motor_state = MOTOR_STATE_COASTING;
		motor_coast_timestamp = get_current_time();
	}

	return ERR_NONE;
}
Exemplo n.º 2
0
// Save history into history file
void save_history(const string& file, Widget origin)
{
    if (!file.empty())
    {
	StatusDelay delay("Saving history in " + quote(file));
	std::ofstream os(file.chars());
	if (os.bad())
	{
	    post_error("Cannot save history in " + quote(file),
		       "history_save_error", origin);
	    delay.outcome = "failed";
	    return;
	}

	// Save the 10 most recently opened files
	int i;
	StringArray recent;
	get_recent(recent);
	for (i = recent.size() - 1; i >= 0 && i >= recent.size() - 10; i--)
	    os << gdb->debug_command(recent[i]) << "\n";

	// Now save the command history itself
	int start = gdb_history.size() - gdb_history_size;
	if (start < 0)
	    start = 0;

	for (i = start; i < gdb_history.size(); i++)
	    os << gdb_history[i] << "\n";
    }
}
const CBBSensorEvent& CLogBatteryImpl::get_value()
{
	CALLSTACKITEM_N(_CL("CLogBatteryImpl"), _CL("get_value"));

#ifndef __WINS__
#  ifndef __S60V2__
	RPhoneType::TBatteryInfo	info;
	TInt err=Phone().GetBatteryInfo(info);
#  else
 	TRequestStatus s;
	RMobilePhone::TMobilePhoneBatteryInfoV1 info;
	iPhone.GetBatteryInfo(s, info);
	User::WaitForRequest(s);
	TInt err=s.Int();
#  endif

	if (err==KErrNone) {
		iValue.iLevel=info.iChargeLevel;
		iValue.iState=info.iStatus;
	} else {
		TBuf<100> msg=_L("failed to get battery status: ");
		msg.AppendNum(err);
		post_error(msg, err);
	}
#else
	iValue.iLevel=100;
	iValue.iState=1;
#endif
	return iEvent;
}
Exemplo n.º 4
0
void gdbEditSourceCB  (Widget w, XtPointer, XtPointer)
{
    string pos = source_view->file_of_cursor();
    string file = pos.before(':');
    string line = pos.after(':');

    if (file == "" || line == "0")
    {
	post_error("No source.", "no_source_edit_error", w);
	return;
    }

    StatusDelay delay("Invoking editor for " + quote(file));

    string cmd = app_data.edit_command;
    cmd.gsub("@FILE@", file);
    cmd.gsub("@LINE@", line);
    cmd = sh_command(cmd);

    // Invoke an editor in the background
    LiterateAgent *edit_agent = 
	new LiterateAgent(XtWidgetToApplicationContext(w), cmd);

    output_buffer = "";

    edit_agent->removeAllHandlers(Died);
    edit_agent->addHandler(InputEOF, gdbEditDoneHP);
    edit_agent->addHandler(Died,     gdbEditDoneHP);
    edit_agent->addHandler(Input,    gdbEditOutputHP);
    edit_agent->addHandler(Error,    gdbEditOutputHP);
    edit_agent->start();
}
Exemplo n.º 5
0
// OK pressed in `Open Process'
static void openProcessDone(Widget w, XtPointer client_data, 
			    XtPointer call_data)
{
    int pid = get_pid(w, client_data, call_data);
    if (pid <= 0)
    {
	gdbUpdateProcessesCB(w, client_data, call_data);	
	return;
    }

    XtUnmanageChild(w);

    ProgramInfo info;

    if (pid == info.pid)
    {
	set_status("Already attached to process " + itostring(pid) + ".");
	return;
    }

    if (info.file == NO_GDB_ANSWER || info.file.empty())
    {
	post_error("No program.", "no_program", w);
	return;
    }

    // GDB does not always detach processes upon opening new
    // files, so we do it explicitly
    if (info.attached)
	gdb_command(gdb->detach_command(info.pid));

    // Attach to new process
    gdb_command(gdb->attach_command(pid, info.file));
}
Exemplo n.º 6
0
static ParseAction get_init_action(MpegTSDemuxer *demuxer, int ret)
{
    if (ret < 0)
    {
        if (!demuxer->is_flushing && !demuxer->context && mpegts_demuxer_expect_more_pads(demuxer))
            post_error(demuxer, "Demuxer error", ret, GST_STREAM_ERROR_DEMUX);

        return PA_STOP;
    }
    else
        return PA_READ_FRAME;
}
void bases::update_database(cell_list_node* n, bool is_current)
{
	CALLSTACKITEM_N(_CL("bases"), _CL("update_database"));

	if (test_flags & NO_DB_UPDATE) return;

	if (!n) {
		post_error(_L("int error, n is NULL"), KErrGeneral);
		return;
	}

	if (n->in_db) {
		TDbSeekKey rk(n->id);
		TInt ret;
		if (! (ret=table.SeekL(rk)) ) {
			// TODO: do what?
			User::Leave(ret);
		}
		table.UpdateL();
	} else {
		if (NoSpaceLeft()) return;

		table.InsertL();
		if (colno_cellid>0) table.SetColL(colno_cellid, _L(""));
		table.SetColL(colno_id, n->id);
	}
	table.SetColL(colno_t, n->t);
	table.SetColL(colno_f, n->f);
	table.SetColL(colno_merged_to, n->merged_to);
	table.SetColL(colno_unaged_t, n->unaged_t);
	table.SetColL(colno_rescaled, bases_info->rescaled);

	TUint32 isbase=0;
	if (n->is_base) { isbase=1; }
	table.SetColL(colno_isbase, isbase);
	table.SetColL(colno_last_seen, n->last_seen);

	TUint32 iscurrent=0;
	if (is_current) iscurrent=1;
	table.SetColL(colno_iscurrent, iscurrent);

	PutL();

	n->in_db=true;

}
Exemplo n.º 8
0
static ParseAction mpegts_demuxer_read_frame(MpegTSDemuxer *demuxer)
{
    ParseAction   result = PA_READ_FRAME;
    GstFlowReturn flow_result = GST_FLOW_OK;
    AVPacket      packet;
    int           ret = av_read_frame(demuxer->context, &packet);

    switch(ret)
    {
        case 0:
#ifdef ENABLE_VIDEO
            if (packet.stream_index == demuxer->video.stream_index) // Video
                flow_result = process_video_packet(demuxer, &packet);
            else
#endif // ENABLE_VIDEO
            if (packet.stream_index == demuxer->audio.stream_index) // Audio
                flow_result = process_audio_packet(demuxer, &packet);

            if (flow_result != GST_FLOW_OK)
            {
                if (flow_result != GST_FLOW_FLUSHING)
                    post_message(demuxer, "Send packet failed", GST_MESSAGE_ERROR, GST_STREAM_ERROR, GST_STREAM_ERROR_DEMUX);

                result = PA_STOP;
            }
#ifdef FAKE_ERROR
            else if (demuxer->read_bytes > 1000000)
            {
                post_message(demuxer, "Fake error", GST_MESSAGE_ERROR, GST_STREAM_ERROR, GST_STREAM_ERROR_DEMUX);
                result = PA_STOP;
            }
#endif
            break;

        default:
            if (demuxer->is_eos && demuxer->is_last_buffer_send) // Send EOS
                mpegts_demuxer_push_to_sources(demuxer, gst_event_new_eos());
            else
                post_error(demuxer, "LibAV stream parse error", ret, GST_STREAM_ERROR_DEMUX); // Send Error
            result = PA_STOP;
            break;
    }

    av_free_packet(&packet);
    return result;
}
Exemplo n.º 9
0
static h2o_http1client_head_cb on_connect(h2o_http1client_t *client, const char *errstr, h2o_iovec_t **reqbufs, size_t *reqbufcnt,
                                          int *method_is_head)
{
    struct st_h2o_mruby_http_request_context_t *ctx = client->data;

    if (errstr != NULL) {
        post_error(ctx, errstr);
        return NULL;
    }

    *reqbufs = h2o_mem_alloc_pool(&ctx->generator->req->pool, sizeof(**reqbufs) * 2);
    **reqbufs = h2o_iovec_init(ctx->req.buf->bytes, ctx->req.buf->size);
    *reqbufcnt = 1;
    if (ctx->req.body.base != NULL)
        (*reqbufs)[(*reqbufcnt)++] = ctx->req.body;
    *method_is_head = ctx->req.method_is_head;
    return on_head;
}
Exemplo n.º 10
0
static void SaveTipCountCB(Widget, XtPointer = 0, XtPointer = 0)
{
    create_session_dir(DEFAULT_SESSION);
    const string file = session_tips_file();

    std::ofstream os(file.chars());
    os << 
	"! " DDD_NAME " tips file\n"
	"\n"
       << app_value(XtNstartupTipCount,
		    itostring(++app_data.startup_tip_count)) << "\n";

    os.close();
    if (os.bad())
    {
	post_error("Cannot save tip count in " + quote(file),
		   "options_save_error");
    }
}
Exemplo n.º 11
0
static h2o_http1client_body_cb on_head(h2o_http1client_t *client, const char *errstr, int minor_version, int status,
                                       h2o_iovec_t msg, struct phr_header *headers, size_t num_headers)
{
    struct st_h2o_mruby_http_request_context_t *ctx = client->data;

    if (errstr != NULL) {
        if (errstr != h2o_http1client_error_is_eos) {
            /* error */
            post_error(ctx, errstr);
            return NULL;
        }
        /* closed without body */
        ctx->client = NULL;
    }

    qsort(headers, num_headers, sizeof(headers[0]), headers_sort_cb);
    post_response(ctx, status, headers, num_headers);
    return on_body;
}
TInt Clog_cellidImpl::CheckedRunError(TInt aError)
{
	CALLSTACKITEM_N(_CL("Clog_cellidImpl"), _CL("CheckedRunError"));
	if (iErrorCount >= 10) return aError;

	TBuf<40> msg;
	msg.Format(_L("Clog_cellidImpl::CheckedRunError %d"), aError);

	post_error(msg, aError, GetTime());

#ifndef __WINS__
	Cancel();

#  ifdef BASICGSM
#    ifndef __S60V2__
	Phone().NotifyChangeOfCurrentNetwork(iStatus, async_info);
#    else
	Phone().NotifyChangeOfCurrentNetworkNS(iStatus, async_info);
#    endif
#  endif

#  ifdef ETEL3RDPARTY
	Telephony().NotifyChange(iStatus, CTelephony::ECurrentNetworkInfoChange, async_infop);
	i3rdpartyState=NOTIFYONCHANGE;
#  endif

#  ifdef MOBINFO

	if (iInfoState==GETTING_FIRST_MCC || iInfoState==GETTING_NEW_MCC) {
		iMobInfo->GetCurrentNetwork(iNetworkInfo, iStatus);
	} else {
		iMobInfo->NotifyCellIdChange(async_infop, iStatus);
	}
#  endif

	SetActive();
	return KErrNone;
#else // __WINS__
	return aError;
#endif
}
Exemplo n.º 13
0
// OK pressed in `Open Core'
static void openCoreDone(Widget w, XtPointer client_data, XtPointer call_data)
{
    string corefile = get_file(w, client_data, call_data);
    if (corefile.empty())
	return;

    ProgramInfo info;

    XtUnmanageChild(w);

    if (corefile != NO_GDB_ANSWER)
    {
	switch(gdb->type())
	{
	case GDB:
	    gdb_command("core-file " + gdb->quote_file(corefile));
	    break;

	case DBX:
	    if (info.file != NO_GDB_ANSWER && !info.file.empty())
		gdb_command(gdb->debug_command(info.file) + " " + 
			    gdb->quote_file(info.core));
	    else
		post_error("No program.", "no_program", w);
	    break;

	case BASH:
	case DBG:
	case JDB:
	case PERL:
	case PYDB:
	case XDB:
	    break;		// FIXME
	}
    }
}
Exemplo n.º 14
0
void motor_run_handler(uint32_t current_time)
{
	if (get_nvm_error_flag() != ERR_NONE)
		return;

	switch (motor_state)
	{
	case MOTOR_STATE_IDLE:
		if (!get_sensor_waiting_for_measurement())
		{
			handle_back_emf_measurement();
			set_sensor_waiting_for_measurement(true);

			if (motor_direction == MOTOR_DIRECTION_STOPPED)
			{
				if (get_last_error(NULL) == ERR_MOTOR_FAULT)
					clear_last_error();
			}
			else
			{
				post_error(ERR_MOTOR_FAULT);
			}
		}
		break;
	case MOTOR_STATE_BRAKING:
		if (check_for_timeout(current_time, motor_brake_timestamp,
				MOTOR_BRAKE_TIME))
		{
			start_brake_coasting();
		}
		break;
	case MOTOR_STATE_BRAKE_COAST:
		if (check_for_timeout(current_time, motor_coast_timestamp,
				MOTOR_COAST_TIME))
		{
			debug_P(PSTR("Stop brake coasting @ %lu\n"), current_time);
			set_sensor_waiting_for_measurement(true);
			motor_state = MOTOR_STATE_BRAKE_READ_BACK_EMF;
			motor_read_back_emf_count = 0;
		}
		break;
	case MOTOR_STATE_BRAKE_READ_BACK_EMF:
		if (!get_sensor_waiting_for_measurement())
		{
			handle_back_emf_measurement();

			// if we have receive a brake command we just keep braking
			if (motor_levels.speed_channel_level == MOTOR_LEVEL_BRAKE)
			{
				if (motor_direction == MOTOR_DIRECTION_STOPPED)
				{
					if (get_last_error(NULL) == ERR_MOTOR_FAULT)
						clear_last_error();
				}
				else
				{
					post_error(ERR_MOTOR_FAULT);
				}
			}
			else if (motor_levels.speed_channel_level > 0)
			{
				if ((motor_direction == MOTOR_DIRECTION_STOPPED)
						|| (motor_direction == MOTOR_DIRECTION_FORWARD))
				{
					motor_state = MOTOR_STATE_ACTIVE;
					set_motor_direction(MOTOR_DIRECTION_FORWARD);
				}
			}
			else if (motor_levels.speed_channel_level < 0)
			{
				if ((motor_direction == MOTOR_DIRECTION_STOPPED)
						|| (motor_direction == MOTOR_DIRECTION_REVERSE))
				{
					motor_state = MOTOR_STATE_ACTIVE;
					set_motor_direction(MOTOR_DIRECTION_REVERSE);
				}
			}
			else if (motor_direction == MOTOR_DIRECTION_STOPPED)
			{
				motor_state = MOTOR_STATE_IDLE;
				set_motor_direction(MOTOR_DIRECTION_STOPPED);
			}

			// motor fault is done
			if (motor_state != MOTOR_STATE_BRAKE_READ_BACK_EMF)
			{
				if (get_last_error(NULL) == ERR_MOTOR_FAULT)
					clear_last_error();
			}
			else if (++motor_read_back_emf_count == BACK_EMF_READ_COUNT)
			{
				start_braking();
			}
			else
			{
				set_sensor_waiting_for_measurement(true);
			}
		}
		break;
	case MOTOR_STATE_COASTING:
		if (check_for_timeout(current_time, motor_coast_timestamp,
				MOTOR_COAST_TIME))
		{
			set_sensor_waiting_for_measurement(true);
			motor_state = MOTOR_STATE_IDLE;
		}
		break;
	case MOTOR_STATE_ACTIVE:
		if (check_for_timeout(current_time, motor_timestamp, motor_timeout))
		{
			motor_levels.speed_channel_level = 0;
			start_braking();
			debug_P(PSTR("MOTOR Timeout @ %lu\n"), get_current_time());
			post_error(ERR_MOTOR_TIMEOUT);
		}
		else
		{
			set_speed_motor_pwm_level(motor_levels.speed_channel_level);
			set_direction_motor_pwm_level(motor_levels.direction_channel_level);
		}
		break;
	}
}
Exemplo n.º 15
0
static gpointer mpegts_demuxer_process_input(gpointer data)
{
    MpegTSDemuxer *demuxer = MPEGTS_DEMUXER(data);
    ParseAction action = PA_INIT;

#ifdef DEBUG_OUTPUT
    g_print("MpegTS: Entered process_input\n");
#endif

    while (demuxer->is_reading)
    {
        switch(action)
        {
        case PA_INIT:
            {
#ifdef DEBUG_OUTPUT
                g_print("MpegTS: action = PA_INIT\n");
#endif

                guchar      *io_buffer = (guchar*)av_malloc(BUFFER_SIZE);
                if (!io_buffer)
                {
                    post_error(demuxer, "LibAV input buffer alloc error", 0, GST_STREAM_ERROR_DEMUX);
                    return NULL;
                }

                AVIOContext *io_context = avio_alloc_context(io_buffer,            // buffer
                                                             BUFFER_SIZE,          // buffer size
                                                             0,                    // read only
                                                             demuxer,              // opaque reference
                                                             mpegts_demuxer_read_packet, // read callback
                                                             NULL,                 // write callback
                                                             mpegts_demuxer_seek); // seek callback

                if (!io_context)
                {
                    post_error(demuxer, "LibAV context alloc error", 0, GST_STREAM_ERROR_DEMUX);
                    return NULL;
                }

                demuxer->context = avformat_alloc_context();
                demuxer->context->pb = io_context;

                demuxer->adapter_limit_type = UNLIMITED;
                demuxer->adapter_limit_size = ADAPTER_LIMIT;

                AVInputFormat* iformat = av_find_input_format("mpegts");

                action = get_init_action(demuxer, avformat_open_input(&demuxer->context, "", iformat, NULL));

                if (action != PA_READ_FRAME)
                    break;

                action = get_init_action(demuxer, avformat_find_stream_info(demuxer->context, NULL));

                g_mutex_lock(&demuxer->lock);
                gint available = gst_adapter_available(demuxer->sink_adapter);
                demuxer->adapter_limit_type = LIMITED;
                gst_adapter_flush(demuxer->sink_adapter, available > demuxer->offset ? demuxer->offset : available);
                demuxer->flush_adapter = TRUE;
                demuxer->offset = 0;
                g_cond_signal(&demuxer->del_cond);
                g_mutex_unlock(&demuxer->lock);

                mpegts_demuxer_check_streams(demuxer);
            }
            break;

        case PA_READ_FRAME:
            //            g_print("action = PA_READ_FRAME, is_eos=%s, is_flushing=%s\n", BV(demuxer->is_eos), BV(demuxer->is_flushing));
            action = mpegts_demuxer_read_frame(demuxer);
            break;

        case PA_STOP:
#ifdef DEBUG_OUTPUT
            g_print("MpegTS: action = PA_STOP\n");
#endif
            demuxer->is_reading = FALSE;

            if (demuxer->context)
            {
                av_free(demuxer->context->pb->buffer);
                av_free(demuxer->context->pb);
                avformat_free_context(demuxer->context);
                demuxer->context = NULL;
            }
            break;

        default:
            break;
        }
    }

#ifdef DEBUG_OUTPUT
    g_print("MpegTS: Exiting process_input\n");
#endif

    return NULL;
}
Exemplo n.º 16
0
static void DoExportCB(Widget w, XtPointer client_data, XtPointer call_data)
{
    SelectPlotCB(w, client_data, call_data);

    PlotWindowInfo *plot = (PlotWindowInfo *)client_data;
    string target = get_file(w, client_data, call_data);
    if (target.empty())
	return;

    const StringArray& titles  = plot->plotter->data_titles();
    const StringArray& sources = plot->plotter->data_files();

    string source = "";
    string title  = "";
    for (int i = 0; source.empty() && i < sources.size(); i++)
    {
	if (!sources[i].empty())
	{
	    source = sources[i];
	    title  = titles[i];
	}
    }
    
    if (source.empty())
	return;			// This should not happen

    if (access(target.chars(), W_OK) == 0 && is_regular_file(target))
    {
	// File exists - request confirmation
	static Widget confirm_overwrite_dialog = 0;
	if (confirm_overwrite_dialog != 0)
	    DestroyWhenIdle(confirm_overwrite_dialog);

	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNdialogStyle, 
		 XmDIALOG_FULL_APPLICATION_MODAL); arg++;
	confirm_overwrite_dialog = 
	    verify(XmCreateQuestionDialog(plot->shell,
					  XMST("confirm_overwrite_dialog"), 
					  args, arg));
	Delay::register_shell(confirm_overwrite_dialog);

	bool yes = false;
	bool no  = false;
	   
	XtAddCallback(confirm_overwrite_dialog,
		      XmNokCallback, SetCB, XtPointer(&yes));
	XtAddCallback(confirm_overwrite_dialog,
		      XmNcancelCallback, SetCB, XtPointer(&no));
	XtAddCallback(confirm_overwrite_dialog, 
		      XmNhelpCallback, ImmediateHelpCB, 0);

	MString question = rm("Overwrite existing file " 
			      + quote(target) + "?");
	XtVaSetValues (confirm_overwrite_dialog, XmNmessageString, 
		       question.xmstring(), XtPointer(0));
	manage_and_raise(confirm_overwrite_dialog);

	XtAppContext app_context = XtWidgetToApplicationContext(plot->shell);
	while (!yes && !no)
	    XtAppProcessEvent(app_context, XtIMAll);

	if (no)
	    return;
    }

    StatusDelay delay("Saving " + title + " data to " + quote(target));

    // Copy SOURCE to TARGET
    std::ifstream is(source.chars());
    std::ofstream os(target.chars());

    if (os.bad())
    {
	FILE *fp = fopen(target.chars(), "w");
	post_error(string("Cannot open ") 
		   + quote(target) + ": " + strerror(errno), 
		   "export_failed_error", plot->shell);
	if (fp)
	    fclose(fp);
	delay.outcome = strerror(errno);
	return;
    }

    int c;
    while ((c = is.get()) != EOF)
	os.put((unsigned char) c);

    XtUnmanageChild(plot->export_dialog);
}
Exemplo n.º 17
0
// Search for local files and directories, using the predicate IS_OKAY
static void searchLocal(Widget fs,
			XmFileSelectionBoxCallbackStruct *cbs,
			bool is_okay(const string& file_name))
{
    String mask;
    if (!XmStringGetLtoR(cbs->mask, MSTRING_DEFAULT_CHARSET, &mask))
	return;

    char **files = glob_filename(mask);
    if (files == (char **)0)
    {
	std::cerr << mask << ": glob failed\n";
    }
    else if (files == (char **)-1)
    {
	post_error(string(mask) + ": " + strerror(errno));
    }
    else
    {
	StatusDelay delay(delay_message);

	int count;
	for (count = 0; files[count] != 0; count++)
	    ;
	smart_sort(files, count);

	XmStringTable items = 
	    XmStringTable(XtMalloc(count * sizeof(XmString)));

	int nitems = 0;
	int i;
	for (i = 0; files[i] != 0; i++)
	{
	    if (is_okay(files[i]))
		items[nitems++] = XmStringCreateLtoR(files[i], 
						     MSTRING_DEFAULT_CHARSET);
	    free(files[i]);

	    int percent     = (i * 100) / count;
	    int old_percent = ((i - 1) * 100) / count;
	    if (percent % 10 == 0 && old_percent % 10 != 0)
	    {
		std::ostringstream status;
		status << delay_message << "... ("
		       << percent << "% processed)";
		string s(status);
		set_status(s, true);
	    }
	}
	free((char *)files);

	if (nitems > 0)
	{
	    XtVaSetValues(fs,
			  XmNfileListItems,     items,
			  XmNfileListItemCount, nitems,
			  XmNdirSpec,           items[0],
			  XmNlistUpdated,       True,
			  XtPointer(0));
	}

	freeXmStringTable(items, nitems);

	if (nitems > 0)
	    return;
    }

    // Error or nothing found 
    XtVaSetValues(fs,
		  XmNfileListItems,     0,
		  XmNfileListItemCount, 0,
		  XmNlistUpdated,       True,
		  XtPointer(0));
}
Exemplo n.º 18
0
static PlotWindowInfo *new_decoration(const string& name)
{
    PlotWindowInfo *plot = 0;

    // Check whether we can reuse an existing decoration
    for (int i = 0; i < plot_infos.size(); i++)
    {
	PlotWindowInfo *info = (PlotWindowInfo *)plot_infos[i];
	if (info->plotter == 0)
	{
	    // Shell is unused - use this one
	    plot = info;
	    break;
	}
    }

    if (plot == 0)
    {
	plot = new PlotWindowInfo;

	// Create decoration windows
	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNallowShellResize, True);       arg++;
	XtSetArg(args[arg], XmNdeleteResponse, XmDO_NOTHING); arg++;

	// Mark shell as `used'
	XtSetArg(args[arg], XmNuserData, XtPointer(True)); arg++;
	plot->shell = verify(XtCreateWidget("plot", topLevelShellWidgetClass,
					    find_shell(), args, arg));

	AddDeleteWindowCallback(plot->shell, CancelPlotCB, XtPointer(plot));

	arg = 0;
	Widget main_window = XmCreateMainWindow(plot->shell, 
						XMST("main_window"), 
						args, arg);
	XtManageChild(main_window);

	MMcreateMenuBar(main_window, "menubar", menubar);
	MMaddCallbacks(file_menu,    XtPointer(plot));
	MMaddCallbacks(simple_edit_menu);
	MMaddCallbacks(view_menu,    XtPointer(plot));
	MMaddCallbacks(plot_menu,    XtPointer(plot));
	MMaddCallbacks(scale_menu,   XtPointer(plot));
	MMaddCallbacks(contour_menu, XtPointer(plot));
	MMaddCallbacks(simple_help_menu);
	MMaddHelpCallback(menubar, ImmediateHelpCB);

	arg = 0;
	XtSetArg(args[arg], XmNscrollingPolicy, XmAPPLICATION_DEFINED); arg++;
	XtSetArg(args[arg], XmNvisualPolicy,    XmVARIABLE);            arg++;
	Widget scroll = 
	    XmCreateScrolledWindow(main_window, XMST("scroll"), args, arg);
	XtManageChild(scroll);

	// Create work window
	Widget work;
	string plot_term_type = downcase(app_data.plot_term_type);
	if (plot_term_type.contains("xlib", 0))
	{
	    // xlib type - create plot area to draw plot commands
	    arg = 0;
	    work = XmCreateDrawingArea(scroll, 
				       XMST(PLOT_AREA_NAME), args, arg);
	    XtManageChild(work);

	    plot->area = 
		new PlotArea(work, make_font(app_data, FixedWidthDDDFont));
	    XtVaSetValues(work, XmNuserData, XtPointer(plot->area), 
			  XtPointer(0));
	}
	else if (plot_term_type.contains("x11", 0))
	{
	    // x11 type - swallow Gnuplot window
	    arg = 0;
	    work = plot->swallower = 
		XtCreateManagedWidget(SWALLOWER_NAME, swallowerWidgetClass, 
				      scroll, args, arg);
	}
	else
	{
	    // Unknown terminal type
	    post_error("Unknown plot terminal type " + 
		       quote(app_data.plot_term_type),
		       "unknown_plot_term_type_error");
	    return 0;
	}

	// Create scroll bars
	const int slider_size = 20;

	arg = 0;
	XtSetArg(args[arg], XmNorientation, XmHORIZONTAL);      arg++;
	XtSetArg(args[arg], XmNminimum,     0);                 arg++;
	XtSetArg(args[arg], XmNmaximum,     360 + slider_size); arg++;
	plot->hsb = XmCreateScrollBar(scroll, XMST("hsb"), args, arg);
	XtManageChild(plot->hsb);

	arg = 0;
	XtSetArg(args[arg], XmNorientation, XmVERTICAL);        arg++;
	XtSetArg(args[arg], XmNminimum,     0);                 arg++;
	XtSetArg(args[arg], XmNmaximum,     180 + slider_size); arg++;
	plot->vsb = XmCreateScrollBar(scroll, XMST("vsb"), args, arg);
	XtManageChild(plot->vsb);

	XtAddCallback(plot->hsb, XmNvalueChangedCallback,
		      SetViewCB, XtPointer(plot));
	XtAddCallback(plot->vsb, XmNvalueChangedCallback,
		      SetViewCB, XtPointer(plot));

#if 0
	XtAddCallback(plot->hsb, XmNdragCallback, SetViewCB, XtPointer(plot));
	XtAddCallback(plot->vsb, XmNdragCallback, SetViewCB, XtPointer(plot));
#endif

	XmScrolledWindowSetAreas(scroll, plot->hsb, plot->vsb, work);

	Delay::register_shell(plot->shell);
	InstallButtonTips(plot->shell);

	plot_infos += plot;
    }

    string title = DDD_NAME ": " + name;
    XtVaSetValues(plot->shell,
		  XmNtitle, title.chars(),
		  XmNiconName, title.chars(),
		  XtPointer(0));

    if (plot->swallower != 0)
    {
	XtRemoveAllCallbacks(plot->swallower, XtNwindowCreatedCallback);
	XtAddCallback(plot->swallower, XtNwindowCreatedCallback,
		      SwallowCB, XtPointer(plot));

	XtRemoveAllCallbacks(plot->swallower, XtNwindowGoneCallback);
	XtAddCallback(plot->swallower, XtNwindowGoneCallback, 
		      SwallowAgainCB, XtPointer(plot));

	if (plot->swallow_timer != 0)
	    XtRemoveTimeOut(plot->swallow_timer);

	plot->swallow_timer = 
	    XtAppAddTimeOut(XtWidgetToApplicationContext(plot->swallower),
			    app_data.plot_window_delay, SwallowTimeOutCB, 
			    XtPointer(plot));
    }

    plot->active = false;

    return plot;
}
Exemplo n.º 19
0
void* HGE_CALL HGE_Impl::Resource_Load(const char* filename, uint32_t* size) {
    static char* res_err = "Can't load resource: %s";

    auto res_item = res_list_;
    char sz_name[_MAX_PATH];
    char sz_zip_name[_MAX_PATH];
    unz_file_info file_info;
    int i;
    void* ptr;

    if (filename[0] == '\\' || filename[0] == '/' || filename[1] == ':') {
        goto _fromfile; // skip absolute paths
    }

    // Load from pack

    strcpy(sz_name, filename);
    strupr(sz_name);
    for (i = 0; sz_name[i]; i++) {
        if (sz_name[i] == '/') {
            sz_name[i] = '\\';
        }
    }

    while (res_item) {
        const auto zip = unzOpen(res_item->filename);
        auto done = unzGoToFirstFile(zip);
        while (done == UNZ_OK) {
            unzGetCurrentFileInfo(zip, &file_info, sz_zip_name, sizeof(sz_zip_name), nullptr, 0,
                                  nullptr, 0);
            strupr(sz_zip_name);
            for (i = 0; sz_zip_name[i]; i++) {
                if (sz_zip_name[i] == '/') {
                    sz_zip_name[i] = '\\';
                }
            }
            if (!strcmp(sz_name, sz_zip_name)) {
                if (unzOpenCurrentFilePassword(zip, res_item->password[0] ? res_item->password : 0)
                    !=
                    UNZ_OK) {
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                ptr = malloc(file_info.uncompressed_size);
                if (!ptr) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }

                if (unzReadCurrentFile(zip, ptr, file_info.uncompressed_size) < 0) {
                    unzCloseCurrentFile(zip);
                    unzClose(zip);
                    free(ptr);
                    sprintf(sz_name, res_err, filename);
                    post_error(sz_name);
                    return nullptr;
                }
                unzCloseCurrentFile(zip);
                unzClose(zip);
                if (size) {
                    *size = file_info.uncompressed_size;
                }
                return ptr;
            }

            done = unzGoToNextFile(zip);
        }

        unzClose(zip);
        res_item = res_item->next;
    }

    // Load from file
_fromfile:
    const auto h_f = CreateFile(Resource_MakePath(filename), GENERIC_READ,
                                FILE_SHARE_READ, nullptr, OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
                                nullptr);
    if (h_f == INVALID_HANDLE_VALUE) {
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    file_info.uncompressed_size = GetFileSize(h_f, nullptr);
    ptr = malloc(file_info.uncompressed_size);
    if (!ptr) {
        CloseHandle(h_f);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }
    if (ReadFile(h_f, ptr, file_info.uncompressed_size, &file_info.uncompressed_size,
                 nullptr) == 0) {
        CloseHandle(h_f);
        free(ptr);
        sprintf(sz_name, res_err, filename);
        post_error(sz_name);
        return nullptr;
    }

    CloseHandle(h_f);
    if (size) {
        *size = file_info.uncompressed_size;
    }
    return ptr;
}
Exemplo n.º 20
0
static void
ripthread (void *thread_arg)
{
    error_code ret;
    RIP_MANAGER_INFO* rmi = (RIP_MANAGER_INFO*) thread_arg;
    debug_ripthread (rmi);
    debug_stream_prefs (rmi->prefs);

    /* Connect to remote server */
    ret = start_ripping (rmi);
    if (ret != SR_SUCCESS) {
	debug_printf ("Ripthread did start_ripping()\n");
	threadlib_signal_sem (&rmi->started_sem);
	post_error (rmi, ret);
	goto DONE;
    }

    rmi->status_callback (rmi, RM_STARTED, (void *)NULL);
    post_status (rmi, RM_STATUS_BUFFERING);
    debug_printf ("Ripthread did initialization\n");
    threadlib_signal_sem(&rmi->started_sem);

    while (TRUE) {
	debug_printf ("Gonna ripstream_rip\n");
        ret = ripstream_rip(rmi);
	debug_printf ("Did ripstream_rip\n");

	if (!rmi->started) {
	    break;
	}
	else if (rmi->megabytes_ripped >= rmi->prefs->maxMB_rip_size 
		 && GET_CHECK_MAX_BYTES (rmi->prefs->flags)) {
	    /* GCS Aug 23, 2003: bytes_ripped can still overflow */
	    socklib_close (&rmi->stream_sock);
	    destroy_subsystems (rmi);
	    //post_error (rmi, SR_ERROR_MAX_BYTES_RIPPED);
	    break;
	}
	else if (ret == SR_SUCCESS_BUFFERING) {
	    post_status (rmi, RM_STATUS_BUFFERING);
	    /* Fall through */
	}
	else if (ret == SR_ERROR_CANT_DECODE_MP3) {
	    post_error (rmi, ret);
	    continue;
	}
	else if ((ret == SR_ERROR_RECV_FAILED || 
		  ret == SR_ERROR_TIMEOUT || 
		  ret == SR_ERROR_NO_TRACK_INFO || 
		  ret == SR_ERROR_SELECT_FAILED) && 
		 GET_AUTO_RECONNECT (rmi->prefs->flags)) {
	    /* Try to reconnect */
	    post_status (rmi, RM_STATUS_RECONNECTING);
	    while (rmi->started) {
		socklib_close(&rmi->stream_sock);
		if (rmi->ep) {
		    debug_printf ("Close external\n");
		    close_external (&rmi->ep);
		}
		destroy_subsystems (rmi);
		ret = start_ripping (rmi);
		if (ret == SR_SUCCESS)
		    break;
		Sleep(1000);
	    }
	    if (!rmi->started) {
		break;
	    }
	    /* Fall through */
	}
	else if (ret == SR_ERROR_ABORT_PIPE_SIGNALLED) {
	    /* Normal exit condition CTRL-C on unix */
	    destroy_subsystems (rmi);
	    break;
	}
	else if (ret != SR_SUCCESS) {
	    destroy_subsystems (rmi);
	    post_error (rmi, ret);
	    break;
	}

	/* All systems go.  Caller should update GUI that it is ripping */
	if (rmi->filesize > 0) {
	    post_status (rmi, RM_STATUS_RIPPING);
	}
    }

    // We get here when there was either a fatal error
    // or we we're not auto-reconnecting and the stream just stopped
    // or when we have been told to stop, via the rmi->started flag
 DONE:
    rmi->status_callback (rmi, RM_DONE, 0);
    rmi->started = 0;
    debug_printf ("ripthread() exiting!\n");
}
void Clog_cellidImpl::CheckedRunL()
{
	CALLSTACKITEM_N(_CL("Clog_cellidImpl"), _CL("CheckedRunL"));

#ifdef __WINS__
	TTimeIntervalMicroSeconds32 wait_time;
#endif
	if (iStatus!=KErrNone) {
		TBuf<40> msg;
		msg.Format(_L("NotifyChangeOfCurrentNetwork %d"), iStatus.Int());
		post_error(msg, iStatus.Int(), GetTime());
		if (iErrorCount++ >= 10) {
			User::Leave(-1005);
		}
	} else {
		iErrorCount=0;
#ifndef __WINS__
#  ifdef BASICGSM
		if (async_info.iNetworkInfo.iShortName.CompareF(_L("elisa"))==0) {
			async_info.iNetworkInfo.iShortName=_L("RADIOLINJA");
		}
		iCell.iMCC()=async_info.iNetworkInfo.iId.iMCC;
		iCell.iMNC()=async_info.iNetworkInfo.iId.iMNC;
		iCell.iShortName=async_info.iNetworkInfo.iShortName;
		iCell.iLocationAreaCode()=async_info.iLocationAreaCode;
		iCell.iCellId()=async_info.iCellId;
		iCell.iMappedId()=iCellMap->GetId(iCell);
#  endif
#  ifdef ETEL3RDPARTY
		iCell.iMCC.FromStringL(async_info.iCountryCode);
		iCell.iMNC.FromStringL(async_info.iNetworkId);
		iCell.iShortName=async_info.iShortName;
		iCell.iLocationAreaCode()=async_info.iLocationAreaCode;
		iCell.iCellId()=async_info.iCellId;
		iCell.iMappedId()=iCellMap->GetId(iCell);
#  endif
#  ifdef MOBINFO
		//TBuf<100> msg=_L("cell mcc ");

		if (iInfoState==GETTING_FIRST_MCC || iInfoState==GETTING_NEW_MCC) {
			iCell.iMCC.FromStringL(iNetworkInfo.iNetworkCountryCode);
		}
		if (iInfoState==GETTING_FIRST_MCC) {
			//post_error(msg, KErrGeneral);
			iInfoState=GETTING_FIRST_CELL;
			iMobInfo->GetCellId(async_infop, iStatus);
			SetActive();
			return;
		}
		/*
		msg.Append(iNetworkInfo.iNetworkCountryCode);
		if (iInfoState==GETTING_CELL) {
			msg.Append(async_infop().iCountryCode);
			msg.Append(_L(" mnc "));
			msg.Append(async_infop().iNetworkIdentity);
			msg.Append(_L(" lac "));
			msg.AppendNum(async_infop().iLocationAreaCode);
			msg.Append(_L(" cellid "));
			msg.AppendNum(async_infop().iCellId);
		}
		post_error(msg, KErrGeneral);
		return;
		*/
		
		iCell.iMNC.FromStringL(async_infop().iNetworkIdentity);
		iCell.iShortName()=iNetworkInfo.iNetworkShortName;
		iCell.iLocationAreaCode()=async_infop().iLocationAreaCode;
		iCell.iCellId()=async_infop().iCellId;
		iCell.iMappedId()=iCellMap->GetId(iCell);

		if (	(iInfoState==GETTING_CELL) && 
				(iCell.iMNC() != prev_info.iLocationAreaCode)) {
			iInfoState=GETTING_NEW_MCC;
			iMobInfo->GetCellId(async_infop, iStatus);
			SetActive();
			return;
		}
		async_infop().iCountryCode=iNetworkInfo.iNetworkCountryCode;
		iInfoState=GETTING_CELL;
#  endif

		if ( iCell.iLocationAreaCode()==0 && iCell.iCellId()==0) {
			if (!iPostedMissing ) {
				iTimeOut->WaitMax(MISSING_TIMEOUT);
			}
		} else {
			ResetMissing();
			post_new_value(&iCell);
		}

#  ifndef MOBINFO
		prev_info=async_info;
#  else
		prev_info=async_infop();
#  endif
	}
#ifdef BASICGSM
#  ifndef __S60V2__
	Phone().NotifyChangeOfCurrentNetwork(iStatus, async_info);
#  else
	Phone().NotifyChangeOfCurrentNetworkNS(iStatus, async_info);
#  endif
#endif //BASICGSM

#ifdef ETEL3RDPARTY
	Telephony().NotifyChange(iStatus, CTelephony::ECurrentNetworkInfoChange, async_infop);
	i3rdpartyState=NOTIFYONCHANGE;
#endif

#ifdef MOBINFO
	post_error(_L("NotifyCellIdChange"), KErrGeneral);
	iMobInfo->NotifyCellIdChange(async_infop, iStatus);
#endif
	SetActive();
#else //WINS
		TTime this_time;
		TBuf<40> val=bases::test_data[test_data_i][1];
		while (! val.Compare(_L("SWITCH"))) {
			val=bases::test_data[++test_data_i][1];
		}
		TPtrC dtd(bases::test_data[test_data_i][0]);
		_LIT(KTime, "t");
		TBBTime t(KTime);
		t.FromStringL(dtd);
		CCellMap::Parse(val, iCell.iCellId(), iCell.iLocationAreaCode(), iCell.iShortName());
		iOpMap->NameToMccMnc(iCell.iShortName(), iCell.iMCC(), iCell.iMNC());
		++test_data_i;
		if (test_data_i == 322) {
			TInt x=0;
		}
		iCell.iMappedId()=iCellMap->GetId(iCell);
		post_new_value(&iCell, t());
		this_time=t();
		TTime next_time;
		{
			val=bases::test_data[test_data_i][1];
			while (! val.Compare(_L("SWITCH"))) {
				val=bases::test_data[++test_data_i][1];
			}
			TPtrC dtd(bases::test_data[test_data_i][0]);
			t.FromStringL(dtd);
			next_time=t();
		}
		TTimeIntervalMicroSeconds w=next_time.MicroSecondsFrom(this_time);
		TInt64 ms=w.Int64();
		//ms/=(60*5);
		wait_time=I64LOW(ms);
	}
void bases::move_into_place(cell_list_node* n, double t)
{
	CALLSTACKITEM_N(_CL("bases"), _CL("move_into_place"));

	// Invariant:
	// the top proportion*total_t nodes have up to date cum_t
	//
	// no other nodes can move up to that group than the
	// one we're moving, so updating nodes under it, if
	// they are within the group is enough to keep the invariant
	//
	// so even though we update cum_t for all nodes on the
	// way when moving the node, not all of them are 
	// necessarily correct

	if (!n) {
		post_error(_L("int error: n is NULL"), KErrGeneral);
		return;
	}

	total_t+=t;
	cell_list_node* update=n->next;
	n->t+=t;
	
	if (n->pos<=up_to_date_cum_pos) {
		if (n->pos==up_to_date_cum_pos) up_to_date_cum_pos=n->pos+1;
		if (n->next) n->next->cum_t=n->cum_t+n->next->t+t;
	}

	while (n->prev && n->prev->t < n->t) {
		cell_list_node* tmp;
		tmp=n->prev;

		if (n->next)
			n->next->prev=tmp;
		else last_cell=tmp;
		tmp->next=n->next;
		n->next=tmp;
		n->prev=tmp->prev;
		tmp->prev=n;

		if (n->prev) {
			n->prev->next=n;
			n->cum_t=n->prev->cum_t+n->t;
			n->pos=n->prev->pos+1;
			if (n->prev->pos==up_to_date_cum_pos) {
				up_to_date_cum_pos+=2;
				update=n->next;
			}
		} else {
			n->cum_t=n->t;
			n->pos=0;
		}
		n->next->cum_t=n->cum_t+n->next->t;	// (1)
		n->next->pos=n->pos+1;
	}
	if (!n->prev) {
		first_cell=n;
		n->cum_t=n->t; // if n was first, cum_t hasn't been updated yet
		n->pos=0;
	} else {
		n->cum_t=n->prev->cum_t+n->t; // if n wasn't moved, cum_t hasn't been updated yet
	}

	if (update && update->pos <= up_to_date_cum_pos) {
		while (update && (update->cum_t)<proportion*total_t) {
			// the first one has been updated by (1) or (2)
			up_to_date_cum_pos=update->pos;
			update=update->next;
			if (!update || !update->prev) {
				post_error(_L("int error, update->prev is NULL"), KErrGeneral);
			} else 
				if (update) update->cum_t=update->prev->cum_t+update->t;
			
		}
		if (update) {
			if (! update->prev ) {
				post_error(_L("int error, update->prev is NULL"), KErrGeneral);
			} else {
				update->cum_t=update->prev->cum_t+update->t;
				up_to_date_cum_pos=update->pos;
			}
		}
	}

	if (!learning_done ) {
		TTimeIntervalDays learning_period(2);

		if (! (first_time+learning_period > previous_time) ) {
			learning_done=true;
			cell_list_node* b=first_cell;
			while (b && b->cum_t<proportion*total_t) {
				add_as_base(b);
				update_database(b, false);
				b=b->next;
			}
			if (b) {
				add_as_base(b);
				update_database(b, false);
			}
		}
	} else {
		if (	(
				( ( (n->cum_t)<(proportion*total_t) ) && n->pos<=up_to_date_cum_pos) || 
				(!(n->prev)) ||
				(n->prev && ( (n->prev->cum_t)<(proportion*total_t) ) && n->prev->pos<=up_to_date_cum_pos) 
			)
				&& !n->is_base) 


			add_as_base(n);
	}

}