int tempzip_make(HWND hwndDlg, TCHAR *fn) { TCHAR buf[MAX_PATH]; GetTempPath(MAX_PATH,buf); GetTempFileName(buf,_T("z2e"),GetTickCount(),tempzip_path); if (!CreateDirectory(tempzip_path,NULL)) { GetTempPath(MAX_PATH,tempzip_path); _tcscat(tempzip_path,_T("\\nsi")); if (!CreateDirectory(tempzip_path,NULL)) { tempzip_path[0]=0; MessageBox(hwndDlg,_T("Error creating temporary directory"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } } FILE *fp=_tfopen(fn,_T("rb")); if (fp) { fseek(fp,0,SEEK_END); g_zipfile_size=ftell(fp); fclose(fp); } else g_zipfile_size=0; unzFile f; f = unzOpen(fn); if (!f || unzGoToFirstFile(f) != UNZ_OK) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error opening ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); return 1; } int nf=0, nkb=0; g_extracting=1; do { char filenameA[MAX_PATH]; unz_file_info info; // ZREAD uses byte size, not TCHAR length. unzGetCurrentFileInfo(f,&info,filenameA,sizeof(filenameA),NULL,0,NULL,0); // was zip created on MS-DOS/Windows? if ((info.version & 0xFF00) == 0) { OemToCharBuffA(filenameA, filenameA, (DWORD)strlen(filenameA)); } #ifdef _UNICODE TCHAR filename[MAX_PATH]; if (MultiByteToWideChar(CP_ACP, 0, filenameA, -1, filename, MAX_PATH) == 0) { if (f) unzClose(f); MessageBox(hwndDlg,_T("Error converting filename to Unicode"), g_errcaption, MB_OK|MB_ICONSTOP); return 1; } #else char* filename = filenameA; #endif if (filename[0] && filename[_tcslen(filename)-1] != _T('\\') && filename[_tcslen(filename)-1] != _T('/')) { TCHAR *pfn=filename; while (*pfn) { if (*pfn == _T('/')) *pfn=_T('\\'); pfn++; } pfn=filename; if (pfn[1] == _T(':') && pfn[2] == _T('\\')) pfn+=3; while (*pfn == _T('\\')) pfn++; TCHAR out_filename[1024]; lstrcpy(out_filename,tempzip_path); lstrcat(out_filename,_T("\\")); lstrcat(out_filename,pfn); if (_tcsstr(pfn,_T("\\"))) { TCHAR buf[1024]; lstrcpy(buf,out_filename); TCHAR *p=buf+_tcslen(buf); while (p > buf && *p != _T('\\')) p--; *p=0; if (buf[0]) doMKDir(buf); } if (unzOpenCurrentFile(f) == UNZ_OK) { SendDlgItemMessage(hwndDlg,IDC_ZIPINFO_FILES,LB_ADDSTRING,0,(LPARAM)pfn); FILE *fp; int l; fp = _tfopen(out_filename,_T("wb")); if (fp) { do { // Jim Park: Local buf, no need to TCHAR char buf[1024]; l=unzReadCurrentFile(f,buf,sizeof(buf)); if (l > 0) { if (fwrite(buf,1,l,fp) != (unsigned int)l) { unzClose(f); fclose(fp); MessageBox(hwndDlg,_T("Error writing output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nkb++; } } while (l > 0); fclose(fp); { // set file time HANDLE hf = CreateFile(out_filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0); if (hf != INVALID_HANDLE_VALUE) { FILETIME ft, lft; DosDateTimeToFileTime(HIWORD(info.dosDate), LOWORD(info.dosDate), &ft); LocalFileTimeToFileTime(&ft, &lft); SetFileTime(hf, 0, 0, &lft); CloseHandle(hf); } } } else { unzClose(f); MessageBox(hwndDlg,_T("Error opening output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } nf++; wsprintf(buf,_T("Extracting: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); MSG msg; int quit=0; while (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message == WM_DESTROY && msg.hwnd == g_hwnd) { quit++; break; } TranslateMessage(&msg); DispatchMessage(&msg); } unzCloseCurrentFile(f); if (quit) break; } else { unzClose(f); MessageBox(hwndDlg,_T("Error extracting from ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP); g_extracting=0; return 1; } } } while (unzGoToNextFile(f) == UNZ_OK); g_extracting=0; wsprintf(buf,_T("Extracted: %d files, %dKB"),nf,nkb); SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf); unzClose(f); return 0; }
bool Strip::Load (const TCHAR* lpszFileName) { // ----- Initialize ----- // FILE* stream = _tfopen(lpszFileName, _T("rb") CHARSET); if (stream == NULL || _pPimpl == NULL) { return false; } TiXmlDocument doc; TiXmlAttribute* pAttr; TiXmlElement* pRoot; TiXmlElement* pBlockNode; TiXmlElement* pUnitNode; TiXmlElement* pBallNode; Block* pBlockObject; Unit* pUnitObject; Ball* pBallObject; const char* sRootName; const char* sAttrName; double dValue; int nValue; if (!doc.LoadFile(stream)) { return false; } pRoot = doc.RootElement(); if (pRoot == false) { return false; } sRootName = pRoot->Value(); if (strcmp(sRootName, ROOT_NAME_STRIP) != 0) { return false; } _pPimpl->vectorBlocks.clear(); // ----- Get a Strip Data ----- // if (pRoot->QueryDoubleAttribute(ATTR_NAME_WIDTH, &dValue) == TIXML_SUCCESS) { _pPimpl->dWidth = dValue; } if (pRoot->QueryDoubleAttribute(ATTR_NAME_HEIGHT, &dValue) == TIXML_SUCCESS) { _pPimpl->dHeight = dValue; } // ----- Get Strip's childs ----- // pBlockNode = pRoot->FirstChildElement(); if (pBlockNode != NULL) { do { pBlockObject = new Block(); // ----- Get a Block Data ----- // if (pBlockNode->QueryIntAttribute (ATTR_NAME_COLUMN, &nValue) == TIXML_SUCCESS) { pBlockObject->SetColumn (nValue); } if (pBlockNode->QueryIntAttribute (ATTR_NAME_ROW, &nValue) == TIXML_SUCCESS) { pBlockObject->SetRow (nValue); } if (pBlockNode->QueryDoubleAttribute (ATTR_NAME_WIDTH, &dValue) == TIXML_SUCCESS) { pBlockObject->SetWidth (dValue); } if (pBlockNode->QueryDoubleAttribute (ATTR_NAME_HEIGHT, &dValue) == TIXML_SUCCESS) { pBlockObject->SetHeight (dValue); } if (pBlockNode->QueryDoubleAttribute (ATTR_NAME_START_X, &dValue) == TIXML_SUCCESS) { pBlockObject->SetStartX (dValue); } if (pBlockNode->QueryDoubleAttribute (ATTR_NAME_START_Y, &dValue) == TIXML_SUCCESS) { pBlockObject->SetStartY (dValue); } // ----- Get Block's childs ----- // pUnitNode = pBlockNode->FirstChildElement(); if (pUnitNode != NULL) { do { pUnitObject = new Unit(); // ----- Get a Unit Data ----- // if (pUnitNode->QueryIntAttribute (ATTR_NAME_COLUMN, &nValue) == TIXML_SUCCESS) { pUnitObject->SetColumn (nValue); } if (pUnitNode->QueryIntAttribute (ATTR_NAME_ROW, &nValue) == TIXML_SUCCESS) { pUnitObject->SetRow (nValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_START_X, &dValue) == TIXML_SUCCESS) { pUnitObject->SetStartX (dValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_START_Y, &dValue) == TIXML_SUCCESS) { pUnitObject->SetStartY (dValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_CENTER_X, &dValue) == TIXML_SUCCESS) { pUnitObject->SetCenterX (dValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_CENTER_Y, &dValue) == TIXML_SUCCESS) { pUnitObject->SetCenterY (dValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_WIDTH, &dValue) == TIXML_SUCCESS) { pUnitObject->SetWidth (dValue); } if (pUnitNode->QueryDoubleAttribute (ATTR_NAME_HEIGHT, &dValue) == TIXML_SUCCESS) { pUnitObject->SetHeight (dValue); } // ----- Get Unit's childs ----- // pBallNode = pUnitNode->FirstChildElement(); if (pBallNode != NULL) { do { pBallObject = new Ball(); // ----- Get a Ball Data ----- // if (pBallNode->QueryDoubleAttribute (ATTR_NAME_DIAMETER, &dValue) == TIXML_SUCCESS) { pBallObject->SetDiameter (dValue); } if (pBallNode->QueryDoubleAttribute (ATTR_NAME_CENTER_X, &dValue) == TIXML_SUCCESS) { pBallObject->SetCenterX (dValue); } if (pBallNode->QueryDoubleAttribute (ATTR_NAME_CENTER_Y, &dValue) == TIXML_SUCCESS) { pBallObject->SetCenterY (dValue); } if (pBallNode->QueryIntAttribute (ATTR_NAME_BALL_STATUS, &nValue) == TIXML_SUCCESS) { pBallObject->SetStatus (nValue); } pUnitObject->InsertBall(pBallObject); } while (pBallNode = pBallNode->NextSiblingElement()); } pBlockObject->InsertUnit(pUnitObject); } while (pUnitNode = pUnitNode->NextSiblingElement()); } // ----- Add Block Object ----- // InsertBlock(pBlockObject); } while (pBlockNode = pBlockNode->NextSiblingElement()); } // ----- Close ----- // fclose(stream); return true; }
static INT_PTR CALLBACK LogDlgProc(HWND hwndDlg,UINT message,WPARAM wParam,LPARAM lParam) { LOGWIN *dat = (LOGWIN*)GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch(message) { case WM_INITDIALOG: { dat = (LOGWIN*)lParam; dat->hwnd = hwndDlg; dat->Scroll = 1; dat->Paused = 0; dat->hList = GetDlgItem(hwndDlg, IDC_LIST); SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)dat); mir_subclassWindow(dat->hList, SubclassProc); // init buttons for(int i = 0; i < SIZEOF(ctrls); i++) { HWND hwnd = GetDlgItem(hwndDlg,ctrls[i].control); SendMessage(hwnd, ctrls[i].type, 0, 0); SendMessage(hwnd, BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcons[i+ICON_FIRST]); SendMessage(hwnd, BUTTONADDTOOLTIP,(WPARAM)TranslateTS(ctrls[i].tooltip), BATF_TCHAR); } CheckDlgButton(hwndDlg, IDC_SCROLL, dat->Scroll ? BST_CHECKED : BST_UNCHECKED); SendDlgItemMessage(hwndDlg,IDC_SCROLL,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcons[(dat->Scroll?ICON_SCROLL:ICON_NOSCROLL)]); if (gSingleMode) { ShowWindow(GetDlgItem(hwndDlg, IDC_PAUSEALL), SW_HIDE); ShowWindow(GetDlgItem(hwndDlg, IDC_STARTALL), SW_HIDE); ShowWindow(GetDlgItem(hwndDlg, IDC_CLOSE), SW_HIDE); } // init listview LVITEM lvi = {0}; LVCOLUMN sLC; //ListView_SetUnicodeFormat(dat->hList, TRUE); ListView_SetImageList(dat->hList, gImg, LVSIL_SMALL); sLC.mask = LVCF_FMT | LVCF_WIDTH; sLC.fmt = LVCFMT_LEFT; sLC.cx = 630; ListView_InsertColumn(dat->hList, 0, &sLC); ListView_SetExtendedListViewStyle(dat->hList, LVS_EX_FULLROWSELECT); lvi.mask = LVIF_TEXT; if (gIcons) { lvi.mask |= LVIF_IMAGE; lvi.iImage = IMG_INFO; } lvi.pszText = TranslateT("*** Console started ***"); ListView_InsertItem(dat->hList, &lvi); SendMessage(hwndDlg, WM_SIZE, 0, 0); } break; case HM_DUMP: if (!lParam) break; if (dat && !dat->Paused) { LVITEM lvi = {0}; int last = 0x7fffffff; TCHAR szBreak; DWORD len, tmplen; DWORD wraplen = gWrapLen; TCHAR *str = ((DUMPMSG*)lParam)->szMsg; lvi.iItem = 0x7fffffff; str = _tcstok(str, _T("\n")); if (gIcons && str != NULL) { lvi.mask = LVIF_TEXT | LVIF_IMAGE; if (_tcsstr(str, _T("Data received"))) { if (gSeparator) ListView_InsertItem(dat->hList, &lvi); lvi.iImage = IMG_IN; } else if (_tcsstr(str, _T("Data sent"))) { if (gSeparator) ListView_InsertItem(dat->hList, &lvi); lvi.iImage = IMG_OUT; } else { if (gSeparator && dat->newline) { ListView_InsertItem(dat->hList, &lvi); dat->newline = 0; } lvi.iImage = IMG_INFO; } } else lvi.mask = LVIF_TEXT; while (str != NULL) { lvi.pszText = &str[0]; tmplen = len = (DWORD)_tcslen(lvi.pszText); while(len > wraplen) { szBreak = lvi.pszText[wraplen]; lvi.pszText[wraplen] = 0; last = ListView_InsertItem(dat->hList, &lvi); lvi.pszText[wraplen] = szBreak; len -= wraplen; lvi.pszText = &str[0] + tmplen - len; dat->newline = 1; lvi.iImage = IMG_EMPTY; } if (len && lvi.pszText[len-1] == '\r') lvi.pszText[len-1] = 0; last = ListView_InsertItem(dat->hList, &lvi); str = _tcstok(NULL, _T("\n")); if (str) dat->newline = 1; lvi.iImage = IMG_EMPTY; } if ( gVisible && dat == pActive && dat->Scroll == 1 ) ListView_EnsureVisible(dat->hList, last, FALSE); if (last > gLimit) { int idx = last - gLimit + gLimit/4; // leave only 75% of LIMIT while (idx >= 0) { ListView_DeleteItem(dat->hList, idx); idx--; } } } mir_free((DUMPMSG*)lParam); return TRUE; case WM_SIZE: { UTILRESIZEDIALOG urd = { sizeof(urd) }; urd.hInstance = hInst; urd.hwndDlg = hwndDlg; urd.lpTemplate = MAKEINTRESOURCEA(IDD_LOG); urd.pfnResizer = LogResize; SetWindowPos(hwndDlg, HWND_TOP, rcTabs.left, rcTabs.top, rcTabs.right - rcTabs.left, rcTabs.bottom - rcTabs.top, SWP_SHOWWINDOW); CallService(MS_UTILS_RESIZEDIALOG, 0, (LPARAM)&urd); } break; case WM_COMMAND: if (!dat) break; switch(LOWORD(wParam)) { case IDC_PAUSE: { LVITEM lvi = {0}; dat->Paused = !(dat->Paused); lvi.mask = LVIF_TEXT | LVIF_IMAGE; lvi.iImage = IMG_INFO; lvi.iItem = 0x7FFFFFFF; lvi.pszText = (dat->Paused) ? TranslateT("*** Console paused ***") : TranslateT("*** Console resumed ***"); ListView_InsertItem(dat->hList, &lvi); CheckDlgButton(hwndDlg, IDC_PAUSE, (dat->Paused) ? BST_CHECKED : BST_UNCHECKED); SendDlgItemMessage(hwndDlg,IDC_PAUSE,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcons[((dat->Paused)?ICON_PAUSED:ICON_STARTED)]); break; } case IDC_SCROLL: dat->Scroll = !(dat->Scroll); CheckDlgButton(hwndDlg, IDC_SCROLL, (dat->Scroll) ? BST_CHECKED : BST_UNCHECKED); SendDlgItemMessage(hwndDlg,IDC_SCROLL,BM_SETIMAGE,IMAGE_ICON,(LPARAM)hIcons[((dat->Scroll)?ICON_SCROLL:ICON_NOSCROLL)]); break; case IDC_COPY: { int idx = 0; TCHAR szText[128]; TCHAR *src, *dst, *buf; int flags = LVNI_BELOW; int count = ListView_GetSelectedCount(dat->hList); if (count) flags |= LVNI_SELECTED; else count = ListView_GetItemCount(dat->hList); dst = buf = (TCHAR*)malloc((count*(sizeof(szText)+1)+1)*sizeof(TCHAR)); if (!buf) break; while ((idx = ListView_GetNextItem(dat->hList, idx, flags)) > 0) { ListView_GetItemText(dat->hList, idx, 0, szText, SIZEOF(szText)-1); src = szText; while (*dst++ = *src++); dst--; *dst++ = '\r'; *dst++ = '\n'; *dst = 0; } if (dst - buf > 0 && OpenClipboard(hwndDlg)) { EmptyClipboard(); HGLOBAL hClipboardData = GlobalAlloc(GMEM_DDESHARE, (dst-buf+1)*sizeof(TCHAR)); if (hClipboardData) { TCHAR *pchData = (TCHAR*)GlobalLock(hClipboardData); _tcscpy(pchData, buf); GlobalUnlock(hClipboardData); SetClipboardData(CF_UNICODETEXT,hClipboardData); } CloseClipboard(); } free(buf); break; } case IDC_DELETE: { int idx = 0; int count = ListView_GetSelectedCount(dat->hList); if ( !count ) break; if ( count == ListView_GetItemCount(dat->hList)) { LVITEM lvi = {0}; ListView_DeleteAllItems(dat->hList); lvi.mask = LVIF_TEXT | LVIF_IMAGE; lvi.iImage = IMG_INFO; lvi.pszText = TranslateT("*** Console cleared ***"); ListView_InsertItem(dat->hList, &lvi); dat->newline = 0; break; } while ((idx = ListView_GetNextItem(dat->hList, idx, LVNI_BELOW|LVNI_SELECTED)) > 0) { ListView_DeleteItem(dat->hList, idx); idx--; } } break; case IDC_SAVE: { TCHAR szFile[MAX_PATH]; if (!Openfile(szFile, ListView_GetSelectedCount(dat->hList))) break; FILE *fp = _tfopen(szFile, _T("wt")); if (fp) { int idx = 0; TCHAR szText[128]; int flags = LVNI_BELOW; if (ListView_GetSelectedCount(dat->hList)) flags |= LVNI_SELECTED; while ((idx = ListView_GetNextItem(dat->hList, idx, flags)) > 0) { ListView_GetItemText(dat->hList, idx, 0, szText, SIZEOF(szText)); _ftprintf(fp, _T("%s\n"), szText); } fclose(fp); } break; } case IDC_OPTIONS: CallServiceSync(MS_NETLIB_LOGWIN,0,0); break; case IDC_STARTALL: SendMessage(hwndConsole, HM_PAUSEALL, 0, 0); break; case IDC_PAUSEALL: SendMessage(hwndConsole, HM_PAUSEALL, 0, 1); break; case IDC_CLOSE: if (tabCount > 1) SendMessage(hwndDlg, WM_CLOSE, 0, 0); break; } break; case WM_CLOSE: DestroyWindow(hwndDlg); break; case WM_DESTROY: SendMessage(hwndConsole, HM_REMOVE, 0, (LPARAM)dat); break; } return FALSE; }
int _tmain(int argc, _TCHAR* argv[]) { if( argc < 2 ) { _tprintf(_T("converts a picture to a tank map\n")); _tprintf(_T("supported formats: bmp, gif, jpg, wmf, ico\n")); _tprintf(_T("using: mkmap bmpfile.bmp [mapfile]\n")); return 0; } _tprintf(_T("input file: \n %s\n"), argv[1]); IPicture *pPicture = LoadPicture(argv[1]); if( NULL == pPicture ) { _tprintf(_T("Loading FAILED!\n")); return -1; } HDC hdc = GetDC(NULL); long height, width; pPicture->get_Height(&height); pPicture->get_Width(&width); long height_ = MulDiv(height, GetDeviceCaps(hdc, LOGPIXELSY), HIMETRIC_INCH); long width_ = MulDiv(width, GetDeviceCaps(hdc, LOGPIXELSX), HIMETRIC_INCH); _tprintf(_T("width %d px\n"), width_); _tprintf(_T("height %d px\n"), height_); HDC hdc_tmp = CreateCompatibleDC(hdc); HBITMAP bmp = CreateCompatibleBitmap(hdc, width_, height_); ReleaseDC(NULL, hdc); HBITMAP old = (HBITMAP) SelectObject(hdc_tmp, bmp); pPicture->Render(hdc_tmp, 0, 0, width_, height_, 0, height, width, -height, NULL); _TCHAR outfn[MAX_PATH]; if( argc > 2 ) _tcscpy(outfn, argv[2]); else _stprintf(outfn, _T("%s.tankmap"), argv[1]); FILE *file = _tfopen(outfn, _T("wt")); if( NULL != file ) { _tprintf(_T("writing map to '%s'\n"), outfn); try { fwassert(_ftprintf(file, _T("<tank map>\n"))); fwassert(_ftprintf(file, _T("width %d\n"), width_)); fwassert(_ftprintf(file, _T("height %d\n"), height_)); _TCHAR name[MAX_OBJNAME]; int objcount = 0; for( int y = 0; y < height_; y++ ) for( int x = 0; x < width_; x++ ) { if( ObjectFromColor(name, GetPixel(hdc_tmp, x, y)) ) { fwassert(_ftprintf(file, _T("%s %d %d\n"), name, 16 + x * 32, 16 + y * 32)); objcount++; } } _tprintf(_T("%d objects written\n"), objcount); _tprintf(_T("done.\n"), objcount); } catch(const _TCHAR *msg) { fclose(file); _tprintf(msg); } } else { _tprintf(_T("can't open file '%s' for writing\n"), outfn); } SelectObject(hdc_tmp, old); DeleteObject(bmp); DeleteDC(hdc_tmp); SAFE_RELEASE(pPicture); return 0; }
// Read in the config file for the whole application int ConfigAppLoad() { TCHAR szConfig[MAX_PATH]; TCHAR szLine[1024]; FILE* h; #ifdef _UNICODE setlocale(LC_ALL, ""); #endif CreateConfigName(szConfig); if ((h = _tfopen(szConfig, _T("rt"))) == NULL) { return 1; } // Go through each line of the config file while (_fgetts(szLine, sizeof(szLine), h)) { int nLen = _tcslen(szLine); // Get rid of the linefeed at the end if (szLine[nLen - 1] == 10) { szLine[nLen - 1] = 0; nLen--; } #define VAR(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = _tcstol(szValue, NULL, 0); } #define VAR64(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = (long long)_tcstod(szValue, NULL); } #define FLT(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x)); \ if (szValue) x = _tcstod(szValue, NULL); } #define STR(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x) _T(" ")); \ if (szValue) _tcscpy(x,szValue); } #define PAT(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x) _T(" ")); \ if (szValue) { _tcscpy(x, szValue); UpdatePath(x); } } #define DRV(x) { TCHAR* szValue = LabelCheck(szLine,_T(#x) _T(" ")); \ if (szValue) x = NameToDriver(szValue); } VAR(nIniVersion); // Emulation VAR(bBurnUseASMCPUEmulation); // Video VAR(nVidDepth); VAR(nVidRefresh); VAR(nVidRotationAdjust); // horizontal oriented VAR(nVidHorWidth); VAR(nVidHorHeight); VAR(bVidArcaderesHor); VAR(VidPreset[0].nWidth); VAR(VidPreset[0].nHeight); VAR(VidPreset[1].nWidth); VAR(VidPreset[1].nHeight); VAR(VidPreset[2].nWidth); VAR(VidPreset[2].nHeight); VAR(VidPreset[3].nWidth); VAR(VidPreset[3].nHeight); VAR(nScreenSizeHor); // vertical oriented VAR(nVidVerWidth); VAR(nVidVerHeight); VAR(bVidArcaderesVer); VAR(VidPresetVer[0].nWidth); VAR(VidPresetVer[0].nHeight); VAR(VidPresetVer[1].nWidth); VAR(VidPresetVer[1].nHeight); VAR(VidPresetVer[2].nWidth); VAR(VidPresetVer[2].nHeight); VAR(VidPresetVer[3].nWidth); VAR(VidPresetVer[3].nHeight); VAR(nScreenSizeVer); VAR(nWindowSize); VAR(nWindowPosX); VAR(nWindowPosY); VAR(bDoGamma); VAR(bVidUseHardwareGamma); VAR(bHardwareGammaOnly); FLT(nGamma); VAR(bVidFullStretch); VAR(bVidCorrectAspect); VAR(bVidAutoSwitchFull); VAR(bVidTripleBuffer); VAR(bVidVSync); //VAR(bVidDWMCore); VAR(bVidScanlines); VAR(nVidScanIntensity); VAR(bMonitorAutoCheck); VAR(nVidScrnAspectX); VAR(nVidScrnAspectY); VAR(bForce60Hz); VAR(bAlwaysDrawFrames); VAR(nVidSelect); VAR(nVidBlitterOpt[0]); VAR64(nVidBlitterOpt[1]); VAR(nVidBlitterOpt[2]); VAR(nVidBlitterOpt[3]); VAR(nVidBlitterOpt[4]); // DirectDraw blitter VAR(bVidScanHalf); // Direct3D blitter VAR(bVidBilinear); VAR(bVidScanDelay); VAR(bVidScanRotate); VAR(bVidScanBilinear); VAR(nVidFeedbackIntensity); VAR(nVidFeedbackOverSaturation); FLT(fVidScreenAngle); FLT(fVidScreenCurvature); VAR(bVidForce16bit); VAR(nVidTransferMethod); // DirectX Graphics blitter FLT(dVidCubicB); FLT(dVidCubicC); // DirectX Graphics 9 Alt blitter VAR(bVidDX9Bilinear); VAR(bVidHardwareVertex); VAR(bVidMotionBlur); // Sound VAR(nAudSelect); VAR(nAudSegCount); VAR(nInterpolation); VAR(nFMInterpolation); VAR(nAudSampleRate[0]); VAR(nAudDSPModule[0]); VAR(nAudSampleRate[1]); VAR(nAudDSPModule[1]); // Other STR(szLocalisationTemplate); VAR(nVidSDisplayStatus); VAR(nMinChatFontSize); VAR(nMaxChatFontSize); VAR(bModelessMenu); VAR(nSplashTime); VAR(bDrvSaveAll); VAR(nAppThreadPriority); VAR(bAlwaysProcessKeyboardInput); VAR(bAutoPause); VAR(bSaveInputs); VAR(nCDEmuSelect); PAT(CDEmuImage); VAR(nLoadMenuShowX); VAR(nLoadMenuBoardTypeFilter); VAR(nLoadMenuGenreFilter); VAR(nLoadMenuFamilyFilter); STR(szAppRomPaths[0]); STR(szAppRomPaths[1]); STR(szAppRomPaths[2]); STR(szAppRomPaths[3]); STR(szAppRomPaths[4]); STR(szAppRomPaths[5]); STR(szAppRomPaths[6]); STR(szAppRomPaths[7]); STR(szNeoCDGamesDir); STR(szAppPreviewsPath); STR(szAppTitlesPath); STR(szAppCheatsPath); STR(szAppHiscorePath); STR(szAppSamplesPath); STR(szAppIpsPath); STR(szNeoCDCoverDir); VAR(bNoChangeNumLock); VAR(EnableHiscores); VAR(nIpsSelectedLanguage); STR(szPrevGames[0]); STR(szPrevGames[1]); STR(szPrevGames[2]); STR(szPrevGames[3]); STR(szPrevGames[4]); STR(szPrevGames[5]); STR(szPrevGames[6]); STR(szPrevGames[7]); STR(szPrevGames[8]); STR(szPrevGames[9]); // MVS cartridges DRV(nBurnDrvSelect[0]); DRV(nBurnDrvSelect[1]); DRV(nBurnDrvSelect[2]); DRV(nBurnDrvSelect[3]); DRV(nBurnDrvSelect[4]); DRV(nBurnDrvSelect[5]); VAR(bNeoCDListScanSub); VAR(bNeoCDListScanOnlyISO); // Default Controls VAR(nPlayerDefaultControls[0]); STR(szPlayerDefaultIni[0]); VAR(nPlayerDefaultControls[1]); STR(szPlayerDefaultIni[1]); VAR(nPlayerDefaultControls[2]); STR(szPlayerDefaultIni[2]); VAR(nPlayerDefaultControls[3]); STR(szPlayerDefaultIni[3]); #undef DRV #undef PAT #undef STR #undef FLT #undef VAR #undef VAR64 } fclose(h); return 0; }
bool CGLCG::loadTGA(const TCHAR *filename, STGA& tgaFile) { FILE *file; unsigned char type[4]; unsigned char info[6]; file = _tfopen(filename, TEXT("rb")); if (!file) return false; fread (&type, sizeof (char), 3, file); fseek (file, 12, SEEK_SET); fread (&info, sizeof (char), 6, file); //image type either 2 (color) or 3 (greyscale) if (type[1] != 0 || (type[2] != 2 && type[2] != 3)) { fclose(file); return false; } tgaFile.width = info[0] + info[1] * 256; tgaFile.height = info[2] + info[3] * 256; tgaFile.byteCount = info[4] / 8; if (tgaFile.byteCount != 3 && tgaFile.byteCount != 4) { fclose(file); return false; } long imageSize = tgaFile.width * tgaFile.height * tgaFile.byteCount; //allocate memory for image data unsigned char *tempBuf = new unsigned char[imageSize]; tgaFile.data = new unsigned char[tgaFile.width * tgaFile.height * 4]; //read in image data fread(tempBuf, sizeof(unsigned char), imageSize, file); //swap line order and convert to RBGA for(int i=0;i<tgaFile.height;i++) { unsigned char* source = tempBuf + tgaFile.width * (tgaFile.height - 1 - i) * tgaFile.byteCount; unsigned char* destination = tgaFile.data + tgaFile.width * i * 4; for(int j=0;j<tgaFile.width;j++) { destination[0]=source[2]; destination[1]=source[1]; destination[2]=source[0]; destination[3]=tgaFile.byteCount==4?source[3]:0xff; source+=tgaFile.byteCount; destination+=4; } } delete [] tempBuf; tgaFile.byteCount = 4; //close file fclose(file); return true; }
int PNGDIB_DECL pngdib_p2d_run(PNGDIB *qq) { struct p2d_struct *p2d; png_structp png_ptr; png_infop info_ptr; jmp_buf jbuf; struct errstruct errinfo; png_uint_32 width, height; int png_bit_depth, color_type, interlace_type; png_colorp png_palette; png_uint_32 res_x, res_y; int has_phys, has_gama; int res_unit_type; FILE *fp; int palette_entries; unsigned char **row_pointers; unsigned char *lpdib; unsigned char *dib_palette; unsigned char *dib_bits; unsigned char *tmprow; int dib_bpp, dib_bytesperrow; int i,j; int rv; png_color_16 bkgd; // used with png_set_background int has_trns, trns_color; int has_bkgd; // ==1 if there a bkgd chunk, and USE_BKGD flag png_color_16p temp_colorp; png_color_16p bg_colorp; // background color (if has_bkgd) png_bytep trns_trans; int manual_trns; int manual_gamma; struct PNGD_COLOR_struct bkgd_color; int is_grayscale,has_alpha_channel; double file_gamma; int dib_alpha32; int write_bitfields; p2d=(struct p2d_struct*)qq; dib_alpha32=0; write_bitfields=0; manual_trns=0; has_trns=has_bkgd=0; rv=PNGD_E_ERROR; png_ptr=NULL; info_ptr=NULL; fp=NULL; row_pointers=NULL; lpdib=NULL; StringCchCopy(p2d->common.errmsg,PNGDIB_ERRMSG_MAX,_T("")); if(p2d->use_custom_bg_flag) { bkgd_color.red= p2d->bgcolor.red; bkgd_color.green= p2d->bgcolor.green; bkgd_color.blue= p2d->bgcolor.blue; } else { bkgd_color.red= 255; // Should never get used. If the bkgd_color.green= 128; // background turns orange, it's a bug. bkgd_color.blue= 0; } // Set the user-defined pointer to point to our jmp_buf. This will // hopefully protect against potentially different sized jmp_buf's in // libpng, while still allowing this library to be threadsafe. errinfo.jbufp = &jbuf; errinfo.errmsg = p2d->common.errmsg; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,(void*)(&errinfo), my_png_error_fn, my_png_warning_fn); if(!png_ptr) { rv=PNGD_E_NOMEM; goto abort; } if(p2d->common.pngptrhook_function) { (*(p2d->common.pngptrhook_function))(p2d->common.userdata,(void*)png_ptr); } info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { //png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); rv=PNGD_E_NOMEM; goto abort; } if(setjmp(jbuf)) { // we'll get here if an error occurred in any of the following // png_ functions rv=PNGD_E_LIBPNG; goto abort; } if(p2d->input_method==PNGD_IO_METHOD_FILENAME) { // reading from a filename if(!p2d->input_filename) { StringCchPrintf(p2d->common.errmsg,PNGDIB_ERRMSG_MAX,_T("Input filename not set")); rv=PNGD_E_ERROR; goto abort; } if((fp = _tfopen(p2d->input_filename,_T("rb"))) == NULL) { rv=PNGD_E_READ; goto abort; } png_init_io(png_ptr, fp); } else if(p2d->input_method==PNGD_IO_METHOD_MEMBLK) { // reading from a memory block p2d->input_memblk_curpos=0; png_set_read_fn(png_ptr, (void*)p2d, my_png_read_fn); } else if(p2d->input_method==PNGD_IO_METHOD_CUSTOM) { png_set_read_fn(png_ptr, (void*)p2d, my_png_read_fn_custom); } else { goto abort; } png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &width, &height, &png_bit_depth, &color_type, &interlace_type, NULL, NULL); p2d->color_type=color_type; p2d->bits_per_sample=png_bit_depth; p2d->interlace=interlace_type; switch(color_type) { case PNG_COLOR_TYPE_RGB: p2d->bits_per_pixel=png_bit_depth*3; break; case PNG_COLOR_TYPE_RGB_ALPHA: p2d->bits_per_pixel=png_bit_depth*4; break; case PNG_COLOR_TYPE_GRAY_ALPHA: p2d->bits_per_pixel=png_bit_depth*2; break; default: p2d->bits_per_pixel=png_bit_depth; } is_grayscale = !(color_type&PNG_COLOR_MASK_COLOR); has_alpha_channel = (color_type&PNG_COLOR_MASK_ALPHA)?1:0; has_trns = png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS); if(p2d->common.dib_alpha32 && (has_trns || has_alpha_channel)) { // Fixme - if trns(for palette) has no transparent entries, // we could skip this. dib_alpha32=1; write_bitfields=1; if (!(color_type&PNG_COLOR_MASK_COLOR)) { png_set_gray_to_rgb(png_ptr); } else if(color_type==PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); } if (has_trns) png_set_tRNS_to_alpha(png_ptr); goto notrans; } // look for bKGD chunk, and process if applicable if(p2d->use_file_bg_flag) { if(png_get_bKGD(png_ptr, info_ptr, &bg_colorp)) { // process the background, store 8-bit RGB in bkgd_color has_bkgd=1; if(is_grayscale && png_bit_depth<8) { bkgd_color.red = bkgd_color.green= bkgd_color.blue = (unsigned char) ( (bg_colorp->gray*255)/( (1<<png_bit_depth)-1 ) ); } else if(png_bit_depth<=8) { bkgd_color.red=(unsigned char)(bg_colorp->red); bkgd_color.green=(unsigned char)(bg_colorp->green); bkgd_color.blue =(unsigned char)(bg_colorp->blue); } else { bkgd_color.red=(unsigned char)(bg_colorp->red>>8); bkgd_color.green=(unsigned char)(bg_colorp->green>>8); bkgd_color.blue =(unsigned char)(bg_colorp->blue>>8); } } }
void SaveBitmap(TCHAR *szFilename,HBITMAP hBitmap) { HDC hdc=NULL; FILE* fp=NULL; LPVOID pBuf=NULL; BITMAPINFO bmpInfo; BITMAPFILEHEADER bmpFileHeader; DWORD dwBufSize = 0; do{ hdc=GetDC(NULL); ZeroMemory(&bmpInfo,sizeof(BITMAPINFO)); bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); GetDIBits(hdc,hBitmap,0,0,NULL,&bmpInfo,DIB_RGB_COLORS); if(bmpInfo.bmiHeader.biSizeImage<=0) bmpInfo.bmiHeader.biSizeImage=(bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biBitCount+31)/32*4*abs(bmpInfo.bmiHeader.biHeight); if((pBuf=malloc(bmpInfo.bmiHeader.biSizeImage))==NULL) { MessageBox(NULL,_T("Unable to Allocate Bitmap Memory"),_T("Error"),MB_OK|MB_ICONERROR); break; } bmpInfo.bmiHeader.biCompression=BI_RGB; GetDIBits(hdc,hBitmap,0,bmpInfo.bmiHeader.biHeight,pBuf,&bmpInfo,DIB_RGB_COLORS); if(bmpInfo.bmiHeader.biCompression==BI_RGB){ dwBufSize = bmpInfo.bmiHeader.biSizeImage; bmpInfo.bmiHeader.biSizeImage = 0; } BYTE *image_buffer = (BYTE*)pBuf; /*for (int i=0, j=0; j < bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight*4; i+=3, j+=4) { *(image_buffer+i)=*(image_buffer+j+2); *(image_buffer+i+1)=*(image_buffer+j+1); *(image_buffer+i+2)=*(image_buffer+j); }*/ //savejpeg("ok.jpg", image_buffer, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight, 3); if((fp=_tfopen(szFilename,_T("wb")))==NULL) { MessageBox(NULL,_T("Unable to Create Bitmap File"),_T("Error"),MB_OK|MB_ICONERROR); break; } bmpFileHeader.bfReserved1=0; bmpFileHeader.bfReserved2=0; bmpFileHeader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+dwBufSize; bmpFileHeader.bfType='MB'; bmpFileHeader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,fp); fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp); fwrite(pBuf,dwBufSize,1,fp); }while(false); if(hdc) ReleaseDC(NULL,hdc); if(pBuf) free(pBuf); if(fp) fclose(fp); }
void CAviHelper::BMPtoAVI(const wstring& szAVIName, const wstring& strBDir) { CFileFind finder; CString strBmpDir; strBmpDir.Format(_T("%s\\*.*"), strBDir.c_str()); AVIFileInit(); AVISTREAMINFO strhdr; PAVIFILE pfile; PAVISTREAM ps; int nFrames =0; HRESULT hr; BOOL bFind = finder.FindFile(strBmpDir); while(bFind) { bFind = finder.FindNextFile(); if(!finder.IsDots() && !finder.IsDirectory()) { CString str = finder.GetFilePath(); FILE *fp = _tfopen(str, _T("rb")); BITMAPFILEHEADER bmpFileHdr; BITMAPINFOHEADER bmpInfoHdr; fseek( fp,0,SEEK_SET); fread(&bmpFileHdr,sizeof(BITMAPFILEHEADER),1, fp); fread(&bmpInfoHdr,sizeof(BITMAPINFOHEADER),1, fp); BYTE *tmp_buf = NULL; if(nFrames ==0 ) { AVIFileOpen(&pfile, WS2S(szAVIName).c_str(), OF_WRITE | OF_CREATE,NULL); memset(&strhdr, 0, sizeof(strhdr)); strhdr.fccType = streamtypeVIDEO;// stream type strhdr.fccHandler = 0; strhdr.dwScale = 1; strhdr.dwRate = 15; // 15 fps strhdr.dwSuggestedBufferSize = bmpInfoHdr.biSizeImage ; SetRect(&strhdr.rcFrame, 0, 0, bmpInfoHdr.biWidth, bmpInfoHdr.biHeight); // And create the stream; hr = AVIFileCreateStream(pfile,&ps,&strhdr); // hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr)); } tmp_buf = new BYTE[bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3]; fread(tmp_buf, 1, bmpInfoHdr.biWidth * bmpInfoHdr.biHeight * 3, fp); hr = AVIStreamSetFormat(ps,nFrames,&bmpInfoHdr,sizeof(bmpInfoHdr)); hr = AVIStreamWrite(ps, // stream pointer nFrames , // time of this frame 1, // number to write (LPBYTE) tmp_buf, bmpInfoHdr.biSizeImage , // size of this frame AVIIF_KEYFRAME, // flags.... NULL, NULL); nFrames ++; fclose(fp); } } AVIStreamClose(ps); if(pfile != NULL) AVIFileRelease(pfile); AVIFileExit(); }
void CCDecoder::DecodeCC(BYTE* buff, int len, __int64 time) { if(!m_rawfn.IsEmpty()) { if(FILE* f = _tfopen(m_rawfn, _T("at"))) { _ftprintf(f, _T("%02d:%02d:%02d.%03d\n"), (int)(time/1000/60/60), (int)((time/1000/60)%60), (int)((time/1000)%60), (int)(time%1000)); for(int i = 0; i < len; i++) { _ftprintf(f, _T("%02x"), buff[i]); if(i < len-1) _ftprintf(f, _T(" ")); if(i > 0 && (i&15)==15) _ftprintf(f, _T("\n")); } if(len > 0) _ftprintf(f, _T("\n\n")); fclose(f); } } for(int i = 0; i < len; i++) { BYTE c = buff[i]&0x7f; if(c >= 0x20) { static WCHAR charmap[0x60] = { ' ','!','"','#','$','%','&','\'','(',')','?','+',',','-','.','/', '0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?', '@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z','[','?',']','?','?', '?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z','?','?','N','n','?' }; PutChar(charmap[c - 0x20]); } else if(buff[i] != 0x80 && i < len-1) { // codes and special characters are supposed to be doubled if(i < len-3 && buff[i] == buff[i+2] && buff[i+1] == buff[i+3]) i += 2; c = buff[i+1]&0x7f; if(buff[i] == 0x91 && c >= 0x20 && c < 0x30) // formating { // TODO } else if(buff[i] == 0x91 && c == 0x39) // transparent space { OffsetCursor(1, 0); } else if(buff[i] == 0x91 && c >= 0x30 && c < 0x40) // special characters { static WCHAR charmap[0x10] = { 0x00ae, // (r)egistered 0x00b0, // degree 0x00bd, // 1/2 0x00bf, // inverted question mark 0x2122, // trade mark 0x00a2, // cent 0x00a3, // pound 0x266a, // music 0x00e0, // a` 0x00ff, // transparent space, handled above 0x00e8, // e` 0x00e2, // a^ 0x00ea, // e^ 0x00ee, // i^ 0x00f4, // o^ 0x00fb, // u^ }; PutChar(charmap[c - 0x30]); } else if(buff[i] == 0x92 && c >= 0x20 && c < 0x40) // extended characters { static WCHAR charmap[0x20] = { 0x00c0, // A' 0x00c9, // E' 0x00d3, // O' 0x00da, // U' 0x00dc, // U: 0x00fc, // u: 0x2018, // ` 0x00a1, // inverted ! 0x002a, // * 0x2019, // ' 0x002d, // - 0x00a9, // (c)opyright 0x2120, // SM 0x00b7, // . (dot in the middle) 0x201c, // inverted " 0x201d, // " 0x00c1, // A` 0x00c2, // A^ 0x00c7, // C, 0x00c8, // E` 0x00ca, // E^ 0x00cb, // E: 0x00eb, // e: 0x00ce, // I^ 0x00cf, // I: 0x00ef, // i: 0x00d4, // O^ 0x00d9, // U` 0x00f9, // u` 0x00db, // U^ 0x00ab, // << 0x00bb, // >> }; PutChar(charmap[c - 0x20]); } else if(buff[i] == 0x13 && c >= 0x20 && c < 0x40) // more extended characters { static WCHAR charmap[0x20] = { 0x00c3, // A~ 0x00e3, // a~ 0x00cd, // I' 0x00cc, // I` 0x00ec, // i` 0x00d2, // O` 0x00f2, // o` 0x00d5, // O~ 0x00f5, // o~ 0x007b, // { 0x007d, // } 0x005c, // /* \ */ 0x005e, // ^ 0x005f, // _ 0x00a6, // | 0x007e, // ~ 0x00c4, // A: 0x00e4, // a: 0x00d6, // O: 0x00f6, // o: 0x00df, // B (ss in german) 0x00a5, // Y= 0x00a4, // ox 0x007c, // | 0x00c5, // Ao 0x00e5, // ao 0x00d8, // O/ 0x00f8, // o/ 0x250c, // |- 0x2510, // -| 0x2514, // |_ 0x2518, // _| }; PutChar(charmap[c - 0x20]); } else if(buff[i] == 0x94 && buff[i+1] == 0xae) // Erase Non-displayed [buffer] Memory { memset(m_buff, 0, sizeof(m_buff)); } else if(buff[i] == 0x94 && buff[i+1] == 0x20) // Resume Caption Loading { memset(m_buff, 0, sizeof(m_buff)); } else if(buff[i] == 0x94 && buff[i+1] == 0x2f) // End Of Caption { if(memcmp(m_disp, m_buff, sizeof(m_disp)) != 0) { if(m_fEndOfCaption) SaveDisp(time + (i/2)*1000/30); m_fEndOfCaption = true; memcpy(m_disp, m_buff, sizeof(m_disp)); m_time = time + (i/2)*1000/30; } } else if(buff[i] == 0x94 && buff[i+1] == 0x2c) // Erase Displayed Memory { if(m_fEndOfCaption) { m_fEndOfCaption = false; SaveDisp(time + (i/2)*1000/30); } memset(m_disp, 0, sizeof(m_disp)); } else if(buff[i] == 0x97 && (buff[i+1] == 0xa1 || buff[i+1] == 0xa2 || buff[i+1] == 0x23)) // Tab Over { OffsetCursor(buff[i+1]&3, 0); } else if(buff[i] == 0x91 || buff[i] == 0x92 || buff[i] == 0x15 || buff[i] == 0x16 || buff[i] == 0x97 || buff[i] == 0x10 || buff[i] == 0x13 || buff[i] == 0x94) // curpos, color, underline { int row = 0; switch(buff[i]) { default: case 0x91: row = 0; break; case 0x92: row = 2; break; case 0x15: row = 4; break; case 0x16: row = 6; break; case 0x97: row = 8; break; case 0x10: row = 10; break; case 0x13: row = 12; break; case 0x94: row = 14; break; } if(buff[i+1]&0x20) row++; int col = buff[i+1]&0xe; if(col == 0 || (col > 0 && !(buff[i+1]&0x10))) col = 0; else col <<= 1; MoveCursor(col, row); } else { int iiii = 0; } i++; } } }
// A helper function that creates a error report for testing BOOL TestUtils::CreateErrorReport(CString sTmpFolder, CString& sErrorReportName, CString& sMD5Hash) { BOOL bStatus = FALSE; CString sReportFolder; DWORD dwExitCode = 1; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; CString sSearchPattern = sTmpFolder + "\\*.zip"; CString sMD5FileName; FILE* f = NULL; TCHAR szHashBuff[256] = _T(""); HKEY hKey = NULL; LONG lResult = -1; CString sKeyName = _T("Software\\CrashRpt&ၸwer\\应用程序名称"); CString sKeyName2 = _T("HKEY_CURRENT_USER\\") + sKeyName; lResult = RegCreateKey(HKEY_CURRENT_USER, sKeyName, &hKey); if(lResult!=ERROR_SUCCESS) goto cleanup; DWORD dwVal = 12345; lResult = RegSetValueEx(hKey, _T("Value$%^!@#&123fer"), 0, REG_DWORD, (LPBYTE)&dwVal, sizeof(DWORD)); if(lResult!=ERROR_SUCCESS) goto cleanup; CR_INSTALL_INFOW infoW; memset(&infoW, 0, sizeof(CR_INSTALL_INFOW)); infoW.cb = sizeof(CR_INSTALL_INFOW); infoW.pszAppName = L"My& app Name &"; // Use appname with restricted XML characters infoW.pszAppVersion = L"1.0.0 &<'a应> \"<"; infoW.pszErrorReportSaveDir = sTmpFolder; infoW.dwFlags = CR_INST_NO_GUI|CR_INST_DONT_SEND_REPORT|CR_INST_STORE_ZIP_ARCHIVES; int nInstallResult = crInstallW(&infoW); if(nInstallResult!=0) goto cleanup; crAddScreenshot(CR_AS_MAIN_WINDOW); crAddPropertyW(L"CustomProp", L"Property Value"); crAddRegKey(sKeyName2, L"regkey.xml", 0); CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(ei); ei.exctype = CR_SEH_EXCEPTION; ei.code = 0x123; // Generate error report int nGenResult = crGenerateErrorReport(&ei); if(nGenResult!=0) goto cleanup; // Wait until CrashSender process exits WaitForSingleObject(ei.hSenderProcess, INFINITE); // Check exit code GetExitCodeProcess(ei.hSenderProcess, &dwExitCode); if(dwExitCode!=0) goto cleanup; // Get ZIP name hFind = FindFirstFile(sSearchPattern, &ffd); if(hFind==INVALID_HANDLE_VALUE) goto cleanup; sErrorReportName = sTmpFolder + _T("\\") + CString(ffd.cFileName); FindClose(hFind); hFind = NULL; // Get MD5 name sSearchPattern = sTmpFolder + "\\*.md5"; hFind = FindFirstFile(sSearchPattern, &ffd); if(hFind==INVALID_HANDLE_VALUE) goto cleanup; sMD5FileName = sTmpFolder + _T("\\") + CString(ffd.cFileName); #if _MSC_VER < 1400 f = _tfopen(sMD5FileName, _T("rt")); #else _tfopen_s(&f, sMD5FileName, _T("rt")); #endif if(f==NULL) goto cleanup; TCHAR* szHash = _fgetts(szHashBuff, 256, f); if(szHash==NULL) goto cleanup; sMD5Hash = szHash; if(sMD5Hash.GetLength()!=32) goto cleanup; // Hash must be 32 characters in length bStatus = TRUE; cleanup: crUninstall(); if(f!=NULL) fclose(f); if(hFind!=INVALID_HANDLE_VALUE) FindClose(hFind); if(hKey) RegCloseKey(hKey); RegDeleteKey(HKEY_CURRENT_USER, sKeyName); return bStatus; }
void HiscoreInit() { if (!CheckHiscoreAllowed()) return; HiscoresInUse = 0; TCHAR szDatFilename[MAX_PATH]; _stprintf(szDatFilename, _T("%shiscore.dat"), szAppHiscorePath); FILE *fp = _tfopen(szDatFilename, _T("r")); if (fp) { char buffer[MAX_CONFIG_LINE_SIZE]; enum { FIND_NAME, FIND_DATA, FETCH_DATA } mode; mode = FIND_NAME; while (fgets(buffer, MAX_CONFIG_LINE_SIZE, fp)) { if (mode == FIND_NAME) { if (matching_game_name(buffer, BurnDrvGetTextA(DRV_NAME))) { mode = FIND_DATA; } } else { if (is_mem_range(buffer)) { if (nHiscoreNumRanges < HISCORE_MAX_RANGES) { const char *pBuf = buffer; HiscoreMemRange[nHiscoreNumRanges].Loaded = 0; HiscoreMemRange[nHiscoreNumRanges].nCpu = hexstr2num(&pBuf); HiscoreMemRange[nHiscoreNumRanges].Address = hexstr2num(&pBuf); HiscoreMemRange[nHiscoreNumRanges].NumBytes = hexstr2num(&pBuf); HiscoreMemRange[nHiscoreNumRanges].StartValue = hexstr2num(&pBuf); HiscoreMemRange[nHiscoreNumRanges].EndValue = hexstr2num(&pBuf); HiscoreMemRange[nHiscoreNumRanges].ApplyNextFrame = 0; HiscoreMemRange[nHiscoreNumRanges].Applied = 0; HiscoreMemRange[nHiscoreNumRanges].Data = (unsigned char*)malloc(HiscoreMemRange[nHiscoreNumRanges].NumBytes); memset(HiscoreMemRange[nHiscoreNumRanges].Data, 0, HiscoreMemRange[nHiscoreNumRanges].NumBytes); #if 1 && defined FBA_DEBUG bprintf(PRINT_IMPORTANT, _T("Hi Score Memory Range %i Loaded - CPU %i, Address %x, Bytes %02x, Start Val %x, End Val %x\n"), nHiscoreNumRanges, HiscoreMemRange[nHiscoreNumRanges].nCpu, HiscoreMemRange[nHiscoreNumRanges].Address, HiscoreMemRange[nHiscoreNumRanges].NumBytes, HiscoreMemRange[nHiscoreNumRanges].StartValue, HiscoreMemRange[nHiscoreNumRanges].EndValue); #endif nHiscoreNumRanges++; mode = FETCH_DATA; } else { break; } } else { if (mode == FETCH_DATA) break; } } } fclose(fp); } if (nHiscoreNumRanges) HiscoresInUse = 1; TCHAR szFilename[MAX_PATH]; _stprintf(szFilename, _T("%s%s.hi"), szAppHiscorePath, BurnDrvGetText(DRV_NAME)); fp = _tfopen(szFilename, _T("r")); int Offset = 0; if (fp) { unsigned int nSize = 0; while (!feof(fp)) { fgetc(fp); nSize++; } unsigned char *Buffer = (unsigned char*)malloc(nSize); rewind(fp); fgets((char*)Buffer, nSize, fp); for (unsigned int i = 0; i < nHiscoreNumRanges; i++) { for (unsigned int j = 0; j < HiscoreMemRange[i].NumBytes; j++) { HiscoreMemRange[i].Data[j] = Buffer[j + Offset]; } Offset += HiscoreMemRange[i].NumBytes; HiscoreMemRange[i].Loaded = 1; #if 1 && defined FBA_DEBUG bprintf(PRINT_IMPORTANT, _T("Hi Score Memory Range %i Loaded from file\n"), i); #endif } if (Buffer) { free(Buffer); Buffer = NULL; } fclose(fp); } nCpuType = -1; }
int OpenDebugLog() { #if defined (FBA_DEBUG) #if defined (APP_DEBUG_LOG) time_t nTime; tm* tmTime; time(&nTime); tmTime = localtime(&nTime); { // Initialise the debug log file #ifdef _UNICODE DebugLog = _tfopen(_T("zzBurnDebug.html"), _T("wb")); if (ftell(DebugLog) == 0) { WRITE_UNICODE_BOM(DebugLog); _ftprintf(DebugLog, _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">")); _ftprintf(DebugLog, _T("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=unicode\"></head><body><pre>")); } #else DebugLog = _tfopen(_T("zzBurnDebug.html"), _T("wt")); if (ftell(DebugLog) == 0) { _ftprintf(DebugLog, _T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">")); _ftprintf(DebugLog, _T("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=windows-%i\"></head><body><pre>"), GetACP()); } #endif _ftprintf(DebugLog, _T("</font><font size=larger color=#000000>")); _ftprintf(DebugLog, _T("Debug log created by ") _T(APP_TITLE) _T(" v%.20s on %s\n<br>"), szAppBurnVer, _tasctime(tmTime)); } #endif { // Initialise the debug console COORD DebugBufferSize = { 80, 1000 }; { // Since AttachConsole is only present in Windows XP, import it manually #if _WIN32_WINNT >= 0x0500 && defined (_MSC_VER) // #error Manually importing AttachConsole() function, but compiling with _WIN32_WINNT >= 0x0500 if (!AttachConsole(ATTACH_PARENT_PROCESS)) { AllocConsole(); } #else #define ATTACH_PARENT_PROCESS ((DWORD)-1) BOOL (WINAPI* pAttachConsole)(DWORD dwProcessId) = NULL; HINSTANCE hKernel32DLL = LoadLibrary(_T("kernel32.dll")); if (hKernel32DLL) { pAttachConsole = (BOOL (WINAPI*)(DWORD))GetProcAddress(hKernel32DLL, "AttachConsole"); } if (pAttachConsole) { if (!pAttachConsole(ATTACH_PARENT_PROCESS)) { AllocConsole(); } } else { AllocConsole(); } if (hKernel32DLL) { FreeLibrary(hKernel32DLL); } #undef ATTACH_PARENT_PROCESS #endif } DebugBuffer = CreateConsoleScreenBuffer(GENERIC_WRITE, FILE_SHARE_READ, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleScreenBufferSize(DebugBuffer, DebugBufferSize); SetConsoleActiveScreenBuffer(DebugBuffer); SetConsoleTitle(_T(APP_TITLE) _T(" Debug console")); SetConsoleTextAttribute(DebugBuffer, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY); _sntprintf(szConsoleBuffer, 1024, _T("Welcome to the ") _T(APP_TITLE) _T(" debug console.\n")); WriteConsole(DebugBuffer, szConsoleBuffer, _tcslen(szConsoleBuffer), NULL, NULL); SetConsoleTextAttribute(DebugBuffer, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); if (DebugLog) { _sntprintf(szConsoleBuffer, 1024, _T("Debug messages are logged in zzBurnDebug.html")); if (!DebugLog || bEchoLog) { _sntprintf(szConsoleBuffer + _tcslen(szConsoleBuffer), 1024 - _tcslen(szConsoleBuffer), _T(", and echod to this console")); } _sntprintf(szConsoleBuffer + _tcslen(szConsoleBuffer), 1024 - _tcslen(szConsoleBuffer), _T(".\n\n")); } else { _sntprintf(szConsoleBuffer, 1024, _T("Debug messages are echod to this console.\n\n")); } WriteConsole(DebugBuffer, szConsoleBuffer, _tcslen(szConsoleBuffer), NULL, NULL); } nPrevConsoleStatus = -1; bprintf = AppDebugPrintf; // Redirect Burn library debug to our function #endif return 0; }
void makeEXE(HWND hwndDlg) { TCHAR buf[2048]; GetTempPath(MAX_PATH,buf); GetTempFileName(buf,_T("zne"),0,nsifilename); #ifdef _UNICODE FILE *fp=_tfopen(nsifilename,_T("w, ccs=UNICODE")); // generate a Unicode .NSI file BUGBUG: MSVCRT version specific #else FILE *fp=_tfopen(nsifilename,_T("w")); #endif if (!fp) { MessageBox(hwndDlg,_T("Error writing .NSI file"),g_errcaption,MB_OK|MB_ICONSTOP); PostMessage(g_hwnd,WM_NOTIFYENDCOMPILE,0,0); return; } _ftprintf(fp,_T("Unicode %s\n"),IsDlgButtonChecked(hwndDlg,IDC_UNICODE)?_T("true"):_T("false")); GetDlgItemText(hwndDlg,IDC_INSTNAME,buf,sizeof(buf)); _ftprintf(fp,_T("!define ZIP2EXE_NAME `%s`\n"),buf); GetDlgItemText(hwndDlg,IDC_OUTFILE,buf,sizeof(buf)); _ftprintf(fp,_T("!define ZIP2EXE_OUTFILE `%s`\n"),buf); if (g_compressor == 1) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_ZLIB\n")); if (g_compressor == 2) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_BZIP2\n")); if (g_compressor == 3) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_LZMA\n")); if (g_compressor_solid == 1) _ftprintf(fp,_T("!define ZIP2EXE_COMPRESSOR_SOLID\n")); GetDlgItemText(hwndDlg,IDC_INSTPATH,buf,sizeof(buf)); int iswinamp=0; LPCTSTR iswinampmode=NULL; if (!_tcscmp(buf,gp_poi)) lstrcpy(buf,_T("$EXEDIR")); if (!_tcscmp(buf,gp_winamp)) { iswinamp=1; } if (!_tcscmp(buf,gp_winamp_plugins)) { iswinamp=1; _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_PLUGINS\n")); } if (!_tcscmp(buf,gp_winamp_vis)) { iswinamp=1; iswinampmode=_T("VisDir"); } if (!_tcscmp(buf,gp_winamp_dsp)) { iswinamp=1; iswinampmode=_T("DSPDir"); } if (!_tcscmp(buf,gp_winamp_skins)) { iswinamp=1; iswinampmode=_T("SkinDir"); _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_SKINS\n")); } if (iswinamp) { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_WINAMP\n")); if (iswinampmode) { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR_WINAMPMODE `%s`\n"),iswinampmode); } } else // set out path to $INSTDIR { _ftprintf(fp,_T("!define ZIP2EXE_INSTALLDIR `%s`\n"),buf); } _ftprintf(fp,_T("!include `${NSISDIR}\\Contrib\\zip2exe\\Base.nsh`\n")); _ftprintf(fp,_T("!include `${NSISDIR}\\Contrib\\zip2exe\\%s.nsh`\n"),g_mui?_T("Modern"):_T("Classic")); _ftprintf(fp,_T("!insertmacro SECTION_BEGIN\n")); _ftprintf(fp,_T("File /r `%s\\*.*`\n"),tempzip_path); _ftprintf(fp,_T("!insertmacro SECTION_END\n")); fclose(fp); TCHAR g_makensis_path[MAX_PATH]; TCHAR *p=g_makensis_path; GetModuleFileName(g_hInstance,g_makensis_path,sizeof(g_makensis_path)); while (*p) p++; while (p >= g_makensis_path && *p != _T('\\')) p--; _tcscpy(p+1,_T("makensis.exe")); WIN32_FIND_DATA fd; HANDLE h=FindFirstFile(g_makensis_path,&fd); if (h==INVALID_HANDLE_VALUE) { if ((p-g_makensis_path>4)&&(_totlower(*(p-1))==_T('n'))&&(_totlower(*(p-2))==_T('i'))&&(_totlower(*(p-3))==_T('b'))&&(*(p-4)==_T('\\'))) { p -= 4; _tcscpy(p+1,_T("makensis.exe")); h=FindFirstFile(g_makensis_path,&fd); if (h==INVALID_HANDLE_VALUE) { MessageBox(hwndDlg,_T("Error finding makensis.exe."),g_errcaption,MB_OK|MB_ICONSTOP); PostMessage(g_hwnd,WM_NOTIFYENDCOMPILE,0,0); return; } } } if (h!=INVALID_HANDLE_VALUE) FindClose(h); wsprintf(g_cmdline,_T("\"%s\" %s \"%s\""),g_makensis_path,g_options,nsifilename); DWORD id; g_hThread=CreateThread(NULL,0,ThreadProc,0,0,&id); }
static int runxfd(int argc,wchar_t *argv[]) { STARTUPINFO si = { 0 }; PROCESS_INFORMATION pi = { 0 }; TCHAR *src, *dst; TCHAR *parms[5]; FILE *f; _tprintf(_T("uaexfd 0.1b by Toni Wilen (c)2010\n")); if (argc < 2) { _tprintf(_T("uaexfd <source> [<destination>]")); return 0; } if (GetFileAttributes(_T("xfd.uae")) == INVALID_FILE_ATTRIBUTES) { _tprintf(_T("xfd.uae missing\n")); return 0; } if (GetFileAttributes(_T("uaexfd.zip")) == INVALID_FILE_ATTRIBUTES) { _tprintf(_T("uaexfd.zip missing\n")); return 0; } dst = src = argv[1]; if (GetFileAttributes(src) == INVALID_FILE_ATTRIBUTES) { _tprintf(_T("can't open '%s'\n"), src); return 0; } if (argc >= 3) dst = argv[2]; DeleteFile(_T("xfd-in-file.dat")); DeleteFile(_T("xfd-out-file.dat")); DeleteFile(_T("xfd-out-text.txt")); CopyFile(src, _T("xfd-in-file.dat"), FALSE); parms[0] = _T("winuae.com"); parms[1] = _T("-f"); parms[2] = _T("xfd.uae"); parms[3] = _T("-datapath"); parms[4] = _T("."); parms[5] = NULL; if (!runmain(5, parms)) { if (GetFileAttributes(_T("xfd-out-file.dat")) != INVALID_FILE_ATTRIBUTES) { DeleteFile(dst); MoveFile(_T("xfd-out-file.dat"), dst); } f = _tfopen(_T("xfd-out-text.txt"), _T("rb")); if (f) { char tmp[1000]; while (fgets(tmp, sizeof tmp, f)) { if (strlen(tmp) <= 1) continue; for (int i = 0; tmp[i]; i++) { if (tmp[i] == -101 || (tmp[i] == 27 && tmp[i + 1] == '[')) { int j = i + 1; if (tmp[i] == 27) j++; while (tmp[j] > 0 && tmp[j] < 0x40) j++; if (tmp[j]) j++; memmove (tmp + i, tmp + j, strlen(tmp + j) + 1); } } if (tmp[strlen(tmp)-1] == 10) tmp[strlen(tmp)-1] = 0; printf("%s\n", tmp); } fclose(f); } else { _tprintf(_T("startup failed\n")); } } DeleteFile(_T("xfd-in-file.dat")); DeleteFile(_T("xfd-out-file.dat")); DeleteFile(_T("xfd-out-text.txt")); DeleteFile(_T("winuaebootlog.txt")); RemoveDirectory(_T("Host")); RemoveDirectory(_T("Hardware")); return 0; }
void CAviHelper::AVItoBmp(const wstring& strAVIFileName, const wstring& strBmpDir) { AVIFileInit(); PAVIFILE avi; int res = AVIFileOpen(&avi, WS2S(strAVIFileName).c_str(), OF_READ, NULL); int n = GetLastError(); if (res!=AVIERR_OK) { //an error occures if (avi!=NULL) AVIFileRelease(avi); return ; } AVIFILEINFO avi_info; AVIFileInfo(avi, &avi_info, sizeof(AVIFILEINFO)); PAVISTREAM pStream; res=AVIFileGetStream(avi, &pStream, streamtypeVIDEO /*video stream*/, 0 /*first stream*/); if (res!=AVIERR_OK) { if (pStream!=NULL) AVIStreamRelease(pStream); AVIFileExit(); return ; } //do some task with the stream int iNumFrames; int iFirstFrame; iFirstFrame = AVIStreamStart(pStream); if (iFirstFrame==-1) { //Error getteing the frame inside the stream if (pStream!=NULL) AVIStreamRelease(pStream); AVIFileExit(); return ; } iNumFrames = AVIStreamLength(pStream); if (iNumFrames==-1) { //Error getteing the number of frames inside the stream if (pStream!=NULL) AVIStreamRelease(pStream); AVIFileExit(); return ; } //getting bitmap from frame BITMAPINFOHEADER bih; ZeroMemory(&bih, sizeof(BITMAPINFOHEADER)); bih.biBitCount=24; //24 bit per pixel bih.biClrImportant=0; bih.biClrUsed = 0; bih.biCompression = BI_RGB; bih.biPlanes = 1; bih.biSize = 40; bih.biXPelsPerMeter = 0; bih.biYPelsPerMeter = 0; //calculate total size of RGBQUAD scanlines (DWORD aligned) bih.biSizeImage = (((bih.biWidth * 3) + 3) & 0xFFFC) * bih.biHeight ; PGETFRAME pFrame; pFrame=AVIStreamGetFrameOpen(pStream, NULL ); AVISTREAMINFO streaminfo; AVIStreamInfo(pStream,&streaminfo,sizeof(AVISTREAMINFO)); //Get the first frame BITMAPINFOHEADER bih2; long lsize = sizeof(bih2); int index= 0; for (int i = iFirstFrame; i < iNumFrames; i++) { index= i-iFirstFrame; BYTE* pDIB = (BYTE*) AVIStreamGetFrame(pFrame, index); // AVIStreamReadFormat(pStream,index,&bih2,&lsize); BITMAPFILEHEADER stFileHdr; BYTE* Bits=new BYTE[bih2.biSizeImage]; AVIStreamRead(pStream,index,1,Bits,bih2.biSizeImage,NULL,NULL); //RtlMoveMemory(Bits, pDIB + sizeof(BITMAPINFOHEADER), bih2.biSizeImage); bih2.biClrUsed =0; stFileHdr.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); stFileHdr.bfSize=sizeof(BITMAPFILEHEADER); stFileHdr.bfType=0x4d42; CString FileName; FileName.Format(_T("Frame-%05d.bmp"), index); CString strtemp; strtemp.Format(_T("%s\\%s"), strBmpDir.c_str(), FileName); FILE* fp=_tfopen(strtemp ,_T("wb")); fwrite(&stFileHdr,1,sizeof(BITMAPFILEHEADER),fp); fwrite(&bih2,1,sizeof(BITMAPINFOHEADER),fp); int ff = fwrite(Bits,1,bih2.biSizeImage,fp); int e = GetLastError(); fclose(fp); ///// delete Bits; //CreateFromPackedDIBPointer(pDIB, index); } AVIStreamGetFrameClose(pFrame); //close the stream after finishing the task if (pStream!=NULL) AVIStreamRelease(pStream); AVIFileExit(); }
bool CGLCG::loadPngImage(const TCHAR *name, int &outWidth, int &outHeight, bool &outHasAlpha, GLubyte **outData) { png_structp png_ptr; png_infop info_ptr; unsigned int sig_read = 0; int color_type, interlace_type; FILE *fp; if ((fp = _tfopen(name, TEXT("rb"))) == NULL) return false; /* Create and initialize the png_struct * with the desired error handler * functions. If you want to use the * default stderr and longjump method, * you can supply NULL for the last * three parameters. We also supply the * the compiler header file version, so * that we know if the application * was compiled with a compatible version * of the library. REQUIRED */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { fclose(fp); return false; } /* Allocate/initialize the memory * for image information. REQUIRED. */ info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { fclose(fp); png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); return false; } /* Set error handling if you are * using the setjmp/longjmp method * (this is the normal method of * doing things with libpng). * REQUIRED unless you set up * your own error handlers in * the png_create_read_struct() * earlier. */ if (setjmp(png_jmpbuf(png_ptr))) { /* Free all of the memory associated * with the png_ptr and info_ptr */ png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); fclose(fp); /* If we get here, we had a * problem reading the file */ return false; } /* Set up the output control if * you are using standard C streams */ png_init_io(png_ptr, fp); /* If we have already * read some of the signature */ png_set_sig_bytes(png_ptr, sig_read); /* * If you have enough memory to read * in the entire image at once, and * you need to specify only * transforms that can be controlled * with one of the PNG_TRANSFORM_* * bits (this presently excludes * dithering, filling, setting * background, and doing gamma * adjustment), then you can read the * entire image (including pixels) * into the info structure with this * call * * PNG_TRANSFORM_STRIP_16 | * PNG_TRANSFORM_PACKING forces 8 bit * PNG_TRANSFORM_EXPAND forces to * expand a palette into RGB */ png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND, (png_voidp)NULL); outWidth = png_get_image_width(png_ptr, info_ptr); outHeight = png_get_image_height(png_ptr, info_ptr); switch (png_get_color_type(png_ptr, info_ptr)) { case PNG_COLOR_TYPE_RGBA: outHasAlpha = true; break; case PNG_COLOR_TYPE_RGB: outHasAlpha = false; break; default: png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); return false; } unsigned int row_bytes = png_get_rowbytes(png_ptr, info_ptr); *outData = (unsigned char*) malloc(row_bytes * outHeight); png_bytepp row_pointers = png_get_rows(png_ptr, info_ptr); for (int i = 0; i < outHeight; i++) { memcpy(*outData+(row_bytes * i), row_pointers[i], row_bytes); } /* Clean up after the read, * and free any memory allocated */ png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL); /* Close the file */ fclose(fp); /* That's it */ return true; }
int _tmain(int argc, _TCHAR* argv[]) { mpg123_handle *m; int i; if (argc < 3) { fprintf(stderr, "\nI will give you the estimated and exact sample lengths of MPEG audio files.\n"); fprintf(stderr, "\nUsage: %s <mpeg audio file list>\n\n", argv[0]); return -1; } mpg123_init(); m = mpg123_new(NULL, NULL); mpg123_param(m, MPG123_RESYNC_LIMIT, -1, 0); /* New in library version 0.0.1 . */ off_t a, b; if (MPG123_OK != mpg123_open_feed(m)) { fprintf(stderr, "open feed failed"); return -1; } FILE* file = _tfopen(argv[1], TEXT("rb")); if (!file) { fprintf(stderr, "open file failed"); return -1; } _stat64i32 st = { 0 }; _tstat(argv[1], &st); if (st.st_size <= 0) { fprintf(stderr, "file size is zero"); return -1; } char* pDataBuf = new char[st.st_size]; memset(pDataBuf, 0, st.st_size); if (st.st_size != fread(pDataBuf, 1, st.st_size, file)) { fprintf(stderr, "read file error"); return -1; } if (MPG123_OK != mpg123_feed(m, (const unsigned char*)pDataBuf, st.st_size)) { fprintf(stderr, "feed failed"); return -1; } // channels; bool bSaved = false; size_t nDone = 0; int res = mpg123_decode(m, NULL, 0, NULL, 0, &nDone); if (res == MPG123_NEW_FORMAT) { long rate = 0; int channels = 0; int enc = 0; mpg123_getformat(m, &rate, &channels, &enc); if (MPG123_ENC_SIGNED_16 == enc) { int nSamples = mpg123_length(m); int nBufCount = nSamples * channels; int nBufSize = nBufCount * sizeof(short); short* pBuf = new short[nBufCount]; res = mpg123_decode(m, NULL, 0, (unsigned char*)pBuf, nBufSize, &nDone); if (res == MPG123_OK) { KWavFile file; file.Init(pBuf, nDone, rate, ""); file.Save(CT2A(argv[2])); bSaved = true; } if (pBuf) { delete[] pBuf; pBuf = NULL; } } } mpg123_tclose(m); mpg123_delete(m); mpg123_exit(); return 0; }
void CVkProto::OnReciveUploadServer(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq) { CVkFileUploadParam *fup = (CVkFileUploadParam *)pReq->pUserInfo; if (!IsOnline()) { SendFileFiled(fup, VKERR_OFFLINE); return; } debugLogA("CVkProto::OnReciveUploadServer %d", reply->resultCode); if (reply->resultCode != 200) { SendFileFiled(fup, VKERR_INVALID_SERVER); return; } JSONNode jnRoot; const JSONNode &jnResponse = CheckJsonResponse(pReq, reply, jnRoot); if (!jnResponse || pReq->m_iErrorCode) { SendFileFiled(fup, pReq->m_iErrorCode); return; } CMStringA uri(jnResponse["upload_url"].as_mstring()); if (uri.IsEmpty()) { SendFileFiled(fup, VKERR_INVALID_URL); return; } FILE *pFile = _tfopen(fup->FileName, _T("rb")); if (pFile == NULL) { SendFileFiled(fup, VKERR_ERR_OPEN_FILE); return; } fseek(pFile, 0, SEEK_END); long iFileLen = ftell(pFile); //FileSize if (iFileLen < 1) { fclose(pFile); SendFileFiled(fup, VKERR_ERR_READ_FILE); return; } fseek(pFile, 0, SEEK_SET); ProtoBroadcastAck(fup->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, (HANDLE)fup); AsyncHttpRequest *pUploadReq = new AsyncHttpRequest(this, REQUEST_POST, uri, false, &CVkProto::OnReciveUpload); pUploadReq->m_bApiReq = false; pUploadReq->m_szParam = ""; CMStringA boundary, header; CMStringA NamePart = fup->atrName(); CMStringA FNamePart = fup->fileName(); // Boundary int iboundary; Utils_GetRandom(&iboundary, sizeof(iboundary)); boundary.AppendFormat("Miranda%dNG%d", iboundary, time(NULL)); // Header header.AppendFormat("multipart/form-data; boundary=%s", boundary); pUploadReq->AddHeader("Content-Type", header); // Content-Disposition { CMStringA DataBegin = "--"; DataBegin += boundary; DataBegin += "\r\n"; DataBegin += "Content-Disposition: form-data; name=\""; DataBegin += NamePart; DataBegin += "\"; filename=\""; DataBegin += FNamePart; DataBegin += "\";\r\n\r\n"; // } Content-Disposition CMStringA DataEnd = "\r\n--"; DataEnd += boundary; DataEnd += "--\r\n"; // Body size long dataLength = iFileLen + DataBegin.GetLength() + DataEnd.GetLength(); // Body { char* pData = (char *)mir_alloc(dataLength); memcpy(pData, (void *)DataBegin.GetBuffer(), DataBegin.GetLength()); pUploadReq->pData = pData; pData += DataBegin.GetLength(); long lBytes = (long)fread(pData, 1, iFileLen, pFile); fclose(pFile); if (lBytes != iFileLen) { SendFileFiled(fup, VKERR_ERR_READ_FILE); mir_free(pUploadReq->pData); delete pUploadReq; return; } pData += iFileLen; memcpy(pData, (void *)DataEnd.GetBuffer(), DataEnd.GetLength()); // } Body pUploadReq->dataLength = (int)dataLength; pUploadReq->pUserInfo = pReq->pUserInfo; Push(pUploadReq); }
// Read in the config file for the game-specific inputs INT32 ConfigGameLoad(bool bOverWrite) { TCHAR szLine[256]; INT32 nFileVersion = 0; FILE* h = _tfopen(GameConfigName(), _T("rt")); if (h == NULL) { return 1; } if (bOverWrite) { nAnalogSpeed = 0x0100; nBurnCPUSpeedAdjust = 0x0100; } // Go through each line of the config file and process inputs while (_fgetts(szLine, sizeof(szLine), h)) { TCHAR *szValue; INT32 nLen = _tcslen(szLine); // Get rid of the linefeed at the end if (szLine[nLen - 1] == 10) { szLine[nLen - 1] = 0; nLen--; } szValue = LabelCheck(szLine, _T("version")); if (szValue) { nFileVersion = _tcstol(szValue, NULL, 0); } if (bOverWrite) { szValue = LabelCheck(szLine, _T("analog")); if (szValue) { nAnalogSpeed = _tcstol(szValue, NULL, 0); } szValue = LabelCheck(szLine, _T("cpu")); if (szValue) { nBurnCPUSpeedAdjust = _tcstol(szValue, NULL, 0); } } if (nConfigMinVersion <= nFileVersion && nFileVersion <= nBurnVer) { szValue = LabelCheck(szLine, _T("input")); if (szValue) { GameInpRead(szValue, bOverWrite); continue; } szValue = LabelCheck(szLine, _T("macro")); if (szValue) { GameInpMacroRead(szValue, bOverWrite); continue; } szValue = LabelCheck(szLine, _T("custom")); if (szValue) { GameInpCustomRead(szValue, bOverWrite); continue; } } } fclose(h); return 0; }
void MarkLocation(const double lon, const double lat, const double altitude) #endif { #if USETOPOMARKS LockTerrainDataGraphics(); if (topo_marks) { topo_marks->addPoint(lon, lat); topo_marks->triggerUpdateCache = true; } UnlockTerrainDataGraphics(); #endif char message[210]; FILE *stream; TCHAR tstring[50]; bool dopreambol=false; TCHAR fname[MAX_PATH]; LocalPath(fname,TEXT(LKD_WAYPOINTS)); _tcscat(fname,_T(DIRSEP)); _stprintf(tstring,_T("LK%04d%02d%02d.cup"), GPS_INFO.Year,GPS_INFO.Month,GPS_INFO.Day); _tcscat(fname,tstring); stream = _tfopen(fname,TEXT("r")); if (stream == NULL) dopreambol=true; else fclose(stream); stream = _tfopen(fname,TEXT("a+")); if (stream != NULL){ if (dopreambol) { // file was created empty, we need to add preambol header for CUP strcpy(message,"name,code,country,lat,lon,elev,style,rwdir,rwlen,freq,desc\r\n"); fwrite(message,strlen(message),1,stream); } char marktime[10], slat[20], slon[20], snear[50]; Units::TimeToTextSimple(tstring,TimeLocal((int)GPS_INFO.Time)); TCHAR2ascii(tstring,marktime,10); LatitudeToCUPString(lat,tstring); TCHAR2ascii(tstring,slat,20); LongitudeToCUPString(lon,tstring); TCHAR2ascii(tstring,slon,20); int j=FindNearestFarVisibleWayPoint(lon,lat,15000,WPT_UNKNOWN); if (j>0) { _tcscpy(tstring,WayPointList[j].Name); // Name is sized NAME_SIZE, 30, so ok with tstring[50] tstring[19]='\0'; // sized 20 chars TCHAR2ascii(tstring,snear,50); } else { strcpy(snear,"unknown"); } sprintf(message,"MK%s%02d,LK8000,,%s,%s,%d.0m,1,,,,Created on %02d-%02d-%04d at h%s near: %s\r\n", marktime,GPS_INFO.Second,slat,slon, iround((int)altitude), GPS_INFO.Day,GPS_INFO.Month,GPS_INFO.Year, marktime, snear ); fwrite(message,strlen(message),1,stream); fclose(stream); j=GetVirtualWaypointMarkerSlot(); WayPointList[j].Latitude=lat; WayPointList[j].Longitude=lon; WayPointList[j].Altitude=altitude; WayPointList[j].Visible=TRUE; WayPointList[j].FarVisible=TRUE; ascii2TCHAR(marktime, tstring,50); _stprintf(WayPointList[j].Name,_T("MK%s%02d"),tstring,GPS_INFO.Second); #if BUGSTOP LKASSERT(WayPointList[j].Comment!=NULL); #endif if (WayPointList[j].Comment!=NULL) { ascii2TCHAR(snear, tstring, 50); _stprintf(WayPointList[j].Comment,_T("Near: %s"),tstring); } WayPointCalc[j].WpType=WPT_TURNPOINT; // Force updating DoRange otherwise it will pass up to 3 minutes // before this marker appears in the 2.3 tps page LastDoRangeWaypointListTime=0; } }
int _tmain(int argc, _TCHAR* argv[]) { c_simplestring_ptr buffer = NULL; char binary_string[512]; c_regex_ptr regex = NULL; c_iterator_ptr iter = NULL; int retval = 0; const char* regex_str = NULL; #ifdef DEBUG_STATE char* state = NULL; #endif /* DEBUG_STATE */ #ifdef YYDEBUG #if YYDEBUG == 1 rexgen_debug = 1; #endif #endif rexgen_setlocale(); regex_str = rexgen_parse_arguments(argc, argv); if (regex_str == NULL) { rexgen_usage(); return 1; } if (infile_name != NULL) { if (0 == _tcscmp(infile_name, _T("-"))) { infile = stdin; } else { infile = _tfopen(infile_name, _T("r")); if (infile == NULL) { perror("unable to open input file"); return 1; } } } regex = c_regex_cb(regex_str, callback); if (regex == NULL) { fprintf(stderr, "Syntax Error:\n%s\n", c_rexgen_get_last_error()); retval = 1; goto cleanup_and_exit; } if (c_regex_uses_callback(regex) && infile == NULL) { fprintf(stderr, "You must specify a filename when you use '\\0'\n"); retval = 1; goto cleanup_and_exit; } iter = c_regex_iterator(regex); if (iter == NULL) { fprintf(stderr, "Syntax Error:\n%s\n", c_rexgen_get_last_error()); retval = 1; goto cleanup_and_exit; } /* to test restore state, simply put the restore string here, AND use exactly the same regex input string */ /* c_iterator_set_state(iter, "RXS1.1,b,0,3,1,1,2,0,9,0,0,a,1,1,0"); */ /* */ #ifdef DEBUG_STATE c_iterator_get_state(iter, &state); printf ("initial state = %s\n", state); c_iterator_delete_state_buffer(state); #endif /* DEBUG_STATE */ buffer = c_simplestring_new(); while (c_iterator_next(iter)) { c_iterator_value(iter, buffer); encoder(buffer, binary_string, sizeof(binary_string)); printf("%s\n", binary_string); #ifdef DEBUG_STATE /* These show how to save-restore state */ c_iterator_get_state(iter, &state); printf ("state = %s\n", state); c_iterator_set_state(iter, state); c_iterator_delete_state_buffer(state); #endif /* DEBUG_STATE */ c_simplestring_clear(buffer); } #ifdef DEBUG_STATE c_iterator_get_state(iter, &state); printf ("final state = %s\n", state); c_iterator_delete_state_buffer(state); #endif /* DEBUG_STATE */ cleanup_and_exit: c_simplestring_delete(buffer); c_iterator_delete(iter); c_regex_delete(regex); #if defined(_WIN32) && defined(_DEBUG) getchar(); #endif return retval; }
// Write out the config file for the whole application int ConfigAppSave() { TCHAR szConfig[MAX_PATH]; FILE *h; if (bCmdOptUsed) { return 1; } #ifdef _UNICODE setlocale(LC_ALL, ""); #endif CreateConfigName(szConfig); if ((h = _tfopen(szConfig, _T("wt"))) == NULL) { return 1; } // Write title _ftprintf(h, _T("// ") _T(APP_TITLE) _T(" v%s --- Main Config File\n\n"), szAppBurnVer); _ftprintf(h, _T("// Don't edit this file manually unless you know what you're doing\n")); _ftprintf(h, _T("// ") _T(APP_TITLE) _T(" will restore default settings when this file is deleted\n")); #define VAR(x) _ftprintf(h, _T(#x) _T(" %d\n"), x) #define VAR64(x) _ftprintf(h, _T(#x) _T(" %lf\n"), (float)x) #define FLT(x) _ftprintf(h, _T(#x) _T(" %lf\n"), x) #define STR(x) _ftprintf(h, _T(#x) _T(" %s\n"), x) #define DRV(x) _ftprintf(h, _T(#x) _T(" %s\n"), DriverToName(x)) _ftprintf(h, _T("\n// The application version this file was saved from\n")); // We can't use the macros for this! _ftprintf(h, _T("nIniVersion 0x%06X"), nBurnVer); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- emulation --------------------------------------------------------------\n")); _ftprintf(h, _T("\n// If non-zero, use A68K for MC68000 emulation\n")); VAR(bBurnUseASMCPUEmulation); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- Video ------------------------------------------------------------------\n")); // Horizontal oriented _ftprintf(h, _T("\n// (Horizontal Oriented) The display mode to use for fullscreen\n")); VAR(nVidHorWidth); VAR(nVidHorHeight); _ftprintf(h, _T("\n// (Horizontal Oriented) If non-zero, use the same fullscreen resolution as the original arcade game\n")); VAR(bVidArcaderesHor); _ftprintf(h, _T("\n// (Horizontal Oriented) The preset resolutions appearing in the menu\n")); VAR(VidPreset[0].nWidth); VAR(VidPreset[0].nHeight); VAR(VidPreset[1].nWidth); VAR(VidPreset[1].nHeight); VAR(VidPreset[2].nWidth); VAR(VidPreset[2].nHeight); VAR(VidPreset[3].nWidth); VAR(VidPreset[3].nHeight); _ftprintf(h, _T("\n// (Horizontal Oriented) Full-screen size (0 = use display mode variables)\n")); VAR(nScreenSizeHor); // Vertical oriented _ftprintf(h, _T("\n// (Vertical Oriented) The display mode to use for fullscreen\n")); VAR(nVidVerWidth); VAR(nVidVerHeight); _ftprintf(h, _T("\n// (Vertical Oriented) If non-zero, use the same fullscreen resolution as the original arcade game\n")); VAR(bVidArcaderesVer); _ftprintf(h, _T("\n// (Vertical Oriented) The preset resolutions appearing in the menu\n")); VAR(VidPresetVer[0].nWidth); VAR(VidPresetVer[0].nHeight); VAR(VidPresetVer[1].nWidth); VAR(VidPresetVer[1].nHeight); VAR(VidPresetVer[2].nWidth); VAR(VidPresetVer[2].nHeight); VAR(VidPresetVer[3].nWidth); VAR(VidPresetVer[3].nHeight); _ftprintf(h, _T("\n// (Vertical Oriented) Full-screen size (0 = use display mode variables)\n")); VAR(nScreenSizeVer); _ftprintf(h, _T("\n// Full-screen bit depth\n")); VAR(nVidDepth); _ftprintf(h, _T("\n// Specify the refresh rate, 0 = default (changing this will not work with many video cards)\n")); VAR(nVidRefresh); _ftprintf(h, _T("\n// If non-zero, do not rotate the graphics for vertical games\n")); VAR(nVidRotationAdjust); _ftprintf(h, _T("\n// Initial window size (0 = autosize)\n")); VAR(nWindowSize); _ftprintf(h, _T("\n// Window position\n")); VAR(nWindowPosX); VAR(nWindowPosY); _ftprintf(h, _T("\n// If non-zero, perform gamma correction\n")); VAR(bDoGamma); _ftprintf(h, _T("\n// If non-zero, use the video hardware to correct gamma\n")); VAR(bVidUseHardwareGamma); _ftprintf(h, _T("\n// If non-zero, don't fall back on software gamma correction\n")); VAR(bHardwareGammaOnly); _ftprintf(h, _T("\n// Gamma to correct with\n")); FLT(nGamma); _ftprintf(h, _T("\n// If non-zero, auto-switch to fullscreen after loading game\n")); VAR(bVidAutoSwitchFull); _ftprintf(h, _T("\n// If non-zero, allow stretching of the image to any size\n")); VAR(bVidFullStretch); _ftprintf(h, _T("\n// If non-zero, stretch the image to the largest size preserving aspect ratio\n")); VAR(bVidCorrectAspect); _ftprintf(h, _T("\n// If non-zero, try to use a triple buffer in fullscreen\n")); VAR(bVidTripleBuffer); _ftprintf(h, _T("\n// If non-zero, try to synchronise blits with the display\n")); VAR(bVidVSync); _ftprintf(h, _T("\n// If non-zero, try to enable custom DWM parameters on Windows 7, this fixes frame stuttering problems.\n")); // VAR(bVidDWMCore); _ftprintf(h, _T("\n// Transfer method: 0 = blit from system memory / use driver/DirectX texture management;\n")); _ftprintf(h, _T("// 1 = copy to a video memory surface, then use bltfast();\n")); _ftprintf(h, _T("// -1 = autodetect for DirectDraw, equals 1 for Direct3D\n")); VAR(nVidTransferMethod); _ftprintf(h, _T("\n// If non-zero, draw scanlines to simulate a low-res monitor\n")); VAR(bVidScanlines); _ftprintf(h, _T("\n// Maximum scanline intensity\n")); VAR(nVidScanIntensity); _ftprintf(h, _T("\n// If non-zero, rotate scanlines and RGB effects for rotated games\n")); VAR(bVidScanRotate); _ftprintf(h, _T("\n// The selected blitter module\n")); VAR(nVidSelect); _ftprintf(h, _T("\n// Options for the blitter modules\n")); VAR(nVidBlitterOpt[0]); VAR64(nVidBlitterOpt[1]); VAR(nVidBlitterOpt[2]); VAR(nVidBlitterOpt[3]); VAR(nVidBlitterOpt[4]); _ftprintf(h, _T("\n// If non-zero, attempt to auto-detect the monitor aspect ratio\n")); VAR(bMonitorAutoCheck); _ftprintf(h, _T("\n// The aspect ratio of the monitor\n")); VAR(nVidScrnAspectX); VAR(nVidScrnAspectY); _ftprintf(h, _T("\n// If non-zero, force all games to use a 60Hz refresh rate\n")); VAR(bForce60Hz); _ftprintf(h, _T("\n// If non-zero, skip frames when needed to keep the emulation running at full speed\n")); VAR(bAlwaysDrawFrames); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- DirectDraw blitter module settings -------------------------------------\n")); _ftprintf(h, _T("\n// If non-zero, draw scanlines at 50%% intensity\n")); VAR(bVidScanHalf); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- Direct3D 7 blitter module settings -------------------------------------\n")); _ftprintf(h, _T("\n// If non-zero, use bi-linear filtering to display the image\n")); VAR(bVidBilinear); _ftprintf(h, _T("\n// If non-zero, simulate slow phosphors (feedback)\n")); VAR(bVidScanDelay); _ftprintf(h, _T("\n// If non-zero, use bi-linear filtering for the scanlines\n")); VAR(bVidScanBilinear); _ftprintf(h, _T("\n// Feedback amount for slow phosphor simulation\n")); VAR(nVidFeedbackIntensity); _ftprintf(h, _T("\n// Oversaturation amount for slow phosphor simulation\n")); VAR(nVidFeedbackOverSaturation); _ftprintf(h, _T("\n// Angle at wich the emulated screen is tilted (in radians)\n")); FLT(fVidScreenAngle); _ftprintf(h, _T("\n// Angle of the sphere segment used for the 3D screen (in radians)\n")); FLT(fVidScreenCurvature); _ftprintf(h, _T("\n// If non-zero, force 16 bit emulation even in 32-bit screenmodes\n")); VAR(bVidForce16bit); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- DirectX Graphics 9 blitter module settings -----------------------------\n")); _ftprintf(h, _T("\n// The filter parameters for the cubic filter\n")); FLT(dVidCubicB); FLT(dVidCubicC); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- DirectX Graphics 9 Alt blitter module settings -------------------------\n")); _ftprintf(h, _T("\n// If non-zero, use bi-linear filtering to display the image\n")); VAR(bVidDX9Bilinear); _ftprintf(h, _T("\n// If non-zero, use hardware vertex to display the image\n")); VAR(bVidHardwareVertex); _ftprintf(h, _T("\n// If non-zero, use motion blur to display the image\n")); VAR(bVidMotionBlur); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- Sound ------------------------------------------------------------------\n")); _ftprintf(h, _T("\n// The selected audio plugin\n")); VAR(nAudSelect); _ftprintf(h, _T("\n// Number of frames in sound buffer (= sound lag)\n")); VAR(nAudSegCount); _ftprintf(h, _T("\n// The order of PCM/ADPCM interpolation\n")); VAR(nInterpolation); _ftprintf(h, _T("\n// The order of FM interpolation\n")); VAR(nFMInterpolation); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- DirectSound plugin settings --------------------------------------------\n")); _ftprintf(h, _T("\n// Sample rate\n")); VAR(nAudSampleRate[0]); _ftprintf(h, _T("\n// DSP module to use for sound enhancement: 0 = none, 1 = low-pass filter\n")); VAR(nAudDSPModule[0]); _ftprintf(h, _T("\n")); _ftprintf(h, _T("// --- XAudio2 plugin settings ------------------------------------------------\n")); _ftprintf(h, _T("\n// Sample rate\n")); VAR(nAudSampleRate[1]); _ftprintf(h, _T("\n// DSP module to use for sound enhancement: 0 = none, 1 = low-pass filter, 2 = reverb\n")); VAR(nAudDSPModule[1]); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- UI ---------------------------------------------------------------------\n")); _ftprintf(h, _T("\n// Filename of the active UI translation template\n")); STR(szLocalisationTemplate); _ftprintf(h, _T("\n// 1 = display pause/record/replay/kaillera icons in the upper right corner of the display\n")); VAR(nVidSDisplayStatus); _ftprintf(h, _T("\n// Minimum height (in pixels) of the font used for the Kaillera chat function (used for arcade resolution)\n")); VAR(nMinChatFontSize); _ftprintf(h, _T("\n// Maximum height (in pixels) of the font used for the Kaillera chat function (used for 1280x960 or higher).\n")); VAR(nMaxChatFontSize); _ftprintf(h, _T("\n// Make the menu modeless\n")); VAR(bModelessMenu); _ftprintf(h, _T("\n// Minimum length of time to display the splash screen (in milliseconds)\n")); VAR(nSplashTime); _ftprintf(h, _T("\n// If non-zero, load and save all ram (the state)\n")); VAR(bDrvSaveAll); _ftprintf(h, _T("\n// The thread priority for the application. Do *NOT* edit this manually\n")); VAR(nAppThreadPriority); _ftprintf(h, _T("\n// If non-zero, process keyboard input even when the application loses focus\n")); VAR(bAlwaysProcessKeyboardInput); _ftprintf(h, _T("\n// If non-zero, pause when the application loses focus\n")); VAR(bAutoPause); _ftprintf(h, _T("\n// If non-zero, save the inputs for each game\n")); VAR(bSaveInputs); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- CD emulation -----------------------------------------------------------\n")); _ftprintf(h, _T("\n // The selected CD emulation module\n")); VAR(nCDEmuSelect); _ftprintf(h, _T("\n // The path to the CD image to use (.cue or .iso)\n")); STR(CDEmuImage); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- Load Game Dialogs ------------------------------------------------------\n")); _ftprintf(h, _T("\n// Load game dialog options\n")); VAR(nLoadMenuShowX); _ftprintf(h, _T("\n// Load game dialog board type filter options\n")); VAR(nLoadMenuBoardTypeFilter); _ftprintf(h, _T("\n// Load game dialog genre filter options\n")); VAR(nLoadMenuGenreFilter); _ftprintf(h, _T("\n// Load game dialog family filter options\n")); VAR(nLoadMenuFamilyFilter); _ftprintf(h, _T("\n// The paths to search for rom zips (include trailing backslash)\n")); STR(szAppRomPaths[0]); STR(szAppRomPaths[1]); STR(szAppRomPaths[2]); STR(szAppRomPaths[3]); STR(szAppRomPaths[4]); STR(szAppRomPaths[5]); STR(szAppRomPaths[6]); STR(szAppRomPaths[7]); _ftprintf(h, _T("\n// The path to search for Neo Geo CDZ isos\n")); STR(szNeoCDGamesDir); _ftprintf(h, _T("\n// The paths to search for support files (include trailing backslash)\n")); STR(szAppPreviewsPath); STR(szAppTitlesPath); STR(szAppCheatsPath); STR(szAppHiscorePath); STR(szAppSamplesPath); STR(szAppIpsPath); STR(szNeoCDCoverDir); _ftprintf(h, _T("\n// The cartridges to use for emulation of an MVS system\n")); DRV(nBurnDrvSelect[0]); DRV(nBurnDrvSelect[1]); DRV(nBurnDrvSelect[2]); DRV(nBurnDrvSelect[3]); DRV(nBurnDrvSelect[4]); DRV(nBurnDrvSelect[5]); _ftprintf(h, _T("\n// Neo Geo CD Load Game Dialog options\n")); VAR(bNeoCDListScanSub); VAR(bNeoCDListScanOnlyISO); _ftprintf(h, _T("\n\n\n")); _ftprintf(h, _T("// --- miscellaneous ---------------------------------------------------------\n")); _ftprintf(h, _T("\n// If non-zero, don't change the status of the Num Lock key.\n")); VAR(bNoChangeNumLock); _ftprintf(h, _T("\n// If non-zero, enable high score saving support.\n")); VAR(EnableHiscores); _ftprintf(h, _T("\n// The language index to use for the IPS Patch Manager dialog.\n")); VAR(nIpsSelectedLanguage); _ftprintf(h, _T("\n// Previous games list.\n")); STR(szPrevGames[0]); STR(szPrevGames[1]); STR(szPrevGames[2]); STR(szPrevGames[3]); STR(szPrevGames[4]); STR(szPrevGames[5]); STR(szPrevGames[6]); STR(szPrevGames[7]); STR(szPrevGames[8]); STR(szPrevGames[9]); _ftprintf(h, _T("\n// Player default controls, number is the index of the configuration in the input dialog\n")); VAR(nPlayerDefaultControls[0]); STR(szPlayerDefaultIni[0]); VAR(nPlayerDefaultControls[1]); STR(szPlayerDefaultIni[1]); VAR(nPlayerDefaultControls[2]); STR(szPlayerDefaultIni[2]); VAR(nPlayerDefaultControls[3]); STR(szPlayerDefaultIni[3]); _ftprintf(h, _T("\n\n\n")); #undef DRV #undef STR #undef FLT #undef VAR #undef VAR64 fclose(h); return 0; }
void CToxProto::SetToxAvatar(std::tstring path) { FILE *hFile = _tfopen(path.c_str(), L"rb"); if (!hFile) { debugLogA(__FUNCTION__": failed to open avatar file"); return; } fseek(hFile, 0, SEEK_END); size_t length = ftell(hFile); rewind(hFile); if (length > TOX_MAX_AVATAR_SIZE) { fclose(hFile); debugLogA(__FUNCTION__": new avatar size is excessive"); return; } uint8_t *data = (uint8_t*)mir_alloc(length); if (fread(data, sizeof(uint8_t), length, hFile) != length) { fclose(hFile); debugLogA(__FUNCTION__": failed to read avatar file"); mir_free(data); return; } fclose(hFile); DBVARIANT dbv; uint8_t hash[TOX_HASH_LENGTH]; tox_hash(hash, data, TOX_HASH_LENGTH); if (!db_get(NULL, m_szModuleName, TOX_SETTINGS_AVATAR_HASH, &dbv)) { if (memcmp(hash, dbv.pbVal, TOX_HASH_LENGTH) == 0) { db_free(&dbv); mir_free(data); debugLogA(__FUNCTION__": new avatar is same with old"); return; } db_free(&dbv); } db_set_blob(NULL, m_szModuleName, TOX_SETTINGS_AVATAR_HASH, (void*)hash, TOX_HASH_LENGTH); if (IsOnline()) { for (MCONTACT hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName)) { if (GetContactStatus(hContact) == ID_STATUS_OFFLINE) continue; int32_t friendNumber = GetToxFriendNumber(hContact); if (friendNumber == UINT32_MAX) { mir_free(data); debugLogA(__FUNCTION__": failed to set new avatar"); return; } TOX_ERR_FILE_SEND error; uint32_t fileNumber = tox_file_send(tox, friendNumber, TOX_FILE_KIND_AVATAR, length, hash, NULL, 0, &error); if (error != TOX_ERR_FILE_SEND_OK) { mir_free(data); debugLogA(__FUNCTION__": failed to set new avatar"); return; } AvatarTransferParam *transfer = new AvatarTransferParam(friendNumber, fileNumber, NULL, length); transfer->pfts.flags |= PFTS_SENDING; memcpy(transfer->hash, hash, TOX_HASH_LENGTH); transfer->pfts.hContact = hContact; transfer->hFile = _tfopen(path.c_str(), L"rb"); transfers.Add(transfer); } } mir_free(data); }
//--------------------------------------------------------------------------- // ----- Methods :: File Serialize (XML) ----- // //--------------------------------------------------------------------------- bool Strip::Save (const TCHAR* lpszFileName) { // ----- Initialize & Declare ----- // FILE* stream = _tfopen(lpszFileName, _T("wb") CHARSET); if (stream == NULL || _pPimpl == NULL) { return false; } TiXmlDocument doc; TiXmlDeclaration* pDecl; TiXmlElement* pRoot; TiXmlElement* pBlockNode; TiXmlElement* pUnitNode; TiXmlElement* pBallNode; Block* pBlockObject; Unit* pUnitObject; Ball* pBallObject; int vectorBlockSize; int vectorUnitCountX; int vectorUnitCountY; int vectorBallSize; pDecl = new TiXmlDeclaration("1.0", "euc-kr", ""); doc.LinkEndChild(pDecl); // ----- Set a Strip Data ----- // pRoot = new TiXmlElement(ROOT_NAME_STRIP); pRoot->SetDoubleAttribute(ATTR_NAME_WIDTH, _pPimpl->dWidth); pRoot->SetDoubleAttribute(ATTR_NAME_HEIGHT, _pPimpl->dHeight); doc.LinkEndChild(pRoot); // ----- Insert a Block Data ----- // pBlockObject = FirstBlock(); if (pBlockObject != NULL) { do { pBlockNode = new TiXmlElement(NODE_NAME_BLOCK); pBlockNode->SetDoubleAttribute(ATTR_NAME_COLUMN, pBlockObject->GetColumn ()); pBlockNode->SetDoubleAttribute(ATTR_NAME_ROW, pBlockObject->GetRow ()); pBlockNode->SetDoubleAttribute(ATTR_NAME_WIDTH, pBlockObject->GetWidth ()); pBlockNode->SetDoubleAttribute(ATTR_NAME_HEIGHT, pBlockObject->GetHeight ()); pBlockNode->SetDoubleAttribute(ATTR_NAME_START_X, pBlockObject->GetStartX ()); pBlockNode->SetDoubleAttribute(ATTR_NAME_START_Y, pBlockObject->GetStartY ()); // ----- Insert a Unit (in Block) Data ----- // pUnitObject = pBlockObject->FirstUnit(); if (pUnitObject != NULL) { do { pUnitNode = new TiXmlElement(NODE_NAME_UNIT); pUnitNode->SetDoubleAttribute(ATTR_NAME_COLUMN, pUnitObject->GetColumn ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_ROW, pUnitObject->GetRow ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_START_X, pUnitObject->GetStartX ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_START_Y, pUnitObject->GetStartY ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_CENTER_X, pUnitObject->GetCenterX ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_CENTER_Y, pUnitObject->GetCenterY ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_WIDTH, pUnitObject->GetWidth ()); pUnitNode->SetDoubleAttribute(ATTR_NAME_HEIGHT, pUnitObject->GetHeight ()); // ----- Insert a Ball (in Unit) Data ----- // pBallObject = pUnitObject->FirstBall(); if (pBallObject != NULL) { do { pBallNode = new TiXmlElement(NODE_NAME_BALL); pBallNode->SetDoubleAttribute(ATTR_NAME_DIAMETER, pBallObject->GetDiameter ()); pBallNode->SetDoubleAttribute(ATTR_NAME_CENTER_X, pBallObject->GetCenterX ()); pBallNode->SetDoubleAttribute(ATTR_NAME_CENTER_Y, pBallObject->GetCenterY ()); pBallNode->SetDoubleAttribute(ATTR_NAME_BALL_STATUS, pBallObject->GetStatus ()); pUnitNode->LinkEndChild(pBallNode); } while ((pBallObject = pUnitObject->NextBall()) != NULL); } pBlockNode->LinkEndChild(pUnitNode); } while ((pUnitObject = pBlockObject->NextUnit()) != NULL); } pRoot->LinkEndChild(pBlockNode); } while ((pBlockObject = NextBlock()) != NULL); } // ----- Save and Close ----- // doc.SaveFile(stream); fclose(stream); return true; }
void SaveDDSFile(TCHAR* pszFile, AMD_TC_Texture& texture) { FILE* pFile = _tfopen(pszFile, _T("wb")); if(!pFile) return; fwrite(&DDS_HEADER, sizeof(DWORD), 1, pFile); DDSD2 ddsd; memset(&ddsd, 0, sizeof(DDSD2)); ddsd.dwSize = sizeof(DDSD2); ddsd.dwFlags = DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_PIXELFORMAT|DDSD_MIPMAPCOUNT|DDSD_LINEARSIZE; ddsd.dwWidth = texture.dwWidth; ddsd.dwHeight = texture.dwHeight; ddsd.dwMipMapCount = 1; ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT); ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE|DDSCAPS_COMPLEX|DDSCAPS_MIPMAP; ddsd.ddpfPixelFormat.dwFourCC = GetFourCC(texture.format); if(ddsd.ddpfPixelFormat.dwFourCC) { ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; if(IsDXT5SwizzledFormat(texture.format)) { ddsd.ddpfPixelFormat.dwPrivateFormatBitCount = ddsd.ddpfPixelFormat.dwFourCC; ddsd.ddpfPixelFormat.dwFourCC = FOURCC_DXT5; } } else { switch(texture.format) { case AMD_TC_FORMAT_ARGB_8888: ddsd.ddpfPixelFormat.dwRBitMask = 0x00ff0000; ddsd.ddpfPixelFormat.dwGBitMask = 0x0000ff00; ddsd.ddpfPixelFormat.dwBBitMask = 0x000000ff; ddsd.lPitch = texture.dwPitch; ddsd.ddpfPixelFormat.dwRGBBitCount = 32; ddsd.ddpfPixelFormat.dwFlags=DDPF_ALPHAPIXELS|DDPF_RGB; ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0xff000000; break; case AMD_TC_FORMAT_RGB_888: ddsd.ddpfPixelFormat.dwRBitMask = 0x00ff0000; ddsd.ddpfPixelFormat.dwGBitMask = 0x0000ff00; ddsd.ddpfPixelFormat.dwBBitMask = 0x000000ff; ddsd.lPitch = texture.dwPitch; ddsd.ddpfPixelFormat.dwRGBBitCount = 24; ddsd.ddpfPixelFormat.dwFlags=DDPF_RGB; break; case AMD_TC_FORMAT_RG_8: ddsd.ddpfPixelFormat.dwRBitMask = 0x0000ff00; ddsd.ddpfPixelFormat.dwGBitMask = 0x000000ff; ddsd.lPitch = texture.dwPitch; ddsd.ddpfPixelFormat.dwRGBBitCount = 16; ddsd.ddpfPixelFormat.dwFlags=DDPF_ALPHAPIXELS|DDPF_LUMINANCE; ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0xff000000; break; case AMD_TC_FORMAT_R_8: ddsd.ddpfPixelFormat.dwRBitMask = 0x000000ff; ddsd.lPitch = texture.dwPitch; ddsd.ddpfPixelFormat.dwRGBBitCount = 8; ddsd.ddpfPixelFormat.dwFlags= DDPF_LUMINANCE; break; case AMD_TC_FORMAT_ARGB_2101010: ddsd.ddpfPixelFormat.dwRBitMask = 0x000003ff; ddsd.ddpfPixelFormat.dwGBitMask = 0x000ffc00; ddsd.ddpfPixelFormat.dwBBitMask = 0x3ff00000; ddsd.ddpfPixelFormat.dwRGBAlphaBitMask = 0xc0000000; ddsd.lPitch = texture.dwPitch; ddsd.ddpfPixelFormat.dwRGBBitCount = 32; ddsd.ddpfPixelFormat.dwFlags=DDPF_ALPHAPIXELS|DDPF_RGB; break; case AMD_TC_FORMAT_ARGB_16: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC|DDPF_ALPHAPIXELS; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_A16B16G16R16; break; case AMD_TC_FORMAT_RG_16: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_G16R16; break; case AMD_TC_FORMAT_R_16: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_L16; break; case AMD_TC_FORMAT_ARGB_16F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC|DDPF_ALPHAPIXELS; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_A16B16G16R16F; break; case AMD_TC_FORMAT_RG_16F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_G16R16F; break; case AMD_TC_FORMAT_R_16F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_R16F; break; case AMD_TC_FORMAT_ARGB_32F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC|DDPF_ALPHAPIXELS; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_A32B32G32R32F; break; case AMD_TC_FORMAT_RG_32F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_G32R32F; break; case AMD_TC_FORMAT_R_32F: ddsd.dwLinearSize = texture.dwDataSize; ddsd.ddpfPixelFormat.dwFlags = DDPF_FOURCC; ddsd.ddpfPixelFormat.dwFourCC = D3DFMT_R32F; break; default: assert(0); break; } } fwrite(&ddsd, sizeof(DDSD2), 1, pFile); fwrite(texture.pData, texture.dwDataSize, 1, pFile); fclose(pFile); }
int KConfig::_ReadVersionInfo() { int nRetCode = false; int nResult = false; FILE* pVerFile = NULL; TCHAR szVersionFile[MAX_PATH]; TCHAR szBuffer[256]; _tcsncpy(szVersionFile, m_szAppPath, sizeof(szVersionFile) / sizeof(TCHAR)); szVersionFile[sizeof(szVersionFile) / sizeof(TCHAR) - 1] = _T('\0'); nRetCode = (int)(sizeof(szVersionFile) / sizeof(TCHAR) - _tcslen(szVersionFile)); _tcsncat(szVersionFile, VERSION_FILE_NAME, nRetCode); szVersionFile[sizeof(szVersionFile) / sizeof(TCHAR) - 1] = _T('\0'); pVerFile = _tfopen(szVersionFile, _T("r")); KGLOG_PROCESS_ERROR(pVerFile); while (TRUE) { size_t uLength = 0; TCHAR *pRet = _fgetts(szBuffer, sizeof(szBuffer) / sizeof(TCHAR), pVerFile); if (!pRet) { if (ferror(pVerFile)) goto Exit0; else goto Exit1; } szBuffer[sizeof(szBuffer) / sizeof(TCHAR) - 1] = _T('\0'); _StringTrim(szBuffer); if (szBuffer[0] == _T('#')) continue; uLength = _tcslen(PRODUCT_VERSION_KEY); nRetCode = _tcsncicmp(szBuffer, PRODUCT_VERSION_KEY, uLength); if (!nRetCode && szBuffer[uLength] == _T('=')) { _tcsncpy(m_szCurrVersion, szBuffer + uLength + 1, sizeof(m_szCurrVersion) / sizeof(TCHAR)); m_szCurrVersion[sizeof(m_szCurrVersion) / sizeof(TCHAR) - 1] = _T('\0'); _FormatVersion(m_szCurrVersion, _T('.')); } uLength = _tcslen(PRODUCT_VERSION_NAME_KEY); nRetCode = _tcsncicmp(szBuffer, PRODUCT_VERSION_NAME_KEY, uLength); if (!nRetCode && szBuffer[uLength] == _T('=')) { _tcsncpy(m_szVersionLineName, szBuffer + uLength + 1, sizeof(m_szVersionLineName) / sizeof(TCHAR)); m_szVersionLineName[sizeof(m_szVersionLineName) / sizeof(TCHAR) - 1] = _T('\0'); } uLength = _tcslen(PRODUCT_VERSION_EX_KEY); nRetCode = _tcsncicmp(szBuffer, PRODUCT_VERSION_EX_KEY, uLength); if (!nRetCode && szBuffer[uLength] == _T('=')) { _tcsncpy(m_szVersionEx, szBuffer + uLength + 1, sizeof(m_szVersionEx) / sizeof(TCHAR)); m_szVersionEx[sizeof(m_szVersionEx) / sizeof(TCHAR) - 1] = _T('\0'); } uLength = _tcslen(PRODUCT_VERSION_PRODUCT_NAME_KEY); nRetCode = _tcsncicmp(szBuffer, PRODUCT_VERSION_PRODUCT_NAME_KEY, uLength); if (!nRetCode && szBuffer[uLength] == _T('=')) { _tcsncpy(m_szVersionName, szBuffer + uLength + 1, sizeof(m_szVersionName) / sizeof(TCHAR)); m_szVersionName[sizeof(m_szVersionName) / sizeof(TCHAR) - 1] = _T('\0'); } } Exit1: KGLOG_PROCESS_ERROR(m_szCurrVersion[0] != _T('\0')); KGLOG_PROCESS_ERROR(m_szVersionLineName[0] != _T('\0')); if (m_szVersionEx[0] != _T('\0')) { _tcscat(m_szVersionLineName, _T("_")); _tcscat(m_szVersionLineName, m_szVersionEx); } nResult = true; Exit0: if (pVerFile) { fclose(pVerFile); pVerFile = NULL; } return nResult; }
int DBSettingChanged(WPARAM wParam, LPARAM lParam) { // We can't upload changes to NULL contact MCONTACT hContact = wParam; if (hContact == NULL) return 0; DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING *) lParam; if (!mir_strcmp(cws->szModule, "CList")) { int invalidpresent = 0; char *szProto = GetContactProto(hContact); if (szProto == NULL || mir_strcmp(szProto, MODULENAME)) return 0; // A contact is renamed if (!mir_strcmp(cws->szSetting, "MyHandle")) { ptrT oldName( db_get_tsa(hContact, MODULENAME, PRESERVE_NAME_KEY)); if (oldName == NULL) return 0; TCHAR nick[100]; ptrT oldnick( db_get_tsa(hContact, "CList", "MyHandle")); if (oldnick != NULL) _tcsncpy_s(nick, oldnick, _TRUNCATE); else nick[0] = 0; for (int i=0; i < _countof(szInvalidChars); i++ ) { TCHAR *p = _tcschr(nick, szInvalidChars[i]); if (p != NULL) { WErrorPopup((UINT_PTR)"ERROR", TranslateT("Invalid symbol present in contact name.")); *p = '_'; invalidpresent =1; } } if (invalidpresent) { srand((unsigned)time(NULL)); TCHAR ranStr[7]; _itot((int)10000 *rand() / (RAND_MAX + 1.0), ranStr, 10); mir_tstrcat(nick, ranStr); } if ( _tcschr(nick, '(') == 0) { db_set_ts(hContact, MODULENAME, PRESERVE_NAME_KEY, nick); db_set_ts(hContact, MODULENAME, "Nick", nick); db_set_ts(hContact, "CList", "MyHandle", nick); } // TEST GET NAME FOR CACHE TCHAR cachepath[MAX_PATH], cachedirectorypath[MAX_PATH]; GetModuleFileName(hInst, cachepath, _countof(cachepath)); TCHAR *cacheend = _tcsrchr(cachepath, '\\'); cacheend++; *cacheend = '\0'; mir_sntprintf(cachedirectorypath, _T("%s")_T(MODULENAME)_T("cache\\"), cachepath); CreateDirectory(cachedirectorypath, NULL); TCHAR newcachepath[MAX_PATH + 50], renamedcachepath[MAX_PATH + 50]; mir_sntprintf(newcachepath, _T("%s")_T(MODULENAME)_T("cache\\%s.txt"), cachepath, oldName); mir_sntprintf(renamedcachepath, _T("%s")_T(MODULENAME)_T("cache\\%s.txt"), cachepath, nick); // file exists? if ( _taccess(newcachepath, 0) != -1) { FILE *pcachefile = _tfopen(newcachepath, _T("r")); if (pcachefile != NULL) { fclose(pcachefile); if (mir_tstrcmp(newcachepath, renamedcachepath)) { MoveFile(newcachepath, renamedcachepath); db_set_ts(hContact, MODULENAME, CACHE_FILE_KEY, renamedcachepath); } } } } } return 0; }
static void ProcessIniFile(TCHAR* szIniPath, char *szSafeSections, char *szUnsafeSections, int secur, bool secFN) { FILE *fp = _tfopen(szIniPath, _T("rt")); if (fp == NULL) return; bool warnThisSection = false; char szSection[128]; szSection[0] = 0; while (!feof(fp)) { char szLine[2048]; if (fgets(szLine, sizeof(szLine), fp) == NULL) break; LBL_NewLine: size_t lineLength = mir_strlen(szLine); while (lineLength && (BYTE)(szLine[lineLength - 1]) <= ' ') szLine[--lineLength] = '\0'; if (szLine[0] == ';' || szLine[0] <= ' ') continue; if (szLine[0] == '[') { char *szEnd = strchr(szLine + 1, ']'); if (szEnd == NULL) continue; if (szLine[1] == '!') szSection[0] = '\0'; else { mir_strncpy(szSection, szLine + 1, min(sizeof(szSection), (int)(szEnd - szLine))); switch (secur) { case 0: warnThisSection = false; break; case 1: warnThisSection = !IsInSpaceSeparatedList(szSection, szSafeSections); break; case 2: warnThisSection = IsInSpaceSeparatedList(szSection, szUnsafeSections); break; default: warnThisSection = true; break; } if (secFN) warnThisSection = 0; } if (szLine[1] == '?') { DBCONTACTENUMSETTINGS dbces; dbces.pfnEnumProc = SettingsEnumProc; mir_strncpy(szSection, szLine+2, min(sizeof(szSection), (int)(szEnd-szLine-1))); dbces.szModule = szSection; dbces.ofsSettings = 0; CallService(MS_DB_CONTACT_ENUMSETTINGS, 0, (LPARAM)&dbces); while (setting_items) { SettingsList *next = setting_items->next; db_unset(NULL, szSection, setting_items->name); mir_free(setting_items->name); mir_free(setting_items); setting_items = next; } } continue; } if (szSection[0] == '\0') continue; char *szValue = strchr(szLine, '='); if (szValue == NULL) continue; char szName[128]; mir_strncpy(szName, szLine, min(sizeof(szName), (int)(szValue-szLine+1))); szValue++; { warnSettingChangeInfo_t warnInfo; warnInfo.szIniPath = szIniPath; warnInfo.szName = szName; warnInfo.szSafeSections = szSafeSections; warnInfo.szSection = szSection; warnInfo.szUnsafeSections = szUnsafeSections; warnInfo.szValue = szValue; warnInfo.warnNoMore = 0; warnInfo.cancel = 0; if (warnThisSection && IDNO == DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_WARNINICHANGE), NULL, WarnIniChangeDlgProc, (LPARAM)&warnInfo)) continue; if (warnInfo.cancel) break; if (warnInfo.warnNoMore) warnThisSection = 0; } switch (szValue[0]) { case 'b': case 'B': db_set_b(NULL, szSection, szName, (BYTE)strtol(szValue+1, NULL, 0)); break; case 'w': case 'W': db_set_w(NULL, szSection, szName, (WORD)strtol(szValue+1, NULL, 0)); break; case 'd': case 'D': db_set_dw(NULL, szSection, szName, (DWORD)strtoul(szValue+1, NULL, 0)); break; case 'l': case 'L': case '-': if (szValue[1] == '*') { LIST<char> arSettings(1); ESFDParam param = { &arSettings, szName }; DBCONTACTENUMSETTINGS dbep = {}; dbep.pfnEnumProc = EnumSettingsForDeletion; dbep.szModule = szSection; dbep.lParam = (LPARAM)¶m; CallService(MS_DB_CONTACT_ENUMSETTINGS, NULL, LPARAM(&dbep)); while (arSettings.getCount()) { db_unset(NULL, szSection, arSettings[0]); mir_free(arSettings[0]); arSettings.remove(0); } } db_unset(NULL, szSection, szName); break; case 'e': case 'E': ConvertBackslashes(szValue+1, Langpack_GetDefaultCodePage()); case 's': case 'S': db_set_s(NULL, szSection, szName, szValue+1); break; case 'g': case 'G': for (char *pstr = szValue + 1; *pstr; pstr++) { if (*pstr == '\\') { switch (pstr[1]) { case 'n': *pstr = '\n'; break; case 't': *pstr = '\t'; break; case 'r': *pstr = '\r'; break; default: *pstr = pstr[1]; break; } memmove(pstr + 1, pstr + 2, mir_strlen(pstr + 2) + 1); } } case 'u': case 'U': db_set_utf(NULL, szSection, szName, szValue + 1); break; case 'm': case 'M': { CMStringA memo(szValue + 1); memo.Append("\r\n"); while (fgets(szLine, sizeof(szLine), fp) != NULL) { switch (szLine[0]) { case 0: case '\r': case '\n': case ' ': case '\t': break; default: db_set_utf(NULL, szSection, szName, memo); goto LBL_NewLine; } memo.Append(rtrim(szLine + 1)); memo.Append("\r\n"); } db_set_utf(NULL, szSection, szName, memo); } break; case 'n': case 'h': case 'N': case 'H': { int len; char *pszValue, *pszEnd; PBYTE buf = (PBYTE)mir_alloc(mir_strlen(szValue + 1)); for (len = 0, pszValue = szValue + 1;; len++) { buf[len] = (BYTE)strtol(pszValue, &pszEnd, 0x10); if (pszValue == pszEnd) break; pszValue = pszEnd; } db_set_blob(NULL, szSection, szName, buf, len); mir_free(buf); } break; default: TCHAR buf[250]; mir_sntprintf(buf, TranslateT("Invalid setting type for '%s'. The first character of every value must be b, w, d, l, s, e, u, g, h or n."), _A2T(szName)); MessageBox(NULL, buf, TranslateT("Install database settings"), MB_ICONWARNING | MB_OK); break; } } fclose(fp); }
void LogTrace(int info, const char *pWhere, const char *format,... ) { char buffer[2048]; TCHAR baseName[512]; DWORD baseNamseSize; time_t timer; struct tm *t; char timebuf [26]; unsigned int uiYear; va_list listArg; int iLog = 0; FILE *fp = NULL; switch (g_uiLogLevel) { case LOGTYPE_ERROR: if ( info == LOGTYPE_ERROR ) { iLog++; } break; case LOGTYPE_WARNING: if ( info <= LOGTYPE_WARNING ) { iLog++; } break; case LOGTYPE_INFO: if ( info <= LOGTYPE_INFO ) { iLog++; } break; case LOGTYPE_TRACE: iLog++; break; default: /* No Logging */ break; } if ( iLog == 0 ) { return; } if ( pWhere == NULL ) { return; } /* get the name of the file that started this process*/ baseNamseSize = GetModuleFileName(NULL,baseName,512); if (baseNamseSize == 0) lstrcpy(baseName,TEXT("Unknown name")); else baseName[511] = 0; //baseNamseSize = GetModuleBaseName(GetCurrentProcess(),NULL,(LPTSTR)baseName,512); //baseNamseSize = GetProcessImageFileName(NULL,(LPTSTR)baseName,512); /* Gets time of day */ timer = time(NULL); /* Converts date/time to a structure */ memset(timebuf, '\0', sizeof(timebuf)); t = localtime(&timer); if (t != NULL) { uiYear = t->tm_year; /* Add century to year */ uiYear += 1900; /* Converts date/time to string */ _snprintf(timebuf, sizeof(timebuf) , "%02d/%02d/%04d - %02d:%02d:%02d" , t->tm_mday , t->tm_mon + 1 , uiYear , t->tm_hour , t->tm_min , t->tm_sec); } memset (buffer, '\0', sizeof(buffer)); va_start(listArg, format); _vsnprintf(buffer, sizeof(buffer), format, listArg); va_end(listArg); fp = _tfopen(g_szLogFile, TEXT("a")); if ( fp != NULL ) { fprintf (fp, "%S %d %d %s|%30s|%s\n",baseName, GetCurrentProcessId(), GetCurrentThreadId(), timebuf, pWhere, buffer); fclose(fp); } }