Exemplo n.º 1
0
void LootMgr::LoadLootProp(uint32 id)
{    
    //std::stringstream ss;
    //ss << "SELECT * FROM lootrandomprop WHERE entryid=" << id << " ORDER BY percentchance DESC";
    //QueryResult *result = sDatabase.Query( ss.str().c_str() );
    QueryResult * result = sDatabase.Query("SELECT * FROM lootrandomprop ORDER BY entryid");
    if(!result)return;

    Field *fields = result->Fetch();
    map<uint32, vector< pair< uint32, float > > > propcache;
    map<uint32, vector< pair< uint32, float > > >::iterator itr;
    uint32 i = 0;
    uint32 m = result->GetRowCount();
    do 
    {
        propcache[fields[0].GetUInt32()].push_back( make_pair( fields[1].GetUInt32(), fields[2].GetFloat() ) );
        ++i;
        if(!(i % 100))
            SetProgressBar(i, m, "random props");
    } while(result->NextRow());
    delete result;

    i = 0;
    m = propcache.size();

    for(itr = propcache.begin(); itr != propcache.end(); ++itr)
    {
        LootPropTable * prop = new LootPropTable;
        prop->iPropsCount = itr->second.size();
        prop->pProps = new LootProp[prop->iPropsCount];
        vector< pair<uint32, float> >::iterator it2 = itr->second.begin();
        uint32 j = 0;
        for(; it2 != itr->second.end(); ++it2, ++j)
        {
            prop->pProps[j].chance = it2->second;
            prop->pProps[j].prop = it2->first;
        }
        LootProperties[itr->first] = prop;
        ++i;
        if(!(i % 10))
            SetProgressBar(i, m, "random props");
    }

    ClearProgressBar();

    
    /*LootPropTable * prop=new LootPropTable;
    prop->iPropsCount =result->GetRowCount();
    prop->pProps=new LootProp[prop->iPropsCount];
    uint32 ind=0;
    do
    {
        fields = result->Fetch();
        prop->pProps[ind].prop =fields[1].GetUInt32();
        prop->pProps[ind].chance =fields[2].GetUInt32();
    } while (result->NextRow());
    delete result;
    LootProperties[id]=prop;*/
}
Exemplo n.º 2
0
void WeatherMgr::LoadFromDB()
{
    QueryResult *result = sDatabase.Query( "SELECT * FROM weather" );

    if( !result )
    {
        sLog.outString("  Query failed.");
        return;
    }
    uint32 total =(uint32) result->GetRowCount();
    int num = 0;

    do
    {
        Field *fields = result->Fetch();
        WeatherInfo *wi = new WeatherInfo;
        wi->m_zoneId = fields[0].GetUInt32();
        wi->m_effectValues[0] = fields[1].GetUInt32();
        wi->m_effectValues[1] = fields[2].GetUInt32();
        wi->m_effectValues[2] = fields[3].GetUInt32();
        wi->m_effectValues[3] = fields[4].GetUInt32();
        wi->m_effectValues[4] = fields[5].GetUInt32();

        m_zoneWeathers[wi->m_zoneId] = wi;

        wi->_GenerateWeather();
        ++num;
        if(!(num % 15)) SetProgressBar(num, total, "Zone Weather");
    } while( result->NextRow() );

    delete result;
    ClearProgressBar();
}
Exemplo n.º 3
0
void PrintSize(){
	double comp = 0;
	while (1){
		comp = GetSize();
		SetProgressBar(comp);
		sleep(1);
	}
}
Exemplo n.º 4
0
void CProgressJob::SetProgressIndicators(CGUIDialogProgressBarHandle* progressBar, CGUIDialogProgress* progressDialog, bool updateProgress /* = true */, bool updateInformation /* = true */)
{
  SetProgressBar(progressBar);
  SetProgressDialog(progressDialog);
  SetUpdateProgress(updateProgress);
  SetUpdateInformation(updateInformation);

  // disable auto-closing
  SetAutoClose(false);
}
Exemplo n.º 5
0
void ProcessingProgressDlg::NextPhoto(int photo, bool after)
{
	if (photo >= 0)
	{
		if (after)
			++current_photo_;
	}
	else if (photo < 0)		// thread finished or interrupted?
	{
		threads_done_--;

		if (threads_done_ <= 0)	// all done?
		{
			progress_wnd_.ShowWindow(SW_HIDE);
			time_left_.SetWindowText(L"--:--:--");
			photo_wnd_.SetWindowText(RString(IDS_RESIZE_ALL_PROCESSED));
			//SetDlgItemText(IDC_OPERATION, RString(IDS_RESIZE_COMPLETED));
			GetDlgItem(IDCANCEL)->SetDlgCtrlID(IDOK);
			GetDlgItem(IDC_LABEL_1)->ShowWindow(SW_HIDE);

			if (slide_show_)
				EnableSlideShowBtn();
			else if (auto_close_)
				PostMessage(WM_COMMAND, IDOK);
			else
				SetDlgItemText(IDOK, L"OK");

			return;
		}
	}

	if (current_photo_ >= 0 && current_photo_ < file_count_)
	{
		SetProgressBar(current_photo_, 0);

		CString photo;
		photo.Format(_T("%d of %d"), static_cast<int>(current_photo_ + 1), static_cast<int>(file_count_));
		photo_wnd_.SetWindowText(photo);

		if (current_photo_ >= pool_.ThreadCount())
		{
			DWORD tick= ::GetTickCount();
			if (tick - last_update_ >= 500)	// refresh every 0.5 s at most
			{
				CString time= est_time_left_.TimeLeft(current_photo_, file_count_);
				time_left_.SetWindowText(time);
				last_update_ = tick;
			}
		}
	}
}
Exemplo n.º 6
0
void World::LoadAreaTriggerInformation()
{
    QueryResult *result = NULL;
//    uint32 MaxID = 0;
    AreaTrigger *pAT = NULL;

    result = sDatabase.Query("SELECT * FROM areatriggers");

    if(result==NULL)
    {
        sLog.outString("  Query failed.");
        return;
    }
    uint32 total =(uint32) result->GetRowCount();
    int num = 0;

    do
    {
        Field *fields = result->Fetch();
        pAT = new AreaTrigger;

        pAT->AreaTriggerID = fields[0].GetUInt32();
        pAT->Type = (uint8)fields[1].GetUInt32();
        pAT->Mapid = fields[2].GetUInt32();
        pAT->PendingScreen = fields[3].GetUInt32();
        pAT->Name= fields[4].GetString();
        pAT->x = fields[5].GetFloat();
        pAT->y = fields[6].GetFloat();
        pAT->z = fields[7].GetFloat();
        pAT->o = fields[8].GetFloat();
        if(result->GetFieldCount() > 9) // bur: crash fix for lazy bastards who dont update their db >.>
        {
            pAT->required_honor_rank = fields[9].GetUInt32();
            pAT->required_level = fields[10].GetUInt32();
        }

        AddAreaTrigger(pAT);
        ++num;
        if(!(num % 10)) SetProgressBar(num, total, "Area Triggers");
    } while( result->NextRow() );
    delete result;
    ClearProgressBar();
}
Exemplo n.º 7
0
BOOL ProcessingProgressDlg::OnInitDialog()
{
	try
	{
		RDialog::OnInitDialog();

		if (output_only_)
		{
			// input photo is the output; hide 'output' fields
			//img_output_wnd_.ShowWindow(SW_HIDE);
			//img_output_wnd_.ShowWindow(SW_HIDE);
			//output_wnd_.ShowWindow(SW_HIDE);
			//if (CWnd* wnd= GetDlgItem(IDC_LABEL_2))
			//	wnd->ShowWindow(SW_HIDE);
		}

//	if (slide_show_)
//		SetWindowText(_T("Slide Show Generation Progress"));

		SetWindowText(title_);
		if (!operation_.IsEmpty())
			SetDlgItemText(IDC_LABEL_1, operation_);

		progress_wnd_.SetRange32(0, static_cast<int>(file_count_ * 100));

		est_time_left_.Start();
		last_update_ = ::GetTickCount();
		time_left_.SetWindowText(L"Calculating...");
		SetProgressBar(0, 0);

		photo_wnd_.SetWindowText(L"-");

		pool_.Start();

		return true;
	}
	CATCH_ALL

	// exception captured; close progress dlg
	EndDialog(IDCANCEL);

	return TRUE;
}
void __cdecl WorkerThread(void *unused)
{
	int task,ret,firstTime;
	ts=time(NULL);

	AddToStatus(STATUS_MESSAGE,TranslateT("Database worker thread activated"));
	SetFilePointer(opts.hFile,0,NULL,FILE_BEGIN);
	spaceUsed=1; spaceProcessed=0; sp=0;
	firstTime=0;

	for(task=0;;) {
		if (spaceProcessed/(spaceUsed/1000+1) > sp) {
			sp = spaceProcessed/(spaceUsed/1000+1);
			SetProgressBar(sp);
		}
		WaitForSingleObject(hEventRun,INFINITE);
		if(WaitForSingleObject(hEventAbort,0)==WAIT_OBJECT_0) {
			AddToStatus(STATUS_FATAL,TranslateT("Processing aborted by user"));
			break;
		}
		ret=Workers[task](firstTime);
		firstTime=0;
		if(ret==ERROR_NO_MORE_ITEMS) {
			if(++task==sizeof(Workers)/sizeof(Workers[0])) {
				AddToStatus(STATUS_MESSAGE,TranslateT("Elapsed time: %d sec"), time(NULL)-ts);
				if(errorCount) 
					AddToStatus(STATUS_SUCCESS,TranslateT("All tasks completed but with errors (%d)"),errorCount);
				else 
					AddToStatus(STATUS_SUCCESS,TranslateT("All tasks completed successfully"));
				break;
			}
			firstTime=1;
		}
		else if(ret!=ERROR_SUCCESS)
			break;
	}
	ProcessingDone();
}
Exemplo n.º 9
0
//PS2メモリーカードから読み込む。
BOOL ReadFromCard()
{
	BOOL res = TRUE;
	int r;
	int pagesize, blocksize, cardsize, cardflags;

	r = usbd_attach_device(0, 0);
	r = mcio_init();

	r = mcio_mcGetInfo(&pagesize, &blocksize, &cardsize, &cardflags);

	if (!r)
	{
		int pages = cardsize / pagesize;
		int eccsize = pagesize >> 5;
		//プログレスバー更新
		SetProgressBar(pages);

		//8MB以上だったら読まない
		if ((pages*(pagesize + eccsize)) > sizeof(byteMemDat))
		{
			res = FALSE;
			TCHAR strBuf[128];
			if (LoadString(hInst, IDS_NOTSUPPORTOVER8MB, strBuf, sizeof(strBuf) / sizeof(strBuf[0])))
			{
				MessageBox(NULL, strBuf, szTitle, MB_OK);
			}
		}
		else
		{
			for (int i = 0; i < pages; i++)
			{
				byte *pagebuf = &(byteMemDat.Byte[i * (pagesize + eccsize)]);
				byte *eccbuf = pagebuf + pagesize;

				int r = mcio_mcReadPageWithEcc(i, pagebuf, eccbuf);
				if (r)
				{
					res = FALSE;
					TCHAR strBuf[128];
					if (LoadString(hInst, IDS_ERROR_READPAGE, strBuf, sizeof(strBuf) / sizeof(strBuf[0])))
					{
						TCHAR strBuf2[128];
						_stprintf_s(strBuf2, sizeof(strBuf2) / sizeof(strBuf2[0]), strBuf, i);
						MessageBox(NULL, strBuf, szTitle, MB_OK);
					}
					break;
				}
				ProgressBar_Step();
			}

			UpdateDataList(&byteMemDat);
			if (res)
			{
				TCHAR strBuf[128];
				if (LoadString(hInst, IDS_READ_FINISH, strBuf, sizeof(strBuf) / sizeof(strBuf[0])))
				{
					MessageBox(NULL, strBuf, szTitle, MB_OK);
				}
			}
		}
	}
Exemplo n.º 10
0
void LootMgr::LoadLootTables(const char * szTableName,LootStore * LootTable)
{
    DBCFile *dbc = new DBCFile();

    dbc->open("DBC/ItemRandomProperties.dbc");
    _propCount = dbc->getRecordCount();
    delete dbc;
    //HM_NAMESPACE::hash_map<uint32, std::vector<loot_tb> > loot_db;
    //HM_NAMESPACE::hash_map<uint32, std::vector<loot_tb> >::iterator itr;
    vector< pair< uint32, vector< pair<uint32, float> > > > db_cache;
    vector< pair< uint32, vector< pair<uint32, float> > > >::iterator itr;
    db_cache.reserve(10000);
    LootStore::iterator tab;

    printf("Waiting on SQL...\r");
    QueryResult *result =sDatabase.Query("SELECT entryid, itemid, percentchance FROM %s ORDER BY entryid ASC",szTableName);
    if(!result)
    {
        sLog.outError("\rWARNING: Loading loot from table %s failed.", szTableName);
        return;
    }
    uint32 entry_id = 0;
    uint32 last_entry = 0;

    uint32 total =(uint32) result->GetRowCount();
    int pos = 0;
    vector< pair<uint32, float> > ttab;
    do 
    {     
        Field *fields = result->Fetch();
        entry_id = fields[0].GetUInt32();
        if(entry_id < last_entry)
        {
            sLog.outError("WARNING: Out of order loot table being loaded.\n");
            return;
        }
        if(entry_id != last_entry)
        {
            if(last_entry != 0)
                db_cache.push_back( make_pair( last_entry, ttab) );
            ttab.clear();
        }

        ttab.push_back( make_pair(fields[1].GetUInt32(), fields[2].GetFloat()) );
        

        /*loot_tb t;           
        t.itemid = fields[1].GetUInt32();
        t.chance = fields[2].GetFloat();
        loot_db[fields[0].GetUInt32()].push_back(t);*/

        last_entry = entry_id;
        ++pos;
        if(!(pos % 10000))
            SetProgressBar(pos, total, szTableName);
    } while( result->NextRow() );
    ClearProgressBar();
    pos = 0;
    total = db_cache.size();
    ItemPrototype* proto;
    uint32 itemid;

    //for(itr=loot_db.begin();itr!=loot_db.end();++itr)
    for( itr = db_cache.begin(); itr != db_cache.end(); ++itr)
    {
        entry_id = (*itr).first;
        if(LootTable->end()==LootTable->find(entry_id))
        {
            StoreLootList list;
            //list.count = itr->second.size();            
            list.count = (*itr).second.size();
            list.items=new StoreLootItem[list.count];
        
            uint32 ind=0;
            //for(std::vector<loot_tb>::iterator itr2=itr->second.begin();itr2!=itr->second.end();++itr2)
            for(vector< pair<uint32, float> >::iterator itr2 = (*itr).second.begin(); itr2 != (*itr).second.end(); ++itr2)
            {
                //Omit items that are not in db to prevent future bugs
                //uint32 itemid=(*itr2).itemid;
                itemid = (*itr2).first;
                proto=objmgr.GetItemPrototype(itemid);
                if(!proto)
                {
                    list.items[ind].item.itemid=0;
                    //sLog.outDetail("WARNING: Loot %u contains item %u that does not exist in the DB.",entry_id,(*itr2).itemid);
                }
                else
                {
                    list.items[ind].item.itemid=itemid;
                    list.items[ind].item.displayid=proto->DisplayInfoID;
                    //list.items[ind].chance=(*itr2).chance;
                    list.items[ind].chance=(*itr2).second;

                    PropStore::iterator ptab =LootProperties.find(itemid);
                
                    if( LootProperties.end()==ptab)
                        list.items[ind].prop=NULL;
                    else
                        list.items[ind].prop=ptab->second;

                    if(LootTable == &GOLoot)
                    {
                        if(proto->Class == ITEM_CLASS_QUEST)
                        {
                            //printf("Quest item \"%s\" allocated to quest ", proto->Name1.c_str());
                            sQuestMgr.SetGameObjectLootQuest(itr->first, itemid);
							quest_loot_go[entry_id].insert(proto->ItemId);
                        }
                    }
                }
                ind++;
            }
            (*LootTable)[entry_id]=list;
        }
        ++pos;
        if(!(pos % 1000)) SetProgressBar(pos, total, szTableName);
    }

    ClearProgressBar();
    //sLog.outString("  %d loot templates loaded from %s", db_cache.size(), szTableName);
 //   loot_db.clear();
    delete result;
}
Exemplo n.º 11
0
static	void
UpdateWidget(WidgetData *data)
{
	GtkWidget	*widget;

	g_return_if_fail(data != NULL);
	widget = GetWidgetByLongName(data->name);
	if (widget == NULL) {
		MessagePrintf("widget [%s] is not found", data->name);
		return;
	}

	switch (data->type) {
// gtk+panda
	case WIDGET_TYPE_NUMBER_ENTRY:
		SetNumberEntry(widget, data,(_NumberEntry *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_COMBO:
		SetPandaCombo(widget, data,(_Combo *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_CLIST:
		SetPandaCList(widget, data,(_CList *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_ENTRY:
		SetEntry(widget, data,(_Entry *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_TEXT:
		SetText(widget, data,(_Text *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_PREVIEW:
		SetPandaPreview(widget, data,(_PREVIEW *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_TIMER:
		SetPandaTimer(widget, data,(_Timer *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_DOWNLOAD:
		SetPandaDownload(widget, data,(_Download *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_HTML:
		SetPandaHTML(widget, data,(_HTML *)data->attrs);
		break;
	case WIDGET_TYPE_PANDA_TABLE:
		SetPandaTable(widget, data,(_Table *)data->attrs);
		break;
// gtk+
	case WIDGET_TYPE_ENTRY:
		SetEntry(widget, data,(_Entry *)data->attrs);
		break;
	case WIDGET_TYPE_TEXT:
		SetText(widget, data,(_Text *)data->attrs);
		break;
	case WIDGET_TYPE_LABEL:
		SetLabel(widget, data,(_Label *)data->attrs);
		break;
	case WIDGET_TYPE_BUTTON:
	case WIDGET_TYPE_TOGGLE_BUTTON:
	case WIDGET_TYPE_CHECK_BUTTON:
	case WIDGET_TYPE_RADIO_BUTTON:
		SetButton(widget, data,(_Button *)data->attrs);
		break;
	case WIDGET_TYPE_CALENDAR:
		SetCalendar(widget, data,(_Calendar*)data->attrs);
		break;
	case WIDGET_TYPE_NOTEBOOK:
		SetNotebook(widget, data,(_Notebook*)data->attrs);
		break;
	case WIDGET_TYPE_PROGRESS_BAR:
		SetProgressBar(widget, data,(_ProgressBar*)data->attrs);
		break;
	case WIDGET_TYPE_WINDOW:
		SetWindow(widget, data,(_Window*)data->attrs);
		break;
	case WIDGET_TYPE_FRAME:
		SetFrame(widget, data,(_Frame *)data->attrs);
		break;
	case WIDGET_TYPE_SCROLLED_WINDOW:
		SetScrolledWindow(widget, data,(_ScrolledWindow *)data->attrs);
		break;
	case WIDGET_TYPE_FILE_CHOOSER_BUTTON:
		SetFileChooserButton(widget, data,(_FileChooserButton *)data->attrs);
		break;
	case WIDGET_TYPE_COLOR_BUTTON:
		SetColorButton(widget, data,(_ColorButton *)data->attrs);
		break;
// Gnome
	case WIDGET_TYPE_FILE_ENTRY:
		SetFileEntry(widget, data,(_FileEntry *)data->attrs);
		break;
	case WIDGET_TYPE_PIXMAP:
		SetPixmap(widget, data,(_Pixmap *)data->attrs);
		break;
	default:
		//MessageLogPrintf("invalid widget [%s]", data->name);
		break;
	}
}
Exemplo n.º 12
0
Comm::ErrorCode Comm::GetData(unsigned long address, unsigned char bytesPerPacket,
                              unsigned char bytesPerAddress, unsigned char bytesPerWord,
                              unsigned long endAddress, unsigned char *pData)
{
    ReadPacket readPacket;
    WritePacket writePacket;
    ErrorCode result;
    unsigned int percentCompletion;
    unsigned int addressesToFetch = endAddress - address;

    //Error check input parameters before using them
    if((pData == NULL) || (bytesPerAddress == 0) || (address > endAddress) || (bytesPerWord == 0))
    {
        qWarning("Bad parameters specified when calling Program() function.");
        return Fail;
    }

    //Check to avoid possible division by zero when computing the percentage completion status.
    if(addressesToFetch == 0)
        addressesToFetch++;


    if(connected) {
        //First error check the input parameters before using them
        if((pData == NULL) || (endAddress < address) || (bytesPerPacket == 0))
        {
            qWarning("Error, bad parameters provided to call of GetData()");
            return Fail;
        }

        // Continue reading from device until the entire programmable region has been read
        while(address < endAddress)
        {
            //Update the progress bar so the user knows things are happening.
            percentCompletion = 100*((float)1 - (float)((float)(endAddress - address)/(float)addressesToFetch));
            if(percentCompletion > 100)
            {
                percentCompletion = 100;
            }
            //Reformat the percent completion so it "fits" in the 33% to 66% region (since erase
            //"completes" 0%-32% of the total erase/program/verify cycle, and verify completes 67%-100%).
            percentCompletion /= 3;
            percentCompletion += 67;
            emit SetProgressBar(percentCompletion);


            // Set up the buffer packet with the appropriate address and with the get data command
            memset((void*)&writePacket, 0x00, sizeof(writePacket));
            writePacket.command = GET_DATA;
            writePacket.address = address;

            //Debug output info.
            qWarning("Fetching packet with address: 0x%x", (unsigned int)writePacket.address);

            // Calculate to see if the entire buffer can be filled with data, or just partially
            if(((endAddress - address) * bytesPerAddress) < bytesPerPacket)
                // If the amount of bytes left over between current address and end address is less than
                //  the max amount of bytes per packet, then make sure the bytesPerPacket info is updated
                writePacket.bytesPerPacket = (endAddress - address) * bytesPerAddress;
            else
                // Otherwise keep it at its maximum
                writePacket.bytesPerPacket = bytesPerPacket;

            // Send the packet
            result = SendPacket((unsigned char*)&writePacket, sizeof(writePacket));

            // If it wasn't successful, then return with error
            if(result != Success)
            {
                qWarning("Error during verify sending packet with address: 0x%x", (unsigned int)writePacket.address);
                return result;
            }

            // Otherwise, read back the packet from the device
            memset((void*)&readPacket, 0x00, sizeof(readPacket));
            result = ReceivePacket((unsigned char*)&readPacket, sizeof(readPacket));

            // If it wasn't successful, then return with error
            if(result != Success)
            {
                qWarning("Error reading packet with address: 0x%x", (unsigned int)readPacket.address);
                return result;
            }

            // Copy contents from packet to data pointer
            memcpy(pData, readPacket.data + 58 - readPacket.bytesPerPacket, readPacket.bytesPerPacket);

            // Increment data pointer
            pData += readPacket.bytesPerPacket;

            // Increment address by however many bytes were received divided by how many bytes per address
            address += readPacket.bytesPerPacket / bytesPerAddress;
        }

        // if successfully received entire region, return success
        return Success;
    }

    // If not connected, return not connected
    return NotConnected;
}
Exemplo n.º 13
0
Comm::ErrorCode Comm::Program(unsigned long address, unsigned char bytesPerPacket,
                              unsigned char bytesPerAddress, unsigned char bytesPerWord, unsigned char deviceFamily,
                              unsigned long endAddress, unsigned char *pData)
{
    WritePacket writePacket;
    ErrorCode result = Success;
    unsigned int i;
    bool allPayloadBytesFF;
    bool firstAllFFPacketFound = false;
    unsigned int bytesToSend;
    unsigned char lastCommandSent = PROGRAM_DEVICE;
    unsigned int percentCompletion;
    unsigned int addressesToProgram;
    unsigned int startOfDataPayloadIndex;

    //Error check input parameters before using them
    if((pData == NULL) || (bytesPerAddress == 0) || (address > endAddress) || (bytesPerWord == 0))
    {
        qWarning("Bad parameters specified when calling Program() function.");
        return Fail;
    }

    //Error check to make sure the requested maximum data payload size is an exact multiple of the bytesPerAddress.
    //If not, shrink the number of bytes we actually send, so that it is always an exact multiple of the
    //programmable media bytesPerAddress.  This ensures that we don't "half" program any memory address (ex: if each
    //flash address is a 16-bit word address, we don't want to only program one byte of the address, we want to program
    //both bytes.
    while((bytesPerPacket % bytesPerWord) != 0)
    {
        bytesPerPacket--;
    }

    //Setup variable, used for progress bar updating computations.
    addressesToProgram = endAddress - address;
    if(addressesToProgram == 0) //Check to avoid potential divide by zero later.
        addressesToProgram++;


    //Make sure the device is still connected before we start trying to communicate with it.
    if(connected)
    {
        //Loop through the entire data set/region, but break it into individual packets before sending it
        //to the device.
        while(address < endAddress)
        {
            //Update the progress bar so the user knows things are happening.
            percentCompletion = 100*((float)1 - (float)((float)(endAddress - address)/(float)addressesToProgram));
            if(percentCompletion > 100)
            {
                percentCompletion = 100;
            }
            //Reformat the percent completion so it "fits" in the 33% to 66% region (since erase
            //"completes" 0%-32% of the total erase/program/verify cycle, and verify completes 67%-100%).
            percentCompletion /= 3;
            percentCompletion += 33;
            emit SetProgressBar(percentCompletion);

            //Prepare the packet to send to the device.
            memset((void*)&writePacket, 0x00, sizeof(writePacket)); //initialize all bytes clear, so unused pad bytes are = 0x00.
            writePacket.command = PROGRAM_DEVICE;
            writePacket.address = address;

            //Check if we are near the end of the programmable region, and need to send a "short packet" (with less than the maximum
            //allowed program data payload bytes).  In this case we need to notify the device by using the PROGRAM_COMPLETE command instead
            //of the normal PROGRAM_DEVICE command.  This lets the bootloader firmware in the device know it should flush any internal
            //buffers it may be using, by programming all of the bufferred data to NVM memory.
            if(((endAddress - address) * bytesPerAddress) < bytesPerPacket)
            {
                writePacket.bytesPerPacket = (endAddress - address) * bytesPerAddress;
                //Copy the packet data to the actual outgoing buffer and then send it over USB to the device.
                memcpy((unsigned char*)&writePacket.data[0] + 58 - writePacket.bytesPerPacket, pData, writePacket.bytesPerPacket);
                //Check to make sure we are completely programming all bytes of the destination address.  If not,
                //increase the data size and set the extra byte(s) to 0xFF (the default/blank value).
                while((writePacket.bytesPerPacket % bytesPerWord) != 0)
                {
                    if(writePacket.bytesPerPacket >= bytesPerPacket)
                    {
                        break; //should never hit this break, due to while((bytesPerPacket % bytesPerWord) != 0) check at start of function
                    }

                    //Shift all the data payload bytes in the packet to the left one (lower address),
                    //so we can insert a new 0xFF byte.
                    for(i = 0; i < (unsigned char)(bytesPerPacket - 1); i++)
                    {
                        writePacket.data[i] = writePacket.data[i+1];
                    }
                    writePacket.data[writePacket.bytesPerPacket] = 0xFF;
                    writePacket.bytesPerPacket++;

                }
                bytesToSend = writePacket.bytesPerPacket;
                qDebug("Preparing short packet of final program data with payload: 0x%x", (unsigned int)writePacket.bytesPerPacket);
            }
            else
            {
                //Else we are planning on sending a full length packet with the full size payload.
                writePacket.bytesPerPacket = bytesPerPacket;
                bytesToSend = bytesPerPacket;
                //Copy the packet data to the actual outgoing buffer and then prepare to send it.
                memcpy((unsigned char*)&writePacket.data[0] + 58 - writePacket.bytesPerPacket, pData, writePacket.bytesPerPacket);
            }


            //Check if all bytes of the data payload section of the packet are == 0xFF.  If so, we can save programming
            //time by skipping the packet by not sending it to the device.  The default/erased value is already = 0xFF, so
            //the contents of the flash memory will be correct (although if we want to be certain we should make sure
            //the 0xFF regions are still getting checked during the verify step, in case the erase procedure failed to set
            //all bytes = 0xFF).
            allPayloadBytesFF = true;   //assume true until we do the actual check below
            //Loop for all of the bytes in the data payload portion of the writePacket.  The data payload is little endian but is stored
            //"right justified" in the packet.  Therefore, writePacket.data[0] isn't necessarily the LSB data byte in the packet.
            startOfDataPayloadIndex = 58 - writePacket.bytesPerPacket;
            for(i = startOfDataPayloadIndex; i < (startOfDataPayloadIndex + writePacket.bytesPerPacket); i++)
            {
                if(writePacket.data[i] != 0xFF)
                {
                    //Special check for PIC24, where every 4th byte from the .hex file is == 0x00,
                    //which is the "phantom byte" (the upper byte of each odd address 16-bit word
                    //is unimplemented, and is probably 0x00 in the .hex file).
                    if((((i - startOfDataPayloadIndex) % bytesPerWord) == 3) && (deviceFamily == Device::PIC24))
                    {
                        //We can ignore this "phantom byte", since it is unimplemented and effectively a "don't care" byte.
                    }
                    else
                    {
                        //We found a non 0xFF (or blank value) byte.  We need to send and program the
                        //packet of useful data into the device.
                        allPayloadBytesFF = false;
                        break;
                    }
                }
            }

            //Check if we need to send a normal packet of data to the device, if the packet was all 0xFF and
            //we need to send a PROGRAM_COMPLETE packet, or if it was all 0xFF and we can simply skip it without
            //doing anything.
            if(allPayloadBytesFF == false)
            {
                qDebug("Sending program data packet with address: 0x%x", (unsigned int)writePacket.address);

                //We need to send a normal PROGRAM_DEVICE packet worth of data to program.
                result = SendPacket((unsigned char*)&writePacket, sizeof(writePacket));
                //Verify the data was successfully received by the USB device.
                if(result != Success)
                {
                    qWarning("Error during program sending packet with address: 0x%x", (unsigned int)writePacket.address);
                    return result;
                }
                firstAllFFPacketFound = true; //reset flag so it will be true the next time a pure 0xFF packet is found
                lastCommandSent = PROGRAM_DEVICE;

            }
            else if((allPayloadBytesFF == true) && (firstAllFFPacketFound == true))
            {
                //In this case we need to send a PROGRAM_COMPLETE command to let the firmware know it should flush
                //its buffer by programming all of it to flash, since we are about to skip to a new address range.
                writePacket.command = PROGRAM_COMPLETE;
                writePacket.bytesPerPacket = 0;
                firstAllFFPacketFound = false;
                qDebug("Sending program complete data packet to skip a packet with address: 0x%x", (unsigned int)writePacket.address);
                result = SendPacket((unsigned char*)&writePacket, sizeof(writePacket));
                //Verify the data was successfully received by the USB device.
                if(result != Success)
                {
                    qWarning("Error during program sending packet with address: 0x%x", (unsigned int)writePacket.address);
                    return result;
                }
                lastCommandSent = PROGRAM_COMPLETE;
            }
            else
            {
                //If we get to here, this means that (allPayloadBytesFF == true) && (firstAllFFPacketFound == false).
                //In this case, the last packet that we processed was all 0xFF, and all bytes of this packet are
                //also all 0xFF.  In this case, we don't need to send any packet data to the device.  All we need
                //to do is advance our pointers and keep checking for a new non-0xFF section.
                qDebug("Skipping data packet with all 0xFF with address: 0x%x", (unsigned int)writePacket.address);
            }

            //Increment pointers now that we successfully programmed (or deliberately skipped) a packet worth of data
            address += bytesPerPacket / bytesPerAddress;
            pData += bytesToSend;

            //Check if we just now exactly finished programming the memory region (in which case address will be exactly == endAddress)
            //region. (ex: we sent a PROGRAM_DEVICE instead of PROGRAM_COMPLETE for the last packet sent).
            //In this case, we still need to send the PROGRAM_COMPLETE command to let the firmware know that it is done,
            //and will not be receiving any subsequent program packets for this memory region.
            if((unsigned int)address >= (unsigned int)endAddress)
            {
                //Check if we still need to send a PROGRAM_COMPLETE command (we don't need to send one if
                //the last command we sent was a PRORAM_COMPLETE already).
                if(lastCommandSent == PROGRAM_COMPLETE)
                {
                    break;
                }

                memset((void*)&writePacket, 0x00, sizeof(writePacket));
                writePacket.command = PROGRAM_COMPLETE;
                writePacket.bytesPerPacket = 0;
                qDebug("Sending final program complete command for this region.");

                result = SendPacket((unsigned char*)&writePacket, sizeof(writePacket));
                break;
            }
        }//while(address < endAddress)

        return result;

    }//if(connected)
    else
    {
        return NotConnected;
    }
}
Exemplo n.º 14
0
INT_PTR CALLBACK MainDlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	int lbItem=0;
	HWND hwndList=0;
	DWORD pid=0xFFFFFFFF;

	HDC dc = 0;
	PAINTSTRUCT ps;
	gHWND = hwndDlg;

	char szpid[1024] = {0};

	switch (message)
	{
		case WM_INITDIALOG:
			// reset progress bar
			SetProgressBar(0);
			gProcList = new ProcessList(hwndDlg, hInst);
			gProcList->FillList();
			szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);	
			if(nArgs > 1) {
				wsprintf(szpid, "%S", szArglist[1]);
				gProcList->SetSelectionFromPid(atoi(szpid));
				if(nArgs >2 ) {
					MemorySnapshot *gMemSnap = new MemorySnapshot;
					char filename[MAX_PATH];
					wsprintf(filename, "%S", szArglist[2]);
					bool res = gMemSnap->Dump(atoi(szpid), filename);
					SendMessage(hwndDlg, WM_CLOSE, IDC_DUMP, (LPARAM)res);
				} else {
					DumpProcess(atoi(szpid));
				}
			}
			return TRUE;

		case WM_PAINT:
			{
				BeginPaint(gHWND, &ps);
				RECT rc;
				GetClientRect(gHWND, &rc); 
				EndPaint(gHWND, &ps);
			}
			break;

		case WM_CLOSE:
			delete gProcList;
			gProcList = 0;
			EndDialog(gHWND, 0);
			ExitProcess((UINT)lParam);
			break;

		case WM_COMMAND:
			switch(LOWORD(wParam))
			{
				case IDC_DUMP:
					pid = gProcList->GetSelectedPid();
					gProcList->EnableDisable(FALSE);
					DumpProcess(pid);
					gProcList->EnableDisable(TRUE);
					break;
					
				case IDC_REFRESH:
					gProcList->FillList();
					break;

				case IDC_EXIT:
					SendMessage(gHWND, WM_CLOSE, 0, 0);
					break;


				case IDC_PROCLIST:
					if(pid == 0xFFFFFFFF) {
						if(gProcList) {
							pid = gProcList->GetSelectedPid();
						}
						if(pid == 0xFFFFFFFF)
							EnableWindow(GetDlgItem(gHWND, IDC_DUMP), TRUE);
					}
					switch (HIWORD(wParam)) 
					{ 
						case LBN_DBLCLK:
								SendMessage(gHWND, WM_COMMAND, IDC_DUMP, 0);
								break;
						default:
							break;
					}

				default:
					break;
			}
		default:
			break;

	}
//	UpdateWindow(gHWND);
	return (INT_PTR)FALSE;
}
Exemplo n.º 15
0
INT_PTR CALLBACK ProgressDlgProc(HWND hdlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	static int fontHeight, listWidth;
	static int manualAbort;
	static HFONT hBoldFont = NULL;

	INT_PTR bReturn;
	if (DoMyControlProcessing(hdlg, message, wParam, lParam, &bReturn))
		return bReturn;

	switch (message) {
	case WM_INITDIALOG:
		EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), FALSE);
		hdlgProgress = hdlg;
		hwndStatus = GetDlgItem(hdlg, IDC_STATUS);
		errorCount = 0;
		bShortModeDone = false;
		hwndBar = GetDlgItem(hdlg, IDC_PROGRESS);
		SendMessage(hwndBar, PBM_SETRANGE, 0, MAKELPARAM(0, 1000));
		{
			HDC hdc;
			HFONT hFont, hoFont;
			SIZE s;
			hdc = GetDC(NULL);
			hFont = (HFONT)SendMessage(hdlg, WM_GETFONT, 0, 0);
			hoFont = (HFONT)SelectObject(hdc, hFont);
			GetTextExtentPoint32(hdc, _T("x"), 1, &s);
			SelectObject(hdc, hoFont);
			ReleaseDC(NULL, hdc);
			fontHeight = s.cy;

			RECT rc;
			GetClientRect(GetDlgItem(hdlg, IDC_STATUS), &rc);
			listWidth = rc.right;

			LOGFONT lf;
			GetObject((HFONT)SendDlgItemMessage(hdlg, IDC_STATUS, WM_GETFONT, 0, 0), sizeof(lf), &lf);
			lf.lfWeight = FW_BOLD;
			hBoldFont = CreateFontIndirect(&lf);
		}
		manualAbort = 0;
		hEventRun = CreateEvent(NULL, TRUE, TRUE, NULL);
		hEventAbort = CreateEvent(NULL, TRUE, FALSE, NULL);
		TranslateDialogDefault(hdlg);
		_beginthread(WorkerThread, 0, NULL);
		return TRUE;

	case WM_MEASUREITEM:
		{
			LPMEASUREITEMSTRUCT mis = (LPMEASUREITEMSTRUCT)lParam;
			mis->itemWidth = listWidth;
			mis->itemHeight = fontHeight;
		}
		return TRUE;

	case WM_DRAWITEM:
		TCHAR str[256];
		{
			LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lParam;
			int bold = 0;
			HFONT hoFont = NULL;
			if ((int)dis->itemID == -1) break;
			SendMessage(dis->hwndItem, LB_GETTEXT, dis->itemID, (LPARAM)str);
			switch (dis->itemData & STATUS_CLASSMASK) {
			case STATUS_MESSAGE:
				SetTextColor(dis->hDC, RGB(0, 0, 0));
				break;
			case STATUS_WARNING:
				SetTextColor(dis->hDC, RGB(192, 128, 0));
				break;
			case STATUS_ERROR:
				SetTextColor(dis->hDC, RGB(192, 0, 0));
				break;
			case STATUS_FATAL:
				bold = 1;
				SetTextColor(dis->hDC, RGB(192, 0, 0));
				break;
			case STATUS_SUCCESS:
				bold = 1;
				SetTextColor(dis->hDC, RGB(0, 192, 0));
				break;
			}
			if (bold) hoFont = (HFONT)SelectObject(dis->hDC, hBoldFont);
			ExtTextOut(dis->hDC, dis->rcItem.left, dis->rcItem.top, ETO_CLIPPED | ETO_OPAQUE, &dis->rcItem, str, (UINT)mir_tstrlen(str), NULL);
			if (bold) SelectObject(dis->hDC, hoFont);
		}
		return TRUE;

	case WM_PROCESSINGDONE:
		SetProgressBar(1000);
		if (bShortMode) {
			EnableWindow(GetDlgItem(GetParent(hdlg), IDC_BACK), FALSE);
			EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), FALSE);
			SetDlgItemText(GetParent(hdlg), IDCANCEL, TranslateT("&Finish"));
			bShortModeDone = true;
			if (bAutoExit)
				PostMessage(GetParent(hdlg), WM_COMMAND, IDCANCEL, 0);
		}
		else {
			AddToStatus(STATUS_SUCCESS, TranslateT("Click Next to continue"));
			EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), TRUE);
		}

		if (manualAbort == 1)
			EndDialog(GetParent(hdlg), 0);
		else if (manualAbort == 2) {
			if (opts.bCheckOnly)
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc);
			else {
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_CLEANING, (LPARAM)CleaningDlgProc);
				CloseHandle(opts.hOutFile);
				opts.hOutFile = NULL;
			}
			break;
		}
		break;

	case WZN_CANCELCLICKED:
		if (bShortModeDone) {
			if (!errorCount) {
				if (bLaunchMiranda)
					CallService(MS_DB_SETDEFAULTPROFILE, (WPARAM)opts.filename, 0);
				wizardResult = 1;
			}
			return TRUE;
		}

		ResetEvent(hEventRun);
		if (IsWindowEnabled(GetDlgItem(GetParent(hdlg), IDOK)))
			break;

		if (MessageBox(hdlg, TranslateT("Processing has not yet completed, if you cancel now then the changes that have currently been made will be rolled back and the original database will be restored. Do you still want to cancel?"), TranslateT("Miranda Database Tool"), MB_YESNO) == IDYES) {
			manualAbort = 1;
			SetEvent(hEventAbort);
		}
		SetEvent(hEventRun);
		SetWindowLongPtr(hdlg, DWLP_MSGRESULT, TRUE);
		return TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_BACK:
			ResetEvent(hEventRun);
			if (!IsWindowEnabled(GetDlgItem(GetParent(hdlg), IDOK))) {
				if (MessageBox(hdlg, TranslateT("Processing has not yet completed, if you go back now then the changes that have currently been made will be rolled back and the original database will be restored. Do you still want to go back?"), TranslateT("Miranda Database Tool"), MB_YESNO) == IDYES) {
					manualAbort = 2;
					SetEvent(hEventAbort);
				}
				SetEvent(hEventRun);
				break;
			}
			SetEvent(hEventRun);
			if (opts.bCheckOnly)
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc);
			else
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_CLEANING, (LPARAM)CleaningDlgProc);
			break;

		case IDOK:
			PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FINISHED, (LPARAM)FinishedDlgProc);
			break;
		}
		break;

	case WM_DESTROY:
		if (hEventAbort) {
			CloseHandle(hEventAbort);
			hEventAbort = NULL;
		}
		if (hEventRun) {
			CloseHandle(hEventRun);
			hEventRun = NULL;
		}
		if (hBoldFont) {
			DeleteObject(hBoldFont);
			hBoldFont = NULL;
		}
		break;
	}
	return FALSE;
}