Ejemplo n.º 1
0
void configServer(CubeServer &server, Value &config)
{
	server.MaxConnections = getSizeT(config["MaxConnections"]);

#ifdef ENABLE_IPV4
	{
		Value &IPVal = config["IPv4"];
		if (IPVal["Enable"].GetBool())
		{
			log_normal("Listening %s:%d...", IPVal["Address"].GetString(), IPVal["Port"].GetUint());
			server.Listen(IPVal["Address"].GetString(), IPVal["Port"].GetUint(), IPVal["Backlog"].GetInt());
		}
	}
#endif

#ifdef ENABLE_IPV6
	{
		Value &IPVal = config["IPv6"];
		if (IPVal["Enable"].GetBool())
		{
			log_normal("Listening [%s]:%d...", IPVal["Address"].GetString(), IPVal["Port"].GetUint());
			server.Listen6(IPVal["Address"].GetString(), IPVal["Port"].GetUint(), IPVal["Backlog"].GetInt());
		}
	}
#endif

	server.NeedAuth = config["Auth"].GetBool();
	server.ServerKey = config["ServerKey"].GetString();
}
Ejemplo n.º 2
0
int main(int argc, char *argv[])
{
	string configFilename = "Config.json";
	string logFilename = "-";

#ifndef _WIN32
	cmdline::parser arg;
	arg.add<string>("config", 'c', "configuration file", false, "Config.json");
	arg.add<string>("log", 'l', "log file", false, "-");
	arg.parse_check(argc, argv);
	configFilename = arg.get<string>("config");
	logFilename = arg.get<string>("log");
#endif 

	log_normal("Using configuration file: %s", configFilename.c_str());
	log_normal("Log file: %s", logFilename.c_str());

	setLogFile(logFilename);

	Document configDoc = loadConfigObj(configFilename);
	Value &roomsVal = configDoc["Rooms"];
	assert(roomsVal.IsArray());
	vector<RoomInfo> rooms(loadRooms(roomsVal));

	initLibraries();

	CubeServer server;
	configRooms(server, rooms);

	server.EnableTimer(CHECK_INTERVAL_uS);

	configServer(server, configDoc["Server"]);

	server.IsRunning = true;
	thread th(eventEntry, &server);

	initHandlers();
	handleCommand(server);

	server.Stop();
	th.join();

	log_normal("%s", "Stopped.");

#ifdef MEM_DEBUG
#ifdef _WIN32
	_CrtDumpMemoryLeaks();
#endif 
#endif 

	return 0;
}
Ejemplo n.º 3
0
int myInit(unsigned int barbase, unsigned int privdata)
{
    log_normal("Reached myInit with barbase %x and privdata %x\n",
               barbase, privdata);

    spin_lock_bh(&RawLock);
    if(privdata == 0x54545454)  // So that this is done only once
    {
        TXbarbase = barbase;
    }
    else if(privdata == 0x54545456)  // So that this is done only once
    {
        RXbarbase = barbase;
    }
    TxBufCnt = 0;
    RxBufCnt = 0;
    ErrCnt = 0;
    TxSeqNo = RxSeqNo = 0;

    /* Stop any running tests. The driver could have been unloaded without
     * stopping running tests the last time. Hence, good to reset everything.
     */
    XIo_Out32(TXbarbase+TX_CONFIG_ADDRESS, 0);
    XIo_Out32(TXbarbase+RX_CONFIG_ADDRESS, 0);

    spin_unlock_bh(&RawLock);

    return 0;
}
Ejemplo n.º 4
0
/**************************************************************************
Only used for isometric view.
**************************************************************************/
void pixmap_put_overlay_tile_draw(GdkDrawable *pixmap,
				  int canvas_x, int canvas_y,
				  struct sprite *ssprite,
				  bool fog)
{
  if (!ssprite) {
    return;
  }

  if (fog && gui_gtk2_better_fog
      && ((ssprite->pixmap && !ssprite->pixmap_fogged)
	  || (!ssprite->pixmap && !ssprite->pixbuf_fogged))) {
    fog_sprite(ssprite);
    if ((ssprite->pixmap && !ssprite->pixmap_fogged)
        || (!ssprite->pixmap && !ssprite->pixbuf_fogged)) {
      log_normal(_("Better fog will only work in truecolor. Disabling it"));
      gui_gtk2_better_fog = FALSE;
    }
  }

  if (fog && gui_gtk2_better_fog) {
    if (ssprite->pixmap) {
      if (ssprite->mask) {
	gdk_gc_set_clip_origin(civ_gc, canvas_x, canvas_y);
	gdk_gc_set_clip_mask(civ_gc, ssprite->mask);
      }
      gdk_draw_drawable(pixmap, civ_gc,
			ssprite->pixmap_fogged,
			0, 0,
			canvas_x, canvas_y,
			ssprite->width, ssprite->height);
      gdk_gc_set_clip_mask(civ_gc, NULL);
    } else {
      gdk_draw_pixbuf(pixmap, civ_gc, ssprite->pixbuf_fogged,
		      0, 0, canvas_x, canvas_y, 
		      ssprite->width, ssprite->height,
		      GDK_RGB_DITHER_NONE, 0, 0);
    }
    return;
  }

  pixmap_put_sprite(pixmap, canvas_x, canvas_y, ssprite,
		    0, 0, ssprite->width, ssprite->height);

  /* I imagine this could be done more efficiently. Some pixels We first
     draw from the sprite, and then draw black afterwards. It would be much
     faster to just draw every second pixel black in the first place. */
  if (fog) {
    gdk_gc_set_clip_origin(fill_tile_gc, canvas_x, canvas_y);
    gdk_gc_set_clip_mask(fill_tile_gc, sprite_get_mask(ssprite));
    gdk_gc_set_foreground(fill_tile_gc,
			  &get_color(tileset, COLOR_MAPVIEW_UNKNOWN)->color);
    gdk_gc_set_ts_origin(fill_tile_gc, canvas_x, canvas_y);
    gdk_gc_set_stipple(fill_tile_gc, black50);

    gdk_draw_rectangle(pixmap, fill_tile_gc, TRUE,
		       canvas_x, canvas_y, ssprite->width, ssprite->height);
    gdk_gc_set_clip_mask(fill_tile_gc, NULL);
  }
}
Ejemplo n.º 5
0
int myPutRxPkt(void * hndl, PktBuf * vaddr, int numpkts, unsigned int privdata)
{
    int i, unused=0;
    unsigned int flags;

    //printk("Reached myPutRxPkt with handle %p, VA %x, size %d, privdata %x\n",
    //            hndl, (u32)vaddr, size, privdata);

    /* Check driver state */
    if(DriverState != REGISTERED)
    {
        printk("Driver does not seem to be ready\n");
        return -1;
    }

    /* Check handle value */
    if(hndl != handle[2])
    {
        log_normal("Came with wrong handle %x\n", (u32)hndl);
        return -1;
    }

    spin_lock_bh(&RawLock);

    for(i=0; i<numpkts; i++)
    {
        flags = vaddr->flags;
        //printk("RX pkt flags %x\n", flags);
        if(flags & PKT_UNUSED)
        {
            unused = 1;
            break;
        }
        if(flags & PKT_EOP)
        {
#ifdef DATA_VERIFY
            VerifyBuffer((unsigned char *)(vaddr->bufInfo), (vaddr->size), (vaddr->userInfo));
#endif
            RxSeqNo++;
        }
        RxBufCnt++;
        vaddr++;
    }

    /* Return packet buffers to free pool */

    //printk("PutRxPkt: Freeing %d packets unused %d\n", numpkts, unused);
    if(unused)
        FreeUnusedBuf(&RxBufs, numpkts);
    else
        FreeUsedBuf(&RxBufs, numpkts);

    spin_unlock_bh(&RawLock);

    return 0;
}
Ejemplo n.º 6
0
int myGetRxPkt(void * hndl, PktBuf * vaddr, unsigned int size, int numpkts, unsigned int privdata)
{
    unsigned char * bufVA;
    PktBuf * pbuf;
    int i;

    //printk(KERN_INFO "myGetRxPkt: Came with handle %p size %d privdata %x\n",
    //                        hndl, size, privdata);

    /* Check driver state */
    if(DriverState != REGISTERED)
    {
        printk("Driver does not seem to be ready\n");
        return 0;
    }

    /* Check handle value */
    if(hndl != handle[2])
    {
        printk("Came with wrong handle\n");
        return 0;
    }

    /* Check size value */
    if(size != BUFSIZE)
        printk("myGetRxPkt: Requested size %d does not match mine %d\n",
               size, (u32)BUFSIZE);

    spin_lock_bh(&RawLock);

    for(i=0; i<numpkts; i++)
    {
        pbuf = &(vaddr[i]);
        /* Allocate a buffer. DMA driver will map to PCI space. */
        bufVA = AllocBuf(&RxBufs);
        log_verbose(KERN_INFO "myGetRxPkt: The buffer after alloc is at address %x size %d\n",
                    (u32) bufVA, (u32) BUFSIZE);
        if (bufVA == NULL)
        {
            log_normal(KERN_ERR "RX: AllocBuf failed\n");
            break;
        }

        pbuf->pktBuf = bufVA;
        pbuf->bufInfo = bufVA;
        pbuf->size = BUFSIZE;
    }
    spin_unlock_bh(&RawLock);

    log_verbose(KERN_INFO "Requested %d, allocated %d buffers\n", numpkts, i);
    return i;
}
Ejemplo n.º 7
0
vector<RoomInfo> loadRooms(Value &rooms)
{
	log_normal("%s", "Loading rooms...");

	size_t count = rooms.Size();
	vector<RoomInfo> ris;

	for (size_t i = 0; i < count; ++i)
	{
		Value &room = rooms[i];

		RoomInfo ri;
		ri.Name = room["Name"].GetString();
		ri.NeedAuth = room["Auth"].GetBool();
		ri.Key = room["Key"].GetString();
		ri.Capacity = getSizeT(room["Capacity"]);
		ris.push_back(move(ri));
		log_normal("%s...", room["Name"].GetString());
	}

	return ris;
}
Ejemplo n.º 8
0
void unmount_filesystems(void)
{
    struct mounted_elem *mnt = mounted_list, *oldmnt;
    while ( mnt ) {
        log_normal(_("Unmounting device %s"), mnt->device);
        if ( run_command(NULL, UMOUNT_PATH, mnt->dir, 1) ) {
            log_warning(_("Failed to unmount device %s mounted on %s"), mnt->device, mnt->dir);
        }
        free(mnt->device);
        free(mnt->dir);
        oldmnt = mnt;
        mnt = mnt->next;
        free(oldmnt);
    }
    mounted_list = NULL;
}
Ejemplo n.º 9
0
/****************************************************************************
  Callback function for when there's an error in the server scan.
****************************************************************************/
void server_scan_error(struct server_scan *scan, const char *message)
{
  output_window_append(ftc_client, message);
  log_normal("%s", message);
  switch (server_scan_get_type(scan)) {
  case SERVER_SCAN_LOCAL:
    server_scan_finish(lan_scan);
    lan_scan = NULL;
    break;
  case SERVER_SCAN_GLOBAL:
    server_scan_finish(meta_scan);
    meta_scan = NULL;
    break;
  case SERVER_SCAN_LAST:
    break;
  }
}
Ejemplo n.º 10
0
int myInit(Xaddr barbase, unsigned int privdata)
{
    log_normal("Reached myInit with barbase %p and privdata %x\n", barbase, privdata);

    spin_lock_bh(&RawLock);
    if(privdata == 0x54545454)  // So that this is done only once
    {
        TXbarbase = barbase;
        log_verbose("guodebug TX: barbase   = %p\n", barbase);
        log_verbose("guodebug TX: TXbarbase = %p\n", TXbarbase);
    }
    else if(privdata == 0x54545456)  // So that this is done only once
    {
        RXbarbase = barbase;
        log_verbose("guodebug RX: barbase   = %x\n", barbase);
        log_verbose("guodebug RX: RXbarbase = %x\n", RXbarbase);
    }
    else
    {
        log_verbose("guodebug: myInit error!\n");
    }

    TxBufCnt = 0; 
    RxBufCnt = 0;
    ErrCnt   = 0;
    TxSeqNo  = RxSeqNo = 0;


    log_verbose("guodebug TXbarbase+TX_CONFIG_ADDRESS = %p\n", TXbarbase+TX_CONFIG_ADDRESS);
    //log_verbose("guodebug TXbarbase+RX_CONFIG_ADDRESS = %p\n", TXbarbase+RX_CONFIG_ADDRESS);

    /* Stop any running tests. The driver could have been unloaded without
     * stopping running tests the last time. Hence, good to reset everything.
     */
    XIo_Out32(TXbarbase+TX_CONFIG_ADDRESS, 0);
#ifndef XAUI
    XIo_Out32(TXbarbase+RX_CONFIG_ADDRESS, 0);
#endif

    spin_unlock_bh(&RawLock);
    return 0;
}
Ejemplo n.º 11
0
/**************************************************************************
  Check for messages sent by player thread
**************************************************************************/
void tai_refresh(struct ai_type *ait, struct player *pplayer)
{
  if (thrai.thread_running) {
    taireq_list_allocate_mutex(thrai.reqs_from.reqlist);
    while(taireq_list_size(thrai.reqs_from.reqlist) > 0) {
       struct tai_req *req;

       req = taireq_list_get(thrai.reqs_from.reqlist, 0);
       taireq_list_remove(thrai.reqs_from.reqlist, req);

       taireq_list_release_mutex(thrai.reqs_from.reqlist);

       log_normal("Plr thr sent %s", taireqtype_name(req->type));

       FC_FREE(req);

       taireq_list_allocate_mutex(thrai.reqs_from.reqlist);
     }
    taireq_list_release_mutex(thrai.reqs_from.reqlist);
  }
}
Ejemplo n.º 12
0
/**************************************************************************
  Do any necessary pre-initialization of the UI, if necessary.
**************************************************************************/
void ui_init(void)
{
    char device[20];
    /*  struct widget *pInit_String = NULL;*/
    SDL_Surface *pBgd;
    Uint32 iSDL_Flags;

    button_behavior.counting = FALSE;
    button_behavior.button_down_ticks = 0;
    button_behavior.hold_state = MB_HOLD_SHORT;
    button_behavior.event = fc_calloc(1, sizeof(SDL_MouseButtonEvent));

    SDL_Client_Flags = 0;
    iSDL_Flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE;

    /* auto center new windows in X enviroment */
    putenv((char *)"SDL_VIDEO_CENTERED=yes");

    init_sdl(iSDL_Flags);

    log_normal(_("Using Video Output: %s"),
               SDL_VideoDriverName(device, sizeof(device)));

    /* create splash screen */
#ifdef SMALL_SCREEN
    {
        SDL_Surface *pTmpSurf = load_surf(fileinfoname(get_data_dirs(),
                                          "misc/intro.png"));
        pBgd = zoomSurface(pTmpSurf, DEFAULT_ZOOM, DEFAULT_ZOOM, 0);
        FREESURFACE(pTmpSurf);
    }
#else  /* SMALL_SCREEN */
    pBgd = load_surf(fileinfoname(get_data_dirs(), "misc/intro.png"));
#endif /* SMALL_SCREEN */

    if (pBgd && SDL_GetVideoInfo()->wm_available) {
        set_video_mode(pBgd->w, pBgd->h, SDL_SWSURFACE | SDL_ANYFORMAT);
#if 0
        /*
         * call this for other than X enviroments - currently not supported.
         */
        center_main_window_on_screen();
#endif /* 0 */
        alphablit(pBgd, NULL, Main.map, NULL);
        putframe(Main.map,
                 0, 0, Main.map->w - 1, Main.map->h - 1,
        &(SDL_Color) {
            255, 255, 255, 255
        });
        FREESURFACE(pBgd);
        SDL_WM_SetCaption(_("SDL Client for Freeciv"), _("Freeciv"));
    } else {

#ifndef SMALL_SCREEN
        set_video_mode(640, 480, SDL_SWSURFACE | SDL_ANYFORMAT);
#else  /* SMALL_SCREEN */
        set_video_mode(320, 240, SDL_SWSURFACE | SDL_ANYFORMAT);
#endif /* SMALL_SCREEN */

        if(pBgd) {
            blit_entire_src(pBgd, Main.map, (Main.map->w - pBgd->w) / 2,
                            (Main.map->h - pBgd->h) / 2);
            FREESURFACE(pBgd);
        } else {
            SDL_FillRect(Main.map, NULL, SDL_MapRGB(Main.map->format, 0, 0, 128));
            SDL_WM_SetCaption(_("SDL Client for Freeciv"), _("Freeciv"));
        }
    }

#if 0
    /* create label beackground */
    pBgd = create_surf_alpha(adj_size(350), adj_size(50), SDL_SWSURFACE);

    SDL_FillRect(pBgd, NULL, SDL_MapRGBA(pBgd->format, 255, 255, 255, 128));
    putframe(pBgd, 0, 0, pBgd->w - 1, pBgd->h - 1, SDL_MapRGB(pBgd->format, 0, 0, 0));

    pInit_String = create_iconlabel(pBgd, Main.gui,
                                    create_str16_from_char(_("Initializing Client"), adj_font(20)),
                                    WF_ICON_CENTER|WF_FREE_THEME);
    pInit_String->string16->style |= SF_CENTER;

    draw_label(pInit_String,
               (Main.screen->w - pInit_String->size.w) / 2,
               (Main.screen->h - pInit_String->size.h) / 2);

    flush_all();

    copy_chars_to_string16(pInit_String->string16,
                           _("Waiting for the beginning of the game"));

#endif /* 0 */

    flush_all();
}
Ejemplo n.º 13
0
static int DmaSetupTransmit(void * hndl, int num)
{
    int i, result;
    static int pktsize=0;
    int total, bufsize, fragment;
    int bufindex;
    unsigned char * bufVA;
    PktBuf * pbuf;
    int origseqno;
    //static unsigned short lastno=0;

    log_verbose("Reached DmaSetupTransmit with handle %p, num %d\n", hndl, num);

    /* Check driver state */
    if(DriverState != REGISTERED)
    {
        printk("Driver does not seem to be ready\n");
        return 0;
    }

    /* Check handle value */
    if(hndl != handle[0])
    {
        printk("Came with wrong handle\n");
        return 0;
    }

    /* Check number of packets */
    if(!num)
    {
        printk("Came with 0 packets for sending\n");
        return 0;
    }

    /* Hold the spinlock only when calling the buffer management APIs. */
    spin_lock_bh(&RawLock);
    origseqno = TxSeqNo;
    for(i=0, bufindex=0; i<num; i++)            /* Total packets loop */
    {
        //printk("i %d bufindex %d\n", i, bufindex);

        /* Fix the packet size to be the maximum entered in GUI */
        pktsize = RawMaxPktSize;

        //printk("pktsize is %d\n", pktsize);

        total = 0;
        fragment = 0;
        while(total < pktsize)      /* Packet fragments loop */
        {
            //printk("Buf loop total %d bufindex %d\n", total, bufindex);

            pbuf = &(pkts[bufindex]);

            /* Allocate a buffer. DMA driver will map to PCI space. */
            bufVA = AllocBuf(&TxBufs);

            log_verbose(KERN_INFO "TX: The buffer after alloc is at address %x size %d\n",
                        (u32) bufVA, (u32) BUFSIZE);
            if (bufVA == NULL)
            {
                //printk("TX: AllocBuf failed\n");
                //printk("[%d]", (num-i-1));
                break;
            }
            pbuf->pktBuf = bufVA;
            pbuf->bufInfo = bufVA;
            bufsize = ((total + BUFSIZE) > pktsize) ?
                      (pktsize - total) : BUFSIZE ;
            total += bufsize;

            //printk("bufsize %d total %d\n", bufsize, total);

            log_verbose(KERN_INFO "Calling FormatBuffer pktsize %d bufsize %d fragment %d\n",
                        pktsize, bufsize, fragment);
            FormatBuffer(bufVA, pktsize, bufsize, fragment);

            pbuf->size = bufsize;
            pbuf->userInfo = TxSeqNo;
            pbuf->flags = PKT_ALL;
            if(!fragment)
                pbuf->flags |= PKT_SOP;
            if(total == pktsize)
            {
                pbuf->flags |= PKT_EOP;
                pbuf->size = bufsize;
            }

            //printk("flags %x\n", pbuf->flags);
            //printk("TxSeqNo %u\n", TxSeqNo);

            bufindex++;
            fragment++;
        }
        if(total < pktsize)
        {
            /* There must have been some error in the middle of the packet */

            if(fragment)
            {
                /* First, adjust the number of buffers to queue up or else
                 * partial packets will get transmitted, which will cause a
                 * problem later.
                 */
                bufindex -= fragment;

                /* Now, free any unused buffers from the partial packet, so
                 * that buffers are not lost.
                 */
                log_normal(KERN_ERR "Tried to send pkt of size %d, only %d fragments possible\n",
                           pktsize, fragment);
                FreeUnusedBuf(&TxBufs, fragment);
            }
            break;
        }


        /* Increment packet sequence number */
        //if(lastno != TxSeqNo) printk(" %u-%u.", lastno, TxSeqNo);
        TxSeqNo++;
        //lastno = TxSeqNo;
    }
    spin_unlock_bh(&RawLock);

    //printk("[p%d-%d-%d] ", num, i, bufindex);

    if(i == 0)
        /* No buffers available */
        return 0;

    log_verbose("%s: Sending packet length %d seqno %d\n",
                MYNAME, pktsize, TxSeqNo);
    result = DmaSendPkt(hndl, pkts, bufindex);
    TxBufCnt += result;
    if(result != bufindex)
    {
        log_normal(KERN_ERR "Tried to send %d pkts in %d buffers, sent only %d\n",
                   num, bufindex, result);
        //printk("[s%d-%d,%d-%d]", bufindex, result, TxSeqNo, origseqno);
        if(result) TxSeqNo = pkts[result].userInfo;
        else TxSeqNo = origseqno;
        //printk("-%u-", TxSeqNo);
        //lastno = TxSeqNo;

        spin_lock_bh(&RawLock);
        FreeUnusedBuf(&TxBufs, (bufindex-result));
        spin_unlock_bh(&RawLock);
        return 0;
    }
    else return 1;
}
Ejemplo n.º 14
0
/**************************************************************************
  Main entry point for freeciv-ruledit
**************************************************************************/
int main(int argc, char **argv)
{
  enum log_level loglevel = LOG_NORMAL;
  int ui_options;

  init_nls();

#ifdef ENABLE_NLS
  (void) bindtextdomain("freeciv-ruledit", LOCALEDIR);
#endif

  registry_module_init();
  init_character_encodings(FC_DEFAULT_DATA_ENCODING, FALSE);

  log_init(NULL, loglevel, NULL, NULL, -1);

  ui_options = re_parse_cmdline(argc, argv);

  if (ui_options != -1) {
    init_connections();

    settings_init(FALSE);

    /* Reset aifill to zero */
    game.info.aifill = 0;

    game_init();
    i_am_server();

    if (source_rs !=  NULL) {
      sz_strlcpy(game.server.rulesetdir, source_rs);
    }

    if (load_rulesets(NULL, FALSE)) {
      log_normal("Terrains:     %d", game.control.terrain_count);
      log_normal("Resources:    %d", game.control.resource_count);
      log_normal("Techs:        %d", game.control.num_tech_types);
      log_normal("Unit classes: %d", game.control.num_unit_classes);
      log_normal("Unit types:   %d", game.control.num_unit_types);
      log_normal("Buildings:    %d", game.control.num_impr_types);
      log_normal("Nations:      %d", game.control.nation_count);
      log_normal("City Styles:  %d", game.control.styles_count);
      log_normal("Specialists:  %d", game.control.num_specialist_types);
      log_normal("Governments:  %d", game.control.government_count);
      log_normal("Disasters:    %d", game.control.num_disaster_types);
      log_normal("Achievements: %d", game.control.num_achievement_types);
      log_normal("Extras:       %d", game.control.num_extra_types);
      log_normal("Bases:        %d", game.control.num_base_types);
      log_normal("Roads:        %d", game.control.num_road_types);

      ruledit_qt_setup(ui_options, argv);
      ruledit_qt_run();
      ruledit_qt_close();
    } else {
      log_error("Loading ruleset %s failed", game.server.rulesetdir);
    }
  }

  log_close();
  registry_module_close();

  return EXIT_SUCCESS;
}
Ejemplo n.º 15
0
/**
 * This function must be called by the user driver to unregister itself from
 * the base DMA driver. After doing required checks to verify the handle
 * and engine state, the DMA engine is reset, interrupts are disabled if
 * required, and the BD ring is freed, while returning all the packet buffers
 * to the user driver.
 *
 * @param handle is the handle which was assigned during the registration
 * process.
 * @param pkts is a PktBuf array, with the array of packets to be sent.
 * @param numpkts is the number of packets in the PktBuf array.
 *
 * @return 0 incase of any error
 * @return Number of packets successfully queued for DMA send, incase of
 * success.
 *
 * @note There may not be enough BDs to accomodate the number of packets
 * requested by the user driver, so the returned value may not match with
 * the requested numpkts. The user driver must be written to manage this
 * appropriately.
 *
 *
 *****************************************************************************/
int DmaSendPkt(void * handle, PktBuf * pkts, int numpkts)
{
#if defined DEBUG_NORMAL || defined DEBUG_VERBOSE
    static int send_count=1;
#endif
    int free_bd_count ;
    Dma_Engine * eptr;
    Dma_BdRing * rptr;
    struct pci_dev *pdev;
    struct privData *lp = NULL;
    Dma_Bd *BdPtr, *BdCurPtr, *PartialBDPtr=NULL;
    dma_addr_t bufPA;
    int result;
    PktBuf * pbuf;
    u32 flags, uflags;
    int i, len;
    int partialBDcount = 0, partialOK = 0;

    log_verbose(KERN_INFO "User send pkt for engine %p, numpkts %d\n",
                handle, numpkts);
    if(DriverState != INITIALIZED)
    {
        printk(KERN_ERR "DMA driver state %d - not ready\n", DriverState);
        return 0;
    }

    eptr = (Dma_Engine *)handle;
    rptr = &(eptr->BdRing);

    /* Check if this engine's pointer is valid */
    if(eptr == NULL)
    {
        printk(KERN_ERR "Handle is a NULL value\n");
        return 0;
    }

    /* Is the number valid? */
    if(numpkts <= 0) {
        log_normal(KERN_ERR "Packet count should be non-zero\n");
        return 0;
    }

    /* Is the engine assigned to any user? */
    if(eptr->EngineState != USER_ASSIGNED) {
        log_normal(KERN_ERR "Engine is not assigned to any user\n");
        return 0;
    }

    /* Is the engine an S2C one? */
    if(rptr->IsRxChannel)
    {
        log_normal(KERN_ERR "The requested engine cannot send packets\n");
        return 0;
    }

    pdev = eptr->pdev;
    lp = pci_get_drvdata(pdev);

    /* Protect this entry point from the handling of sent packets */
    spin_lock_bh(&DmaLock);

    /* Ensure that requested number of packets can be queued up */
    free_bd_count = Dma_mBdRingGetFreeCnt(rptr);

#if defined DEBUG_NORMAL || defined DEBUG_VERBOSE
    log_normal(KERN_INFO "DmaSendPkt: #%d \n", send_count);
    send_count += numpkts;
    log_verbose(KERN_INFO "BD ring %x Free BD count is %d\n",
                (u32)rptr, free_bd_count);
    //disp_frag((unsigned char *)bufVA, pktsize);
#endif

    /* Maintain a separation between start and end of BD ring. This is
     * required because DMA will stall if the two pointers coincide -
     * this will happen whether ring is full or empty.
     */
    if(free_bd_count > 2) free_bd_count -= 2;
    else
    {
        log_verbose(KERN_ERR "Not enough BDs to handle %d pkts\n", numpkts);
        spin_unlock_bh(&DmaLock);
        return 0;
    }

    log_normal("DmaSendPkt: numpkts %d free_bd_count %d\n", numpkts, free_bd_count);

    /* Fewer BDs are available than required */
    if(numpkts > free_bd_count)
        numpkts = free_bd_count;

    /* Allocate BDs from ring */
    result = Dma_BdRingAlloc(rptr, numpkts, &BdPtr);
    if (result != XST_SUCCESS) {
        /* we really shouldn't get this */
        printk(KERN_ERR "DmaSendPkt: BdRingAlloc unsuccessful (%d)\n", result);
        spin_unlock_bh(&DmaLock);
        return 0;
    }

    BdCurPtr = BdPtr;
    partialBDcount = 0;
    for(i=0; i<numpkts; i++)
    {
        pbuf = &(pkts[i]);
        bufPA = pci_map_single(pdev, pbuf->pktBuf, pbuf->size, PCI_DMA_TODEVICE);
        log_verbose(KERN_INFO "DmaSendPkt: BD %x buf PA %x VA %x size %d\n",
                    (u32)BdCurPtr, bufPA, (u32) (pbuf->pktBuf), pbuf->size);

        Dma_mBdSetBufAddr(BdCurPtr, bufPA);
        Dma_mBdSetCtrlLength(BdCurPtr, pbuf->size);
        Dma_mBdSetStatLength(BdCurPtr, pbuf->size); // Required for TX BDs
        Dma_mBdSetId(BdCurPtr, (unsigned long)pbuf->bufInfo); //guodebug: error prone

        uflags = pbuf->flags;
        flags = 0;
        if(uflags & DMA_BD_SOP_MASK)
        {
            flags |= DMA_BD_SOP_MASK;

            partialOK = (uflags & PKT_ALL) ? 0 : 1;
            if(!partialOK) PartialBDPtr = BdCurPtr;
        }

        /* Keep track of whether the buffer is the last one in a packet */
        if(uflags & DMA_BD_EOP_MASK)
        {
            flags |= DMA_BD_EOP_MASK;
            partialBDcount = 0;
        }
        else
            partialBDcount++;
        //printk("partialBDcount = %d partialOK = %d PartialBDPtr = %x\n",
        //                        partialBDcount, partialOK, (u32)PartialBDPtr);

        Dma_mBdSetCtrl(BdCurPtr, flags);                 // No ints also.
        Dma_mBdSetUserData(BdCurPtr, pbuf->userInfo);

#ifdef TH_BH_ISR
        /* Enable interrupts for errors and completion based on
         * coalesce count.
         */
        flags |= DMA_BD_INT_ERROR_MASK;
        if(!(eptr->intrCount % INT_COAL_CNT))
            flags |= DMA_BD_INT_COMP_MASK;
        eptr->intrCount += 1;
        Dma_mBdSetCtrl(BdCurPtr, flags);
#endif

        log_verbose("DmaSendPkt: free %d BD %x buf PA %x VA %x size %d flags %x\n",
                    free_bd_count, (u32)BdCurPtr, bufPA, (u32) (pbuf->pktBuf),
                    pbuf->size, flags);

        BdCurPtr = Dma_mBdRingNext(rptr, BdCurPtr);
    }

    /* Ensure that the user does not require all or no fragments of a packet
     * to be handled. For example, incase of a SG-list of multi-BD packets,
     * the user might require all fragments to be handled together.
     */
    if(partialBDcount && !partialOK)
        log_normal(KERN_ERR "Cannot accomodate %d buffers. Discarding %d.\n",
                   numpkts, partialBDcount);

    /* enqueue TxBD with the attached buffer such that it is
     * ready for frame transmission.
     */
    result = Dma_BdRingToHw(rptr, (numpkts-partialBDcount), BdPtr);
    if((result != XST_SUCCESS) || partialBDcount)
    {
        int count=0;
        if(result != XST_SUCCESS)
        {
            /* We should not come here. Incase of error, unmap buffers,
             * unallocated BDs, and return zero count so that app driver
             * can recover unused buffers.
             */
            printk(KERN_ERR "DmaSendPkt: BdRingToHw unsuccessful (%d)\n",
                   result);
            BdCurPtr = BdPtr;
            count = numpkts;
        }
        else if(partialBDcount)
        {
            /* Don't allow partial packets to be queued for DMA incase user
             * does not wish it. Unmap buffers, unallocate BDs, return the
             * count so that app driver can recover unused buffers.
             */
            log_verbose(KERN_ERR "DmaSendPkt: Recovering partial buffers\n");

            BdPtr = BdCurPtr = PartialBDPtr;
            count = partialBDcount;
        }

        for(i=0; i<count; i++)
        {
            bufPA = Dma_mBdGetBufAddr(BdCurPtr);
            len = Dma_mBdGetCtrlLength(BdCurPtr);
            pci_unmap_single(pdev, bufPA, len, PCI_DMA_TODEVICE);
            Dma_mBdSetId(BdCurPtr, 0LL);
            BdCurPtr = Dma_mBdRingNext(rptr, BdCurPtr);
        }
        Dma_BdRingUnAlloc(rptr, count, BdPtr);
        numpkts -= count;
    }

    spin_unlock_bh(&DmaLock);

    log_verbose("DmaSendPkt: Successfully transmitted %d buffers\n", numpkts);
    return numpkts;
}
Ejemplo n.º 16
0
/* Function to detect the MB of diskspace on a path */
int detect_diskspace(const char *path)
{
	long long avail = 0LL;

	if ( path[0] == '/' ) {
#ifdef HAVE_SYS_STATVFS_H
		struct statvfs fs;
#else
		struct statfs fs;
#endif
		char buf[PATH_MAX], *cp;

		strcpy(buf, path);
        cp = buf+strlen(buf);
        while ( buf[0] && (access(buf, F_OK) < 0) ) {
            while ( (cp > (buf+1)) && (*cp != '/') ) {
                --cp;
            }
            *cp = '\0';
        }
		if ( buf[0] ) {
#ifdef HAVE_SYS_STATVFS_H
			if ( statvfs(buf, &fs) ) {
#else
			if ( statfs(buf, &fs) ) {
#endif
				perror("statfs");
				return 0;
			}
			avail = fs.f_bsize;
			avail *= fs.f_bavail;
		}
	}
	return avail / (1024*1024LL);
}

int detect_and_mount_cdrom(char *path[SETUP_MAX_DRIVES])
{
	int num_cdroms = 0;

#ifdef __FreeBSD__
	int mounted;
    struct fstab *fstab;

    /* Try to mount unmounted CDROM filesystems */
    while( (fstab = getfsent()) != NULL ){
        if ( !strcmp(fstab->fs_vfstype, MNTTYPE_CDROM)) {
            if ( !is_fs_mounted(fstab->fs_spec)) {
                if ( ! run_command(NULL, MOUNT_PATH, fstab->fs_spec, 1) ) {
                    add_mounted_entry(fstab->fs_spec, fstab->fs_file);
                    log_normal(_("Mounted device %s"), fstab->fs_spec);
                }
            }
        }
    }
    endfsent();

    mounted = getfsstat(NULL, 0, MNT_WAIT);
    if ( mounted > 0 ) {
        int i;
		struct statfs *mnts = (struct statfs *)malloc(sizeof(struct statfs) * mounted);

		mounted = getfsstat(mnts, mounted * sizeof(struct statfs), MNT_WAIT);
		for ( i = 0; i < mounted && num_cdroms < SETUP_MAX_DRIVES; ++ i ) {
			if ( ! strcmp(mnts[i].f_fstypename, MNTTYPE_CDROM) ) {
				path[num_cdroms ++] = strdup(mnts[i].f_mntonname);
			}
		}
		
		free(mnts);
    }
#elif defined(darwin)
{
    const char *devPrefix = "/dev/";
    int prefixLen = strlen(devPrefix);
    mach_port_t masterPort = 0;
    struct statfs *mntbufp;
    int i, mounts;

    if (IOMasterPort(MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
    {
        mounts = getmntinfo(&mntbufp, MNT_WAIT);  /* NOT THREAD SAFE! */
        for (i = 0; i < mounts && num_cdroms < SETUP_MAX_DRIVES; i++)
        {
            char *dev = mntbufp[i].f_mntfromname;
            char *mnt = mntbufp[i].f_mntonname;
            if (strncmp(dev, devPrefix, prefixLen) != 0)  /* virtual device? */
                continue;

            /* darwinIsMountedDisc needs to skip "/dev/" part of string... */
            if (darwinIsMountedDisc(dev + prefixLen, masterPort))
            {
                strcpy(darwinEjectThisCDDevice, dev + prefixLen);
                path[num_cdroms ++] = strdup(mnt);
            }
        }
    }
}
#elif defined(sco)
	/* Quite horrible. We have to parse mount's output :( */
	/* And of course, we can't try to mount unmounted filesystems */
	FILE *cmd = popen("/etc/mount", "r");
	if ( cmd ) {
		char device[32] = "", mountp[PATH_MAX] = "";
		while ( fscanf(cmd, "%s on %32s %*[^\n]", mountp, device) > 0 ) {
			if ( !strncmp(device, "/dev/cd", 7) ) {
				path[num_cdroms ++] = strdup(mountp);
				break;
			}
		}
		pclose(cmd);
	}

#elif defined(hpux)
    char mntdevpath[PATH_MAX];
    FILE *mountfp;
    struct mntent *mntent;
    const char *fstab, *mtab, *mount_cmd, *mnttype;

    /* HPUX: We need to support PFS */
    if ( !access("/etc/pfs_fstab", F_OK) ) {
		fstab = "/etc/pfs_fstab";
		mtab = "/etc/pfs_mtab";
		mount_cmd = "/usr/sbin/pfs_mount";
		mnttype = "pfs-rrip";
    } else {
		fstab = SETUP_FSTAB;
		mtab = MOUNTS_FILE;
		mnttype = MNTTYPE_CDROM;
		mount_cmd = MOUNT_PATH;
    }

    /* Try to mount unmounted CDROM filesystems */
    mountfp = setmntent( fstab, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL ){
            if ( !strcmp(mntent->mnt_type, mnttype) ) {
                char *fsname = strdup(mntent->mnt_fsname);
                char *dir = strdup(mntent->mnt_dir);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, mount_cmd, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
            }
        }
        endmntent(mountfp);
    }
    
    mountfp = setmntent(mtab, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL && num_cdroms < SETUP_MAX_DRIVES){
            char mntdev[1024], mnt_type[32];

            strcpy(mntdev, mntent->mnt_fsname);
            strcpy(mnt_type, mntent->mnt_type);
            if( strncmp(mntdev, "/dev", 4) || 
                realpath(mntdev, mntdevpath) == NULL ) {
                continue;
            }
            if ( strcmp(mnt_type, mnttype) == 0 ) {
				path[num_cdroms ++] = strdup(mntent->mnt_dir);
            }
        }
        endmntent( mountfp );
    }
#elif defined(__svr4__)
	struct mnttab mnt;

	FILE *fstab = fopen(SETUP_FSTAB, "r");
	if ( fstab != NULL ) {
		while ( getmntent(fstab, &mnt)==0 ) {
			if ( !strcmp(mnt.mnt_fstype, MNTTYPE_CDROM) ) {
                char *fsname = strdup(mnt.mnt_special);
                char *dir = strdup(mnt.mnt_mountp);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, MOUNT_PATH, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
				break;
			}
		}
		fclose(fstab);
		fstab = fopen(MOUNTS_FILE, "r");
		if (fstab) {
			while ( getmntent(fstab, &mnt)==0 && num_cdroms < SETUP_MAX_DRIVES) {
				if ( !strcmp(mnt.mnt_fstype, MNTTYPE_CDROM) ) {
					path[num_cdroms ++] = strdup(mnt.mnt_mountp);
				}
			}
			fclose(fstab);
		}
	}
    
#else
//#ifndef darwin
    char mntdevpath[PATH_MAX];
    FILE *mountfp;
    struct mntent *mntent;

    /* Try to mount unmounted CDROM filesystems */
    mountfp = setmntent( SETUP_FSTAB, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL ){
            if ( (!strcmp(mntent->mnt_type, MNTTYPE_CDROM) 
#ifdef sgi
				 || !strcmp(mntent->mnt_type, "cdfs")
				 || !strcmp(mntent->mnt_type, "efs")
#endif
				 || !strcmp(mntent->mnt_type, "auto"))
				 && strncmp(mntent->mnt_fsname, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY)) ) {
                char *fsname = strdup(mntent->mnt_fsname);
                char *dir = strdup(mntent->mnt_dir);
                if ( !is_fs_mounted(fsname)) {
                    if ( ! run_command(NULL, MOUNT_PATH, fsname, 1) ) {
                        add_mounted_entry(fsname, dir);
                        log_normal(_("Mounted device %s"), fsname);
                    }
                }
                free(fsname);
                free(dir);
            }
        }
        endmntent(mountfp);
    }
    
    mountfp = setmntent(MOUNTS_FILE, "r" );
    if( mountfp != NULL ) {
        while( (mntent = getmntent( mountfp )) != NULL && num_cdroms < SETUP_MAX_DRIVES){
            char *tmp, mntdev[1024], mnt_type[32];

			if ( strncmp(mntent->mnt_fsname, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY)) == 0)
				continue;

            strcpy(mntdev, mntent->mnt_fsname);
            strcpy(mnt_type, mntent->mnt_type);
            if ( strcmp(mnt_type, MNTTYPE_SUPER) == 0 ) {
                tmp = strstr(mntent->mnt_opts, "fs=");
                if ( tmp ) {
                    strcpy(mnt_type, tmp+strlen("fs="));
                    tmp = strchr(mnt_type, ',');
                    if ( tmp ) {
                        *tmp = '\0';
                    }
                }
		tmp = strstr(mntent->mnt_opts, "dev=");
		if ( tmp ) {
                    strcpy(mntdev, tmp+strlen("dev="));
                    tmp = strchr(mntdev, ',');
                    if ( tmp ) {
                        *tmp = '\0';
                    }
                }
            }
            if( strncmp(mntdev, "/dev", 4) || 
                realpath(mntdev, mntdevpath) == NULL ) {
                continue;
            }
            if ( strcmp(mnt_type, MNTTYPE_CDROM) == 0 ) {
	        path[num_cdroms ++] = strdup(mntent->mnt_dir);
            } else if ( strcmp(mnt_type, "auto") == 0 &&
			strncmp(mntdev, DEVICE_FLOPPY, strlen(DEVICE_FLOPPY))) {
	        path[num_cdroms ++] = strdup(mntent->mnt_dir);		
	    }
#ifdef sgi
            else if ( strcmp(mnt_type, "cdfs") == 0 ||
                      strcmp(mnt_type, "efs")  == 0 ) {
	      path[num_cdroms ++] = strdup(mntent->mnt_dir);
            }
#endif
        }
        endmntent( mountfp );
    }
//#endif
#endif
	return num_cdroms;
}
Ejemplo n.º 17
0
/**
 * This function must be called by the user driver to register itself with
 * the base DMA driver. After doing required checks to verify the choice
 * of engine and BAR register, it initializes the engine and the BD ring
 * associated with the engine, and enables interrupts if required.
 *
 * Only one user is supported per engine at any given time. Incase the
 * engine has already been registered with another user driver, an error
 * will be returned.
 *
 * @param engine is the DMA engine the user driver wants to use.
 * @param bar is the BAR register the user driver wants to use.
 * @param uptr is a pointer to the function callbacks in the user driver.
 * @param pktsize is the size of packets that the user driver will normally
 *        use.
 *
 * @return NULL incase of any error in completing the registration.
 * @return Handle with which the user driver is registered.
 *
 * @note This function should not be called in an interrupt context
 *
 *****************************************************************************/
void * DmaRegister(int engine, int bar, UserPtrs * uptr, int pktsize)
{
    Dma_Engine * eptr;
    Xaddr barbase;
    int result;

    log_verbose(KERN_INFO "User register for engine %d, BAR %d, pktsize %d\n", engine, bar, pktsize);

    if(DriverState != INITIALIZED)
    {
        printk(KERN_ERR "DMA driver state %d - not ready\n", DriverState);
        return NULL;
    }

    if((bar < 0) || (bar > 5)) {
        printk(KERN_ERR "Requested BAR %d is not valid\n", bar);
        return NULL;
    }

    if(!((dmaData->engineMask) & (1LL << engine))) {
        printk(KERN_ERR "Requested engine %d does not exist\n", engine);
        return NULL;
    }
    eptr = &(dmaData->Dma[engine]);
    barbase = (Xaddr)(dmaData->barInfo[bar].baseVAddr);
    log_verbose("guodebug DmaReg: barbase = %p\n", barbase);

    if(eptr->EngineState != INITIALIZED) {
        printk(KERN_ERR "Requested engine %d is not free\n", engine);
        return NULL;
    }

    /* Later, add check for reasonable packet size !!!! */

    /* Later, add check for mandatory user function pointers. For optional
     * ones, assign a stub function pointer. This is better than doing
     * a NULL value check in the performance path. !!!!
     */

    /* Copy user-supplied parameters */
    eptr->user = *uptr;
    eptr->pktSize = pktsize;

    /* Should check for errors returned here !!!! */
    (uptr->UserInit)(barbase, uptr->privData);

    spin_lock_bh(&DmaLock);

    /* Should inform the user of the errors !!!! */
    result = descriptor_init(eptr->pdev, eptr);
    if (result) {
        /* At this point, handle has not been returned to the user.
         * So, user refuses to prepare buffers. Will be trying again in
         * the poll_routine. So, do not abort here.
         */
        printk(KERN_ERR "Cannot create BD ring, will try again later.\n");
        //return NULL;
    }

    /* Change the state of the engine, and increment the user count */
    eptr->EngineState = USER_ASSIGNED;
    dmaData->userCount ++ ;

    /* Start the DMA engine */
    if (Dma_BdRingStart(&(eptr->BdRing)) == XST_FAILURE) {
        log_normal(KERN_ERR "DmaRegister: Could not start Dma channel\n");
        return NULL;
    }

#ifdef TH_BH_ISR
    printk("Now enabling interrupts\n");
    Dma_mEngIntEnable(eptr);
#endif

    spin_unlock_bh(&DmaLock);

    log_verbose(KERN_INFO "Returning user handle %p\n", eptr);

    return eptr;
}
Ejemplo n.º 18
0
/**************************************************************************
  Initialize audio system and autoselect a plugin
**************************************************************************/
void audio_real_init(const char *const spec_name,
		     const char *const prefered_plugin_name)
{
  const char *filename;
  const char *file_capstr;
  char us_capstr[] = "+soundspec";

  if (strcmp(prefered_plugin_name, "none") == 0) {
    /* We explicitly choose none plugin, silently skip the code below */
    log_verbose("Proceeding with sound support disabled.");
    tagfile = NULL;
    return;
  }
  if (num_plugins_used == 1) {
    /* We only have the dummy plugin, skip the code but issue an advertise */
    log_normal(_("No real audio plugin present."));
    log_normal(_("Proceeding with sound support disabled."));
    log_normal(_("For sound support, install SDL_mixer"));
    log_normal("http://www.libsdl.org/projects/SDL_mixer/index.html");
    tagfile = NULL;
    return;
  }
  if (!spec_name) {
    log_fatal("No sound spec-file given!");
    exit(EXIT_FAILURE);
  }
  log_verbose("Initializing sound using %s...", spec_name);
  filename = soundspec_fullname(spec_name);
  if (!filename) {
    log_error("Cannot find sound spec-file \"%s\".", spec_name);
    log_normal(_("To get sound you need to download a sound set!"));
    log_normal(_("Get sound sets from <%s>."),
               "http://www.freeciv.org/wiki/Sounds");
    log_normal(_("Proceeding with sound support disabled."));
    tagfile = NULL;
    return;
  }
  if (!(tagfile = secfile_load(filename, TRUE))) {
    log_fatal(_("Could not load sound spec-file '%s':\n%s"), filename,
              secfile_error());
    exit(EXIT_FAILURE);
  }

  file_capstr = secfile_lookup_str(tagfile, "soundspec.options");
  if (NULL == file_capstr) {
    log_fatal("Audio spec-file \"%s\" doesn't have capability string.",
              filename);
    exit(EXIT_FAILURE);
  }
  if (!has_capabilities(us_capstr, file_capstr)) {
    log_fatal("sound spec-file appears incompatible:");
    log_fatal("  file: \"%s\"", filename);
    log_fatal("  file options: %s", file_capstr);
    log_fatal("  supported options: %s", us_capstr);
    exit(EXIT_FAILURE);
  }
  if (!has_capabilities(file_capstr, us_capstr)) {
    log_fatal("sound spec-file claims required option(s) "
              "which we don't support:");
    log_fatal("  file: \"%s\"", filename);
    log_fatal("  file options: %s", file_capstr);
    log_fatal("  supported options: %s", us_capstr);
    exit(EXIT_FAILURE);
  }

  free((void *) filename);

  atexit(audio_shutdown);

  if (prefered_plugin_name[0] != '\0') {
    if (!audio_select_plugin(prefered_plugin_name))
      log_normal(_("Proceeding with sound support disabled."));
    return;
  }

#ifdef AUDIO_SDL
  if (audio_select_plugin("sdl")) return; 
#endif
  log_normal(_("No real audio subsystem managed to initialize!"));
  log_normal(_("Perhaps there is some misconfiguration or bad permissions."));
  log_normal(_("Proceeding with sound support disabled."));
}
Ejemplo n.º 19
0
/**************************************************************************
  SDL-client main loop.
**************************************************************************/
Uint16 gui_event_loop(void *pData,
                      void (*loop_action)(void *pData),
                      Uint16 (*key_down_handler)(SDL_keysym Key, void *pData),
                      Uint16 (*key_up_handler)(SDL_keysym Key, void *pData),
                      Uint16 (*mouse_button_down_handler)(SDL_MouseButtonEvent *pButtonEvent, void *pData),
                      Uint16 (*mouse_button_up_handler)(SDL_MouseButtonEvent *pButtonEvent, void *pData),
                      Uint16 (*mouse_motion_handler)(SDL_MouseMotionEvent *pMotionEvent, void *pData))
{
    Uint16 ID;
    static struct timeval tv;
    static fd_set civfdset;
    Uint32 t_current, t_last_unit_anim, t_last_map_scrolling;
    Uint32 real_timer_next_call;
    static int result, schot_nr = 0;
    static char schot[32];

    ID = ID_ERROR;
    t_last_map_scrolling = t_last_unit_anim = real_timer_next_call = SDL_GetTicks();
    while (ID == ID_ERROR) {
        /* ========================================= */
        /* net check with 10ms delay event loop */
        if ((net_socket >= 0) || (ggz_socket >= 0)) {
            FD_ZERO(&civfdset);

            if (net_socket >= 0) {
                FD_SET(net_socket, &civfdset);
            }
            if (ggz_socket >= 0) {
                FD_SET(ggz_socket, &civfdset);
            }

            tv.tv_sec = 0;
            tv.tv_usec = 10000;/* 10ms*/

            result = fc_select(MAX(net_socket, ggz_socket) + 1, &civfdset, NULL, NULL, &tv);
            if (result < 0) {
                if (errno != EINTR) {
                    break;
                } else {
                    continue;
                }
            } else {
                if (result > 0) {
                    if ((net_socket >= 0) && FD_ISSET(net_socket, &civfdset)) {
                        SDL_PushEvent(pNet_User_Event);
                    }
                    if ((ggz_socket >= 0) && FD_ISSET(ggz_socket, &civfdset)) {
                        SDL_PushEvent(pGGZ_User_Event);
                    }
                }
            }
        } else { /* if connection is not establish */
            SDL_Delay(10);
        }
        /* ========================================= */

        t_current = SDL_GetTicks();

        if (t_current > real_timer_next_call) {
            real_timer_next_call = t_current + (real_timer_callback() * 1000);
        }

        if ((t_current - t_last_unit_anim) > UNITS_TIMER_INTERVAL) {
            if (autoconnect) {
                widget_info_counter++;
                SDL_PushEvent(pAnim_User_Event);
            } else {
                SDL_PushEvent(pAnim_User_Event);
            }

            t_last_unit_anim = SDL_GetTicks();
        }

        if (is_map_scrolling) {
            if ((t_current - t_last_map_scrolling) > MAP_SCROLL_TIMER_INTERVAL) {
                SDL_PushEvent(pMap_Scroll_User_Event);
                t_last_map_scrolling = SDL_GetTicks();
            }
        } else {
            t_last_map_scrolling = SDL_GetTicks();
        }

        if (widget_info_counter > 0) {
            SDL_PushEvent(pInfo_User_Event);
            widget_info_counter = 0;
        }

        /* ========================================= */

        if (loop_action) {
            loop_action(pData);
        }

        /* ========================================= */

        while (SDL_PollEvent(&Main.event) == 1) {

            switch (Main.event.type) {

            case SDL_QUIT:
                return MAX_ID;
                break;

            case SDL_KEYUP:
                switch (Main.event.key.keysym.sym) {
                /* find if Shifts are released */
                case SDLK_RSHIFT:
                    RSHIFT = FALSE;
                    break;
                case SDLK_LSHIFT:
                    LSHIFT = FALSE;
                    break;
                case SDLK_LCTRL:
                    LCTRL = FALSE;
                    break;
                case SDLK_RCTRL:
                    RCTRL = FALSE;
                    break;
                case SDLK_LALT:
                    LALT = FALSE;
                    break;
                default:
                    if(key_up_handler) {
                        ID = key_up_handler(Main.event.key.keysym, pData);
                    }
                    break;
                }
                break;

            case SDL_KEYDOWN:
                switch(Main.event.key.keysym.sym) {
                case SDLK_PRINT:
                    fc_snprintf(schot, sizeof(schot), "fc_%05d.bmp", schot_nr++);
                    log_normal(_("Making screenshot %s"), schot);
                    SDL_SaveBMP(Main.screen, schot);
                    break;

                case SDLK_RSHIFT:
                    /* Right Shift is Pressed */
                    RSHIFT = TRUE;
                    break;

                case SDLK_LSHIFT:
                    /* Left Shift is Pressed */
                    LSHIFT = TRUE;
                    break;

                case SDLK_LCTRL:
                    /* Left CTRL is Pressed */
                    LCTRL = TRUE;
                    break;

                case SDLK_RCTRL:
                    /* Right CTRL is Pressed */
                    RCTRL = TRUE;
                    break;

                case SDLK_LALT:
                    /* Left ALT is Pressed */
                    LALT = TRUE;
                    break;

                default:
                    if(key_down_handler) {
                        ID = key_down_handler(Main.event.key.keysym, pData);
                    }
                    break;
                }
                break;

            case SDL_MOUSEBUTTONDOWN:
                if(mouse_button_down_handler) {
                    ID = mouse_button_down_handler(&Main.event.button, pData);
                }
                break;

            case SDL_MOUSEBUTTONUP:
                if(mouse_button_up_handler) {
                    ID = mouse_button_up_handler(&Main.event.button, pData);
                }
                break;

            case SDL_MOUSEMOTION:
                if(mouse_motion_handler) {
                    ID = mouse_motion_handler(&Main.event.motion, pData);
                }
                break;

            case SDL_USEREVENT:
                switch(Main.event.user.code) {
                case NET:
                    input_from_server(net_socket);
                    break;
                case GGZ:
                    input_from_ggz(ggz_socket);
                    break;
                case ANIM:
                    update_button_hold_state();
                    animate_mouse_cursor();
                    draw_mouse_cursor();
                    break;
                case SHOW_WIDGET_INFO_LABBEL:
                    draw_widget_info_label();
                    break;
                case TRY_AUTO_CONNECT:
                    if (try_to_autoconnect()) {
                        pInfo_User_Event->user.code = SHOW_WIDGET_INFO_LABBEL;
                        autoconnect = FALSE;
                    }
                    break;
                case FLUSH:
                    unqueue_flush();
                    break;
                case MAP_SCROLL:
                    scroll_mapview(scroll_dir);
                    break;
                case EXIT_FROM_EVENT_LOOP:
                    return MAX_ID;
                    break;
                default:
                    break;
                }
                break;

            }
        }

        if (ID == ID_ERROR) {
            if (callbacks && callback_list_size(callbacks) > 0) {
                struct callback *cb = callback_list_get(callbacks, 0);
                callback_list_remove(callbacks, cb);
                (cb->callback)(cb->data);
                free(cb);
            }
        }
    }

    return ID;
}