Beispiel #1
0
bool ProxySession::RunOne(FileDesc& epoll_fd, FileDesc& client_fd, std::error_code &ec)
{
    epoll_event event; // TODO - process more than 1 event at a time?

    int num = epoll_wait(epoll_fd, &event, 1, -1);

    if(num < 0)
    {
            ec = std::error_code(errno, std::system_category());
            return false;
    }

    if(event.events & EPOLLIN)
    {
            if(event.data.fd == client_fd)
            {
                    return Transfer(client_fd, m_server_fd, *m_c2sParser, ec);
            }
            else
            {
                    // otherwise assume source is server id
                    return Transfer(m_server_fd, client_fd, *m_s2cParser, ec);
            }
    }
    else
    {
            ec = Error::EPOLL_SOCKET_ERR;
            return false;
    }
}
Beispiel #2
0
void Transfer(int remaining, std::array<std::stack<int>, 3>& pegs, int from, int to, int inbetween)
{
    if(remaining > 0)
    {
        Transfer(remaining-1, pegs, from, inbetween, to);
        pegs[to].push(pegs[from].top());
        pegs[from].pop();
        std::cout << "Move " << pegs[to].top() << " from peg " << from << " to peg " << to << std::endl;
        Transfer(remaining-1, pegs, inbetween, to, from);
    }
}
Beispiel #3
0
bool TraktorF1MK2::sendLedsAndDisplay()
{
  if (m_TextDisplay.dirty() || true)
  {
    const auto displayData = m_TextDisplay.displayData();
    for (size_t i = 0; i < m_TextDisplay.dataSize(); i++)
    {
      for (uint8_t j = 0; j < 8; j++)
      {
        size_t displayIndex = (m_TextDisplay.dataSize() - 1 - i);
        m_leds[(displayIndex * 8) + j] = (((1 << j) & displayData[i]) > 0) ? 0x7f : 0x00;
      }
    }
    m_isDirtyLeds = true;
  }
  if (m_isDirtyLeds)
  {
    if (!writeToDeviceHandle(Transfer({0x80}, &m_leds[0], kF1MK2_nLeds), kF1MK2_epOut))
    {
      return false;
    }
    m_isDirtyLeds = false;
  }
  return true;
}
Beispiel #4
0
int main(int argc, char *argv[])
{
    initConnection();
    
    char file_name[FILE_NAME_MAX_SIZE+1];
    bzero(file_name, FILE_NAME_MAX_SIZE+1);
    if (argc>1){
        strncpy(file_name,argv[1],strlen(argv[1]));
    }
    FILE *fp = NULL;
    if (ShakeHands(file_name, &fp)>0){
        printf("Sending...\n"); 
        fp = fopen(file_name, "rb");
        if (NULL == fp){
            printf("File:\t %s can not open to read.\n",file_name);exit(1);
        }
        struct timeval start,finish;
        gettimeofday(&start,NULL);
        Transfer(client_socket,server_addr, &fp);
        fclose(fp);
        gettimeofday(&finish,NULL);
        printf("Send File:\t %s To Server [%s] Finished.\n", file_name, IP);
        double duration = (double)((finish.tv_sec-start.tv_sec)*1000000.0+finish.tv_usec-start.tv_usec)/1000000.0;
        printf("Duration: %.3lf sec\n",duration);
    }
    
    return 0;
}
bool CBPersistMgr::TransferValue(IWmeSubFrame** Value)
{
	CBSubFrame* Temp;
	if(m_Saving)
	{
		Temp = (CBSubFrame*)*Value;
		Transfer("", &Temp);
	}
	else
	{
		Transfer("", &Temp);
		*Value = (IWmeSubFrame*)Temp;
	}

	return S_OK;
}
Beispiel #6
0
void Neuron::Process()
{
  input = 0;
  for (int i=0; i<nbconnexions; i++)
    input += connexions[i].neuron->output * connexions[i].weight ;
  output = Transfer(input);
}
bool CBPersistMgr::TransferValue(IWmeObject** Value)
{
	CBScriptable* Temp;
	if(m_Saving)
	{
		Temp = (CBScriptable*)*Value;
		Transfer("", &Temp);
	}
	else
	{
		Transfer("", &Temp);
		*Value = (IWmeObject*)Temp;
	}

	return S_OK;
}
Beispiel #8
0
void CSendFileWidget::onTransferButtonClick()
{
	QString hostName = host->text();
	int portValue = port->value();
	QString transferFileName = fileName->text();

	emit Transfer( hostName, portValue, transferFileName );
}
Beispiel #9
0
// Returns true if all pieces were moved.
bool RequestQueue::Transfer(RequestQueue &dstq)
{
  bool result = true;

  while( rq_head ){
    if( !Transfer(dstq, rq_head->slices->index) ) result = false;
  }
  rq_send = (SLICE *)0;
  return result;
}
Beispiel #10
0
void MoveTowerHanoi (int n)
{
    std::array<std::stack<int>, 3> pegs;
    for (int i = n; i > 0; --i)
    {
        pegs[0].push(i);
    }
    
    Transfer(n, pegs, 0, 1, 2);
}
Beispiel #11
0
void TF_2Port::Evaluate (Path* path) {
    Transfer();

    for (int i = 0; i < Outputs(); ++i) {
        if (ChangedOutput(i)) {
            StateVar* output = GetOutput(i);
            Connector* conn = GetBinding(output);
            conn->Transmit(path);
        }
    }
}
/**
 * Decode the image from BuffObj 
 * \param BuffObj: buffer object
 * \return true if is ok
 */
bool bufferImage::decodeBuffer(BuffObj *handledObj)
{
	bufferImageJPG newima;
	
	if (newima.decodeBuffer(handledObj)) 
	{ 
		 Transfer(newima); return true; 
	}
	
	if (newima.decodeBuffer(handledObj))
	{
		Transfer(newima);
		return true;
	} 
	else 
	{
		return false;
	}
	
	strcpy(info.Error,"decodeBuffer: Error");
	return false;
}
Beispiel #13
0
int main ()
{
    GetWn ();
    while (scanf ("%s%s", A, B) != EOF)
    {
        int len;

        Prepare (A, B, a, b, len);
        Conv (a, b, len);
        Transfer (a, len);
        Print (a, len);
    }
    return 0;
}
Beispiel #14
0
static void 
RealEnqueue(RF_CvscanHeader_t * hdr, RF_DiskQueueData_t * req)
{
	RF_ASSERT(req->priority == RF_IO_NORMAL_PRIORITY || req->priority == RF_IO_LOW_PRIORITY);

	DO_CHECK_STATE(hdr);
	if (hdr->left_cnt == 0 && hdr->right_cnt == 0) {
		hdr->nxt_priority = req->priority;
	}
	if (req->priority > hdr->nxt_priority) {
		/*
		** dump all other outstanding requests on the back burner
		*/
		Transfer(&hdr->burner, &hdr->left);
		Transfer(&hdr->burner, &hdr->right);
		hdr->left_cnt = 0;
		hdr->right_cnt = 0;
		hdr->nxt_priority = req->priority;
	}
	if (req->priority < hdr->nxt_priority) {
		/*
		** yet another low priority task!
		*/
		PriorityInsert(&hdr->burner, req);
	} else {
		if (req->sectorOffset < hdr->cur_block) {
			/* this request is to the left of the current arms */
			ReqInsert(&hdr->left, req, rf_cvscan_LEFT);
			hdr->left_cnt++;
		} else {
			/* this request is to the right of the current arms */
			ReqInsert(&hdr->right, req, rf_cvscan_RIGHT);
			hdr->right_cnt++;
		}
	}
	DO_CHECK_STATE(hdr);
}
Beispiel #15
0
/*********************************
*            主函数
**********************************/
void main()
{ 
    //uchar i;
	Init_IO();                                    //I/O口初始化,
	Init_MCU();                                   //主函数初始化,T0定时器工作在方式1初始化,显示"请稍等,初始化中",GATE=0,
	Init_RAM();                                   //位变量初始化
	Init_Para();                                  //参数初始化,初始化参数,从IIC读取阈值等信息赋予给参量
	Init_Buf();									//并口通讯数组初始化
//	Select_Mast();                                //判断主从机	
	Init_Time0();	                             //开启定时器0。定时器0初始化,工作在方式一,定时初值:H:0xDC,L:0x00;中断计数初始化?定时5ms,NumT0=0;
    Lcd_Clear();								//LCD清屏
	Lcd_Start();								//显示"清华大学/n核能与新能源技术研究院"
	EX0=1;                                        //只允许外部0中断,中断0为键盘
	IT0=1;                                        //外部中断0 
	while(1)
	{  	
//	   BackUp_Display();	
	   Select_Mast();                                //判断主从机,写入主从机标志Flag_Mast=1(主机)0(从机)
	   key_function(); 								//按键功能,在while循环中不断检测按键标志,按键标志由按键外部中断来更改
	   if(Flag_Tim0)	                         //8253计数定时结束时,读取探头的计数,刚开始Flag_Tim0=0,仅当Flag8253Counting计数定时标识为1,且计数器中断次数大于设定的中断次数时,Flag_timo才会等于1
	    {										//Flag_Tim0为计数器结束标志,初始为0,开机打开定时器中断后,定时器5ms中断一次,检查Flag_Tim0一次,为一表示计数器计时结束
			Flag_Tim0 = 0;		                 //定时标志清0
			Flag_Warn = 0;		                 //报警标志清0
			GetAndDisdata(); 	                 //从8253的锁存器得到测量计数器结果,存入至buf数组
			ShowData();                          //显示测量数据 
			shortdelay(1000);	          		//
	        Transfer();                          //并行传输数据
//			bakeup_conv_data();           
			Init_8253();   						//初始化8253
			                                      //定时结束时,立刻又开始初始化进行计数
	   }
	    if(Flag_Tim0 == 0)                        //开启8253计数过程中,处理报警中断,报警有中断吗?
       {
			if(Flag_Warn_Flash == 1)                   //主机LED指示灯闪烁间隔定时,Flag_Warn_Flash为LED灯闪烁标志
			{
				Flag_Warn_Flash = 0;
	            Led_Flash();
			}
			if((Flag_Warn_Led==1) && (PCOLSIG==0))      //屏幕上红灯闪烁间隔定时,程序中没有找到PCOLSIG=0的程序段
			{	
				Flag_Warn_Led = 0;
				RedLed_Flash();							//灯闪烁
			 } 
	    }
	}             
}
Beispiel #16
0
    bool QuorumStep(docpos loBound, docpos hiBound, docpos &foundDoc, int &accum) {

        docpos currentDoc = 0;
        bool goodEnd = true;
        
        while (1) {
            docpos elementPos = Heap.Current();
            docpos elementDoc = elementPos >> 16;
            if (elementDoc != currentDoc) {
                if (accum >= Quorum && elementDoc >= loBound) {
                    if (currentDoc < loBound) {
                        currentDoc = loBound;
                    }
                    break;
                }
                if (elementDoc > hiBound) {
                    currentDoc = hiBound;
                    goodEnd = false;
                    break;
                }
                currentDoc = elementDoc;
            }
            accum += Transfer(elementPos);
        }
        

        for (size_t index = 0; index < Count; ++index) {
            if (Free[index]) {
                docpos elementDoc = Iterators[index]->Skip(currentDoc);
                if (elementDoc > currentDoc) {
                    int delta = Modify(-Weights[index], index);
                    accum += delta;
                    Heap.Add((elementDoc << 16) + index);
                    Free[index] = false;
                    if (accum < Quorum && goodEnd) {
                        foundDoc = currentDoc;
                        return false;
                    }
                }
            }
        }

        foundDoc = currentDoc;
        return true;
    }
Beispiel #17
0
/* transaction time: 1.1 to 2 ms typically */
int lgw_spi_r(void *spi_target, uint8_t spi_mux_mode, uint8_t spi_mux_target, uint8_t address, uint8_t *data) {
	struct mpsse_context *mpsse = spi_target;
	uint8_t out_buf[3];
    uint8_t command_size;
	uint8_t *in_buf = NULL;
	int a, b;
	
	/* check input variables */
	CHECK_NULL(spi_target);
	if ((address & 0x80) != 0) {
		DEBUG_MSG("WARNING: SPI address > 127\n");
	}
	CHECK_NULL(data);
	
    /* prepare frame to be sent */
    if (spi_mux_mode == LGW_SPI_MUX_MODE1) {
        out_buf[0] = spi_mux_target;
        out_buf[1] = READ_ACCESS | (address & 0x7F);
        out_buf[2] = 0x00;
        command_size = 3;
    } else {
        out_buf[0] = READ_ACCESS | (address & 0x7F);
        out_buf[1] = 0x00;
        command_size = 2;
    }
	
	/* MPSSE transaction */
	a = Start(mpsse);
	in_buf = (uint8_t *)Transfer(mpsse, (char *)out_buf, command_size);
	b = Stop(mpsse);
	
	/* determine return code */
	if ((in_buf == NULL) || (a != MPSSE_OK) || (b != MPSSE_OK)) {
		DEBUG_MSG("ERROR: SPI READ FAILURE\n");
		if (in_buf != NULL) {
			free(in_buf);
		}
		return LGW_SPI_ERROR;
	} else {
		DEBUG_MSG("Note: SPI read success\n");
		*data = in_buf[1];
		free(in_buf);
		return LGW_SPI_SUCCESS;
	}
}
Beispiel #18
0
void FGPropulsion::DoRefuel(double time_slice)
{
  unsigned int i;

  double fillrate = 100 * time_slice;   // 100 lbs/sec = 6000 lbs/min
  int TanksNotFull = 0;

  for (i=0; i<numTanks; i++) {
    if (Tanks[i]->GetPctFull() < 99.99) ++TanksNotFull;
  }

  if (TanksNotFull) {
    for (i=0; i<numTanks; i++) {
      if (Tanks[i]->GetPctFull() < 99.99)
          Transfer(-1, i, fillrate/TanksNotFull);
    }
  }
}
Beispiel #19
0
void FGPropulsion::DumpFuel(double time_slice)
{
  unsigned int i;
  int TanksDumping = 0;

  for (i=0; i<numTanks; i++) {
    if (Tanks[i]->GetContents() > Tanks[i]->GetStandpipe()) ++TanksDumping;
  }

  if (TanksDumping == 0) return;

  double dump_rate_per_tank = DumpRate / 60.0 * time_slice / TanksDumping;

  for (i=0; i<numTanks; i++) {
    if (Tanks[i]->GetContents() > Tanks[i]->GetStandpipe()) {
      Transfer(i, -1, dump_rate_per_tank);
    }
  }
}
Beispiel #20
0
void FGPropulsion::DoRefuel(double time_slice)
{
  unsigned int i;

  double fillrate = RefuelRate / 60.0 * time_slice;   
  int TanksNotFull = 0;

  for (i=0; i<numTanks; i++) {
    if (Tanks[i]->GetPctFull() < 99.99) ++TanksNotFull;
  }

  // adds fuel equally to all tanks that are not full
  if (TanksNotFull) {
    for (i=0; i<numTanks; i++) {
      if (Tanks[i]->GetPctFull() < 99.99)
          Transfer(-1, i, fillrate/TanksNotFull);
    }
  }
}
Beispiel #21
0
int main(int argc, char *argv[])
{
    initConnection();
    for(;;)
    {
        char message[BUFFER_SIZE];
        FILE *fp = NULL;
        int req_num = 0;
        req_num = WaitShakeHands(message, &fp);
        // req_num 对应请求的dataID:1表示下载,2表示显示目录,3表示上传。若req_num<0,则无须后续传输。
        if ( req_num==1 )
        {
            Packet req;
            Recvfrom(server_socket, (char *)&req, sizeof(Packet),0, (struct sockaddr *)&client_addr, &clen);
            if ( req.dataID == 0 && req.flag ==-1)
                Transfer(server_socket, client_addr,&fp);
        }
        else if (req_num == 2)
        {
            Packet req;
            Recvfrom(server_socket, (char *)&req, sizeof(Packet),0, (struct sockaddr *)&client_addr, &clen);
            if ( req.dataID == 0 && req.flag ==-1)
                Show_dir(server_socket, client_addr);
        }
        else if (req_num == 3)
        {
            char file_name[BUFFER_SIZE],md5sum[33]={'\0'};
            int filesize;
            sscanf(message,"%s\t%d\t%s",file_name,&filesize,md5sum);
            fp = fopen(file_name, "wb");
            if (NULL == fp){
                printf("File:\t %s can not open to write.\n",file_name);exit(1);}
            printf("Begin Recvfile.\n");
            FileReceive(server_socket, client_addr,&fp);
            fclose(fp);
        }
        printf("Finished.\n");
    }
    return 0;
}
Beispiel #22
0
/**
 * Blends the alpha channel and the alpha palette with the pixels. The result is a 24 bit image.
 * The background color can be selected using SetTransColor().
 */
void CxImage::AlphaStrip()
{
	bool bAlphaPaletteIsValid = AlphaPaletteIsValid();
	bool bAlphaIsValid = AlphaIsValid();
	if (!(bAlphaIsValid || bAlphaPaletteIsValid)) return;
	RGBQUAD c;
	long a, a1;
	if (head.biBitCount==24){
		for(long y=0; y<head.biHeight; y++){
			for(long x=0; x<head.biWidth; x++){
				c=GetPixelColor(x,y);
				if (bAlphaIsValid) a=(AlphaGet(x,y)*info.nAlphaMax)/255; else a=info.nAlphaMax;
				a1 = 255-a;
				c.rgbBlue = (BYTE)((c.rgbBlue * a + a1 * info.nBkgndColor.rgbBlue)/255);
				c.rgbGreen = (BYTE)((c.rgbGreen * a + a1 * info.nBkgndColor.rgbGreen)/255);
				c.rgbRed = (BYTE)((c.rgbRed * a + a1 * info.nBkgndColor.rgbRed)/255);
				SetPixelColor(x,y,c);
			}
		}
		AlphaDelete();
	} else {
		CxImage tmp(head.biWidth,head.biHeight,24);
		if (!tmp.IsValid()) return;
		for(long y=0; y<head.biHeight; y++){
			for(long x=0; x<head.biWidth; x++){
				c=GetPixelColor(x,y);
				if (bAlphaIsValid) a=(AlphaGet(x,y)*info.nAlphaMax)/255; else a=info.nAlphaMax;
				if (bAlphaPaletteIsValid) a=(c.rgbReserved*a)/255;
				a1 = 255-a;
				c.rgbBlue = (BYTE)((c.rgbBlue * a + a1 * info.nBkgndColor.rgbBlue)/255);
				c.rgbGreen = (BYTE)((c.rgbGreen * a + a1 * info.nBkgndColor.rgbGreen)/255);
				c.rgbRed = (BYTE)((c.rgbRed * a + a1 * info.nBkgndColor.rgbRed)/255);
				tmp.SetPixelColor(x,y,c);
			}
		}
		Transfer(tmp);
	}
	return;
}
Beispiel #23
0
// エントリーポイント
int main(int ac, char **av)
{
    int sts = -1;
    char szDevicePath[256];
    HANDLE hDevice = INVALID_HANDLE_VALUE;
    BOOL doDisplay = FALSE;
    DWORD dwError;

    // 引数無しなら受信モード
    if (ac < 2) {
        doDisplay = TRUE;
    }
    // USB IR REMOCON のデバイスパスを得る
    dwError = GetDevicePath(szDevicePath, sizeof(szDevicePath));
    if (dwError != ERROR_SUCCESS) {
        fprintf(stderr, "failed to get device path: err=%u", dwError);
        goto DONE;
    }
    // データ送受信用にデバイスをオープン
    hDevice = CreateFile(szDevicePath, GENERIC_WRITE|GENERIC_READ,
            FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    if (hDevice == INVALID_HANDLE_VALUE) {
        DWORD err = GetLastError();
        fprintf(stderr, "CreateFile: err=%u\n", err);
        goto DONE;
    }
    if (doDisplay) {
        sts = Display(hDevice); // 受信モードへ
    } else {
        sts = Transfer(hDevice, ac, av); // 送信モードへ
    }

DONE:
    if (hDevice != INVALID_HANDLE_VALUE) {
        CloseHandle(hDevice);
    }
    return sts;
}
Beispiel #24
0
int CSIDevice_GBA::RunBuffer(u8* _pBuffer, int _iLength)
{
	Transfer((char*)_pBuffer);
	return _iLength;
}
Beispiel #25
0
uint8_t NEO_TransferPixels(void) {
  return Transfer((uint32_t)&transmitBuf[0], sizeof(transmitBuf));
}
bool CBPersistMgr::TransferValue(bool* Value)
{
	return SUCCEEDED(Transfer("", Value));
}
Beispiel #27
0
//--------------------------------------------------------------------------------------------------

void MaschineMK1::setKeyLed(unsigned index_, const Color& color_)
{
  setLedImpl(led(index_), color_);
}

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

void MaschineMK1::sendMidiMsg(tRawData midiMsg_)
{
  uint8_t lengthH = (midiMsg_.size() >> 8) & 0xFF;
  uint8_t lengthL = midiMsg_.size() & 0xFF;
  writeToDeviceHandle(
    Transfer({0x07, lengthH, lengthL}, midiMsg_.data(), midiMsg_.size()), kMASMK1_epOut);
}

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

Canvas* MaschineMK1::graphicDisplay(size_t displayIndex_)
{
  static NullCanvas s_dummyDisplay;
  if (displayIndex_ > 1)
  {
    return &s_dummyDisplay;
  }

  return &m_displays[displayIndex_];
}
bool CBPersistMgr::TransferValue(unsigned char* Value)
{
	return SUCCEEDED(Transfer("", Value));
}
Beispiel #29
0
/**
 * Loads an image from CxFile object
 * \param hFile: file handle (CxMemFile or CxIOFile), with read access.
 * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS
 * \return true if everything is ok
 * \sa ENUM_CXIMAGE_FORMATS
 */
bool CxImage::Decode(CxFile *hFile, uint32_t imagetype)
{
	if (hFile == NULL){
		strcpy(info.szLastError,CXIMAGE_ERR_NOFILE);
		return false;
	}

	uint32_t pos = hFile->Tell();

#if CXIMAGE_SUPPORT_BMP
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_BMP==imagetype){
		CxImageBMP *newima = new CxImageBMP;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_JPG
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_JPG==imagetype){
		CxImageJPG *newima = new CxImageJPG;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_ICO
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_ICO==imagetype){
		CxImageICO *newima = new CxImageICO;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			info.nNumFrames = newima->info.nNumFrames;
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_GIF
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_GIF==imagetype){
		CxImageGIF *newima = new CxImageGIF;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			info.nNumFrames = newima->info.nNumFrames;
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_PNG
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_PNG==imagetype){
		CxImagePNG *newima = new CxImagePNG;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_TIF
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_TIF==imagetype){
		CxImageTIF *newima = new CxImageTIF;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			info.nNumFrames = newima->info.nNumFrames;
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_MNG
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_MNG==imagetype){
		CxImageMNG *newima = new CxImageMNG;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			info.nNumFrames = newima->info.nNumFrames;
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_TGA
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_TGA==imagetype){
		CxImageTGA *newima = new CxImageTGA;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_PCX
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_PCX==imagetype){
		CxImagePCX *newima = new CxImagePCX;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_WBMP
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_WBMP==imagetype){
		CxImageWBMP *newima = new CxImageWBMP;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_WMF && CXIMAGE_SUPPORT_WINDOWS
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_WMF==imagetype){
		CxImageWMF *newima = new CxImageWMF;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_JBG
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_JBG==imagetype){
		CxImageJBG *newima = new CxImageJBG;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_JASPER
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype ||
#if	CXIMAGE_SUPPORT_JP2
	 CXIMAGE_FORMAT_JP2==imagetype ||
#endif
#if	CXIMAGE_SUPPORT_JPC
	 CXIMAGE_FORMAT_JPC==imagetype ||
#endif
#if	CXIMAGE_SUPPORT_PGX
	 CXIMAGE_FORMAT_PGX==imagetype ||
#endif
#if	CXIMAGE_SUPPORT_PNM
	 CXIMAGE_FORMAT_PNM==imagetype ||
#endif
#if	CXIMAGE_SUPPORT_RAS
	 CXIMAGE_FORMAT_RAS==imagetype ||
#endif
	 false ){
		CxImageJAS *newima = new CxImageJAS;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_SKA
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_SKA==imagetype){
		CxImageSKA *newima = new CxImageSKA;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_RAW
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_RAW==imagetype){
		CxImageRAW *newima = new CxImageRAW;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif
#if CXIMAGE_SUPPORT_PSD
	if (CXIMAGE_FORMAT_UNKNOWN==imagetype || CXIMAGE_FORMAT_PSD==imagetype){
		CxImagePSD *newima = new CxImagePSD;
		if (!newima)
			return false;
		newima->CopyInfo(*this);
		if (newima->Decode(hFile)) {
			Transfer(*newima);
			delete newima;
			return true;
		} else {
			strcpy(info.szLastError,newima->GetLastError());
			hFile->Seek(pos,SEEK_SET);
			delete newima;
			if (CXIMAGE_FORMAT_UNKNOWN!=imagetype)
				return false;
		}
	}
#endif

	strcpy(info.szLastError,"Decode: Unknown or wrong format");
	return false;
}
Beispiel #30
0
bool CxImageICO::Decode(CxFile *hFile)
{
	if (hFile==NULL) return false;

	DWORD off = hFile->Tell(); //<yuandi>
	int	page=info.nFrame;	//internal icon structure indexes

	// read the first part of the header
	ICONHEADER icon_header;
	hFile->Read(&icon_header,sizeof(ICONHEADER),1);

	icon_header.idType = my_ntohs(icon_header.idType);
	icon_header.idCount = my_ntohs(icon_header.idCount);

	// check if it's an icon or a cursor
	if ((icon_header.idReserved == 0) && ((icon_header.idType == 1)||(icon_header.idType == 2))) {

		info.nNumFrames = icon_header.idCount;

		// load the icon descriptions
		ICONDIRENTRY *icon_list = (ICONDIRENTRY *)malloc(icon_header.idCount * sizeof(ICONDIRENTRY));
		int c;
		for (c = 0; c < icon_header.idCount; c++) {
			hFile->Read(icon_list + c, sizeof(ICONDIRENTRY), 1);

			icon_list[c].wPlanes = my_ntohs(icon_list[c].wPlanes);
			icon_list[c].wBitCount = my_ntohs(icon_list[c].wBitCount);
			icon_list[c].dwBytesInRes = my_ntohl(icon_list[c].dwBytesInRes);
			icon_list[c].dwImageOffset = my_ntohl(icon_list[c].dwImageOffset);
		}
		
		if ((page>=0)&&(page<icon_header.idCount)){

			if (info.nEscape == -1) {
				// Return output dimensions only
				head.biWidth = icon_list[page].bWidth;
				head.biHeight = icon_list[page].bHeight;
#if CXIMAGE_SUPPORT_PNG
				if (head.biWidth==0 && head.biHeight==0)
				{	// Vista icon support
					hFile->Seek(off + icon_list[page].dwImageOffset, SEEK_SET);
					CxImage png;
					png.SetEscape(-1);
					if (png.Decode(hFile,CXIMAGE_FORMAT_PNG)){
						Transfer(png);
						info.nNumFrames = icon_header.idCount;
					}
				}
#endif //CXIMAGE_SUPPORT_PNG
				free(icon_list);
				info.dwType = CXIMAGE_FORMAT_ICO;
				return true;
			}

			// get the bit count for the colors in the icon <CoreyRLucier>
			BITMAPINFOHEADER bih;
			hFile->Seek(off + icon_list[page].dwImageOffset, SEEK_SET);

			if (icon_list[page].bWidth==0 && icon_list[page].bHeight==0)
			{	// Vista icon support
#if CXIMAGE_SUPPORT_PNG
				CxImage png;
				if (png.Decode(hFile,CXIMAGE_FORMAT_PNG)){
					Transfer(png);
					info.nNumFrames = icon_header.idCount;
				}
				SetType(CXIMAGE_FORMAT_ICO);
#endif //CXIMAGE_SUPPORT_PNG
			}
			else
			{	// standard icon
				hFile->Read(&bih,sizeof(BITMAPINFOHEADER),1);

				bihtoh(&bih);

				c = bih.biBitCount;

				// allocate memory for one icon
				Create(icon_list[page].bWidth,icon_list[page].bHeight, c, CXIMAGE_FORMAT_ICO);	//image creation

				// read the palette
				RGBQUAD pal[256];
				if (bih.biClrUsed)
					hFile->Read(pal,bih.biClrUsed*sizeof(RGBQUAD), 1);
				else
					hFile->Read(pal,head.biClrUsed*sizeof(RGBQUAD), 1);

				SetPalette(pal,head.biClrUsed);	//palette assign

				//read the icon
				if (c<=24){
					hFile->Read(info.pImage, head.biSizeImage, 1);
				} else { // 32 bit icon
					BYTE* buf=(BYTE*)malloc(4*head.biHeight*head.biWidth);
					BYTE* src = buf;
					hFile->Read(buf, 4*head.biHeight*head.biWidth, 1);
#if CXIMAGE_SUPPORT_ALPHA
					if (!AlphaIsValid()) AlphaCreate();
#endif //CXIMAGE_SUPPORT_ALPHA
					for (long y = 0; y < head.biHeight; y++) {
						BYTE* dst = GetBits(y);
						for(long x=0;x<head.biWidth;x++){
							*dst++=src[0];
							*dst++=src[1];
							*dst++=src[2];
#if CXIMAGE_SUPPORT_ALPHA
							AlphaSet(x,y,src[3]);
#endif //CXIMAGE_SUPPORT_ALPHA
							src+=4;
						}
					}
					free(buf);
				}
				// apply the AND and XOR masks
				int maskwdt = ((head.biWidth+31) / 32) * 4;	//line width of AND mask (always 1 Bpp)
				int masksize = head.biHeight * maskwdt;				//size of mask
				BYTE *mask = (BYTE *)malloc(masksize);
				if (hFile->Read(mask, masksize, 1)){

					bool bGoodMask=false;
					for (int im=0;im<masksize;im++){
						if (mask[im]!=255){
							bGoodMask=true;
							break;
						}
					}

					if (bGoodMask && c != 32){
#if CXIMAGE_SUPPORT_ALPHA
						bool bNeedAlpha = false;
						if (!AlphaIsValid()){
							AlphaCreate();
						} else { 
							bNeedAlpha=true; //32bit icon
						}
						int x,y;
						for (y = 0; y < head.biHeight; y++) {
							for (x = 0; x < head.biWidth; x++) {
								if (((mask[y*maskwdt+(x>>3)]>>(7-x%8))&0x01)){
									AlphaSet(x,y,0);
									bNeedAlpha=true;
								}
							}
						}
						if (!bNeedAlpha) AlphaDelete();
#endif //CXIMAGE_SUPPORT_ALPHA

						//check if there is only one transparent color
						RGBQUAD cc,ct;
						long* pcc = (long*)&cc;
						long* pct = (long*)&ct;
						int nTransColors=0;
						int nTransIndex=0;
						for (y = 0; y < head.biHeight; y++){
							for (x = 0; x < head.biWidth; x++){
								if (((mask[y*maskwdt+(x>>3)] >> (7-x%8)) & 0x01)){
									cc = GetPixelColor(x,y,false);
									if (nTransColors==0){
										nTransIndex = GetPixelIndex(x,y);
										nTransColors++;
										ct = cc;
									} else {
										if (*pct!=*pcc){
											nTransColors++;
										}
									}
								}
							}
						}
						if (nTransColors==1){
							SetTransColor(ct);
							SetTransIndex(nTransIndex);
#if CXIMAGE_SUPPORT_ALPHA
							AlphaDelete(); //because we have a unique transparent color in the image
#endif //CXIMAGE_SUPPORT_ALPHA
						}

						// <vho> - Transparency support w/o Alpha support
						if (c <= 8){ // only for icons with less than 256 colors (XP icons need alpha).
							  
							// find a color index, which is not used in the image
							// it is almost sure to find one, bcs. nobody uses all possible colors for an icon

							BYTE colorsUsed[256];
							memset(colorsUsed, 0, sizeof(colorsUsed));

							for (y = 0; y < head.biHeight; y++){
								for (x = 0; x < head.biWidth; x++){
									colorsUsed[BlindGetPixelIndex(x,y)] = 1;
								}
							}

							int iTransIdx = -1;
							for (x = (int)(head.biClrUsed-1); x>=0 ; x--){
								if (colorsUsed[x] == 0){
									iTransIdx = x; // this one is not in use. we may use it as transparent color
									break;
								}
							}

							// Go thru image and set unused color as transparent index if needed
							if (iTransIdx >= 0){
								bool bNeedTrans = false;
								for (y = 0; y < head.biHeight; y++){
									for (x = 0; x < head.biWidth; x++){
										// AND mask (Each Byte represents 8 Pixels)
										if (((mask[y*maskwdt+(x>>3)] >> (7-x%8)) & 0x01)){
											// AND mask is set (!=0). This is a transparent part
											SetPixelIndex(x, y, (BYTE)iTransIdx);
											bNeedTrans = true;
										}
									}
								}
								// set transparent index if needed
								if (bNeedTrans)	SetTransIndex(iTransIdx);
#if CXIMAGE_SUPPORT_ALPHA
								AlphaDelete(); //because we have a transparent color in the palette
#endif //CXIMAGE_SUPPORT_ALPHA
							}
						}
					} else if(c != 32){