Exemple #1
0
//# MENU config
void ram(void){
    uint8_t numentries = 0;
    signed char menuselection = 0;
    uint8_t visible_lines = 0;
    uint8_t current_offset = 0;

    for (int i=0;the_config[i].name!=NULL;i++){
        if(!the_config[i].disabled)
            numentries++;
    };

    visible_lines = ((RESY/getFontHeight())-1)/2;

    while (1) {
        // Display current menu page
        lcdClear();
        lcdPrint("Config");
        
        lcdSetCrsrX(60);
        lcdPrint("[");
        lcdPrint(IntToStr((current_offset/visible_lines)+1,1,0));
        lcdPrint("/");
        lcdPrint(IntToStr(((numentries-1)/visible_lines)+1,1,0));
        lcdPrint("]");
        lcdNl();

        lcdNl();

        uint8_t j=0;
        for (uint8_t i=0;i<current_offset;i++)
            while (the_config[++j].disabled);

        uint8_t t=0;
        for (uint8_t i=0;i<menuselection;i++)
            while (the_config[++t].disabled);

        for (uint8_t i = current_offset; i < (visible_lines + current_offset) && i < numentries; i++,j++) {
            while(the_config[j].disabled)j++;
            if(i==0){
                lcdPrintln("Save changes:");
                if (i == t)
                    lcdPrint("*");
                lcdSetCrsrX(14);
                if (i == t)
                    lcdPrintln("YES");
                else
                    lcdPrintln("no");
            }else{
                lcdPrintln(the_config[j].name);
                if (j == t)
                    lcdPrint("*");
                lcdSetCrsrX(14);
                lcdPrint("<");
                lcdPrint(IntToStr(the_config[j].value,3,F_LONG));
                lcdPrintln(">");
            };
        lcdRefresh();
        }

        switch (getInputWaitRepeat()) {
            case BTN_UP:
                menuselection--;
                if (menuselection < current_offset) {
                    if (menuselection < 0) {
                        menuselection = numentries-1;
                        current_offset = ((numentries-1)/visible_lines) * visible_lines;
                    } else {
                        current_offset -= visible_lines;
                    }
                }
                break;
            case BTN_DOWN:
                menuselection++;
                if (menuselection > (current_offset + visible_lines-1) || menuselection >= numentries) {
                    if (menuselection >= numentries) {
                        menuselection = 0;
                        current_offset = 0;
                    } else {
                        current_offset += visible_lines;
                    }
                }
                break;
            case BTN_LEFT:
                if(the_config[t].value >
                        the_config[t].min)
                    the_config[t].value--;
                if(the_config[t].value > the_config[t].max)
                    the_config[t].value=
                        the_config[t].max;
                applyConfig();
                break;
            case BTN_RIGHT:
                if(the_config[t].value <
                        the_config[t].max)
                    the_config[t].value++;
                if(the_config[t].value < the_config[t].min)
                    the_config[t].value=
                        the_config[t].min;
                applyConfig();
                break;
            case BTN_ENTER:
                if(menuselection==0)
                    saveConfig();
                return;
        }
    }
    /* NOTREACHED */
}
PluginLoader::~PluginLoader() {
	saveConfig();
    unloadPlugins();
}
void CalibrationMain::on_SaveConfigButton_clicked()
{
    saveConfig(currentFile);
}
void MultiLayerBGS::process(const cv::Mat &img_input, cv::Mat &img_output, cv::Mat &img_bgmodel)
{
  if (img_input.empty())
    return;

  loadConfig();

  CvSize img_size = cvSize(cvCeil((double)img_input.size().width), cvCeil((double)img_input.size().height));

  if (firstTime)
  {
    if (disableDetectMode)
      status = MLBGS_LEARN;

    if (status == MLBGS_LEARN)
      std::cout << "MultiLayerBGS in LEARN mode" << std::endl;

    if (status == MLBGS_DETECT)
      std::cout << "MultiLayerBGS in DETECT mode" << std::endl;

    org_img = new IplImage(img_input);

    fg_img = cvCreateImage(img_size, org_img->depth, org_img->nChannels);
    bg_img = cvCreateImage(img_size, org_img->depth, org_img->nChannels);
    fg_prob_img = cvCreateImage(img_size, org_img->depth, 1);
    fg_mask_img = cvCreateImage(img_size, org_img->depth, 1);
    fg_prob_img3 = cvCreateImage(img_size, org_img->depth, org_img->nChannels);
    merged_img = cvCreateImage(cvSize(img_size.width * 2, img_size.height * 2), org_img->depth, org_img->nChannels);

    BGS = new CMultiLayerBGS();
    BGS->Init(img_size.width, img_size.height);
    BGS->SetForegroundMaskImage(fg_mask_img);
    BGS->SetForegroundProbImage(fg_prob_img);

    if (bg_model_preload.empty() == false)
    {
      std::cout << "MultiLayerBGS loading background model: " << bg_model_preload << std::endl;
      BGS->Load(bg_model_preload.c_str());
    }

    if (status == MLBGS_DETECT)
    {
      BGS->m_disableLearning = disableLearning;

      if (disableLearning)
        std::cout << "MultiLayerBGS disabled learning in DETECT mode" << std::endl;
      else
        std::cout << "MultiLayerBGS enabled learning in DETECT mode" << std::endl;
    }

    if (loadDefaultParams)
    {
      std::cout << "MultiLayerBGS loading default params" << std::endl;

      max_mode_num = 5;
      weight_updating_constant = 5.0;
      texture_weight = 0.5;
      bg_mode_percent = 0.6f;
      pattern_neig_half_size = 4;
      pattern_neig_gaus_sigma = 3.0f;
      bg_prob_threshold = 0.2f;
      bg_prob_updating_threshold = 0.2f;
      robust_LBP_constant = 3;
      min_noised_angle = 10.0 / 180.0 * PI; //0,01768
      shadow_rate = 0.6f;
      highlight_rate = 1.2f;
      bilater_filter_sigma_s = 3.0f;
      bilater_filter_sigma_r = 0.1f;
    }
    else
      std::cout << "MultiLayerBGS loading config params" << std::endl;

    BGS->m_nMaxLBPModeNum = max_mode_num;
    BGS->m_fWeightUpdatingConstant = weight_updating_constant;
    BGS->m_fTextureWeight = texture_weight;
    BGS->m_fBackgroundModelPercent = bg_mode_percent;
    BGS->m_nPatternDistSmoothNeigHalfSize = pattern_neig_half_size;
    BGS->m_fPatternDistConvGaussianSigma = pattern_neig_gaus_sigma;
    BGS->m_fPatternColorDistBgThreshold = bg_prob_threshold;
    BGS->m_fPatternColorDistBgUpdatedThreshold = bg_prob_updating_threshold;
    BGS->m_fRobustColorOffset = robust_LBP_constant;
    BGS->m_fMinNoisedAngle = min_noised_angle;
    BGS->m_fRobustShadowRate = shadow_rate;
    BGS->m_fRobustHighlightRate = highlight_rate;
    BGS->m_fSigmaS = bilater_filter_sigma_s;
    BGS->m_fSigmaR = bilater_filter_sigma_r;

    if (loadDefaultParams)
    {
      //frame_duration = 1.0 / 30.0;
      //frame_duration = 1.0 / 25.0;
      frame_duration = 1.0f / 10.0f;
    }

    BGS->SetFrameRate(frame_duration);

    if (status == MLBGS_LEARN)
    {
      if (loadDefaultParams)
      {
        mode_learn_rate_per_second = 0.5;
        weight_learn_rate_per_second = 0.5;
        init_mode_weight = 0.05f;
      }
      else
      {
        mode_learn_rate_per_second = learn_mode_learn_rate_per_second;
        weight_learn_rate_per_second = learn_weight_learn_rate_per_second;
        init_mode_weight = learn_init_mode_weight;
      }
    }

    if (status == MLBGS_DETECT)
    {
      if (loadDefaultParams)
      {
        mode_learn_rate_per_second = 0.01f;
        weight_learn_rate_per_second = 0.01f;
        init_mode_weight = 0.001f;
      }
      else
      {
        mode_learn_rate_per_second = detect_mode_learn_rate_per_second;
        weight_learn_rate_per_second = detect_weight_learn_rate_per_second;
        init_mode_weight = detect_init_mode_weight;
      }
    }

    BGS->SetParameters(max_mode_num, mode_learn_rate_per_second, weight_learn_rate_per_second, init_mode_weight);

    saveConfig();

    delete org_img;
  }

  //IplImage* inputImage = new IplImage(img_input);
  //IplImage* img = cvCreateImage(img_size, IPL_DEPTH_8U, 3);
  //cvCopy(inputImage, img);
  //delete inputImage;

  if (detectAfter > 0 && detectAfter == frameNumber)
  {
    std::cout << "MultiLayerBGS in DETECT mode" << std::endl;

    status = MLBGS_DETECT;

    mode_learn_rate_per_second = 0.01f;
    weight_learn_rate_per_second = 0.01f;
    init_mode_weight = 0.001f;

    BGS->SetParameters(max_mode_num, mode_learn_rate_per_second, weight_learn_rate_per_second, init_mode_weight);

    BGS->m_disableLearning = disableLearning;

    if (disableLearning)
      std::cout << "MultiLayerBGS disabled learning in DETECT mode" << std::endl;
    else
      std::cout << "MultiLayerBGS enabled learning in DETECT mode" << std::endl;
  }

  IplImage* img = new IplImage(img_input);

  BGS->SetRGBInputImage(img);
  BGS->Process();

  BGS->GetBackgroundImage(bg_img);
  BGS->GetForegroundImage(fg_img);
  BGS->GetForegroundProbabilityImage(fg_prob_img3);
  BGS->GetForegroundMaskImage(fg_mask_img);
  BGS->MergeImages(4, img, bg_img, fg_prob_img3, fg_img, merged_img);

  img_merged = cv::Mat(merged_img);
  img_foreground = cv::Mat(fg_mask_img);
  img_background = cv::Mat(bg_img);

  if (showOutput)
  {
    //cv::imshow("MLBGS Layers", img_merged);
   // cv::imshow("MLBGS FG Mask", img_foreground);
  }

  img_foreground.copyTo(img_output);
  img_background.copyTo(img_bgmodel);

  delete img;
  //cvReleaseImage(&img);

  firstTime = false;
  frameNumber++;
}
Exemple #5
0
void Config::save() const
{
    char filename[MAX_STRING_SIZE];
    getConfigFileName(filename, MAX_STRING_SIZE);
    saveConfig(filename);
}
Exemple #6
0
bool MICCD::SetFilterNames()
{
    // Cannot save it in hardware, so let's just save it in the config file to be loaded later
    saveConfig();
    return true;
}
Exemple #7
0
void T2FMRF_UM::process(const cv::Mat &img_input, cv::Mat &img_output, cv::Mat &img_bgmodel)
{
  if(img_input.empty())
    return;

  loadConfig();

  if(firstTime)
    saveConfig();

  frame = new IplImage(img_input);
  
  if(firstTime)
    frame_data.ReleaseMemory(false);
  frame_data = frame;

  if(firstTime)
  {
    int width	= img_input.size().width;
    int height = img_input.size().height;

    lowThresholdMask = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
    lowThresholdMask.Ptr()->origin = IPL_ORIGIN_BL;

    highThresholdMask = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
    highThresholdMask.Ptr()->origin = IPL_ORIGIN_BL;

    params.SetFrameSize(width, height);
    params.LowThreshold() = threshold;
    params.HighThreshold() = 2*params.LowThreshold();
    params.Alpha() = alpha;
    params.MaxModes() = gaussians;
    params.Type() = TYPE_T2FMRF_UM;
    params.KM() = km; // Factor control for the T2FMRF-UM [0,3] default: 2
    params.KV() = kv; // Factor control for the T2FMRF-UV [0.3,1] default: 0.9

    bgs.Initalize(params);
    bgs.InitModel(frame_data);

    old_labeling = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
    old = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);

    mrf.height = height;
	  mrf.width = width;
    mrf.Build_Classes_OldLabeling_InImage_LocalEnergy();

    firstTime = false;
  }

  bgs.Subtract(frameNumber, frame_data, lowThresholdMask, highThresholdMask);
  cvCopy(lowThresholdMask.Ptr(), old);

  /************************************************************************/
	/* the code for MRF, it can be noted when using other methods   */
	/************************************************************************/
	//the optimization process is done when the foreground detection is stable, 
	if(frameNumber >= 10)
	{
		gmm = bgs.gmm();
		hmm = bgs.hmm();
		mrf.background2 = frame_data.Ptr();
		mrf.in_image = lowThresholdMask.Ptr();
		mrf.out_image = lowThresholdMask.Ptr();
		mrf.InitEvidence2(gmm,hmm,old_labeling);
		mrf.ICM2();
		cvCopy(mrf.out_image, lowThresholdMask.Ptr());
	}

  cvCopy(old, old_labeling);

  lowThresholdMask.Clear();
  bgs.Update(frameNumber, frame_data, lowThresholdMask);
  
  cv::Mat foreground(highThresholdMask.Ptr());

  if(showOutput)
    cv::imshow("T2FMRF-UM", foreground);
  
  foreground.copyTo(img_output);

  delete frame;
  frameNumber++;
}
void VehicleCouting::process()
{



    if(idspeeds.size()>0){
        idspeeds.clear();
    }
    if(img_input.empty())
        return;

    img_w = img_input.size().width;
    img_h = img_input.size().height;

    loadConfig();

    //--------------------------------------------------------------------------

    if(FAV1::use_roi == true && FAV1::roi_defined == false && firstTime == true)
    {
        do
        {
            cv::putText(img_input, "Please, set the counting line", cv::Point(10,15), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(0,0,255));
            cv::imshow("VehicleCouting", img_input);
            FAV1::img_input1 = new IplImage(img_input);
            cvSetMouseCallback("VehicleCouting", FAV1::VehicleCouting_on_mouse, NULL);
            key = cvWaitKey(0);
            delete FAV1::img_input1;

            if(FAV1::roi_defined)
            {
                std::cout << "Counting line defined (" << FAV1::roi_x0 << "," << FAV1::roi_y0 << "," << FAV1::roi_x1 << "," << FAV1::roi_y1 << ")" << std::endl;
                break;
            }
            else
                std::cout << "Counting line undefined!" << std::endl;
        }while(1);
    }

    if(FAV1::use_roi == true && FAV1::roi_defined == true)
        cv::line(img_input, cv::Point(FAV1::roi_x0,FAV1::roi_y0), cv::Point(FAV1::roi_x1,FAV1::roi_y1), cv::Scalar(0,0,255));

    bool ROI_OK = false;

    if(FAV1::use_roi == true && FAV1::roi_defined == true)
        ROI_OK = true;

    if(ROI_OK)
    {
        LaneOrientation = LO_NONE;

        if(abs(FAV1::roi_x0 - FAV1::roi_x1) < abs(FAV1::roi_y0 - FAV1::roi_y1))
        {
            if(!firstTime)
                cv::putText(img_input, "HORIZONTAL", cv::Point(10,15), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
            LaneOrientation = LO_HORIZONTAL;

            cv::putText(img_input, "(A)", cv::Point(FAV1::roi_x0-32,FAV1::roi_y0), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
            cv::putText(img_input, "(B)", cv::Point(FAV1::roi_x0+12,FAV1::roi_y0), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
        }

        if(abs(FAV1::roi_x0 - FAV1::roi_x1) > abs(FAV1::roi_y0 - FAV1::roi_y1))
        {
            if(!firstTime)
                cv::putText(img_input, "VERTICAL", cv::Point(10,15), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
            LaneOrientation = LO_VERTICAL;

            cv::putText(img_input, "(A)", cv::Point(FAV1::roi_x0,FAV1::roi_y0+22), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
            cv::putText(img_input, "(B)", cv::Point(FAV1::roi_x0,FAV1::roi_y0-12), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
        }
    }

    //--------------------------------------------------------------------------

    for(std::map<cvb::CvID,cvb::CvTrack*>::iterator it = tracks.begin() ; it != tracks.end(); it++)
    {
        //std::cout << (*it).first << " => " << (*it).second << std::endl;
        cvb::CvID id = (*it).first;
        cvb::CvTrack* track = (*it).second;

        CvPoint2D64f centroid = track->centroid;

        //            std::cout << "---------------------------------------------------------------" << std::endl;
        //            std::cout << "0)id:" << id << " (" << centroid.x << "," << centroid.y << ")" << std::endl;
        //            std::cout << "track->active:" << track->active << std::endl;
        //            std::cout << "track->inactive:" << track->inactive << std::endl;
        //            std::cout << "track->lifetime:" << track->lifetime << std::endl;




        if(1==track->lifetime)
        {
            //            std::map<cvb::CvID, CarSpeed>::iterator speedit2 =carspeeds.find(id);

            //            if(speedit2 != NULL){

            //            }
            //            CarSpeed carspeed2 =speedit->second;
            //            time(&end);
            //            carspeed2.lasttime = end;
            //            carspeed2.lastcentroid = centroid;
            //            carspeeds.insert(std::pair<cvb::CvID, CarSpeed>(id,carspeed2));
            //            std::cout<<"lifetime==1-----------------------------------------";



            CarSpeed carspeed;
            time(&start);
            carspeed.starttime = start;
            carspeed.startcentroid = centroid;


            std::map<cvb::CvID, CarSpeed>::iterator speeditupdatestartcentroid =carspeeds.find(id);


            if(speeditupdatestartcentroid != carspeeds.end()){
                carspeeds.erase(speeditupdatestartcentroid);
                carspeeds.insert(std::pair<cvb::CvID, CarSpeed>(id,carspeed));
            }else{
                carspeeds.insert(std::pair<cvb::CvID, CarSpeed>(id,carspeed));
            }


        }
        //    if(1==track->active )
        //    {
        //        time(&start);
        //        startpoint=centroid;

        //    }



        //----------------------------------------------------------------------------

        if(track->inactive == 0)
        {
            if(positions.count(id) > 0)
            {
                std::map<cvb::CvID, VehiclePosition>::iterator it2 = positions.find(id);
                VehiclePosition old_position = it2->second;

                VehiclePosition current_position = getVehiclePosition(centroid);

                if(current_position != old_position)
                {
                    if(old_position == VP_A && current_position == VP_B)
                        countAB++;

                    if(old_position == VP_B && current_position == VP_A)
                        countBA++;

                    positions.erase(positions.find(id));
                }
            }
            else
            {
                VehiclePosition vehiclePosition = getVehiclePosition(centroid);

                if(vehiclePosition != VP_NONE)
                    positions.insert(std::pair<cvb::CvID, VehiclePosition>(id,vehiclePosition));
            }
        }
        else
        {
            if(positions.count(id) > 0)
                positions.erase(positions.find(id));
        }

        //----------------------------------------------------------------------------

        if(points.count(id) > 0)
        {
            std::map<cvb::CvID, std::vector<CvPoint2D64f>>::iterator it2 = points.find(id);
            std::vector<CvPoint2D64f> centroids = it2->second;

            //      if (centroids.size()==1){
            //          time(&start);
            //      }

            std::vector<CvPoint2D64f> centroids2;
            if(track->inactive == 0 && centroids.size() < 30)
            {
                centroids2.push_back(centroid); // the latest center point

                //                std::map<cvb::CvID, CarSpeed>::iterator speedit =carspeeds.find(id);
                //                CarSpeed carspeed2 =speedit->second;
                //                time(&end);
                //                carspeed2.lasttime = end;
                //                carspeed2.lastcentroid = centroid;
                //                carspeeds.insert(std::pair<cvb::CvID, CarSpeed>(id,carspeed2));
                //                std::cout << "latest center point...id:" << id <<"  cost time: "<<difftime(carspeed2.lasttime,carspeed2.starttime) << " (" << carspeed2.startcentroid.x << "," << carspeed2.startcentroid.y << ")"  << " (" << carspeed2.lastcentroid.x << "," << carspeed2.lastcentroid.y << ")" << std::endl;
                //                carspeeds.erase(speedit);

                for(std::vector<CvPoint2D64f>::iterator it3 = centroids.begin() ; it3 != centroids.end(); it3++)
                {
                    centroids2.push_back(*it3);
                }

                for(std::vector<CvPoint2D64f>::iterator it3 = centroids2.begin() ; it3 != centroids2.end(); it3++)
                {
                    cv::circle(img_input, cv::Point((*it3).x,(*it3).y), 3, cv::Scalar(255,255,255), -1);
                }

                points.erase(it2);
                points.insert(std::pair<cvb::CvID, std::vector<CvPoint2D64f>>(id,centroids2));
            }
            else
            {
                points.erase(it2);
            }
        }
        else
        {
            if(track->inactive == 0)
            {
                std::vector<CvPoint2D64f> centroids;
                centroids.push_back(centroid);
                //        time(&start);
                points.insert(std::pair<cvb::CvID, std::vector<CvPoint2D64f>>(id,centroids));
            }

            //
            std::map<cvb::CvID, CarSpeed>::iterator speedit =carspeeds.find(id);
            CarSpeed carspeed2 =speedit->second;
            time(&end);
            carspeed2.lasttime = end;
            carspeed2.lastcentroid = centroid;
            carspeeds.insert(std::pair<cvb::CvID, CarSpeed>(id,carspeed2));
            //            std::cout << "latest center point...id:" << id <<"  cost time: "<<difftime(carspeed2.lasttime,carspeed2.starttime) << " (" << carspeed2.startcentroid.x << "," << carspeed2.startcentroid.y << ")"  << " (" << carspeed2.lastcentroid.x << "," << carspeed2.lastcentroid.y << ")" << std::endl;
            //
            if(difftime(carspeed2.lasttime,carspeed2.starttime)>0){
                double costtime =difftime(carspeed2.lasttime,carspeed2.starttime);
                double distance =sqrt((carspeed2.startcentroid.y - carspeed2.lastcentroid.y) *(carspeed2.startcentroid.y - carspeed2.lastcentroid.y)+(carspeed2.startcentroid.x - carspeed2.lastcentroid.x)*(carspeed2.startcentroid.x - carspeed2.lastcentroid.x));
//                std::cout<<"ID:"<<id<<" Distance: "<<distance<<" Time: "<<costtime<<" speed: "<<distance/costtime<<std::endl;
                IdSpeed is;
                is.id=id;
                is.speed=distance/costtime;
                idspeeds.push_back(is);
            }

        }
        //    time(&end);
        //    double sec=difftime(end,start);
        endpoint = centroid;

        //    double distance =sqrt((endpoint.y-startpoint.y) *(endpoint.y-startpoint.y)+(endpoint.x-startpoint.x)*(endpoint.x-startpoint.x));
        //    std::cout <<"track->id:"<<track->id << "   track->lifetime:    " << track->lifetime ;
        //    printf("distance : %f  ",distance);
        //    printf("time cost: %lf \n ",sec);




        //cv::waitKey(0);
    }

    //--------------------------------------------------------------------------

//    std::cout<<"endtime"<<std::endl;
    time(&endtime);
    //if 30 second has passed ,please recount the car num.
    if(difftime(endtime,origintime)>30){
        std::cout<<"30 seconds has passed"<<std::endl;
        countAB=0;
        countBA=0;

        std::cout<<"restarttime"<<std::endl;
        time(&origintime);

    }


    if(showAB == 0)
    {
        cv::putText(img_input, "A->B: " + boost::lexical_cast<std::string>(countAB), cv::Point(10,img_h-20), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
        cv::putText(img_input, "B->A: " + boost::lexical_cast<std::string>(countBA), cv::Point(10,img_h-8), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));
    }

    if(showAB == 1){

        cv::putText(img_input, "A->B: " + boost::lexical_cast<std::string>(countAB), cv::Point(10,img_h-8), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));

    }

    if(showAB == 2)
    {

        cv::putText(img_input, "B->A: " + boost::lexical_cast<std::string>(countBA), cv::Point(10,img_h-8), cv::FONT_HERSHEY_PLAIN, 1, cv::Scalar(255,255,255));


    }

    if(showOutput)
        cv::imshow("VehicleCouting", img_input);

    if(firstTime)
        saveConfig();

    firstTime = false;
}
PRL_RESULT  CDspDispConfigGuard::saveConfig( bool bNoSaveNetwork )
{
	QString path = ParallelsDirs::getDispatcherConfigFilePath();
	return saveConfig( path, bNoSaveNetwork );
}
ApokalypseApp::~ApokalypseApp(){
	if (screen) delete screen;
	if (!configfile.isEmpty())
		saveConfig();
}
Exemple #11
0
int realmain(int argc, char *argv[])
{
	wzMain(argc, argv);
	int utfargc = argc;
	const char** utfargv = (const char**)argv;

#ifdef WZ_OS_MAC
	cocoaInit();
#endif

	debug_init();
	debug_register_callback( debug_callback_stderr, NULL, NULL, NULL );
#if defined(WZ_OS_WIN) && defined(DEBUG_INSANE)
	debug_register_callback( debug_callback_win32debug, NULL, NULL, NULL );
#endif // WZ_OS_WIN && DEBUG_INSANE

	// *****
	// NOTE: Try *NOT* to use debug() output routines without some other method of informing the user.  All this output is sent to /dev/nul at this point on some platforms!
	// *****
	if (!getUTF8CmdLine(&utfargc, &utfargv))
	{
		return EXIT_FAILURE;
	}
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));	// make Qt treat all C strings in Warzone as UTF-8

	setupExceptionHandler(utfargc, utfargv, version_getFormattedVersionString());

	/*** Initialize PhysicsFS ***/
	initialize_PhysicsFS(utfargv[0]);

	/*** Initialize translations ***/
	initI18n();

	// find early boot info
	if (!ParseCommandLineEarly(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	/* Initialize the write/config directory for PhysicsFS.
	 * This needs to be done __after__ the early commandline parsing,
	 * because the user might tell us to use an alternative configuration
	 * directory.
	 */
	initialize_ConfigDir();

	/*** Initialize directory structure ***/
	make_dir(ScreenDumpPath, "screenshots", NULL);
	make_dir(SaveGamePath, "savegames", NULL);
	PHYSFS_mkdir("savegames/campaign");
	PHYSFS_mkdir("savegames/skirmish");
	make_dir(MultiCustomMapsPath, "maps", NULL); // MUST have this to prevent crashes when getting map
	PHYSFS_mkdir("music");
	PHYSFS_mkdir("logs");		// a place to hold our netplay, mingw crash reports & WZ logs
	PHYSFS_mkdir("userdata");	// a place to store per-mod data user generated data
	memset(rulesettag, 0, sizeof(rulesettag)); // tag to add to userdata to find user generated stuff
	make_dir(MultiPlayersPath, "multiplay", NULL);
	make_dir(MultiPlayersPath, "multiplay", "players");

	if (!customDebugfile)
	{
		// there was no custom debug file specified  (--debug-file=blah)
		// so we use our write directory to store our logs.
		time_t aclock;
		struct tm *newtime;
		char buf[PATH_MAX];

		time( &aclock );					// Get time in seconds
		newtime = localtime( &aclock );		// Convert time to struct
		// Note: We are using fopen(), and not physfs routines to open the file
		// log name is logs/(or \)WZlog-MMDD_HHMMSS.txt
		snprintf(buf, sizeof(buf), "%slogs%sWZlog-%02d%02d_%02d%02d%02d.txt", PHYSFS_getWriteDir(), PHYSFS_getDirSeparator(),
			newtime->tm_mon + 1, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec );
		debug_register_callback( debug_callback_file, debug_callback_file_init, debug_callback_file_exit, buf );

		// FIXME: Change this to LOG_WZ on next release
		debug(LOG_INFO, "Using %s debug file", buf);
	}

	// NOTE: it is now safe to use debug() calls to make sure output gets captured.
	check_Physfs();
	debug(LOG_WZ, "Warzone 2100 - %s", version_getFormattedVersionString());
	debug(LOG_WZ, "Using language: %s", getLanguage());
	debug(LOG_WZ, "Backend: %s", BACKEND);
	debug(LOG_MEMORY, "sizeof: SIMPLE_OBJECT=%ld, BASE_OBJECT=%ld, DROID=%ld, STRUCTURE=%ld, FEATURE=%ld, PROJECTILE=%ld",
	      (long)sizeof(SIMPLE_OBJECT), (long)sizeof(BASE_OBJECT), (long)sizeof(DROID), (long)sizeof(STRUCTURE), (long)sizeof(FEATURE), (long)sizeof(PROJECTILE));


	/* Put in the writedir root */
	sstrcpy(KeyMapPath, "keymap.map");

	// initialise all the command line states
	war_SetDefaultStates();

	debug(LOG_MAIN, "initializing");

	PhysicsEngineHandler engine;	// register abstract physfs filesystem

	loadConfig();

	// parse the command line
	if (!ParseCommandLine(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	// Save new (commandline) settings
	saveConfig();

	// Find out where to find the data
	scanDataDirs();

	// Now we check the mods to see if they exist or not (specified on the command line)
	// They are all capped at 100 mods max(see clparse.c)
	// FIX ME: I know this is a bit hackish, but better than nothing for now?
	{
		char *modname;
		char modtocheck[256];
		int i = 0;
		int result = 0;

		// check global mods
		for(i=0; i < 100; i++)
		{
			modname = global_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/global/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The (global) mod (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("(global) mod (%s) is enabled", modname);
			}
		}
		// check campaign mods
		for(i=0; i < 100; i++)
		{
			modname = campaign_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/campaign/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_ca (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_ca (%s) is enabled", modname);
			}
		}
		// check multiplay mods
		for(i=0; i < 100; i++)
		{
			modname = multiplay_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/multiplay/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_mp (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_mp (%s) is enabled", modname);
			}
		}
	}

	if (!wzMain2())
	{
		return EXIT_FAILURE;
	}
	int w = pie_GetVideoBufferWidth();
	int h = pie_GetVideoBufferHeight();

	char buf[256];
	ssprintf(buf, "Video Mode %d x %d (%s)", w, h, war_getFullscreen() ? "fullscreen" : "window");
	addDumpInfo(buf);

	debug(LOG_MAIN, "Final initialization");
	if (!frameInitialise())
	{
		return EXIT_FAILURE;
	}
	war_SetWidth(pie_GetVideoBufferWidth());
	war_SetHeight(pie_GetVideoBufferHeight());

	// Fix up settings from the config file
	// And initialize shader usage setting
	if (!pie_GetShaderAvailability())
	{
		war_SetShaders(FALLBACK);
		pie_SetShaderUsage(false);
	}
	else
	{
		if (war_GetShaders() == FALLBACK)
		{
			war_SetShaders(SHADERS_OFF);
		}
		if (!pie_GetFallbackAvailability())
		{
			war_SetShaders(SHADERS_ONLY);
			pie_SetShaderUsage(true);
		}
		else if (war_GetShaders() == SHADERS_ONLY || war_GetShaders() == SHADERS_ON)
		{
			war_SetShaders(SHADERS_ON);
			pie_SetShaderUsage(true);
		}
		else  // (war_GetShaders() == SHADERS_OFF)
		{
			pie_SetShaderUsage(false);
		}
	}

	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	pal_Init();

	pie_LoadBackDrop(SCREEN_RANDOMBDROP);
	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	if (!systemInitialise())
	{
		return EXIT_FAILURE;
	}

	//set all the pause states to false
	setAllPauseStates(false);

	// Copy this info to be used by the crash handler for the dump file
	ssprintf(buf,"Using Backend: %s", BACKEND);
	addDumpInfo(buf);
	ssprintf(buf,"Using language: %s", getLanguageName());
	addDumpInfo(buf);

	// Do the game mode specific initialisation.
	switch(GetGameMode())
	{
		case GS_TITLE_SCREEN:
			startTitleLoop();
			break;
		case GS_SAVEGAMELOAD:
			initSaveGameLoad();
			break;
		case GS_NORMAL:
			startGameLoop();
			break;
		default:
			debug(LOG_ERROR, "Weirdy game status, I'm afraid!!");
			break;
	}

#if defined(WZ_CC_MSVC) && defined(DEBUG)
	debug_MEMSTATS();
#endif
	debug(LOG_MAIN, "Entering main loop");
	wzMain3();
	saveConfig();
	systemShutdown();
#ifdef WZ_OS_WIN	// clean up the memory allocated for the command line conversion
	for (int i=0; i<argc; i++)
	{
		const char*** const utfargvF = &utfargv;
		free((void *)(*utfargvF)[i]);
	}
	free(utfargv);
#endif
	wzShutdown();
	debug(LOG_MAIN, "Completed shutting down Warzone 2100");
	return EXIT_SUCCESS;
}
Exemple #12
0
KChatBaseModel::~KChatBaseModel()
{
// kDebug(11000) << "KChatBaseModelPrivate: DESTRUCT (" << this << ")";
 saveConfig();
}
Exemple #13
0
bool QHYCCD::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
{
    //  first check if it's for our device
    //IDLog("INDI::CCD::ISNewNumber %s\n",name);
    if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
    {
        if (strcmp(name, FilterSlotNP.name) == 0)
        {
            INDI::FilterInterface::processNumber(dev, name, values, names, n);
            return true;
        }

        if (strcmp(name, GainNP.name) == 0)
        {
            IUUpdateNumber(&GainNP, values, names, n);
            GainRequest = GainN[0].value;
            if (LastGainRequest != GainRequest)
            {
                SetQHYCCDParam(camhandle, CONTROL_GAIN, GainN[0].value);
                LastGainRequest = GainRequest;
            }
            DEBUGF(INDI::Logger::DBG_SESSION, "Current %s value %f", GainNP.name, GainN[0].value);
            GainNP.s = IPS_OK;
            IDSetNumber(&GainNP, NULL);
            return true;
        }

        if (strcmp(name, OffsetNP.name) == 0)
        {
            IUUpdateNumber(&OffsetNP, values, names, n);
            SetQHYCCDParam(camhandle, CONTROL_OFFSET, OffsetN[0].value);
            DEBUGF(INDI::Logger::DBG_SESSION, "Current %s value %f", OffsetNP.name, OffsetN[0].value);
            OffsetNP.s = IPS_OK;
            IDSetNumber(&OffsetNP, NULL);
            saveConfig(true, OffsetNP.name);
            return true;
        }

        if (strcmp(name, SpeedNP.name) == 0)
        {
            IUUpdateNumber(&SpeedNP, values, names, n);
            SetQHYCCDParam(camhandle, CONTROL_SPEED, SpeedN[0].value);
            DEBUGF(INDI::Logger::DBG_SESSION, "Current %s value %f", SpeedNP.name, SpeedN[0].value);
            SpeedNP.s = IPS_OK;
            IDSetNumber(&SpeedNP, NULL);
            saveConfig(true, SpeedNP.name);
            return true;
        }

        if (strcmp(name, USBTrafficNP.name) == 0)
        {
            IUUpdateNumber(&USBTrafficNP, values, names, n);
            SetQHYCCDParam(camhandle, CONTROL_USBTRAFFIC, USBTrafficN[0].value);
            DEBUGF(INDI::Logger::DBG_SESSION, "Current %s value %f", USBTrafficNP.name, USBTrafficN[0].value);
            USBTrafficNP.s = IPS_OK;
            IDSetNumber(&USBTrafficNP, NULL);
            saveConfig(true, USBTrafficNP.name);
            return true;
        }
    }
    //  if we didn't process it, continue up the chain, let somebody else
    //  give it a shot
    return INDI::CCD::ISNewNumber(dev, name, values, names, n);
}
Exemple #14
0
/*! \brief Load new configuration.
 *  \param cfgfile
 *  \returns True if config is OK, False if not (e.g. no input device specified).
 *
 * If cfgfile is an absolute path it will be used as is, otherwise it is assumed to be the
 * name of a file under m_cfg_dir.
 *
 * If cfgfile does not exist it will be created.
 *
 * If no input device is specified, we return false to signal that the I/O configuration
 * dialog should be run.
 *
 * FIXME: Refactor.
 */
bool MainWindow::loadConfig(const QString cfgfile, bool check_crash)
{
    bool conf_ok = false;
    bool skipLoadingSettings = false;

    qDebug() << "Loading configuration from:" << cfgfile;

    if (m_settings)
        delete m_settings;

    if (QDir::isAbsolutePath(cfgfile))
        m_settings = new QSettings(cfgfile, QSettings::IniFormat);
    else
        m_settings = new QSettings(QString("%1/%2").arg(m_cfg_dir).arg(cfgfile), QSettings::IniFormat);

    qDebug() << "Configuration file:" << m_settings->fileName();

    if (check_crash)
    {
        if (m_settings->value("crashed", false).toBool())
        {
            qDebug() << "Crash guard triggered!" << endl;
            QMessageBox* askUserAboutConfig =
                    new QMessageBox(QMessageBox::Warning, tr("Crash Detected!"),
                                    tr("<p>Gqrx has detected problems with the current configuration. "
                                       "Loading the configuration again could cause the application to crash.</p>"
                                       "<p>Do you want to edit the settings?</p>"),
                                    QMessageBox::Yes | QMessageBox::No);
            askUserAboutConfig->setDefaultButton(QMessageBox::Yes);
            askUserAboutConfig->setTextFormat(Qt::RichText);
            askUserAboutConfig->exec();
            if (askUserAboutConfig->result() == QMessageBox::Yes)
                skipLoadingSettings = true;

            delete askUserAboutConfig;
        }
        else
        {
            m_settings->setValue("crashed", true); // clean exit will set this to FALSE
            saveConfig(cfgfile);
        }
    }

    if (skipLoadingSettings)
        return false;

    emit configChanged(m_settings);

    // manual reconf (FIXME: check status)
    bool conv_ok = false;

    QString indev = m_settings->value("input/device", "").toString();
    if (!indev.isEmpty())
    {
        conf_ok = true;
        rx->set_input_device(indev.toStdString());

        // Update window title
        QRegExp regexp("'([a-zA-Z0-9 \\-\\_\\/\\.\\,\\(\\)]+)'");
        QString devlabel;
        if (regexp.indexIn(indev, 0) != -1)
            devlabel = regexp.cap(1);
        else
            devlabel = indev; //"Unknown";

        setWindowTitle(QString("Gqrx %1 - %2").arg(VERSION).arg(devlabel));

        // Add available antenna connectors to the UI
        std::vector<std::string> antennas = rx->get_antennas();
        uiDockInputCtl->setAntennas(antennas);
    }

    QString outdev = m_settings->value("output/device", "").toString();
    rx->set_output_device(outdev.toStdString());

    int sr = m_settings->value("input/sample_rate", 0).toInt(&conv_ok);
    if (conv_ok && (sr > 0))
    {
        double actual_rate = rx->set_input_rate(sr);
        qDebug() << "Requested sample rate:" << sr;
        qDebug() << "Actual sample rate   :" << QString("%1").arg(actual_rate, 0, 'f', 6);
        uiDockRxOpt->setFilterOffsetRange((qint64)(0.9*actual_rate));
        ui->plotter->setSampleRate(actual_rate);
        ui->plotter->setSpanFreq((quint32)actual_rate);
    }

    uiDockInputCtl->readSettings(m_settings);
    uiDockRxOpt->readSettings(m_settings);
    uiDockFft->readSettings(m_settings);
    uiDockAudio->readSettings(m_settings);

    ui->freqCtrl->setFrequency(m_settings->value("input/frequency", 144500000).toLongLong(&conv_ok));
    setNewFrequency(ui->freqCtrl->getFrequency()); // ensure all GUI and RF is updated

    return conf_ok;
}
bool CConfigFile::saveConfig(const std::string & filename)
{
	return saveConfig(filename.c_str());
}
void FuzzySugenoIntegral::process(const cv::Mat &img_input, cv::Mat &img_output)
{
  if(img_input.empty())
    return;

  cv::Mat img_input_f3(img_input.size(), CV_32F);
  img_input.convertTo(img_input_f3, CV_32F, 1./255.);

  loadConfig();

  if(firstTime)
  {
    std::cout << "FuzzySugenoIntegral parameters:" << std::endl;
      
    std::string colorSpaceName = "";
    switch(colorSpace)
    {
      case 1: colorSpaceName = "RGB";  break;
      case 2: colorSpaceName = "OHTA"; break;
      case 3: colorSpaceName = "HSV";  break;
      case 4: colorSpaceName = "YCrCb"; break;
    }
    std::cout << "Color space: " << colorSpaceName << std::endl;

    if(option == 1)
      std::cout << "Fuzzing by 3 color components" << std::endl;
    if(option == 2)
      std::cout << "Fuzzing by 2 color components + 1 texture component" << std::endl;
    
    saveConfig();
  }

  if(frameNumber <= framesToLearn)
  {
    if(frameNumber == 0)
      std::cout << "FuzzySugenoIntegral initializing background model by adaptive learning..." << std::endl;

    if(img_background_f3.empty())
      img_input_f3.copyTo(img_background_f3);
    else
      img_background_f3 = alphaLearn*img_input_f3 + (1-alphaLearn)*img_background_f3;

    if(showOutput)
      cv::imshow("SI BG Model", img_background_f3);
  }
  else
  {
    cv::Mat img_input_f1;
    cv::cvtColor(img_input_f3, img_input_f1, CV_BGR2GRAY);

    cv::Mat img_background_f1;
    cv::cvtColor(img_background_f3, img_background_f1, CV_BGR2GRAY);

    IplImage* input_f3 = new IplImage(img_input_f3);
    IplImage* input_f1 = new IplImage(img_input_f1);
    IplImage* background_f3 = new IplImage(img_background_f3);
    IplImage* background_f1 = new IplImage(img_background_f1);

    IplImage* lbp_input_f1 = cvCreateImage(cvSize(input_f1->width, input_f1->height), IPL_DEPTH_32F, 1);
    cvFillImage(lbp_input_f1, 0.0);
    fu.LBP(input_f1, lbp_input_f1);

    IplImage* lbp_background_f1 = cvCreateImage(cvSize(background_f1->width, background_f1->height), IPL_DEPTH_32F , 1);
    cvFillImage(lbp_background_f1, 0.0);
    fu.LBP(background_f1, lbp_background_f1);

    IplImage* sim_texture_f1 = cvCreateImage(cvSize(input_f1->width, input_f1->height), IPL_DEPTH_32F, 1);
    fu.SimilarityDegreesImage(lbp_input_f1, lbp_background_f1, sim_texture_f1, 1, colorSpace);

    IplImage* sim_color_f3 = cvCreateImage(cvSize(input_f3->width, input_f3->height), IPL_DEPTH_32F, 3);
    fu.SimilarityDegreesImage(input_f3, background_f3, sim_color_f3, 3, colorSpace);	

    float* measureG = (float*) malloc(3*(sizeof(float)));
    IplImage* integral_sugeno_f1 = cvCreateImage(cvSize(input_f1->width, input_f1->height), IPL_DEPTH_32F, 1);

    // 3 color components
    if(option == 1)
    {
      fu.FuzzyMeasureG(0.4, 0.3, 0.3, measureG);
      fu.getFuzzyIntegralSugeno(sim_texture_f1, sim_color_f3, option, measureG, integral_sugeno_f1);
    }

    // 2 color components + 1 texture component
    if(option == 2)
    {
      fu.FuzzyMeasureG(0.6, 0.3, 0.1, measureG);
      fu.getFuzzyIntegralSugeno(sim_texture_f1, sim_color_f3, option, measureG, integral_sugeno_f1);
    }

    free(measureG);
    cv::Mat img_integral_sugeno_f1(integral_sugeno_f1);

    if(smooth)
      cv::medianBlur(img_integral_sugeno_f1, img_integral_sugeno_f1, 3);

    cv::Mat img_foreground_f1(img_input.size(), CV_32F);
    cv::threshold(img_integral_sugeno_f1, img_foreground_f1, threshold, 255, cv::THRESH_BINARY_INV);

    cv::Mat img_foreground_u1(img_input.size(), CV_8U);
    double minVal = 0., maxVal = 1.;
    img_foreground_f1.convertTo(img_foreground_u1, CV_8U, 255.0/(maxVal - minVal), -minVal);
    img_foreground_u1.copyTo(img_output);

    if(showOutput)
    {
      cvShowImage("SI LBP Input", lbp_input_f1);
      cvShowImage("SI LBP Background", lbp_background_f1);
      cvShowImage("SI Prob FG Mask", integral_sugeno_f1);

      cv::imshow("SI BG Model", img_background_f3);
      cv::imshow("SI FG Mask", img_foreground_u1);
    }

    if(frameNumber == (framesToLearn + 1))
      std::cout << "FuzzySugenoIntegral updating background model by adaptive-selective learning..." << std::endl;

    IplImage* updated_background_f3 = cvCreateImage(cvSize(input_f1->width, input_f1->height), IPL_DEPTH_32F, 3);
    cvFillImage(updated_background_f3, 0.0);
    fu.AdaptativeSelectiveBackgroundModelUpdate(input_f3, background_f3, updated_background_f3, integral_sugeno_f1, threshold, alphaUpdate);
    cv::Mat img_updated_background_f3(updated_background_f3);
    img_updated_background_f3.copyTo(img_background_f3);

    cvReleaseImage(&lbp_input_f1);
    cvReleaseImage(&lbp_background_f1);
    cvReleaseImage(&sim_texture_f1);
    cvReleaseImage(&sim_color_f3);
    cvReleaseImage(&integral_sugeno_f1);
    cvReleaseImage(&updated_background_f3);
    
    delete background_f1;
    delete background_f3;
    delete input_f1;
    delete input_f3;
  }

  firstTime = false;
  frameNumber++;
}
Exemple #17
0
int Server::run(const char * ini)
{
	readServerData(ini);

	//clients = new Client[maxPlayers];
	clients = vector<Client*>();
	clients.reserve(maxPlayers);
	for (int i = 0; i < maxPlayers; i++) {
		clients.push_back(new Client());
		clients[i]->setID(i);
	}
		
	double elapsedTime = 0.0;
	double timePerFrame = 1000.0 / updateRate;
	double timePerRenderFrame = 1000.0 / renderRefreshRate;
	static double timeSinceLastRender = 0.0;
	long lastTime = 0;

	double targetSleep = 0.0;
	double sleepRemainder = 0.0;
	double startSleep = 0.0;
	double sleepTime = 0.0;

	loadConfig();
	initSDL();
	initGlew();
	initBullet();
	initGLContexts();
	initObjects();
	
	running = true;
	HANDLE listenThreadHandle = HostListener::start();

	loadResources();
	loadLevel("asdf");

	while (running) {
		frameCount++;
		if (GetAsyncKeyState(VK_ESCAPE) && (GetForegroundWindow() == consoleWindow) &&
			MessageBox(0, "Shutdown the Server?", "Rune Server Shutdown", MB_YESNO) == IDYES) break;

		lastTime = lastTime = SDL_GetTicks();

		serverEventsTCP->clearSendBuffer();
		serverEventsTCP->clearReceiveBuffer();
		serverEventsUDP->clearSendBuffer();
		serverEventsUDP->clearReceiveBuffer();

		//Get all commands from clients
		for (int i = 0; i < maxPlayers; i++) {
			DataBuffer * temp;
			aquireClientsMutex(i);
				temp = clients[i]->popReceiveData();
				if (!clients[i]->isConnected() && playerObjects->at(i) != NULL) {
					int index = -1;
					int x = 0;
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) == iter->second) {
							index = x;
							break;
						}
						x++;
					}
					/*for (int x = 0; x < gameObjects->size(); x++) {
						if (playerObjects->at(i) == gameObjects->at(x))
							index = x;
					}*/
					gameObjects->remove(playerObjects->at(i)->getNetID());
					delete playerObjects->at(i);
					playerObjects->at(i) = NULL;
					//gameObjects->erase(gameObjects->begin() + index);
					serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(index));
				}
			releaseClientsMutex(i);
			serverEventsTCP->appendToReceiveBuffer(temp);
		}

		//Receive All UDP Events
		sockaddr_in * originAddress = NULL;
		DataBuffer * udpBuffer = UDPManager::recvDatagram(&originAddress);
		while (udpBuffer != NULL) {
			//origin Address matches client address?
			unsigned long packetFrameCount = 0;
			memcpy(&packetFrameCount, udpBuffer->getData(), 4);

			int clientID = getClientIDByAddress(originAddress->sin_addr.s_addr, originAddress->sin_port);
			if (clientID == -1) {
				int asdfadsfasdf = 123123;
			}
			else {
				//compare clientFrameCount to client->frameCount
				unsigned long clientFrameCount;
				aquireClientsMutex(clientID);
					clientFrameCount = clients[clientID]->getFrameCount();
				releaseClientsMutex(clientID);

				if (packetFrameCount < clientFrameCount) {
					//discard
					printf("Packet from Client %d discarded\n", clientID);
				}
				else {
					serverEventsUDP->appendToReceiveBuffer(udpBuffer->getData() + 4, udpBuffer->getSize() - 4);
					aquireClientsMutex(clientID);
						clients[clientID]->setFrameCount(packetFrameCount);
					releaseClientsMutex(clientID);
				}

			}
			
			delete udpBuffer; udpBuffer = NULL;
			delete originAddress; originAddress = NULL;
			udpBuffer = UDPManager::recvDatagram(&originAddress);
		}

		NetworkFunctions::translateReceivedEvents(serverEventsTCP);
		NetworkFunctions::translateReceivedEvents(serverEventsUDP);
		
		//Execute my own gamelogic commands
		SDL_Event e;
		while (SDL_PollEvent(&e)) { 
			if (e.key.keysym.sym == SDLK_ESCAPE)
						running = false;
			if (e.key.keysym.sym == SDLK_m) {
				((RigidObject*)gameObjects->getValue(2))->setPosition(5, 10, 0);
				((RigidObject*)gameObjects->getValue(3))->setPosition(0, 10, 0);
				((RigidObject*)gameObjects->getValue(4))->setPosition(-5, 10, 0);
				((RigidObject*)gameObjects->getValue(2))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(3))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(4))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(2))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(3))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(4))->setGravity(0, -9.81f*4.0f, 0);
				printf("reset boxes\n");
			}
		}

		//if (update((long)(elapsedTime + sleepTime)) == -1) break;

		//dynamicsWorld->stepSimulation((float)(elapsedTime + sleepTime)*0.001f, 50, (float)(elapsedTime + sleepTime)*0.001f);
		dynamicsWorld->stepSimulation(1.0f / 64.0f, 100, 1.0f / 64.0f); //1.0f/(float)Settings::getMaxFPS());

		list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin();
		while (iter != gameObjects->end())
		{
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				GameObject * tempObject = iter->second;
				iter = gameObjects->erase(iter);
				delete tempObject;
			}
			else iter++;
		}

		/*for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				gameObjects->remove(iter->first, iter->second);
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/

		/*for (int i = 0; i < (int)gameObjects->size(); i++) {
			(*gameObjects)[i]->update(elapsedTime);
			if (!(*gameObjects)[i]->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(i));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == (*gameObjects)[i]) {
						playerObjects->at(p) = NULL;
					}
				}
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/
		
		//Update each client
		//for (int i = 0; i < gameObjects->size(); i++)
		//	serverEvents->appendToSendBuffer(NetworkFunctions::createUpdateObjectBuffer(i));

		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
				if (clients[i]->isConnected()) {
					if (clients[i]->requiresSynch()) {
						synchClient(i);
						clients[i]->setSynch(false);
					}
					else {
						clients[i]->pushSendData(serverEventsTCP->getSendBuffer(), serverEventsTCP->getSendBufferSize());
					}
				}
			releaseClientsMutex(i);
		}
		
		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
			if (clients[i]->isConnected()) {
				//unsigned long clientPortUDP = clients[i]->getPortUDP();
				if (!clients[i]->requiresSynch()) {
					serverEventsUDP->clearSendBuffer();
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) != iter->second /* && dont force player */) {
							DataBuffer * temp = NetworkFunctions::createUpdateObjectBuffer(iter->second->getNetID());
							serverEventsUDP->appendToSendBuffer(temp);
						}
					}
					UDPManager::sendDatagram(serverEventsUDP->getSendBuffer(), serverEventsUDP->getSendBufferSize(), clients[i]->getIPAddress(), clients[i]->getPortUDP(), frameCount);
				}
			}
			releaseClientsMutex(i);
		}

		/*timeSinceLastRender += elapsedTime;
		if (timeSinceLastRender >= timePerRenderFrame) {
			timeSinceLastRender = 0.0;
			renderFrame();
		}*/
		renderFrame();

		//Update Rate Calculations
		//Framerate Limit Calculations
		elapsedTime = SDL_GetTicks() - lastTime;
		targetSleep = timePerFrame - elapsedTime + sleepRemainder;
		if (targetSleep > 0) sleepRemainder = targetSleep - (Uint32)targetSleep;

		//Sleep(1000.0 / 64.0);
		
		startSleep = SDL_GetTicks();
		while ((Uint32)(startSleep + targetSleep) > SDL_GetTicks());
		sleepTime = SDL_GetTicks() - startSleep;
	}

	cout << "Shutting Down\n";
	HostThread::stopAll();
	HostListener::stop();
	UDPManager::cleanup();
	WSACleanup();
	WaitForSingleObject(listenThreadHandle, INFINITE);

	saveConfig();

	cleanupObjects();
	//saveConfig();
	killBullet();
		
	//delete [] clients;
	
	return 0;
}
Exemple #18
0
void SettingsDBManager::addSettings(const std::string& key, const std::string&value) {
    config[key] = value;
    //записать в файл сразу же!
    saveConfig();

}
ThumbView::~ThumbView()
{
   saveConfig();
}
ShareConfigMainWindow::ShareConfigMainWindow()
{
  configuration = Share::Configuration::getInstance();

  // Create de main window.
  ShareConfigWidget *mainWidget = new ShareConfigWidget;

  QMainWindow::setCentralWidget(mainWidget);

  statusBar()->showMessage(tr("Loading..."));
  connect(mainWidget,SIGNAL(quitRequest()),this,SIGNAL(quitRequest()));

  // connect mainWidget with configuration instance
  // Tab<System>.system
  connect(configuration,SIGNAL(changeSystem_SystemDeamon(bool)),mainWidget,SLOT(setSystemSystemDeamon(bool)));
  connect(configuration,SIGNAL(changeSystem_SystemCommunicationMode(Share::Communication::Type)),mainWidget,SLOT(setSystemSystemCommunicationMode(Share::Communication::Type)));
  connect(configuration,SIGNAL(changeSystem_SystemListenPort(int)),mainWidget,SLOT(setSystemSystemListenPort(int)));
  connect(configuration,SIGNAL(changeSystem_SystemLocalListenPort(int)),mainWidget,SLOT(setSystemSystemLocalListenPort(int)));
  connect(configuration,SIGNAL(changeSystem_SystemCachePath(QString)),mainWidget,SLOT(setSystemSystemCachePath(QString)));
  connect(configuration,SIGNAL(changeSystem_SystemCacheQuota(int)),mainWidget,SLOT(setSystemSystemCacheQuota(int)));
  // Tab<System>.User
  connect(configuration,SIGNAL(changeSystem_UserDeamon(bool)),mainWidget,SLOT(setSystemUserDeamon(bool)));
  connect(configuration,SIGNAL(changeSystem_UserCommViaSystemDeamon(bool)),mainWidget,SLOT(setSystemUserCommViaSystemDeamon(bool)));
  connect(configuration,SIGNAL(changeSystem_UserListenPort(int)),mainWidget,SLOT(setSystemUserListenPort(int)));
  connect(configuration,SIGNAL(changeSystem_UserCommunicationMode(Share::Communication::Type)),mainWidget,SLOT(setSystemUserCommunicationMode(Share::Communication::Type)));
  connect(configuration,SIGNAL(changeSystem_UserLocalListenPort(int)),mainWidget,SLOT(setSystemUserLocalListenPort(int)));
  connect(configuration,SIGNAL(changeSystem_UserCachePath(QString)),mainWidget,SLOT(setSystemUserCachePath(QString)));
  connect(configuration,SIGNAL(changeSystem_UserCacheQuota(int)),mainWidget,SLOT(setSystemUserCacheQuota(int)));
  // Tab<User>
  connect(configuration,SIGNAL(changeUser_UseSystemSettings(bool)),mainWidget,SLOT(setUserUseSystemSettings(bool)));
  connect(configuration,SIGNAL(changeUser_UserDeamon(bool)),mainWidget,SLOT(setUserUserDeamon(bool)));
  connect(configuration,SIGNAL(changeUser_UserCommunicationMode(Share::Communication::Type)),mainWidget,SLOT(setUserUserCommunicationMode(Share::Communication::Type)));
  connect(configuration,SIGNAL(changeUser_UserListenPort(int)),mainWidget,SLOT(setUserUserListenPort(int)));
  connect(configuration,SIGNAL(changeUser_UserLocalListenPort(int)),mainWidget,SLOT(setUserUserLocalListenPort(int)));
  connect(configuration,SIGNAL(changeUser_UserCachePath(QString)),mainWidget,SLOT(setUserUserCachePath(QString)));
  connect(configuration,SIGNAL(changeUser_UserCacheQuota(int)),mainWidget,SLOT(setUserUserCacheQuota(int)));

  // Inform configuration class
  connect(mainWidget,SIGNAL(validateConfig()),this,SLOT(startSaving()));
  connect(mainWidget,SIGNAL(validateConfig()),configuration,SLOT(saveConfig()));

  // Connect events saving...
  connect(configuration,SIGNAL(configLoaded(bool)),this,SLOT(configLoaded(bool)));
  connect(configuration,SIGNAL(configLoaded(bool)),mainWidget,SLOT(configLoaded(bool)));
  connect(configuration,SIGNAL(configSaved(bool)),this,SLOT(configSaved(bool)));
  connect(configuration,SIGNAL(configSaved(bool)),mainWidget,SLOT(configSaved(bool)));

  // Connect changes on interface to the configuration class
  connect(mainWidget,SIGNAL(changeSystemSystemDeamon(bool)),configuration,SLOT(setSystem_SystemDeamon(bool)));
  connect(mainWidget,SIGNAL(changeSystemSystemListenPort(int)),configuration,SLOT(setSystem_SystemListenPort(int)));
  connect(mainWidget,SIGNAL(changeSystemSystemCommunicationMode(Share::Communication::Type)),configuration,SLOT(setSystem_SystemCommunicationMode(Share::Communication::Type)));
  connect(mainWidget,SIGNAL(changeSystemSystemLocalListenPort(int)),configuration,SLOT(setSystem_SystemLocalListenPort(int)));
  connect(mainWidget,SIGNAL(changeSystemSystemCachePath(QString)),configuration,SLOT(setSystem_SystemCachePath(QString)));
  connect(mainWidget,SIGNAL(changeSystemSystemCacheQuota(int)),configuration,SLOT(setSystem_SystemCacheQuota(int)));

  connect(mainWidget,SIGNAL(changeSystemUserDeamon(bool)),configuration,SLOT(setSystem_UserDeamon(bool)));
  connect(mainWidget,SIGNAL(changeSystemUserCommViaSystemDeamon(bool)),configuration,SLOT(setSystem_UserCommViaSystemDeamon(bool)));
  connect(mainWidget,SIGNAL(changeSystemUserListenPort(int)),configuration,SLOT(setSystem_UserListenPort(int)));
  connect(mainWidget,SIGNAL(changeSystemUserCommunicationMode(Share::Communication::Type)),configuration,SLOT(setSystem_UserCommunicationMode(Share::Communication::Type)));
  connect(mainWidget,SIGNAL(changeSystemUserLocalListenPort(int)),configuration,SLOT(setSystem_UserLocalListenPort(int)));
  connect(mainWidget,SIGNAL(changeSystemUserCachePath(QString)),configuration,SLOT(setSystem_UserCachePath(QString)));
  connect(mainWidget,SIGNAL(changeSystemUserCacheQuota(int)),configuration,SLOT(setSystem_UserCacheQuota(int)));

  connect(mainWidget,SIGNAL(changeUserUseSystemSettings(bool)),configuration,SLOT(setUser_UseSystemSettings(bool)));
  connect(mainWidget,SIGNAL(changeUserUserDeamon(bool)),configuration,SLOT(setUser_UserDeamon(bool)));
  connect(mainWidget,SIGNAL(changeUserUserCommunicationMode(Share::Communication::Type)),configuration,SLOT(setUser_UserCommunicationMode(Share::Communication::Type)));
  connect(mainWidget,SIGNAL(changeUserUserListenPort(int)),configuration,SLOT(setUser_UserListenPort(int)));
  connect(mainWidget,SIGNAL(changeUserUserLocalListenPort(int)),configuration,SLOT(setUser_UserLocalListenPort(int)));
  connect(mainWidget,SIGNAL(changeUserUserCachePath(QString)),configuration,SLOT(setUser_UserCachePath(QString)));
  connect(mainWidget,SIGNAL(changeUserUserCacheQuota(int)),configuration,SLOT(setUser_UserCacheQuota(int)));
  // Send configuration
  configuration->loadConfig();
}
Exemple #21
0
//====================================
void openCommand()
//====================================
{
  struct stat st;
  int ch,nsteps=1000,x,i,n,stop=0,loop,projNo = 0,ok=0,tmp;
  char *p,str[120],sstr[20],fileName[120],temp[120],syscom[120];
  char command[40][40];

  s_mode = S_ADMIN;
  g_silent = 0;

  readMsg(gplFile);

  while(strstr(str,"ex") == NULL)
    {
      anyErrors();
      unoInfo();

      wmove(uno,board_h-2,1);
      wprintw(uno,"                                                  ");
      if(g_silent==S_NO )mvwprintw(uno,board_h-2,1,"A%1d>",confWinMode);
      if(g_silent==S_YES)mvwprintw(uno,board_h-2,1,"A%1d<",confWinMode);

      strcpy(command[0],"");

      wgetstr(uno,str);

      n = tokCommand(command,str);

      strcpy(sstr,command[0]);

      p = str;

      projNo = atoi(sstr);

      if(strstr(sstr,"gpl"))
        {
          readMsg(gplFile);
        }
      else if(strstr(sstr,"err"))
        {
          readMsg(fileTemp);
        }
      else if(strstr(sstr,"run"))
	{
	  stop = 1;
          if(n == 2)stop = atoi(command[1]);
	  stop = checkRange(HEAL,"step",stop);

	  runMode(stop);
          if(stop==0)putMsg(2,"Back in Admin Mode!");
	}
      else if(strstr(sstr,"res")) // reset simulation
	{
	  resetSim();
	  init(confWinMode);
	  unoInfo();
	  readMsg(currentConf);
	}
      else if(strstr(sstr,"help")) //
	{
	  strcpy(fileName,fileInfoAdmin);
	  readMsg(fileName);
	}
      else if(strstr(sstr,"rem")) //
	{
	  if(n == 4)
	    {
	      if(strstr(command[1],"a"))g_pinType = ANA;
	      if(strstr(command[1],"d"))g_pinType = DIG;
	      g_pinNo   = atoi(command[2]);
	      g_pinStep = atoi(command[3]);
	      if(g_pinType == ANA)
		ok = checkRange(S_OK,"anapin",g_pinNo);
	      if(g_pinType == DIG)
		ok = checkRange(S_OK,"digpin",g_pinNo);
	      if(ok == S_OK)
		{
		  g_scenSource = 1;
		  sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,0,g_pinStep,S_DELETE);
		  //putMsg(2,syscom);
		  tmp=system(syscom);
		  initSim();
		  readSketchInfo();
		  readSimulation();
		  runStep(S_FORWARD);
		  readMsg(fileServScen);
		}
	      else
		putMsg(2,"Wrong pin number or pin type!");
	    }
	  else
	    putMsg(2,"Syntax: rem <a or d> <pin> <step>");
	}
      else if(strstr(sstr,"add")) //
	{
	  if(n == 5)
	    {
	      if(strstr(command[1],"a"))g_pinType = ANA;
	      if(strstr(command[1],"d"))g_pinType = DIG;

	      g_pinNo    = atoi(command[2]);
	      g_pinStep  = atoi(command[3]);
	      g_pinValue = atoi(command[4]);

	      ok = S_OK;
	      if(g_pinType == ANA)
		ok = checkRange(S_OK,"anapin",g_pinNo);
	      if(g_pinType == DIG)
		ok = checkRange(S_OK,"digpin",g_pinNo);

	      ok = ok + checkRange(S_OK,"step",g_pinStep);

	      if(ok == S_OK)
		{
		  g_scenSource = 1;
		  sprintf(syscom,"cd servuino;./servuino %d %d %d %d %d %d %d;",confSteps,g_scenSource,g_pinType,g_pinNo,g_pinValue,g_pinStep,S_ADD);
		  tmp=system(syscom);
		  initSim();
		  readSketchInfo();
		  readSimulation();
		  runStep(S_FORWARD);
		  readMsg(fileServScen);
		}
	    }
	  else
	    putMsg(2,"Syntax: add <a or d> <pin> <step> <value>");
	}
      else if(strstr(sstr,"info"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"conf"))
		{
		  readMsg(fileDefault);
		}
	      else if(strstr(command[1],"err"))
		{
		  readMsg(fileServError);
		}
	      else if(strstr(command[1],"g++"))
		{
		  readMsg(fileServComp);
		}
	      else if(strstr(command[1],"help"))
		{
		  readMsg(fileInfoAdmin);
		}
	      else if(strstr(command[1],"loop")) 
		{
		  showLoops();
		}
	      else if(strstr(command[1],"scen")) // scenario
		{
		  readMsg(fileServScen);
		}
	    }
	  else
	    {
	      readMsg(fileInfoAdmin);
	    }
	}

      else if(strstr(sstr,"proj"))
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
	      readConfig(currentConf);
              g_warning = S_YES;
	      unoInfo();
	    }
	  readMsg(currentConf);
	}
      else if(strstr(sstr,"list"))
	{
	  readMsg(fileProjList);	
	}
      else if(strstr(sstr,"sketch"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"conf"))
		{
		  readMsg(confSketchFile);
		}
	      else if(strstr(command[1],"work"))
		{
		  readMsg(fileServSketch);
		}
	    }
	  else
	    readMsg(fileServSketch);	
	}
      else if(strstr(sstr,"conf"))
	{
	  if(n == 3)
	    {
	      if(strstr(command[1],"sim"))
		{
		  confSteps = atoi(command[2]);	
		}
	      else if(strstr(command[1],"win"))
		{
		  confWinMode = atoi(command[2]);
		  if(confWinMode > WIN_MODES)confWinMode = 0;
		  init(confWinMode);
		  unoInfo();
		}
	      else if(strstr(command[1],"sketch"))
		{
		  strcpy(temp,command[2]);
		  if(stat(temp,&st) == 0)
		    {
		      strcpy(confSketchFile,command[2]);
		    }
		  else
		    {
		      sprintf(temp,"Sketch not found: %s",command[2]);// Issue 16
		      putMsg(msg_h-2,temp);
		    }
		}
	      saveConfig(currentConf);
	    }
	  readMsg(currentConf); 
	}
      
      
      else if(strstr(sstr,"sav")) //save config
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
              
	    }
	  saveConfig(currentConf);
	  readMsg(currentConf);
	  sprintf(syscom,"ls *.conf > %s;",fileProjList);
	  x=system(syscom);
	}
      else if(strstr(sstr,"del")) //delete config
	{
	  if(n == 2)
	    {
	      strcpy(currentConf,command[1]);
	      strcat(currentConf,".conf");
              
	    }
          if(strstr(currentConf,"default") == NULL)
	    {
	      sprintf(syscom,"rm %s;",currentConf);
	      x=system(syscom);
	      sprintf(syscom,"ls *.conf > %s;",fileProjList);
	      x=system(syscom);
	      readMsg(fileProjList);
	      strcpy(currentConf,fileDefault);
	    }	
	}
      else if(strstr(sstr,"win")) //windows layout
        {
          if(n == 2)
	    {
              confWinMode = atoi(command[1]);
              if(confWinMode > WIN_MODES)confWinMode = 0;
              init(confWinMode);
              unoInfo();
	    }
        }
      else if(strstr(sstr,"loop"))
	{
          if(n == 2)loop = atoi(command[1]);
	  loop = checkRange(HEAL,"loop",loop);
	  runLoops(loop);
	}
      else if(strstr(sstr,"clear"))
	{
	  sprintf(syscom,"rm servuino/sketch.ino;rm servuino/data.su;rm servuino/data.scen;");
	  x=system(syscom);
	}
      else if(strstr(sstr,"load"))
	{
          if(n == 2)
	    {
	      confSteps = atoi(command[1]);
	    }
          g_scenSource = 0;
	  loadCurrentProj();
	}
      else if(projNo > 0 && projNo < 10)
        {
	  selectProj(projNo,currentConf);
	  readConfig(currentConf);
	  g_warning = S_YES;
	  unoInfo();
	  readMsg(currentConf);   
        }
      else if(strstr(sstr,"data"))
	{
	  if(n == 2)
	    {
	      if(strstr(command[1],"ard"))
		{
		  readMsg(fileServArduino);
		}
	      else if(strstr(command[1],"cus"))
		{
		  readMsg(fileServCustom);
		}
	      else if(strstr(command[1],"cod"))
		{
		  readMsg(fileServCode);
		}
	      else if(strstr(command[1],"err"))
		{
		  readMsg(fileServError);
		}
	      else if(strstr(command[1],"sce"))
		{
		  readMsg(fileServScen);
		}
	    }
	  else
	    readMsg(fileServArduino);
	}
      else 
	{
	  putMsg(msg_h-2,"Unknown Admin command");
	}
    }
}
Exemple #22
0
void CALLBACK dispatchEvents(SIMCONNECT_RECV*  pData, DWORD  cbData, void *  pContext)
{
	HRESULT hr;

	switch (pData->dwID)
	{
	case SIMCONNECT_RECV_ID_EVENT:
	{
		SIMCONNECT_RECV_EVENT *evt = (SIMCONNECT_RECV_EVENT*)pData;

		switch (evt->uEventID)
		{
		case STARTUP:
			stats.lastDeleted = 0;
			stats.nrOfDeletions = 0;
			stats.nrOfRequests = 0;
			// Now the sim is running, request information on the user aircraft
			hr = SimConnect_RequestDataOnSimObjectType(hSimConnect, R1, AIPARKDATA, conf.radius, SIMCONNECT_SIMOBJECT_TYPE_AIRCRAFT);
			++stats.nrOfRequests;
			break;


		case R2:
			fsecCnt++;

			if (fsecCnt >= (conf.requestEveryXSec/4))
			{
				fsecCnt = 0;
				if (SUCCEEDED(SimConnect_RequestDataOnSimObjectType(hSimConnect, R1, AIPARKDATA, conf.radius, SIMCONNECT_SIMOBJECT_TYPE_AIRCRAFT)))
				{
					++stats.nrOfRequests;
				}
			}
			break;

		case MENU:
			getMenu(menu, sizeof(menu));
			SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
			break;

		case SELECTION:
			res = (SIMCONNECT_TEXT_RESULT)(evt->dwData);
			switch (res) {
			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_1:
				if (conf.requestEveryXSec < 3600)
				{
					conf.requestEveryXSec += 30;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_2:
				if (conf.requestEveryXSec > 45)
				{
					conf.requestEveryXSec -= 30;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_3:
				if (conf.radius < 190000)
				{
					conf.radius += 5000;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_4:
				if (conf.radius > 5000)
				{
					conf.radius -= 5000;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_5:
				if (conf.maxetd > 5400)
				{
					conf.maxetd -= 3600;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;


			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_6:
				if (conf.maxetd < 7*86400) // must be smaller than a week
				{
					conf.maxetd += 3600;
				}
				getMenu(menu, sizeof(menu));
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(menu), (void*)menu);
				break;

			case SIMCONNECT_TEXT_RESULT_MENU_SELECT_8:
				SimConnect_Text(hSimConnect, SIMCONNECT_TEXT_TYPE_MENU, 0, SELECTION, sizeof(empty), (void*)empty);
				break;
			default: //default cannot be close as displayed is also an event
				break;
			}
			saveConfig(conf);
			break;
		default:
			break;
		}
		break;
	}


	case SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE:
	{
		SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE *pObjData = (SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE*)pData;

		switch (pObjData->dwRequestID)
		{
		case R1:
		{
			DWORD ObjectID = pObjData->dwObjectID;
			DWORD entry = pObjData->dwentrynumber;
			DWORD outof = pObjData->dwoutof;
			DWORD length = pObjData->dwDefineCount;
			AIData *pS = (AIData*)&pObjData->dwData;
			if (ObjectID != SIMCONNECT_OBJECT_ID_USER)
			{
				if (strcmp(pS->state, "sleep") == 0 && pS->ETD > conf.maxetd)
				{
					if (FS10DeleteAIAircraft != NULL)
					{
						FS10DeleteAIAircraft(ObjectID, 1);
						++stats.nrOfDeletions;
						deletedSome = true;
					}
				}
			}

			if (entry == outof)
			{
				if (deletedSome)
				{
					stats.lastDeleted = GetTickCount64();
				}
				deletedSome = false;
			}


		}

		default:
			break;
		}
		break;
	}

	case SIMCONNECT_RECV_ID_EXCEPTION:
	{
		SIMCONNECT_RECV_EXCEPTION *except = (SIMCONNECT_RECV_EXCEPTION*)pData;
		printf("\n\n***** EXCEPTION=%d  SendID=%d  Index=%d  cbData=%d\n", except->dwException, except->dwSendID, except->dwIndex, cbData);
		break;
	}

	case SIMCONNECT_RECV_ID_QUIT:
	{
		quit = 1;
		break;
	}

	default:
		printf("\nReceived:%d", pData->dwID);
		break;
	}
}
Exemple #23
0
int main(int argc, char* argv[])
{
    u8 *tex_ptrone=GRRLIB_LoadTexture(handpointerred_png);
    u8 *tex_ptrtwo=GRRLIB_LoadTexture(handpointergreen_png);
    u8 *tex_back=GRRLIB_LoadJPG(bigmenuback_jpg, bigmenuback_jpg_size);
    u8 *tex_fore=GRRLIB_LoadTexture(credits_png);

    fatInitDefault();
    GRRLIB_InitVideo();
    WPAD_Init();

    SYS_SetResetCallback(WiiResetPressed);
    SYS_SetPowerCallback(WiiPowerPressed);
    WPAD_SetPowerButtonCallback(WiimotePowerPressed);
    rmode = VIDEO_GetPreferredMode(NULL);

    AESND_Init(NULL);
    MODPlay_Init(&mod_track);
    Init_Voice();

    AESND_Pause(0);                // the sound loop is running now

                                 // set the MOD song
    if (MODPlay_SetMOD (&mod_track, dojo_dan_oriental_mod) < 0 ) {
        MODPlay_Unload (&mod_track);
    } else {
        // set the music volume to the minimum so we don't hear the music before saved volume is known
        MODPlay_SetVolume( &mod_track, 0,0);
        MODPlay_Start (&mod_track);// Play the MOD
    }

    WPAD_SetDataFormat(WPAD_CHAN_ALL, WPAD_FMT_BTNS_ACC_IR);

    WPAD_SetVRes(WPAD_CHAN_ALL, rmode->fbWidth, rmode->xfbHeight);

    initMain();

    MODPlay_SetVolume( &mod_track, opt_music, opt_music);

    while( HWButton == 0) {
        WPAD_ScanPads();
        u32 wpad_one_down = WPAD_ButtonsDown(0);
        u32 wpad_two_down = WPAD_ButtonsDown(1);

        u32 type;
        WPADData *wd_one, *wd_two;
        WPAD_ReadPending(WPAD_CHAN_ALL, countevs);
        WPAD_Probe(WPAD_CHAN_ALL, &type);

        wd_one = WPAD_Data(0);
        wd_two = WPAD_Data(1);

        switch(main_mode) {
            case STARTUP :
                GRRLIB_FillScreen(0xFF000000);
                GRRLIB_DrawImg(0, 0, 640, 480, tex_back, 0, 1, 1, alpha>255?255:alpha);
                GRRLIB_DrawImg(68,308, 256, 80, tex_fore, 0, 1, 1, alpha>255?255:alpha);
                if(alpha++>394 || wpad_one_down > 0) {
                    main_mode=MENU;
                    if(tex_back) free(tex_back);
                    if(tex_fore) free(tex_fore);
                    initMenu();
                }
                break;
            case MENU :
                GRRLIB_FillScreen(0xFF000000);
                int menuopt = menuWiimote(wd_one,wpad_one_down);
                if(menuopt==EXIT) {
                    if(tex_ptrone) free(tex_ptrone);
                    if(tex_ptrtwo) free(tex_ptrtwo);
                }

                if(menuopt>NOTHING) {
                    processMenuOption(menuopt);
                    if(main_mode==GAME) {
                        MODPlay_Unload (&mod_track);
                        if(opt_tileset==SPOOKY)
                            MODPlay_SetMOD (&mod_track, graveyard_mod);
                        else
                        if(opt_tileset==EGYPTIAN)
                            MODPlay_SetMOD (&mod_track, egypt_crap_mod);
                        else
                        if(opt_tileset==SIMPLE)
                            MODPlay_SetMOD (&mod_track, childhood_mod);
                        else
                        if(opt_tileset==SPACE)
                            MODPlay_SetMOD (&mod_track, nebulos_mod);
                        else
                            MODPlay_SetMOD (&mod_track, sushi_mod);
                        MODPlay_SetVolume( &mod_track, opt_music, opt_music);
                        MODPlay_Start (&mod_track);
                    }
                    else
                        drawMenu(wd_one);
                }
                else
                    drawMenu(wd_one);
                break;
            case GAME :
                if(gameWiimote(wd_one,wpad_one_down,wd_two,wpad_two_down)) {
                    // we are exiting the game back to the menu
                    main_mode=MENU;
                    MODPlay_Unload (&mod_track);
                    MODPlay_SetMOD (&mod_track, dojo_dan_oriental_mod);
                    MODPlay_SetVolume( &mod_track, opt_music, opt_music);
                    MODPlay_Start (&mod_track);
                    killGame();
                    initMenu();
                }
                else {
                    drawGame();
                }
                break;
        }

        // alternate which pointer is on top every frame to not give the advantage to player one in two player mode
        static int ticktock=0;

        ticktock++;

        if(wd_two->ir.valid && ticktock%2==0) {
            if(main_mode==GAME && whatGameMode()==ONE_PLAYER_GAME) {
                // don't display second pointer in one player mode
            }
            else
                GRRLIB_DrawColImg(wd_two->ir.x - 9,wd_two->ir.y - 7,68,80,tex_ptrtwo,0,1,1,0xEEFFFFFF);
        }

        if(wd_one->ir.valid) {
            GRRLIB_DrawColImg(wd_one->ir.x - 9,wd_one->ir.y - 7,68,80,tex_ptrone,0,1,1,0xEEFFFFFF);
        }

        if(wd_two->ir.valid && ticktock%2!=0) {
            if(main_mode==GAME && whatGameMode()==ONE_PLAYER_GAME) {
                // don't display second pointer in one player mode
            }
            else
                GRRLIB_DrawColImg(wd_two->ir.x - 9,wd_two->ir.y - 7,68,80,tex_ptrtwo,0,1,1,0xEEFFFFFF);
        }

        if(wd_one->btns_h & WPAD_BUTTON_1) {
            GRRLIB_ScrShot("MahjonggWii_Screen_%y%m%d_%H%M%S.png",time(NULL));
        }

        GRRLIB_Render();
    }

    // we are exiting, free the mallocs
    switch( main_mode) {
        case GAME:
            killGame();

    }
    if(tex_ptrone) free(tex_ptrone);
    if(tex_ptrtwo) free(tex_ptrtwo);
    killMenuLanguages();
    MODPlay_Unload (&mod_track);
    Free_Voice();
    WPAD_Shutdown();
    GRRLIB_Stop();
    saveConfig(FILE_CFG);
    SYS_ResetSystem(HWButton, 0, 0);

    return 0;
}
Exemple #24
0
int CLCDD::main(int argc, char **argv)
{
	debugoutput = true;
	printf("Network LCD-Driver $Id: lcdd.cpp,v 1.57 2002/10/17 10:16:35 thegoodguy Exp $\n\n");

	InitNewClock();

	loadConfig();

	if(!lcdPainter.init())
	{
		//fehler beim lcd-init aufgetreten
		return -1;
	}

	//network-setup
	int listenfd, connfd;
	struct sockaddr_un servaddr;
	int clilen;

	std::string filename = LCDD_UDS_NAME;

	memset(&servaddr, 0, sizeof(struct sockaddr_un));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, filename.c_str());
	clilen = sizeof(servaddr.sun_family) + strlen(servaddr.sun_path);
	unlink(filename.c_str());

	//network-setup
	if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
	{
		perror("socket");
		return -1;
	}

	if ( bind(listenfd, (struct sockaddr*) &servaddr, clilen) <0 )
	{
		perror("[lcdd] bind failed...\n");
		return -1;
	}

	if (listen(listenfd, 5) !=0)
	{
		perror("[lcdd] listen failed...\n");
		return -1;
	}

	switch (fork())
	{
		case -1: /* can't fork */
			perror("[lcdd] fork");
			return -1;

		case 0: /* child, process becomes a daemon */
			if (setsid() == -1)
			{
				perror("[lcdd] setsid");
				return -1;
			}
			break;

		default: /* parent returns to calling process */
			return 0;
	}

	signal(SIGHUP,sig_catch);
	signal(SIGINT,sig_catch);
	signal(SIGQUIT,sig_catch);
	signal(SIGTERM, sig_catch);

	/* Thread erst nach dem forken erstellen, da sonst Abbruch */
	if (pthread_create (&thrTime, NULL, TimeThread, NULL) != 0 )
	{
		perror("[lcdd]: pthread_create(TimeThread)");
		return -1;
	}

	shall_exit = false;
	while(!shall_exit)
	{
		connfd = accept(listenfd, (struct sockaddr*) &servaddr, (socklen_t*) &clilen);
		CLcddMsg::Header rmsg;
		read(connfd,&rmsg,sizeof(rmsg));
		parse_command(connfd, rmsg);
		close(connfd);
	}
	close(listenfd);
	saveConfig();
	return 0;
}
void KWatchGnuPGConfig::slotSave()
{
    saveConfig();
    emit reconfigure();
}
Exemple #26
0
void CLCDD::parse_command(int connfd, CLcddMsg::Header rmsg)
{
	if(rmsg.version != CLcddMsg::ACTVERSION)
	{
		printf("[lcdd] unknown version\n");
		return;
	}

	switch (rmsg.cmd)
	{
		case CLcddMsg::CMD_SHUTDOWN:
			saveConfig();
			exit(0);
			break;
		case CLcddMsg::CMD_SETSERVICENAME:
			CLcddMsg::commandServiceName msg;
			read(connfd, &msg, sizeof(msg));
			lcdPainter.show_servicename( msg.servicename);
			break;
		case CLcddMsg::CMD_SETVOLUME:
			CLcddMsg::commandVolume msg2;
			read(connfd, &msg2, sizeof(msg2));
			lcdPainter.show_volume(msg2.volume);
			break;
		case CLcddMsg::CMD_SETMUTE:
			CLcddMsg::commandMute msg3;
			read(connfd, &msg3, sizeof(msg3));
			lcdPainter.setMuted(msg3.mute);
			break;
		case CLcddMsg::CMD_SETMODE:
			CLcddMsg::commandMode msg4;
			read(connfd, &msg4, sizeof(msg4));
			lcdPainter.set_mode((CLcddTypes::mode) msg4.mode, msg4.text);
			break;
		case CLcddMsg::CMD_SETMENUTEXT:
			CLcddMsg::commandMenuText msg5;
			read(connfd, &msg5, sizeof(msg5));
			lcdPainter.show_menu(msg5.position, msg5.text, msg5.highlight);
			break;
		case CLcddMsg::CMD_SETLCDBRIGHTNESS:
			CLcddMsg::commandSetBrightness msg6;
			read(connfd, &msg6, sizeof(msg6));
			lcdPainter.setBrightness(msg6.brightness);
			break;
		case CLcddMsg::CMD_SETLCDCONTRAST:
			CLcddMsg::commandSetBrightness msg7;
			read(connfd, &msg7, sizeof(msg7));
			lcdPainter.setContrast(msg7.brightness);
			break;
		case CLcddMsg::CMD_SETSTANDBYLCDBRIGHTNESS:
			CLcddMsg::commandSetBrightness msg8;
			read(connfd, &msg8, sizeof(msg8));
			lcdPainter.setBrightnessStandby(msg8.brightness);
			break;
		case CLcddMsg::CMD_GETLCDBRIGHTNESS:
			CLcddMsg::responseGetBrightness msg9;
			msg9.brightness = lcdPainter.getBrightness();
			write(connfd, &msg9, sizeof(msg9));
			break;
		case CLcddMsg::CMD_GETLCDCONTRAST:
			CLcddMsg::responseGetBrightness msg10;
			msg10.brightness = lcdPainter.getContrast();
			write(connfd, &msg10, sizeof(msg10));
			break;
		case CLcddMsg::CMD_GETSTANDBYLCDBRIGHTNESS:
			CLcddMsg::responseGetBrightness msg11;
			msg11.brightness = lcdPainter.getBrightnessStandby();
			write(connfd, &msg11, sizeof(msg11));
			break;

		case CLcddMsg::CMD_SETLCDPOWER:
			CLcddMsg::commandPower msg12;
			read(connfd, &msg12, sizeof(msg12));
			lcdPainter.setPower(msg12.power);
			break;
		case CLcddMsg::CMD_GETLCDPOWER:
			CLcddMsg::commandPower msg13;
			msg13.power = lcdPainter.getPower();
			write(connfd, &msg13, sizeof(msg13));
			break;
		case CLcddMsg::CMD_SETLCDINVERSE:
			CLcddMsg::commandInverse msg14;
			read(connfd, &msg14, sizeof(msg14));
			lcdPainter.setInverse(msg14.inverse);
			break;
		case CLcddMsg::CMD_GETLCDINVERSE:
			CLcddMsg::commandInverse msg15;
			msg15.inverse = lcdPainter.getInverse();
			write(connfd, &msg15, sizeof(msg15));
			break;
		case CLcddMsg::CMD_UPDATE:
			lcdPainter.update();
			break;
		case CLcddMsg::CMD_PAUSE:
			lcdPainter.pause();
			break;
		case CLcddMsg::CMD_RESUME:
			lcdPainter.resume();
			break;

		default:
			printf("unknown command %i\n", rmsg.cmd);
	}
}
Exemple #27
0
bool SynscanDriver::sendLocation()
{
    char res[SYN_RES] = {0};

    LOG_DEBUG("Reading mount location...");

    if (isSimulation())
    {
        LocationN[LOCATION_LATITUDE].value  = 29.5;
        LocationN[LOCATION_LONGITUDE].value = 48;
        IDSetNumber(&LocationNP, nullptr);
        return true;
    }

    if (!sendCommand("w", res))
        return false;

    double lat, lon;
    //  lets parse this data now
    int a, b, c, d, e, f, g, h;
    a = res[0];
    b = res[1];
    c = res[2];
    d = res[3];
    e = res[4];
    f = res[5];
    g = res[6];
    h = res[7];

    double t1, t2, t3;

    t1  = c;
    t2  = b;
    t3  = a;
    t1  = t1 / 3600.0;
    t2  = t2 / 60.0;
    lat = t1 + t2 + t3;

    t1  = g;
    t2  = f;
    t3  = e;
    t1  = t1 / 3600.0;
    t2  = t2 / 60.0;
    lon = t1 + t2 + t3;

    if (d == 1)
        lat = lat * -1;
    if (h == 1)
        lon = 360 - lon;
    LocationN[LOCATION_LATITUDE].value  = lat;
    LocationN[LOCATION_LONGITUDE].value = lon;
    IDSetNumber(&LocationNP, nullptr);

    saveConfig(true, "GEOGRAPHIC_COORD");

    char LongitudeStr[32] = {0}, LatitudeStr[32] = {0};
    fs_sexa(LongitudeStr, lon, 2, 3600);
    fs_sexa(LatitudeStr, lat, 2, 3600);
    LOGF_INFO("Mount Longitude %s Latitude %s", LongitudeStr, LatitudeStr);

    return true;
}
Exemple #28
0
MainWindow::MainWindow()
  : m_settings(QString::fromAscii("Doxygen.org"), QString::fromAscii("Doxywizard"))
{
  QMenu *file = menuBar()->addMenu(tr("File"));
  file->addAction(tr("Open..."), 
                  this, SLOT(openConfig()), Qt::CTRL+Qt::Key_O);
  m_recentMenu = file->addMenu(tr("Open recent"));
  file->addAction(tr("Save"), 
                  this, SLOT(saveConfig()), Qt::CTRL+Qt::Key_S);
  file->addAction(tr("Save as..."), 
                  this, SLOT(saveConfigAs()), Qt::SHIFT+Qt::CTRL+Qt::Key_S);
  file->addAction(tr("Quit"),  
                  this, SLOT(quit()), Qt::CTRL+Qt::Key_Q);

  QMenu *settings = menuBar()->addMenu(tr("Settings"));
  settings->addAction(tr("Reset to factory defaults"),
                  this,SLOT(resetToDefaults()));
  settings->addAction(tr("Use current settings at startup"),
                  this,SLOT(makeDefaults()));
  settings->addAction(tr("Clear recent list"),
                  this,SLOT(clearRecent()));

  QMenu *help = menuBar()->addMenu(tr("Help"));
  help->addAction(tr("Online manual"), 
                  this, SLOT(manual()), Qt::Key_F1);
  help->addAction(tr("About"), 
                  this, SLOT(about()) );

  m_expert = new Expert;
  m_wizard = new Wizard(m_expert->modelData());

  // ----------- top part ------------------
  QWidget *topPart = new QWidget;
  QVBoxLayout *rowLayout = new QVBoxLayout(topPart);

  // select working directory
  QHBoxLayout *dirLayout = new QHBoxLayout;
  m_workingDir = new QLineEdit;
  m_selWorkingDir = new QPushButton(tr("Select..."));
  dirLayout->addWidget(m_workingDir);
  dirLayout->addWidget(m_selWorkingDir);

  //------------- bottom part --------------
  QWidget *runTab = new QWidget;
  QVBoxLayout *runTabLayout = new QVBoxLayout(runTab);

  // run doxygen
  QHBoxLayout *runLayout = new QHBoxLayout;
  m_run = new QPushButton(tr("Run doxygen"));
  m_run->setEnabled(false);
  m_runStatus = new QLabel(tr("Status: not running"));
  m_saveLog = new QPushButton(tr("Save log..."));
  m_saveLog->setEnabled(false);
  QPushButton *showSettings = new QPushButton(tr("Show configuration"));
  runLayout->addWidget(m_run);
  runLayout->addWidget(m_runStatus);
  runLayout->addStretch(1);
  runLayout->addWidget(showSettings);
  runLayout->addWidget(m_saveLog);

  // output produced by doxygen
  runTabLayout->addLayout(runLayout);
  runTabLayout->addWidget(new QLabel(tr("Output produced by doxygen")));
  QGridLayout *grid = new QGridLayout;
  m_outputLog = new QTextEdit;
  m_outputLog->setReadOnly(true);
  m_outputLog->setFontFamily(QString::fromAscii("courier"));
  m_outputLog->setMinimumWidth(600);
  grid->addWidget(m_outputLog,0,0);
  grid->setColumnStretch(0,1);
  grid->setRowStretch(0,1);
  QHBoxLayout *launchLayout = new QHBoxLayout;
  m_launchHtml = new QPushButton(tr("Show HTML output"));
  launchLayout->addWidget(m_launchHtml);

  launchLayout->addStretch(1);
  grid->addLayout(launchLayout,1,0);
  runTabLayout->addLayout(grid);

  QTabWidget *tabs = new QTabWidget;
  tabs->addTab(m_wizard,tr("Wizard"));
  tabs->addTab(m_expert,tr("Expert"));
  tabs->addTab(runTab,tr("Run"));

  rowLayout->addWidget(new QLabel(tr("Step 1: Specify the working directory from which doxygen will run")));
  rowLayout->addLayout(dirLayout);
  rowLayout->addWidget(new QLabel(tr("Step 2: Configure doxygen using the Wizard and/or Expert tab, then switch to the Run tab to generate the documentation")));
  rowLayout->addWidget(tabs);

  setCentralWidget(topPart);
  statusBar()->showMessage(tr("Welcome to Doxygen"),messageTimeout);

  m_runProcess = new QProcess;
  m_running = false;
  m_timer = new QTimer;

  // connect signals and slots
  connect(tabs,SIGNAL(currentChanged(int)),SLOT(selectTab(int)));
  connect(m_selWorkingDir,SIGNAL(clicked()),SLOT(selectWorkingDir()));
  connect(m_recentMenu,SIGNAL(triggered(QAction*)),SLOT(openRecent(QAction*)));
  connect(m_workingDir,SIGNAL(returnPressed()),SLOT(updateWorkingDir()));
  connect(m_runProcess,SIGNAL(readyReadStandardOutput()),SLOT(readStdout()));
  connect(m_runProcess,SIGNAL(finished(int, QProcess::ExitStatus)),SLOT(runComplete()));
  connect(m_timer,SIGNAL(timeout()),SLOT(readStdout()));
  connect(m_run,SIGNAL(clicked()),SLOT(runDoxygen()));
  connect(m_launchHtml,SIGNAL(clicked()),SLOT(showHtmlOutput()));
  connect(m_saveLog,SIGNAL(clicked()),SLOT(saveLog()));
  connect(showSettings,SIGNAL(clicked()),SLOT(showSettings()));
  connect(m_expert,SIGNAL(changed()),SLOT(configChanged()));

  loadSettings();
  updateLaunchButtonState();
  m_modified = false;
  updateTitle();
  m_wizard->refresh();
}
/** Load configuration values from file. */
bool UserConfig::loadConfig()
{
    const std::string filename = file_manager->getUserConfigFile(m_filename);
    XMLNode* root = file_manager->createXMLTree(filename);
    if(!root || root->getName() != "stkconfig")
    {
        Log::error("UserConfig",
                   "Could not read user config file '%s'.", filename.c_str());
        if(root) delete root;
        // Create a default config file - just in case that stk crashes later
        // there is a config file that can be modified (to e.g. disable
        // shaders)
        saveConfig();
        return false;
    }

    // ---- Read config file version
    int config_file_version = m_current_config_version;
    if(root->get("version", &config_file_version) < 1)
    {
        GUIEngine::showMessage( _("Your config file was malformed, so it was deleted and a new one will be created."), 10.0f);
        Log::error("UserConfig",
                   "Warning, malformed user config file! Contains no version");
    }
    if (config_file_version < m_current_config_version)
    {
        // current version (8) is 100% incompatible with other versions (which were lisp)
        // so we just delete the old config. in the future, for smaller updates, we can
        // add back the code previously there that upgraded the config file to the new
        // format instead of overwriting it.

        GUIEngine::showMessage(_("Your config file was too old, so it was deleted and a new one will be created."), 10.0f);
        Log::info("UserConfig", "Your config file was too old, so it was deleted and a new one will be created.");
        delete root;
        return false;

    }   // if configFileVersion<SUPPORTED_CONFIG_VERSION

    // ---- Read parameters values (all parameter objects must have been created before this point if
    //      you want them automatically read from the config file)
    const int paramAmount = all_params.size();
    for(int i=0; i<paramAmount; i++)
    {
        all_params[i].findYourDataInAChildOf(root);
    }


    // ---- Read Saved GP's
    UserConfigParams::m_saved_grand_prix_list.clearAndDeleteAll();
    std::vector<XMLNode*> saved_gps;
    root->getNodes("SavedGP", saved_gps);
    const int gp_amount = saved_gps.size();
    for (int i=0; i<gp_amount; i++)
    {
        UserConfigParams::m_saved_grand_prix_list.push_back(
                                           new SavedGrandPrix( saved_gps[i]) );
    }
    delete root;

    return true;
}   // loadConfig
Exemple #30
0
CIoConfig::CIoConfig(QSettings * settings,
                     std::map<QString, QVariant> &devList,
                     QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CIoConfig),
    m_settings(settings)
{
    unsigned int i=0;
    QString devstr;
    bool cfgmatch=false; //flag to indicate that device from config was found

    ui->setupUi(this);

    QString indev = settings->value("input/device", "").toString();

    // insert the device list in device combo box
    std::map<QString, QVariant>::iterator I = devList.begin();
    i = 0;
    while (I != devList.end())
    {
        devstr = (*I).second.toString();
        ui->inDevCombo->addItem((*I).first, devstr);

        // is this the device stored in config?
        if (indev == devstr)
        {
            ui->inDevCombo->setCurrentIndex(i);
            ui->inDevEdit->setText(devstr);
            cfgmatch = true;
        }
        ++I;
        ++i;
    }


    ui->inDevCombo->addItem(tr("Other..."), QVariant(""));

    // If device string from config is not one of the detected devices
    // it could be that device is not plugged in (in which case we select
    // other) or that this is the first time (select the first detected device).
    if (!cfgmatch)
    {
        if (indev.isEmpty())
        {
            // First time config: select the first detected device
            ui->inDevCombo->setCurrentIndex(0);
            ui->inDevEdit->setText(ui->inDevCombo->itemData(0).toString());
            if (ui->inDevEdit->text().isEmpty())
                ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
        }
        else
        {
            // Select other
            ui->inDevCombo->setCurrentIndex(i);
            ui->inDevEdit->setText(indev);
        }
    }

    // input rate
    updateInputSampleRates(settings->value("input/sample_rate", 0).toInt());

    // decimation
    int idx = decim2idx(settings->value("input/decimation", 0).toInt());
    ui->decimCombo->setCurrentIndex(idx);
    decimationChanged(idx);

    // Analog bandwidth
    ui->bwSpinBox->setValue(1.0e-6*settings->value("input/bandwidth", 0.0).toDouble());

    // LNB LO
    ui->loSpinBox->setValue(1.0e-6 * settings->value("input/lnb_lo", 0.0).toDouble());

    // Output device
    QString outdev = settings->value("output/device", "").toString();

     // get list of audio output devices
#ifdef WITH_PULSEAUDIO
    pa_device_list devices;
    outDevList = devices.get_output_devices();

    qDebug() << __FUNCTION__ << ": Available output devices:";
    for (i = 0; i < outDevList.size(); i++)
    {
        qDebug() << "   " << i << ":" << QString(outDevList[i].get_description().c_str());
        //qDebug() << "     " << QString(outDevList[i].get_name().c_str());
        ui->outDevCombo->addItem(QString(outDevList[i].get_description().c_str()));

        // note that item #i in devlist will be item #(i+1)
        // in combo box due to "default"
        if (outdev == QString(outDevList[i].get_name().c_str()))
            ui->outDevCombo->setCurrentIndex(i+1);
    }
#elif WITH_PORTAUDIO
    portaudio_device_list   devices;

    outDevList = devices.get_output_devices();
    for (i = 0; i < outDevList.size(); i++)
    {
        ui->outDevCombo->addItem(QString(outDevList[i].get_description().c_str()));

        // note that item #i in devlist will be item #(i+1)
        // in combo box due to "default"
        if (outdev == QString(outDevList[i].get_name().c_str()))
            ui->outDevCombo->setCurrentIndex(i+1);
    }
    //ui->outDevCombo->setEditable(true);

#elif defined(GQRX_OS_MACX)
    osxaudio_device_list devices;
    outDevList = devices.get_output_devices();

    qDebug() << __FUNCTION__ << ": Available output devices:";
    for (i = 0; i < outDevList.size(); i++)
    {
        qDebug() << "   " << i << ":" << QString(outDevList[i].get_name().c_str());
        ui->outDevCombo->addItem(QString(outDevList[i].get_name().c_str()));

        // note that item #i in devlist will be item #(i+1)
        // in combo box due to "default"
        if (outdev == QString(outDevList[i].get_name().c_str()))
            ui->outDevCombo->setCurrentIndex(i+1);
    }

#else
    ui->outDevCombo->addItem(settings->value("output/device", "Default").toString(),
                             settings->value("output/device", "Default").toString());
    ui->outDevCombo->setEditable(true);
#endif // WITH_PULSEAUDIO

    // Signals and slots
    connect(this, SIGNAL(accepted()), this, SLOT(saveConfig()));
    connect(ui->inDevCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(inputDeviceSelected(int)));
    connect(ui->inDevEdit, SIGNAL(textChanged(QString)), this, SLOT(inputDevstrChanged(QString)));
    connect(ui->inSrCombo, SIGNAL(editTextChanged(QString)), this, SLOT(inputRateChanged(QString)));
    connect(ui->decimCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(decimationChanged(int)));
}