void StopLogger(void) { TCHAR szMessage[(MAX_PATH*2)+1] = TEXT("\0"); int iLoggerError=0; // see switch statement for error handler TCHAR sztmplogfile[MAX_PATH+1] = TEXT("\0"); int retval=0; _tcscpy(sztmplogfile,szLoggerFileName); // use LOGGER_TMP, unsigned if (LoggerActive) { LoggerActive = false; if (LoggerClearFreeSpace()) { #if (TESTBENCH && DEBUG_LOGGER) if (LoggerGActive()) #else if (!SIMMODE && LoggerGActive()) #endif { extern int RunSignature(); retval = RunSignature(); if (retval!=0) { StartupStore(_T(".... LOGGER SIGNATURE ERROR, CODE=%d%s"),retval,NEWLINE); switch(retval) { case -1: StartupStore(_T(".... (EXEQ DEBUG FAILURE)%s"),NEWLINE); break; case 1: StartupStore(_T(".... (SOURCE FILE DISAPPEARED)%s"),NEWLINE); break; case 3: StartupStore(_T(".... (EXEQ WITH WRONG ARGUMENTS)%s"),NEWLINE); break; case 4: StartupStore(_T(".... (BAD ENVIRONMENT)%s"),NEWLINE); break; case 11: StartupStore(_T(".... (LOGGER_TMP DISAPPEARED)%s"),NEWLINE); break; case 12: StartupStore(_T(".... (LOGGER_SIG ALREADY EXISTING)%s"),NEWLINE); break; case 21: StartupStore(_T(".... (MUTEX FAILURE=)%s"),NEWLINE); break; case 259: StartupStore(_T(".... (PROCESS DID NOT TERMINATE!)%s"),NEWLINE); break; default: break; } // we shall be moving LOGGER_TMP, and leave LOGGER_SIG untouched. In fact we do not know // if LOGGER_SIG is or will be available. } else { // RunSig ok, change logfile to new logger_sig StartupStore(_T(". Logger OK, IGC signed with G-Record%s"),NEWLINE); DeleteFile(szLoggerFileName); // remove old LOGGER_TMP _tcscpy(sztmplogfile,szSLoggerFileName); // use LOGGER_SIG, signed } } // logger active int imCount=0; const int imMax=3; for (imCount=0; imCount < imMax; imCount++) { // MoveFile() nonzero==Success if (0 != MoveFile( sztmplogfile, szFLoggerFileName)) { iLoggerError=0; break; // success } Sleep(750); // wait for file system cache to fix itself? } if (imCount == imMax) { // MoveFile() failed all attempts if (0 == MoveFile( sztmplogfile, szFLoggerFileNameRoot)) { // try rename it and leave in root iLoggerError=1; //Fail. NoMoveNoRename } else { iLoggerError=2; //NoMoveYesRename } } } // logger clearfreespace else { // Insufficient disk space. // MoveFile() nonzero==Success if (0 == MoveFile( sztmplogfile, szFLoggerFileNameRoot)) { // try rename it and leave in root iLoggerError=3; //Fail. Insufficient Disk Space, NoRename } else { iLoggerError=4; //Success. Insufficient Disk Space, YesRename } } switch (iLoggerError) { //0=Success 1=NoMoveNoRename 2=NoMoveYesRename 3=NoSpaceNoRename 4=NoSpaceYesRename case 0: StartupStore(TEXT(". Logger: File saved %s%s"),WhatTimeIsIt(),NEWLINE); break; case 1: // NoMoveNoRename LK_tcsncpy(szMessage,TEXT("--- Logger file not copied. It is in the root folder of your device and called "),MAX_PATH); _tcsncat(szMessage,sztmplogfile,MAX_PATH); MessageBoxX(hWndMapWindow, gettext(szMessage), // LKTOKEN _@M404_ = "Logger Error" gettext(TEXT("_@M404_")), MB_OK| MB_ICONERROR); _tcsncat(szMessage,TEXT(SNEWLINE),MAX_PATH); StartupStore(szMessage); break; case 2: // NoMoveYesRename LK_tcsncpy(szMessage,TEXT("--- Logger file not copied. It is in the root folder of your device"),MAX_PATH); MessageBoxX(hWndMapWindow, gettext(szMessage), // LKTOKEN _@M404_ = "Logger Error" gettext(TEXT("_@M404_")), MB_OK| MB_ICONERROR); _tcsncat(szMessage,TEXT(SNEWLINE),MAX_PATH); StartupStore(szMessage); break; case 3: // Insufficient Storage. NoRename LK_tcsncpy(szMessage,TEXT("++++++ Insuff. storage. Logger file in device's root folder, called "),MAX_PATH); _tcsncat(szMessage,sztmplogfile,MAX_PATH); MessageBoxX(hWndMapWindow, gettext(szMessage), // LKTOKEN _@M404_ = "Logger Error" gettext(TEXT("_@M404_")), MB_OK| MB_ICONERROR); _tcsncat(szMessage,TEXT(SNEWLINE),MAX_PATH); StartupStore(szMessage); break; case 4: // Insufficient Storage. YesRename LK_tcsncpy(szMessage,TEXT("++++++ Insufficient storage. Logger file is in the root folder of your device"),MAX_PATH); MessageBoxX(hWndMapWindow, gettext(szMessage), // LKTOKEN _@M404_ = "Logger Error" gettext(TEXT("_@M404_")), MB_OK| MB_ICONERROR); _tcsncat(szMessage,TEXT(SNEWLINE),MAX_PATH); StartupStore(szMessage); break; } // error handler NumLoggerBuffered = 0; } }
// This is painting traffic icons on the screen. void MapWindow::LKDrawFLARMTraffic(LKSurface& Surface, const RECT& rc, const ScreenProjection& _Proj, const POINT& Orig_Aircraft) { if (!EnableFLARMMap) return; if (!DrawInfo.FLARM_Available) return; // init scaled coords for traffic icon static int iCircleSize = 7; static int iRectangleSize = 4; static short tscaler=0; if (DoInit[MDI_DRAWFLARMTRAFFIC]) { switch (ScreenSize) { case ss480x640: case ss480x800: case ss800x480: case ss640x480: iCircleSize = 9; iRectangleSize = 5; tscaler=NIBLSCALE(7)-2; break; case ss240x320: case ss272x480: case ss320x240: case ss480x272: case ss480x234: case ss400x240: iCircleSize = 7; iRectangleSize = 4; tscaler=NIBLSCALE(13)-2; break; default: iCircleSize = 7; iRectangleSize = 4; tscaler=NIBLSCALE(7); break; } DoInit[MDI_DRAWFLARMTRAFFIC]=false; } POINT Arrow[5]; TCHAR lbuffer[50]; const auto hpold = Surface.SelectObject(LKPen_Black_N1); int i; int painted=0; // double dX, dY; TextInBoxMode_t displaymode = {0}; displaymode.NoSetFont = 1; #if 0 double screenrange = GetApproxScreenRange(); double scalefact = screenrange/6000.0; // FIX 100820 #endif const auto oldfont = Surface.SelectObject(LK8MapFont); for (i=0,painted=0; i<FLARM_MAX_TRAFFIC; i++) { // limit to 10 icons map traffic if (painted>=10) { i=FLARM_MAX_TRAFFIC; continue; } if ( (DrawInfo.FLARM_Traffic[i].ID !=0) && (DrawInfo.FLARM_Traffic[i].Status != LKT_ZOMBIE) ) { double target_lon; double target_lat; target_lon = DrawInfo.FLARM_Traffic[i].Longitude; target_lat = DrawInfo.FLARM_Traffic[i].Latitude; if (!PointVisible(target_lon, target_lat)) { // StartupStore(_T("... This traffic is not visible on map with current zoom%s"),NEWLINE); continue; } painted++; #if (0) // No scaling, wrong if ((EnableFLARMMap==2)&&(scalefact>1.0)) { double distance; double bearing; DistanceBearing(DrawInfo.Latitude, DrawInfo.Longitude, target_lat, target_lon, &distance, &bearing); FindLatitudeLongitude(DrawInfo.Latitude, DrawInfo.Longitude, bearing, distance*scalefact, &target_lat, &target_lon); } #endif POINT sc, sc_name, sc_av; sc = _Proj.ToRasterPoint(target_lat, target_lon); sc_name = sc; sc_name.y -= NIBLSCALE(16); sc_av = sc_name; _tcscpy(lbuffer,_T("")); if (DrawInfo.FLARM_Traffic[i].Cn[0]!=_T('?')) { // 100322 _tcscat(lbuffer,DrawInfo.FLARM_Traffic[i].Cn); } if (DrawInfo.FLARM_Traffic[i].Average30s>=0.1) { size_t len = _tcslen(lbuffer); if (len > 0) _stprintf(lbuffer + len,_T(":%.1f"),LIFTMODIFY*DrawInfo.FLARM_Traffic[i].Average30s); else _stprintf(lbuffer,_T("%.1f"),LIFTMODIFY*DrawInfo.FLARM_Traffic[i].Average30s); } displaymode.Border=1; if (_tcslen(lbuffer)>0) TextInBox(Surface, &rc, lbuffer, sc.x+tscaler, sc.y+tscaler, &displaymode, false); // red circle if ((DrawInfo.FLARM_Traffic[i].AlarmLevel>0) && (DrawInfo.FLARM_Traffic[i].AlarmLevel<4)) { DrawBitmapIn(Surface, sc, hFLARMTraffic); } #if 1 // 1 Arrow[0].x = -4; Arrow[0].y = 5; Arrow[1].x = 0; Arrow[1].y = -6; Arrow[2].x = 4; Arrow[2].y = 5; Arrow[3].x = 0; Arrow[3].y = 2; Arrow[4].x = -4; Arrow[4].y = 5; for (int q=0; q < 5; q++) { Arrow[q].x = (LONG) ((double)Arrow[q].x * 1.7); Arrow[q].y = (LONG) ((double)Arrow[q].y * 1.7); } #else Arrow[0].x = scaler[0]; Arrow[0].y = scaler[1]; Arrow[1].x = 0; Arrow[1].y = scaler[2]; Arrow[2].x = scaler[3]; Arrow[2].y = scaler[1]; Arrow[3].x = 0; Arrow[3].y = scaler[4]; Arrow[4].x = scaler[0]; Arrow[4].y = scaler[1]; #endif /* switch (DrawInfo.FLARM_Traffic[i].Status) { // 100321 case LKT_GHOST: Surface.SelectObject(yellowBrush); break; case LKT_ZOMBIE: Surface.SelectObject(redBrush); break; default: Surface.SelectObject(greenBrush); break; } */ /************************************************************************* * calculate climb color *************************************************************************/ int iVarioIdx = (int)(2*DrawInfo.FLARM_Traffic[i].Average30s -0.5)+NO_VARIO_COLORS/2; if(iVarioIdx < 0) iVarioIdx =0; if(iVarioIdx >= NO_VARIO_COLORS) iVarioIdx =NO_VARIO_COLORS-1; Surface.SelectObject(*variobrush[iVarioIdx]); switch (DrawInfo.FLARM_Traffic[i].Status) { // 100321 case LKT_GHOST: Surface.Rectangle(sc.x-iRectangleSize, sc.y-iRectangleSize,sc.x+iRectangleSize, sc.y+iRectangleSize); break; case LKT_ZOMBIE: Surface.DrawCircle(sc.x, sc.x, iCircleSize, rc, true ); break; default: PolygonRotateShift(Arrow, 5, sc.x, sc.y, DrawInfo.FLARM_Traffic[i].TrackBearing - DisplayAngle); Surface.Polygon(Arrow,5); break; } } } Surface.SelectObject(oldfont); Surface.SelectObject(hpold); }
void setuservariable(int varnum, TCHAR *var) { if (var != NULL && varnum >= 0 && varnum < __INST_LAST) _tcscpy(g_variables + varnum*g_stringsize, var); }
//Activate the Previous Instance of our Application. HWND CInstanceChecker::ActivatePreviousInstance(LPCTSTR lpCmdLine, ULONG_PTR dwCopyDataItemData, DWORD dwTimeout) { //What will be the return value from this function (assume the worst) HWND hWindow = NULL; //Try to open the previous instances MMF HANDLE hPrevInstance = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, GetMMFFilename()); if (hPrevInstance) { //Open up the MMF int nMMFSize = sizeof(CWindowInstance); CWindowInstance* pInstanceData = static_cast<CWindowInstance*>(MapViewOfFile(hPrevInstance, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, nMMFSize)); if (pInstanceData) //Opening the MMF should work { //Lock the data prior to reading from it CSingleLock dataLock(&m_instanceDataMutex, TRUE); //activate the old window ASSERT(pInstanceData->hMainWnd); //Something gone wrong with the MMF hWindow = pInstanceData->hMainWnd; if (::IsWindow(hWindow)) { CWnd wndPrev; wndPrev.Attach(hWindow); CWnd* pWndChild = wndPrev.GetLastActivePopup(); //Restore the focus to the previous instance and bring it to the foreground if (wndPrev.IsIconic()) wndPrev.ShowWindow(SW_RESTORE); if (pWndChild) pWndChild->SetForegroundWindow(); if (lpCmdLine) { //Send the current apps command line to the previous instance using WM_COPYDATA COPYDATASTRUCT cds; cds.dwData = dwCopyDataItemData; DWORD dwCmdLength = static_cast<DWORD>(_tcslen(lpCmdLine) + 1); cds.cbData = dwCmdLength * sizeof(TCHAR); TCHAR* pszLocalCmdLine = new TCHAR[dwCmdLength]; //We use a local buffer so that we can specify a constant parameter //to this function #if (_MSC_VER >= 1400) _tcscpy_s(pszLocalCmdLine, dwCmdLength, lpCmdLine); #else _tcscpy(pszLocalCmdLine, lpCmdLine); #endif cds.lpData = pszLocalCmdLine; CWnd* pMainWindow = AfxGetMainWnd(); HWND hSender = NULL; if (pMainWindow) hSender = pMainWindow->GetSafeHwnd(); //Send the message to the previous instance. Use SendMessageTimeout instead of SendMessage to ensure we //do not hang if the previous instance itself is hung DWORD_PTR dwResult = 0; if (SendMessageTimeout(hWindow, WM_COPYDATA, reinterpret_cast<WPARAM>(hSender), reinterpret_cast<LPARAM>(&cds), SMTO_ABORTIFHUNG, dwTimeout, &dwResult) == 0) { //Previous instance is not responding to messages hWindow = NULL; } //Tidy up the heap memory we have used delete [] pszLocalCmdLine; } //Detach the CWnd we were using wndPrev.Detach(); } //Unmap the MMF we were using UnmapViewOfFile(pInstanceData); } //Close the file handle now that we CloseHandle(hPrevInstance); //When we have activate the previous instance, we can release the lock ReleaseLock(); } return hWindow; }
//----------------------------------------------------------------------------- // Name: GetHandleInfo // Object: fill CSelectWindow object information depending of the handle // Parameters : // in : HWND hWnd handle of the window // Return : TRUE on success //----------------------------------------------------------------------------- BOOL CSelectWindow::GetHandleInfo(HWND hWnd) { DWORD PID; DWORD TID; // get window thread and pid from handle TID = GetWindowThreadProcessId (hWnd, &PID); /////////////////////////// // parent window /////////////////////////// this->ParentWindowHandle = GetParent (hWnd); if (this->ParentWindowHandle != NULL) { // parent text GetWindowText (this->ParentWindowHandle, this->ParentWindowText, MAX_PATH); // parent class name GetClassName (this->ParentWindowHandle, this->ParentWindowClassName, MAX_PATH); } else { _tcscpy(this->ParentWindowText,_T("Not Available")); _tcscpy(this->ParentWindowClassName,_T("Not Available")); } /////////////////////////// // window under cursor /////////////////////////// // window handle this->WindowHandle=hWnd; // window extended style this->WindowExStyle=(DWORD)GetWindowLongPtr (this->WindowHandle, GWL_EXSTYLE); // window style this->WindowStyle=(DWORD)GetWindowLongPtr (this->WindowHandle, GWL_STYLE); // address of the window procedure this->WindowProc=(DWORD)GetWindowLongPtr (this->WindowHandle, GWLP_WNDPROC); // handle to the application instance this->WindowHinst=(DWORD)GetWindowLongPtr (this->WindowHandle, GWLP_HINSTANCE); // user data associated with the window this->WindowUserData=(DWORD)GetWindowLongPtr (this->WindowHandle, GWLP_USERDATA); // control ID this->WindowControlID=(DWORD)GetWindowLongPtr(this->WindowHandle, GWLP_ID); // RECT GetWindowRect(this->WindowHandle, &this->WindowRect); // thread ID this->WindowThreadID=TID; // process ID this->WindowProcessID=PID; // class name GetClassName (this->WindowHandle, WindowClassName, MAX_PATH); // The following values are also available when the hWnd parameter identifies a dialog box. // address of the dialog box procedure this->WindowDlgProc=(DWORD)GetWindowLongPtr (this->WindowHandle, DWLP_DLGPROC); // value of a message processed in the dialog box procedure this->WindowDlgMsgResult=(DWORD)GetWindowLongPtr (this->WindowHandle, DWLP_MSGRESULT); // extra information private to the application this->WindowDlgUser=(DWORD)GetWindowLongPtr (this->WindowHandle, DWLP_USER); return TRUE; }
BOOL CALLBACK SessionDialog::SessDlgProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { // This is a static method, so we don't know which instantiation we're // dealing with. But we can get a pseudo-this from the parameter to // WM_INITDIALOG, which we therafter store with the window and retrieve // as follows: SessionDialog*_this = helper::SafeGetWindowUserData<SessionDialog>(hwnd); switch (uMsg) { case WM_INITDIALOG: { helper::SafeSetWindowUserData(hwnd, lParam); SessionDialog *l_this = (SessionDialog *) lParam; CentreWindow(hwnd); SetForegroundWindow(hwnd); l_this->m_pCC->m_hSessionDialog = hwnd; // Set up recently-used list HWND hcombo = GetDlgItem( hwnd, IDC_HOSTNAME_EDIT); TCHAR valname[256]; for (int i = 0; i < l_this->m_pMRU->NumItems(); i++) { l_this->m_pMRU->GetItem(i, valname, 255); int pos = SendMessage(hcombo, CB_ADDSTRING, 0, (LPARAM) valname); } SendMessage(hcombo, CB_SETCURSEL, 0, 0); // sf@2002 - List available DSM Plugins HWND hPlugins = GetDlgItem(hwnd, IDC_PLUGINS_COMBO); int nPlugins = l_this->m_pDSMPlugin->ListPlugins(hPlugins); if (!nPlugins) { SendMessage(hPlugins, CB_ADDSTRING, 0, (LPARAM) sz_F11); } else { // Use the first detected plugin, so the user doesn't have to check the option // HWND hUsePlugin = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); // SendMessage(hUsePlugin, BM_SETCHECK, TRUE, 0); } SendMessage(hPlugins, CB_SETCURSEL, 0, 0); HWND hButton = GetDlgItem(hwnd, IDC_PLUGIN_BUTTON); EnableWindow(hButton, FALSE); // sf@2009 - Disable plugin config button by default //AaronP if( strcmp( l_this->m_pOpt->m_szDSMPluginFilename, "" ) != 0 && l_this->m_pOpt->m_fUseDSMPlugin ) { int pos = SendMessage(hPlugins, CB_FINDSTRINGEXACT, -1, (LPARAM)&(l_this->m_pOpt->m_szDSMPluginFilename[0])); if( pos != CB_ERR ) { SendMessage(hPlugins, CB_SETCURSEL, pos, 0); HWND hUsePlugin = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); SendMessage(hUsePlugin, BM_SETCHECK, TRUE, 0); EnableWindow(hButton, TRUE); // sf@2009 - Enable plugin config button } } //EndAaronP TCHAR tmphost[256]; TCHAR tmphost2[256]; _tcscpy(tmphost, l_this->m_pOpt->m_proxyhost); if (strcmp(tmphost,"")!=NULL) { _tcscat(tmphost,":"); _tcscat(tmphost,_itoa(l_this->m_pOpt->m_proxyport,tmphost2,10)); SetDlgItemText(hwnd, IDC_PROXY_EDIT, tmphost); } HWND hViewOnly = GetDlgItem(hwnd, IDC_VIEWONLY_CHECK); SendMessage(hViewOnly, BM_SETCHECK, l_this->m_pOpt->m_ViewOnly, 0); HWND hAutoScaling = GetDlgItem(hwnd, IDC_AUTOSCALING_CHECK); SendMessage(hAutoScaling, BM_SETCHECK, l_this->m_pOpt->m_fAutoScaling, 0); HWND hExitCheck = GetDlgItem(hwnd, IDC_EXIT_CHECK); //PGM @ Advantig SendMessage(hExitCheck, BM_SETCHECK, l_this->m_pOpt->m_fExitCheck, 0); //PGM @ Advantig HWND hProxy = GetDlgItem(hwnd, IDC_PROXY_CHECK); SendMessage(hProxy, BM_SETCHECK, l_this->m_pOpt->m_fUseProxy, 0); // sf@2005 - Make the save settings optional but always enabled by default (for now) // (maybe disabled as default is better ?) HWND hSave = GetDlgItem(hwnd, IDC_SETDEFAULT_CHECK); //ACT SendMessage(hSave, BM_SETCHECK, true, 0); // sf@2002 - Select Modem Option as default l_this->SetQuickOption(l_this, hwnd); l_this->m_fFromOptions = false; l_this->m_fFromFile = false; return TRUE; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_DELETE: { char optionfile[MAX_PATH]; VNCOptions::GetDefaultOptionsFileName(optionfile); DeleteFile(optionfile); } return TRUE; case IDOK: { TCHAR tmphost[256]; TCHAR display[256]; TCHAR fulldisplay[256]; // sf@2005 HWND hSave = GetDlgItem(hwnd, IDC_SETDEFAULT_CHECK); _this->m_pCC->saved_set = SendMessage(hSave, BM_GETCHECK, 0, 0) == BST_CHECKED; GetDlgItemText(hwnd, IDC_HOSTNAME_EDIT, display, 256); _tcscpy(fulldisplay, display); if (!ParseDisplay(display, tmphost, 255, &_this->m_port)) { MessageBox(hwnd, sz_F8, sz_F10, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); } else { for (size_t i = 0, len = strlen(tmphost); i < len; i++) { tmphost[i] = toupper(tmphost[i]); } _tcscpy(_this->m_host_dialog, tmphost); _this->m_pMRU->AddItem(fulldisplay); // _tcscpy(_this->m_remotehost, fulldisplay); EndDialog(hwnd, TRUE); } GetDlgItemText(hwnd, IDC_PROXY_EDIT, display, 256); _tcscpy(fulldisplay, display); if (!ParseDisplay(display, tmphost, 255, &_this->m_proxyport)) { MessageBox(hwnd, sz_F8, sz_F10, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); } else { _tcscpy(_this->m_proxyhost, tmphost); EndDialog(hwnd, TRUE); } HWND hProxy = GetDlgItem(hwnd, IDC_PROXY_CHECK); if (SendMessage(hProxy, BM_GETCHECK, 0, 0) == BST_CHECKED) { _this->m_pOpt->m_fUseProxy = true; _this->m_fUseProxy = true; } else { _this->m_pOpt->m_fUseProxy = false; _this->m_fUseProxy = false; } // sf@2002 - DSMPlugin loading // If Use plugin is checked, load the plugin if necessary HWND hPlugin = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); if (SendMessage(hPlugin, BM_GETCHECK, 0, 0) == BST_CHECKED) { TCHAR szPlugin[MAX_PATH]; GetDlgItemText(hwnd, IDC_PLUGINS_COMBO, szPlugin, MAX_PATH); _this->m_pOpt->m_fUseDSMPlugin = true; strcpy(_this->m_pOpt->m_szDSMPluginFilename, szPlugin); if (!_this->m_pDSMPlugin->IsLoaded()) { _this->m_pDSMPlugin->LoadPlugin(szPlugin, _this->m_pOpt->m_listening); if (_this->m_pDSMPlugin->IsLoaded()) { if (_this->m_pDSMPlugin->InitPlugin()) { _this->m_pDSMPlugin->SetEnabled(true); _this->m_pDSMPlugin->DescribePlugin(); } else { _this->m_pDSMPlugin->SetEnabled(false); MessageBox(hwnd, sz_F7, sz_F6, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); return TRUE; } } else { _this->m_pDSMPlugin->SetEnabled(false); MessageBox(hwnd, sz_F5, sz_F6, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); return TRUE; } } else { // sf@2003 - If the plugin is already loaded here it has been loaded // by clicking on the config button: we need to init it ! // But we must first check that the loaded plugin is the same that // the one currently selected... _this->m_pDSMPlugin->DescribePlugin(); if (_stricmp(_this->m_pDSMPlugin->GetPluginFileName(), szPlugin)) { // Unload the previous plugin _this->m_pDSMPlugin->UnloadPlugin(); // Load the new selected one _this->m_pDSMPlugin->LoadPlugin(szPlugin, _this->m_pOpt->m_listening); } if (_this->m_pDSMPlugin->IsLoaded()) { if (_this->m_pDSMPlugin->InitPlugin()) { _this->m_pDSMPlugin->SetEnabled(true); _this->m_pDSMPlugin->DescribePlugin(); } else { _this->m_pDSMPlugin->SetEnabled(false); MessageBox(hwnd, sz_F7, sz_F6, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); return TRUE; } } else { _this->m_pDSMPlugin->SetEnabled(false); MessageBox(hwnd, sz_F5, sz_F6, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); return TRUE; } } } else // If Use plugin unchecked but the plugin is loaded, unload it { _this->m_pOpt->m_fUseDSMPlugin = false; if (_this->m_pDSMPlugin->IsEnabled()) { _this->m_pDSMPlugin->UnloadPlugin(); _this->m_pDSMPlugin->SetEnabled(false); } } if (_this->m_fFromOptions || _this->m_fFromFile) { EndDialog(hwnd, TRUE); return TRUE; } // sf@2002 - Quick options handling _this->ManageQuickOptions(_this, hwnd); HWND hViewOnly = GetDlgItem(hwnd, IDC_VIEWONLY_CHECK); _this->m_pOpt->m_ViewOnly = (SendMessage(hViewOnly, BM_GETCHECK, 0, 0) == BST_CHECKED); HWND hAutoScaling = GetDlgItem(hwnd, IDC_AUTOSCALING_CHECK); _this->m_pOpt->m_fAutoScaling = (SendMessage(hAutoScaling, BM_GETCHECK, 0, 0) == BST_CHECKED); HWND hExitCheck = GetDlgItem(hwnd, IDC_EXIT_CHECK); //PGM @ Advantig _this->m_pOpt->m_fExitCheck = (SendMessage(hExitCheck, BM_GETCHECK, 0, 0) == BST_CHECKED); //PGM @ Advantig EndDialog(hwnd, TRUE); return TRUE; } case IDCANCEL: EndDialog(hwnd, FALSE); return TRUE; case IDC_OPTIONBUTTON: { if (!_this->m_fFromFile) { _this->ManageQuickOptions(_this, hwnd); HWND hViewOnly = GetDlgItem(hwnd, IDC_VIEWONLY_CHECK); _this->m_pOpt->m_ViewOnly = (SendMessage(hViewOnly, BM_GETCHECK, 0, 0) == BST_CHECKED); HWND hAutoScaling = GetDlgItem(hwnd, IDC_AUTOSCALING_CHECK); _this->m_pOpt->m_fAutoScaling = (SendMessage(hAutoScaling, BM_GETCHECK, 0, 0) == BST_CHECKED); HWND hExitCheck = GetDlgItem(hwnd, IDC_EXIT_CHECK); //PGM @ Advantig _this->m_pOpt->m_fExitCheck = (SendMessage(hExitCheck, BM_GETCHECK, 0, 0) == BST_CHECKED); //PGM @ Advantig } if (_this->m_pOpt->DoDialog()) { _this->m_fFromOptions = true; HWND hDyn = GetDlgItem(hwnd, IDC_DYNAMIC); SendMessage(hDyn, BM_SETCHECK, false, 0); HWND hLan = GetDlgItem(hwnd, IDC_LAN_RB); SendMessage(hLan, BM_SETCHECK, false, 0); HWND hUltraLan = GetDlgItem(hwnd, IDC_ULTRA_LAN_RB); SendMessage(hUltraLan, BM_SETCHECK, false, 0); HWND hMedium = GetDlgItem(hwnd, IDC_MEDIUM_RB); SendMessage(hMedium, BM_SETCHECK, false, 0); HWND hModem = GetDlgItem(hwnd, IDC_MODEM_RB); SendMessage(hModem, BM_SETCHECK, false, 0); HWND hSlow = GetDlgItem(hwnd, IDC_SLOW_RB); SendMessage(hSlow, BM_SETCHECK, false, 0); HWND hManual = GetDlgItem(hwnd, IDC_MANUAL); SendMessage(hManual, BM_SETCHECK, true, 0); _this->m_pOpt->m_quickoption = 8; } return TRUE; } // sf@2002 case IDC_PLUGIN_CHECK: { HWND hUse = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); BOOL enable = SendMessage(hUse, BM_GETCHECK, 0, 0) == BST_CHECKED; HWND hButton = GetDlgItem(hwnd, IDC_PLUGIN_BUTTON); EnableWindow(hButton, enable); } return TRUE; case IDC_PLUGIN_BUTTON: { HWND hPlugin = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); if (SendMessage(hPlugin, BM_GETCHECK, 0, 0) == BST_CHECKED) { TCHAR szPlugin[MAX_PATH]; GetDlgItemText(hwnd, IDC_PLUGINS_COMBO, szPlugin, MAX_PATH); // sf@2003 - The config button can be clicked several times with // different selected plugins... bool fLoadIt = true; char szParams[64]; strcpy(szParams, sz_F4); // If a plugin is already loaded, check if it is the same that the one // we want to load. if (_this->m_pDSMPlugin->IsLoaded()) { _this->m_pDSMPlugin->DescribePlugin(); if (!_stricmp(_this->m_pDSMPlugin->GetPluginFileName(), szPlugin)) { fLoadIt = false; _this->m_pDSMPlugin->SetPluginParams(hwnd, szParams); } else { // Unload the previous plugin _this->m_pDSMPlugin->UnloadPlugin(); fLoadIt = true; } } if (!fLoadIt) return TRUE; if (_this->m_pDSMPlugin->LoadPlugin(szPlugin, _this->m_pOpt->m_listening)) { // We don't know the password yet... no matter the plugin requires // it or not, we will provide it later (at plugin "real" startup) // Knowing the environnement ("viewer") right now can be usefull or // even mandatory for the plugin (specific params saving and so on...) // The plugin receives environnement info but isn't inited at this point _this->m_pDSMPlugin->SetPluginParams(hwnd, szParams); } else { MessageBox(hwnd, sz_F1, sz_F3, MB_OK | MB_ICONEXCLAMATION | MB_SETFOREGROUND | MB_TOPMOST); } } return TRUE; } case IDC_LOADPROFILE_B: { TCHAR szFileName[MAX_PATH]; memset(szFileName, '\0', MAX_PATH); if (_this->m_pCC->LoadConnection(szFileName, true) != -1) { TCHAR szHost[250]; if (_this->m_pCC->m_port == 5900) _tcscpy(szHost, _this->m_pCC->m_host); else if (_this->m_pCC->m_port > 5900 && _this->m_pCC->m_port <= 5999) _stprintf(szHost, TEXT("%s:%d"), _this->m_pCC->m_host, _this->m_pCC->m_port - 5900); else _stprintf(szHost, TEXT("%s::%d"), _this->m_pCC->m_host, _this->m_pCC->m_port); SetDlgItemText(hwnd, IDC_HOSTNAME_EDIT, szHost); //AaronP HWND hPlugins = GetDlgItem(hwnd, IDC_PLUGINS_COMBO); if( strcmp( _this->m_pOpt->m_szDSMPluginFilename, "" ) != 0 && _this->m_pOpt->m_fUseDSMPlugin ) { int pos = SendMessage(hPlugins, CB_FINDSTRINGEXACT, -1, (LPARAM)&(_this->m_pOpt->m_szDSMPluginFilename[0])); if( pos != CB_ERR ) { SendMessage(hPlugins, CB_SETCURSEL, pos, 0); HWND hUsePlugin = GetDlgItem(hwnd, IDC_PLUGIN_CHECK); SendMessage(hUsePlugin, BM_SETCHECK, TRUE, 0); } } //EndAaronP } SetFocus(GetDlgItem(hwnd, IDC_HOSTNAME_EDIT)); _this->SetQuickOption(_this, hwnd); HWND hViewOnly = GetDlgItem(hwnd, IDC_VIEWONLY_CHECK); SendMessage(hViewOnly, BM_SETCHECK, _this->m_pOpt->m_ViewOnly, 0); HWND hAutoScaling = GetDlgItem(hwnd, IDC_AUTOSCALING_CHECK); SendMessage(hAutoScaling, BM_SETCHECK, _this->m_pOpt->m_fAutoScaling, 0); HWND hExitCheck = GetDlgItem(hwnd, IDC_EXIT_CHECK); //PGM @ Advantig SendMessage(hExitCheck, BM_SETCHECK, _this->m_pOpt->m_fExitCheck, 0); //PGM @ Advantig _this->m_fFromOptions = true; _this->m_fFromFile = true; return TRUE; } // [v1.0.2-jp1 fix] case IDC_HOSTNAME_DEL: HWND hcombo = GetDlgItem( hwnd, IDC_HOSTNAME_EDIT); int sel = SendMessage(hcombo, CB_GETCURSEL, 0, 0); if(sel != CB_ERR){ SendMessage(hcombo, CB_DELETESTRING, sel, 0); _this->m_pMRU->RemoveItem(sel); } return TRUE; } break; case WM_DESTROY: EndDialog(hwnd, FALSE); return TRUE; } return 0; }
LONG __stdcall DCUnhandledExceptionFilter( LPEXCEPTION_POINTERS e ) { #ifdef __DEBUG MessageBox(NULL, _T("If you would like to debug DCUnhandledExceptionFilter - attach to this process now"), _T(APPNAME), MB_OK); #endif Lock l(cs); if(recursion++ > 30) exit(-1); #ifndef _DEBUG #if _MSC_VER == 1200 __pfnDliFailureHook = FailHook; #elif _MSC_VER == 1300 || _MSC_VER == 1310 || _MSC_VER == 1400 __pfnDliFailureHook2 = FailHook; #else #error Unknown Compiler version #endif // The release version loads the dll and pdb:s here... InitSymInfo(Text::toT(Util::getDataPath()).c_str()); #endif TCHAR pdbPath[MAX_PATH]; GetModuleFileName(NULL, pdbPath, sizeof(pdbPath)); TCHAR* dotPtr = _tcschr(pdbPath, '.'); if (dotPtr != NULL) { _tcscpy(dotPtr, _T(".pdb")); } if (GetFileAttributes(pdbPath) == INVALID_FILE_ATTRIBUTES) { // No debug symbols, we're not interested... ::MessageBox(WinUtil::mainWnd, _T(APPNAME) _T(" has crashed and you don't have .PDB file installed. Hence, I can't find out why it crashed, so don't report this as a bug unless you find a solution..."), _T(APPNAME) _T(" has crashed"), MB_OK); #ifndef _DEBUG exit(1); #else return EXCEPTION_CONTINUE_SEARCH; #endif } File f(Util::getConfigPath() + "exceptioninfo.txt", File::WRITE, File::OPEN | File::CREATE); f.setEndPos(0); char buf[DEBUG_BUFSIZE]; sprintf(buf, "Code: %x (%s)\r\n" "Version: %d (%s)\r\n", e->ExceptionRecord->ExceptionCode, getExceptionName(e->ExceptionRecord->ExceptionCode), BUILDID, Util::getCompileDate().c_str()); tstring exceptioninfo = Text::toT(buf); f.write(buf, strlen(buf)); OSVERSIONINFOEX ver; WinUtil::getVersionInfo(ver); const char *productType; if (ver.wProductType == VER_NT_DOMAIN_CONTROLLER) { productType = "domain controller"; } else if (ver.wProductType == VER_NT_SERVER) { productType = "server"; } else if (ver.wProductType == VER_NT_WORKSTATION) { productType = "workstation"; } else { productType = "unknown product type"; } sprintf(buf, "OS Version: %d.%d build %d service pack %d %s\r\n", (DWORD)ver.dwMajorVersion, (DWORD)ver.dwMinorVersion, (DWORD)ver.dwBuildNumber, (DWORD)ver.wServicePackMajor, productType); exceptioninfo += Text::toT(buf); f.write(buf, strlen(buf)); time_t now; time(&now); strftime(buf, DEBUG_BUFSIZE, "Time: %Y-%m-%d %H:%M:%S\r\n", localtime(&now)); exceptioninfo += Text::toT(buf); f.write(buf, strlen(buf)); #if 0 WinUtil::exceptioninfo += LIT(_T("TTH: ")); WinUtil::exceptioninfo += Text::toT(tth); WinUtil::exceptioninfo += LIT(_T("\r\n\r\n")); #endif f.write(LIT("\r\n")); exceptioninfo += _T("\r\n"); // !SMT! sprintf(buf, "exception code %08X at eip=%08X, nested: %08X\r\n" "eax=%08X ebx=%08X ecx=%08X edx=%08X\r\n" "esi=%08X edi=%08X ebp=%08X esp=%08X\r\n", e->ExceptionRecord->ExceptionCode, e->ExceptionRecord->ExceptionAddress, e->ExceptionRecord->ExceptionRecord, e->ContextRecord->Eax, e->ContextRecord->Ebx, e->ContextRecord->Ecx, e->ContextRecord->Edx, e->ContextRecord->Esi, e->ContextRecord->Edi, e->ContextRecord->Ebp, e->ContextRecord->Esp); exceptioninfo += Text::toT(buf); f.write(buf, strlen(buf)); const tstring trace = StackTrace(GetCurrentThread(), e->ContextRecord); f.write(LIT("\r\n")); f.write(Text::fromT(trace)); f.close(); #if 0 memcpy(&CurrExceptionRecord, e->ExceptionRecord, sizeof(EXCEPTION_RECORD)); memcpy(&CurrContext, e->ContextRecord, sizeof(CONTEXT)); #endif exceptioninfo += _T("\r\n"); exceptioninfo += trace; Sounds::PlaySound(SettingsManager::SOUND_EXC); if (WinUtil::mainWnd != NULL) { NOTIFYICONDATA m_nid = {0}; m_nid.cbSize = sizeof(NOTIFYICONDATA); m_nid.hWnd = WinUtil::mainWnd; m_nid.uID = 0; m_nid.uFlags = NIF_INFO; m_nid.uTimeout = 5000; m_nid.dwInfoFlags = NIIF_WARNING; _tcsncpy(m_nid.szInfo, _T("exceptioninfo.txt was generated"), 255); _tcsncpy(m_nid.szInfoTitle, _T(APPNAME) _T(" has crashed"), 63); Shell_NotifyIcon(NIM_MODIFY, &m_nid); } CExceptionDlg dlg(exceptioninfo); int iLastExceptionDlgResult = dlg.DoModal(WinUtil::mainWnd); if (iLastExceptionDlgResult == IDCANCEL) { ExitProcess(1); } #ifndef _DEBUG UninitSymInfo(); return EXCEPTION_CONTINUE_EXECUTION; #else return EXCEPTION_CONTINUE_SEARCH; #endif }
CLanguage::CLanguage( LPCTSTR pszName, CM_LANGUAGE *pLang ) { ////////////////////////////////// // Must make complete copy of language details ////////////////////////////////// ASSERT( pszName ); ASSERT( pLang ); _tcsncpy( m_szName, pszName, ARRAY_SIZE(m_szName) ); m_szName[ARRAY_SIZE(m_szName) - 1] = 0; int nLen = ( pLang->pszKeywords ? _tcslen( pLang->pszKeywords ) + 1 : 0 ) + ( pLang->pszOperators ? _tcslen( pLang->pszOperators ) + 1 : 0 ) + ( pLang->pszSingleLineComments ? _tcslen( pLang->pszSingleLineComments ) + 1 : 0 ) + ( pLang->pszMultiLineComments1 ? _tcslen( pLang->pszMultiLineComments1 ) + 1 : 0 ) + ( pLang->pszMultiLineComments2 ? _tcslen( pLang->pszMultiLineComments2 ) + 1 : 0 ) + ( pLang->pszScopeKeywords1 ? _tcslen( pLang->pszScopeKeywords1 ) + 1 : 0 ) + ( pLang->pszScopeKeywords2 ? _tcslen( pLang->pszScopeKeywords2 ) + 1 : 0 ) + ( pLang->pszStringDelims ? _tcslen( pLang->pszStringDelims ) + 1 : 0 ) + ( pLang->pszTagElementNames ? _tcslen( pLang->pszTagElementNames ) + 1 : 0 ) + ( pLang->pszTagAttributeNames ? _tcslen( pLang->pszTagAttributeNames ) + 1 : 0 ) + ( pLang->pszTagEntities ? _tcslen( pLang->pszTagEntities ) + 1 : 0 ); int cbLang = sizeof( CM_LANGUAGE ) + // the language structure sizeof( DWORD ) + // size of language struct sizeof( TCHAR ) * ( nLen + 1 ); // the lang buffer. +1 in case nLen = 0 m_pLang = ( CM_LANGUAGE * ) new BYTE[ cbLang ]; ZeroMemory( m_pLang, cbLang ); *( ( LPDWORD ) ( m_pLang + 1 ) ) = cbLang; m_pLang->bIsCaseSensitive = pLang->bIsCaseSensitive; m_pLang->chEscape = pLang->chEscape; m_pLang->chTerminator = pLang->chTerminator; m_pLang->dwStyle = pLang->dwStyle; LPTSTR pszOut = ( LPTSTR ) ( ( LPBYTE ) ( m_pLang + 1 ) + sizeof( DWORD ) ); if ( pLang->pszKeywords ) { _tcscpy( pszOut, pLang->pszKeywords ); m_pLang->pszKeywords = pszOut; pszOut += _tcslen( pLang->pszKeywords ) + 1; } if ( pLang->pszOperators ) { _tcscpy( pszOut, pLang->pszOperators ); m_pLang->pszOperators = pszOut; pszOut += _tcslen( pLang->pszOperators ) + 1; } if ( pLang->pszSingleLineComments ) { _tcscpy( pszOut, pLang->pszSingleLineComments ); m_pLang->pszSingleLineComments = pszOut; pszOut += _tcslen( pLang->pszSingleLineComments ) + 1; } if ( pLang->pszMultiLineComments1 ) { _tcscpy( pszOut, pLang->pszMultiLineComments1 ); m_pLang->pszMultiLineComments1 = pszOut; pszOut += _tcslen( pLang->pszMultiLineComments1 ) + 1; _tcscpy( pszOut, pLang->pszMultiLineComments2 ); m_pLang->pszMultiLineComments2 = pszOut; pszOut += _tcslen( pLang->pszMultiLineComments2 ) + 1; } if ( pLang->pszScopeKeywords1 ) { _tcscpy( pszOut, pLang->pszScopeKeywords1 ); m_pLang->pszScopeKeywords1 = pszOut; pszOut += _tcslen( pLang->pszScopeKeywords1 ) + 1; _tcscpy( pszOut, pLang->pszScopeKeywords2 ); m_pLang->pszScopeKeywords2 = pszOut; pszOut += _tcslen( pLang->pszScopeKeywords2 ) + 1; } if ( pLang->pszStringDelims ) { _tcscpy( pszOut, pLang->pszStringDelims ); m_pLang->pszStringDelims = pszOut; pszOut += _tcslen( pLang->pszStringDelims ) + 1; } if ( pLang->pszTagElementNames ) { _tcscpy( pszOut, pLang->pszTagElementNames ); m_pLang->pszTagElementNames = pszOut; pszOut += _tcslen( pLang->pszTagElementNames ) + 1; } if ( pLang->pszTagAttributeNames ) { _tcscpy( pszOut, pLang->pszTagAttributeNames ); m_pLang->pszTagAttributeNames = pszOut; pszOut += _tcslen( pLang->pszTagAttributeNames ) + 1; } if ( pLang->pszTagEntities ) { _tcscpy( pszOut, pLang->pszTagEntities ); m_pLang->pszTagEntities = pszOut; pszOut += _tcslen( pLang->pszTagEntities ) + 1; } ASSERT( pszOut <= ( LPTSTR ) ( ( ( LPBYTE ) m_pLang ) + cbLang ) ); }
void MapWindow::LKDrawMultimap_Test(LKSurface& Surface, const RECT& rc) { if (DoInit[MDI_MAPTEST]) { // init statics here and then clear init to false DoInit[MDI_MAPTEST]=false; } // // X,Y coordinates of last clicked point on screen // These coordinates are related to any point clicked, even for a page flip, for bottom bar etc. // In some cases, you will read old coordinates because for example after clicking in the center of // bottom bar, the page changed out of multimap and entered nearest pages. // int X=startScreen.x; int Y=startScreen.y; // // Duration of key is inside long VKtime, in milliseconds. // // // Draw a boxed terrain/topology example // -------------------------------------- // RECT rct=rc; // desired area is 400x180, topleft is (20,30) rct.top=20; rct.bottom=rct.top+180; rct.left=30; rct.right=rct.left+400; MapWindow::ChangeDrawRect(rct); // set new area for terrain and topology PanLatitude = DrawInfo.Latitude; PanLongitude = DrawInfo.Longitude; // Current position is in center map POINT Orig = { (rct.right-rct.left)/2,(rct.bottom-rct.top)/2}; POINT Orig_Aircraft= {0,0}; //zoom.ModifyMapScale(); //zoom.UpdateMapScale(); const ScreenProjection _Proj = CalculateScreenPositions( Orig, rct, &Orig_Aircraft); CalculateScreenPositionsAirspace(rct, _Proj); double sunelevation = 40.0; double sunazimuth=GetAzimuth(); if (IsMultimapTerrain() && DerivedDrawInfo.TerrainValid) { LockTerrainDataGraphics(); DrawTerrain(Surface, rct, _Proj, sunazimuth, sunelevation); UnlockTerrainDataGraphics(); } ResetLabelDeclutter(); // This is needed to reset at each run the declutter, for topology and waypoints! // SaturateLabelDeclutter(); // Use this to force no labels be printed, from now on. DrawTopology(Surface, rct, _Proj); DrawAirSpace(Surface, rct, _Proj); // ResetLabelDeclutter(); // If you saturated labels for topology, now you can reset the declutter to allow // printing only waypoints, DrawWaypointsNew(Surface,rct); const auto oldpen = Surface.SelectObject(LKPen_White_N1); const auto oldbrush = Surface.SelectObject(LKBrush_LightGrey); LKWriteBoxedText(Surface, rct, _T("MULTIMAP PAGE EXAMPLE"), 1, 1, WTALIGN_LEFT, RGB_BLACK, RGB_WHITE); TCHAR ttext[100]; switch(LKevent) { // // USABLE EVENTS // case LKEVENT_NEWRUN: // CALLED ON ENTRY: when we select this page coming from another mapspace _tcscpy(ttext,_T("Event = NEW RUN")); break; case LKEVENT_UP: // click on upper part of screen, excluding center _tcscpy(ttext,_T("Event = UP")); break; case LKEVENT_DOWN: // click on lower part of screen, excluding center _tcscpy(ttext,_T("Event = DOWN")); break; case LKEVENT_LONGCLICK: _stprintf(ttext,_T("Event = LONG CLICK")); break; case LKEVENT_PAGEUP: _tcscpy(ttext,_T("Event = PAGE UP")); break; case LKEVENT_PAGEDOWN: _tcscpy(ttext,_T("Event = PAGE DOWN")); break; case LKEVENT_TOPLEFT: _tcscpy(ttext,_T("Event = TOP LEFT")); break; case LKEVENT_TOPRIGHT: _tcscpy(ttext,_T("Event = TOP RIGHT")); break; case LKEVENT_SHORTCLICK: _tcscpy(ttext,_T("Event = SHORT CLICK")); break; // // THESE EVENTS ARE NOT AVAILABLE IN MULTIMAPS! // case LKEVENT_ENTER: // click longer on center, like to confirm a selection _tcscpy(ttext,_T("Event = ENTER")); break; case LKEVENT_NEWPAGE: // swipe gesture up/down produces NEW PAGE in this case _tcscpy(ttext,_T("Event = NEW PAGE")); break; case LKEVENT_NONE: // Normally no event. _tcscpy(ttext,_T("Event = NONE")); break; // default: // THIS SHOULD NEVER HAPPEN, but always CHECK FOR IT! _tcscpy(ttext,_T("Event = unknown")); break; } LKWriteBoxedText(Surface, rct, ttext, 1, 50 , WTALIGN_LEFT, RGB_BLACK, RGB_WHITE); // // Be sure to check that an EVENT was generated, otherwise you are checking even bottombar key presses. // if (LKevent!=LKEVENT_NONE) { _stprintf(ttext,_T("Last coords: X=%d Y=%d , duration=%ld ms"),X,Y,VKtime); LKWriteBoxedText(Surface, rct, ttext, 1, 100 , WTALIGN_LEFT, RGB_BLACK, RGB_WHITE); } // After using the event, WE MUST CLEAR IT, otherwise it will survive for next run. // This can be good for something, though, like automatic redo of last action. // You can also clear this event at the end of this function, to know during execution which was // the key pressed, but remember to clear it. LKevent=LKEVENT_NONE; Surface.SelectObject(oldbrush); Surface.SelectObject(oldpen); }
void InfoBoxFormatter::AssignValue(int i) { switch (i) { case 0: Value = ALTITUDEMODIFY*Basic().Altitude; break; case 1: Value = ALTITUDEMODIFY*Calculated().AltitudeAGL ; Valid = Calculated().TerrainValid; break; case 2: Value = LIFTMODIFY*Calculated().Average30s; break; case 3: Value = Calculated().WaypointBearing; Valid = Calculated().WaypointDistance > 10.0; break; case 4: if (Calculated().LD== 999) { Valid = false; } else { Valid = true; Value = Calculated().LD; } break; case 5: if (Calculated().CruiseLD== 999) { Valid = false; } else { Valid = true; Value = Calculated().CruiseLD; } break; case 6: Value = SPEEDMODIFY*Basic().Speed; break; case 7: Value = LIFTMODIFY*Calculated().LastThermalAverage; break; case 8: Value = ALTITUDEMODIFY*Calculated().LastThermalGain; break; case 10: Value = iround(LIFTMODIFY*GlidePolar::GetMacCready()*10)/10.0; break; case 11: Value = DISTANCEMODIFY*Calculated().WaypointDistance; Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 12: Value = ALTITUDEMODIFY*Calculated().NextAltitudeDifference; Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 13: Value = ALTITUDEMODIFY*Calculated().NextAltitudeRequired; Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 14: Value = 0; // Next Waypoint Text break; case 15: Value = ALTITUDEMODIFY*Calculated().TaskAltitudeDifference; Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 16: Value = ALTITUDEMODIFY*Calculated().TaskAltitudeRequired; Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 17: Value = TASKSPEEDMODIFY*Calculated().TaskSpeed; if (task.getActiveIndex()>=1) { Valid = task.ValidTaskPoint(task.getActiveIndex()); } else { Valid = false; } break; case 18: if (Calculated().ValidFinish) { Value = DISTANCEMODIFY*Calculated().WaypointDistance; } else { Value = DISTANCEMODIFY*Calculated().TaskDistanceToGo; } Valid = task.ValidTaskPoint(task.getActiveIndex()); break; case 19: if (Calculated().LDFinish== 999) { Valid = false; } else { Valid = task.ValidTaskPoint(task.getActiveIndex()); if (Calculated().ValidFinish) { Value = 0; } else { Value = Calculated().LDFinish; } } break; case 20: Value = ALTITUDEMODIFY*Calculated().TerrainAlt ; Valid = Calculated().TerrainValid; break; case 21: Value = LIFTMODIFY*Calculated().AverageThermal; break; case 22: Value = ALTITUDEMODIFY*Calculated().ThermalGain; break; case 23: Value = Basic().TrackBearing; break; case 24: if (Basic().VarioAvailable) { Value = LIFTMODIFY*Basic().Vario; } else { Value = LIFTMODIFY*Calculated().Vario; } break; case 25: Value = SPEEDMODIFY*Calculated().WindSpeed; break; case 26: Value = Calculated().WindBearing; break; case 28: Value = DISTANCEMODIFY*Calculated().AATMaxDistance ; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; break; case 29: Value = DISTANCEMODIFY*Calculated().AATMinDistance ; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; break; case 30: Value = TASKSPEEDMODIFY*Calculated().AATMaxSpeed; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; if (Calculated().AATTimeToGo<1) { Valid = false; } break; case 31: Value = TASKSPEEDMODIFY*Calculated().AATMinSpeed; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; if (Calculated().AATTimeToGo<1) { Valid = false; } break; case 32: Valid = Basic().AirspeedAvailable; Value = SPEEDMODIFY*Basic().IndicatedAirspeed; break; case 33: Valid = Basic().BaroAltitudeAvailable; Value = ALTITUDEMODIFY*Basic().BaroAltitude; break; case 34: Value = SPEEDMODIFY*Calculated().VMacCready; break; case 35: Value = Calculated().PercentCircling; break; case 37: Valid = Basic().AccelerationAvailable; Value = Basic().Gload; break; case 38: if (Calculated().LDNext== 999) { Valid = false; } else { Valid = task.ValidTaskPoint(task.getActiveIndex()); Value = Calculated().LDNext; } break; case 43: // Valid = Basic().AirspeedAvailable; Value = Calculated().VOpt*SPEEDMODIFY; break; case 44: // Valid = Basic().AirspeedAvailable; Value = Calculated().NettoVario*LIFTMODIFY; break; case 48: Value = Basic().OutsideAirTemperature; break; case 49: Value = Basic().RelativeHumidity; break; case 50: Value = CuSonde::maxGroundTemperature; break; case 51: Value = DISTANCEMODIFY*Calculated().AATTargetDistance ; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; break; case 52: Value = TASKSPEEDMODIFY*Calculated().AATTargetSpeed; Valid = task.ValidTaskPoint(task.getActiveIndex()) && task.getSettings().AATEnabled; if (Calculated().AATTimeToGo<1) { Valid = false; } break; case 53: if (Calculated().LDvario== 999) { Valid = false; } else { Valid = Basic().VarioAvailable && Basic().AirspeedAvailable; Value = Calculated().LDvario; } break; case 54: Valid = Basic().AirspeedAvailable; Value = SPEEDMODIFY*Basic().TrueAirspeed; break; case 56: // team bearing Value = Calculated().TeammateBearing; Valid = true; case 58: // team range if (SettingsComputer().TeammateCodeValid) { Value = DISTANCEMODIFY*Calculated().TeammateRange; if (Value > 100) { _tcscpy(Format, _T("%.0lf")); } else { _tcscpy(Format, _T("%.1lf")); } Valid = true; } else { Valid = false; } break; case 59: Value = TASKSPEEDMODIFY*Calculated().TaskSpeedInstantaneous; if (task.getActiveIndex()>=1) { Valid = task.ValidTaskPoint(task.getActiveIndex()); } else { Valid = false; } break; case 60: Value = DISTANCEMODIFY*Calculated().HomeDistance ; if (SettingsComputer().HomeWaypoint>=0) { Valid = way_points.verify_index(SettingsComputer().HomeWaypoint); } else { Valid = false; } break; case 61: Value = TASKSPEEDMODIFY*Calculated().TaskSpeedAchieved; if (task.getActiveIndex()>=1) { Valid = task.ValidTaskPoint(task.getActiveIndex()); } else { Valid = false; } break; case 63: if (Calculated().timeCircling>0) { Value = LIFTMODIFY*Calculated().TotalHeightClimb /Calculated().timeCircling; Valid = true; } else { Value = 0.0; Valid = false; } break; case 64: Value = LIFTMODIFY*Calculated().DistanceVario; if (task.getActiveIndex()>=1) { Valid = task.ValidTaskPoint(task.getActiveIndex()); } else { Valid = false; } break; case 65: // battery voltage #if !defined(WINDOWSPC) && !defined(HAVE_POSIX) #ifndef GNAV Value = PDABatteryPercent; Valid = true; #else Value = Basic().SupplyBatteryVoltage; if (Value>0.0) { Valid = true; } else { Valid = false; } #endif #else Value = 0.0; Valid = false; #endif break; case 66: // VENTA-ADDON added GR Final if (Calculated().GRFinish== 999) { Valid = false; } else { Valid = task.ValidTaskPoint(task.getActiveIndex()); if (Calculated().ValidFinish) { Value = 0; } else { Value = Calculated().GRFinish; if (Value >100 ) { _tcscpy(Format, _T("%1.0f")); } else { _tcscpy(Format, _T("%1.1f")); } } } break; case 70: // VENTA3 QFE // Valid = Basic().Altitude; Value = ALTITUDEMODIFY* (Basic().Altitude-QFEAltitudeOffset); break; case 71: if ( Calculated().AverageLD == 0) { Valid = false; } else { Valid = true; Value = Calculated().AverageLD; if (Value<0) _tcscpy(Format, _T("^^^")); else if (Value>=999) _tcscpy(Format, _T("+++")); else _tcscpy(Format, _T("%2.0f")); } break; case 72: Value = Calculated().Experimental; Valid = true; break; /* TODO feature: add extra infoboxes from Lars case 68: // distance flown if (Calculated().TaskDistanceCovered != 0) { Value = DISTANCEMODIFY*Calculated().TaskDistanceCovered; Valid = true; } else { Value = 0.0; Valid = false; } break; case 67: // termik liga points if (Calculated().TermikLigaPoints != 0) { Value = Calculated().TermikLigaPoints; Valid = true; } else { Value = 0.0; Valid = false; } break; */ default: break; }; }
void CFileMoveProcess::ProcessFiles ( CList<CFileInfo *, CFileInfo *> & FileList) { CString Msg; SHFILEOPSTRUCT fos; TCHAR pDirBuffer[MAX_PATH]; TCHAR pFilenameBuffer[MAX_PATH]; CFileInfo * pFileInfo; POSITION ListPos; // setup to directory buffer // pDirBuffer = new TCHAR[m_Dir.GetLength()+2]; strcpy( pDirBuffer, (LPCSTR) m_Dir); pDirBuffer[m_Dir.GetLength()] = '\0'; pDirBuffer[m_Dir.GetLength()+1] = '\0'; // // setup struct fos.hwnd = AfxGetMainWnd()->m_hWnd; fos.wFunc= FO_MOVE; fos.pTo = pDirBuffer; fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI; fos.lpszProgressTitle = "NULL"; // // set confirmation flag if ( m_YesToAll ) fos.fFlags |= FOF_NOCONFIRMATION; // /* for ( int i = 0; i < FileList.GetSize(); i++) { //if ( ((CDuffDlg*)GetParent()->GetParent())->m_DuplicatePage.m_DupeList.GetCheck(i) == BST_CHECKED ) //{ Temp = FileList.ElementAt(i).m_Filename; //TotalLength += Temp.GetLength() +1; FilesToDelete.Add(Temp); //} } */ // update progress information pDuffStatus->Lock(); pDuffStatus->CurrentTaskStr = "Moving selected duplicate files..."; pDuffStatus->CurrentTaskInfo = ""; pDuffStatus->SubProgress1.Min = 0; pDuffStatus->SubProgress1.Pos = 0; pDuffStatus->SubProgress1.Max = FileList.GetCount(); pDuffStatus->Unlock(); // ListPos = FileList.GetHeadPosition(); while (ListPos) { pFileInfo = FileList.GetAt(ListPos); // process only the selected files if ( pFileInfo->Selected) { if ( ! (pFileInfo->Attributes & FILE_ATTRIBUTE_READONLY) || m_MoveReadOnly ) { /* // remove read-only attribute if ( FileList.ElementAt(i)->ReadOnly ) { DWORD FileAttributes; FileAttributes = GetFileAttributes( FileList.ElementAt(i)->Filename ) FileAttributes ^= FILE_ATTRIBUTE_READONLY; SetFileAttributes(FileList.ElementAt(i)->Filename,FileAttributes ); }*/ _tcscpy(pFilenameBuffer, pFileInfo->GetFullName() ); UINT Length = _tcslen( pFilenameBuffer ); // for (int x = 0; x < FileList.ElementAt(i)->Filename.GetLength(); x++) // { // pFilenameBuffer[x] = FileList.ElementAt(i)->Filename.GetAt(x); // } pFilenameBuffer[Length] = 0; pFilenameBuffer[Length+1] = 0; fos.pFrom = pFilenameBuffer; // g_DupeFileFind.GetDuffDlg()->m_CurrentTaskInfoText.SetWindowText(FileList.ElementAt(i)->GetFullName()); // g_DupeFileFind.GetDuffDlg()->m_CurrentTaskInfoText.RedrawWindow(); // update progress information pDuffStatus->Lock(); pDuffStatus->CurrentTaskInfo = pFileInfo->GetFullName(); pDuffStatus->SubProgress1.Pos++; pDuffStatus->Unlock(); // /* Msg.Format("Moving:\n%s\nto:\n%s",FileList.ElementAt(i)->m_Filename,fos.pTo); MessageBox(NULL,Msg,"FYI",MB_OK); */ if ( SHFileOperation(&fos) ) { Msg.Format("ERROR moving file: %s to %s",pFileInfo->GetFullName(),m_Dir); // g_DupeFileFind.GetDuffDlg()->Log(Msg); } else { Msg.Format("Moved file: %s to %s",pFileInfo->GetFullName(),m_Dir); // g_DupeFileFind.GetDuffDlg()->Log(Msg); } // g_DupeFileFind.GetDuffDlg()->m_ProgressEntire.StepIt(); // delete []pFilenameBuffer; } } FileList.GetNext(ListPos); } // delete[] pDirBuffer; }
void InfoBoxFormatter::RenderInvalid(int *color) { _tcscpy(CommentText, _T("")); _tcscpy(Text, _T("---")); *color = -1; }
bool EWDevice::AddWaypoint(const Waypoint &way_point, OperationEnvironment &env) { char EWRecord[100]; TCHAR IDString[12]; int DegLat, DegLon; double tmp, MinLat, MinLon; char NoS, EoW; // check for max 6 TP's if (ewDecelTpIndex > 6) return false; // copy at most 6 chars CopyString(IDString, way_point.name.c_str(), 7); // fill up with spaces while (_tcslen(IDString) < 6) _tcscat(IDString, _T(" ")); #if USESHORTTPNAME > 0 // truncate to short name _tcscpy(&IDString[3], _T(" ")); #endif // prepare lat tmp = (double)way_point.location.latitude.Degrees(); NoS = 'N'; if (tmp < 0) { NoS = 'S'; tmp = -tmp; } DegLat = (int)tmp; MinLat = (tmp - DegLat) * 60 * 1000; // prepare long tmp = (double)way_point.location.longitude.Degrees(); EoW = 'E'; if (tmp < 0) { EoW = 'W'; tmp = -tmp; } DegLon = (int)tmp; MinLon = (tmp - DegLon) * 60 * 1000; // Calc E/W and N/S flags // prepare flags const unsigned EoW_Flag = EoW == 'W' ? 0x08 : 0x04; const unsigned NoS_Flag = NoS == 'N' ? 0x01 : 0x02; // Do the calculation const unsigned EW_Flags = (short)(EoW_Flag | NoS_Flag); // setup command string sprintf(EWRecord, "#STP%02X%02X%02X%02X%02X%02X%02X%02X%02X%04X%02X%04X", ewDecelTpIndex, IDString[0], IDString[1], IDString[2], IDString[3], IDString[4], IDString[5], EW_Flags, DegLat, (int)MinLat / 10, DegLon, (int)MinLon / 10); WriteWithChecksum(port, EWRecord); // wait for response if (!port.ExpectString("OK\r", env)) return false; // increase TP index ewDecelTpIndex++; return true; }
void LCT_DumpResult(const TCHAR* pszHint) { const LCT_LINE* pl; const LCT_FILE* pf; TCHAR szFile[2*MAX_PATH]; long nNewHits; long nOldHits; long nAllTest; FILE* pFile; return; szFile[0] = 0; GetModuleFileName(NULL, szFile, FC_ARRAY_LEN(szFile)); _tcscat(szFile, _T(".clt")); if(!FC_Exist(szFile)) { _tprintf(_T("TEST: line coverage: create '%s'\n"), szFile); pFile = _tfopen(szFile, _T("at")); if(!pFile) { _tprintf(_T("error: line coverage test: cannot write file '%s'\n"),szFile); return; } for(pf= &g_lctfileList[0]; pf->pszSrc; pf++) { fprintf(pFile, "\n[%s]\n", pf->pszSrc); for(pl= &pf->pLines[0]; pl->lineNo>0; pl++) fprintf(pFile, "%d=TODO: %s\n", pl->lineNo, pl->pszInf); } fclose(pFile); } // _tprintf(_T("TEST: line coverage: update '%s'\n"), szFile); if(pszHint) WritePrivateProfileString(_T("<History>"), "12.56.2002", pszHint, szFile); nNewHits = nOldHits = nAllTest = 0; for(pf= &g_lctfileList[0]; pf->pszSrc; pf++) { TCHAR szLineNo[64]; TCHAR szBuffer[MAX_PATH]; for(pl= &pf->pLines[0]; pl->lineNo>0; pl++) { nAllTest++; ltoa(pl->lineNo, szLineNo, 10); if(LCT_IsHit(pf->pszSrc, pl->lineNo)) { _tcscpy(szBuffer, _T("OK: ")); _tcscat(szBuffer, pl->pszInf); WritePrivateProfileString(pf->pszSrc, szLineNo, szBuffer, szFile); nNewHits++; } else { GetPrivateProfileString(pf->pszSrc, szLineNo, _T(""), szBuffer, FC_ARRAY_LEN(szBuffer), szFile); if(FC_StringBeginI(szBuffer, _T("OK:"))) nOldHits++; } } } _tprintf(_T("TEST: line coverage: new hits=%d, old hits=%d (left to do=%d of %d)\n"), nNewHits, nOldHits, nAllTest-nNewHits-nOldHits, nAllTest); if(g_lctHash) { g_lctHash->deletePtrs(); delete(g_lctHash); g_lctHash = NULL; } }
void PortCache::GetPortStateText(DWORD dwPortState, int nLanguageID, TCHAR szPortState[]) { switch (dwPortState) { case MIB_TCP_STATE_CLOSED: _tcscpy(szPortState, nLanguageID == 0 ? _T("已经关闭") : _T("CLOSED")); break; case MIB_TCP_STATE_LISTEN: _tcscpy(szPortState, nLanguageID == 0 ? _T("正在监听") : _T("LISTEN")); break; case MIB_TCP_STATE_SYN_SENT: _tcscpy(szPortState, nLanguageID == 0 ? _T("发送请求") : _T("SYN_SENT")); break; case MIB_TCP_STATE_SYN_RCVD: _tcscpy(szPortState, nLanguageID == 0 ? _T("接收请求") : _T("SYN_RCVD")); break; case MIB_TCP_STATE_ESTAB: _tcscpy(szPortState, nLanguageID == 0 ? _T("已经建立") : _T("ESTABLISHED")); break; case MIB_TCP_STATE_FIN_WAIT1: _tcscpy(szPortState, nLanguageID == 0 ? _T("等待 1") : _T("FIN_WAIT1")); break; case MIB_TCP_STATE_FIN_WAIT2: _tcscpy(szPortState, nLanguageID == 0 ? _T("等待 2") : _T("FIN_WAIT2")); break; case MIB_TCP_STATE_CLOSE_WAIT: _tcscpy(szPortState, nLanguageID == 0 ? _T("等待关闭") : _T("CLOSE_WAIT")); break; case MIB_TCP_STATE_CLOSING: _tcscpy(szPortState, nLanguageID == 0 ? _T("正在关闭") : _T("CLOSING")); break; case MIB_TCP_STATE_LAST_ACK: _tcscpy(szPortState, nLanguageID == 0 ? _T("等待中断") : _T("LAST_ACK")); break; case MIB_TCP_STATE_TIME_WAIT: _tcscpy(szPortState, nLanguageID == 0 ? _T("等待超时") : _T("TIME_WAIT")); break; case MIB_TCP_STATE_DELETE_TCB: _tcscpy(szPortState, nLanguageID == 0 ? _T("删除TCB") : _T("DELETE")); break; default: break; } }
// Fetch the map file full path name. HANDLE LocationDialog::openMapFile(char* mapName) { HANDLE hMap; TCHAR fileName[MAX_PATH]; int len; // Get subdir containing this plugin. GetModuleFileName(hInstance, fileName, MAX_PATH); // Append subdir string containing maps. TCHAR *slash = _tcsrchr(fileName, '\\'); if (slash) { _tcscpy(slash, SGEOLOC); } else { // If the plugin filename contains no path information, look in plugcfg. _tcscpy(fileName,theInterface->GetDir(APP_PLUGCFG_DIR)); len = _tcslen(fileName); if (len) { if (_tcscmp(&fileName[len-1],_T("\\"))) _tcscat(fileName,_T("\\")); } } _tcscat(fileName,mapName); hMap = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hMap == INVALID_HANDLE_VALUE) { // If that fails, look in the MaxStart dir. _tcscpy(fileName,theInterface->GetDir(APP_MAXSTART_DIR)); len = _tcslen(fileName); if (len) { if (_tcscmp(&fileName[len-1],_T("\\"))) _tcscat(fileName,_T("\\")); _tcscat(fileName, GEOLOC); } _tcscat(fileName,mapName); hMap = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hMap == INVALID_HANDLE_VALUE) { // If THAT fails, look beneath the main exe dir. _tcscpy(fileName,theInterface->GetDir(APP_MAXROOT_DIR)); len = _tcslen(fileName); if (len) { if (_tcscmp(&fileName[len-1],_T("\\"))) _tcscat(fileName,_T("\\")); } _tcscat(fileName, GEOLOC); _tcscat(fileName,mapName); hMap = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hMap == INVALID_HANDLE_VALUE) { // Last try: If THAT fails, look IN the main exe dir. _tcscpy(fileName,theInterface->GetDir(APP_MAXROOT_DIR)); len = _tcslen(fileName); if (len) { if (_tcscmp(&fileName[len-1],_T("\\"))) _tcscat(fileName,_T("\\")); } _tcscat(fileName,mapName); hMap = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); } } } return hMap; }
int TestPathCchStripPrefix(int argc, char* argv[]) { HRESULT status; TCHAR Path[PATHCCH_MAX_CCH]; int i; /** * PathCchStripPrefix returns S_OK if the prefix was removed, S_FALSE if * the path did not have a prefix to remove, or an HRESULT failure code. */ /* Path with prefix (File Namespace) */ _tcscpy(Path, testPathPrefixFileNamespace); status = PathCchStripPrefix(Path, sizeof(testPathPrefixFileNamespace) / sizeof(TCHAR)); if (status != S_OK) { _tprintf(_T("PathCchStripPrefix status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathNoPrefixFileNamespace) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathNoPrefixFileNamespace); return -1; } /* Path with prefix (Device Namespace) */ _tcscpy(Path, testPathPrefixDeviceNamespace); status = PathCchStripPrefix(Path, sizeof(testPathPrefixDeviceNamespace) / sizeof(TCHAR)); if (status != S_FALSE) { _tprintf(_T("PathCchStripPrefix status: 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathPrefixDeviceNamespace) != 0) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathPrefixDeviceNamespace); return -1; } /* NULL Path */ status = PathCchStripPrefix(NULL, PATHCCH_MAX_CCH); if (status != E_INVALIDARG) { _tprintf(_T("PathCchStripPrefix with null path unexpectedly succeeded with status 0x%08X\n"), status); return -1; } /* Invalid cchPath values: 0, 1, 2, 3 and > PATHCCH_MAX_CCH */ for (i = 0; i < 5; i++) { _tcscpy(Path, testPathPrefixFileNamespace); if (i == 4) i = PATHCCH_MAX_CCH + 1; status = PathCchStripPrefix(Path, i); if (status != E_INVALIDARG) { _tprintf(_T("PathCchStripPrefix with invalid cchPath value %d unexpectedly succeeded with status 0x%08X\n"), i, status); return -1; } } /* Minimum Path that would get successfully stripped on windows */ _tcscpy(Path, testPathPrefixFileNamespaceMinimum); i = sizeof(testPathPrefixFileNamespaceMinimum) / sizeof(TCHAR); i = i - 1; /* include testing of a non-null terminated string */ status = PathCchStripPrefix(Path, i); if (status != S_OK) { _tprintf(_T("PathCchStripPrefix with minimum valid strippable path length unexpectedly returned status 0x%08X\n"), status); return -1; } if (_tcscmp(Path, testPathNoPrefixFileNamespaceMinimum)) { _tprintf(_T("Path Mismatch: Actual: %s, Expected: %s\n"), Path, testPathNoPrefixFileNamespaceMinimum); return -1; } /* Invalid drive letter symbol */ _tcscpy(Path, _T("\\\\?\\5:")); status = PathCchStripPrefix(Path, 6); if (status == S_OK) { _tprintf(_T("PathCchStripPrefix with invalid drive letter symbol unexpectedly succeeded\n")); return -1; } return 0; }
void SetUnits(const TCHAR *text) { _tcscpy(mUnits, text); }
/////////////////////////////////////////////////////////////////////////////// // OnPaint void CXHTMLStatic::OnPaint() { CPaintDC dc(this); // device context for painting // get text from control CString strText = _T(""); GetWindowText(strText); // replace character entity names with codes TCHAR ent[3] = { 0 }; ent[0] = _T('\001'); // each entity name is replaced with a two-character // code that begins with \001 for (int i = 0; m_aCharEntities[i].pszName != NULL; i++) { ent[1] = m_aCharEntities[i].cCode; strText.Replace(m_aCharEntities[i].pszName, ent); } CString str1 = _T(""); int index = 0; // set text and background colors COLORREF crText = m_crText; COLORREF prev_crText = crText; COLORREF crBackground = m_crBackGround; COLORREF prev_crBackground = crBackground; CFont *pOldFont = dc.SelectObject(&m_font); int n = strText.GetLength(); CRect rect; GetClientRect(&rect); //dc.FillSolidRect(&rect, m_crBackGround); // allow for margins rect.left += m_nLeftMargin; rect.right -= m_nRightMargin; int nInitialXOffset = 0;//m_nLeftMargin; m_yStart = rect.top; LOGFONT lf, prev_lf; if (m_bLogFont) { memcpy(&lf, &m_lf, sizeof(lf)); } else { CFont* cf = GetFont(); if (cf) cf->GetObject(sizeof(lf), &lf); else GetObject(GetStockObject(SYSTEM_FONT), sizeof(lf), &lf); } memcpy(&prev_lf, &lf, sizeof(lf)); CString strAnchorText = _T(""); BOOL bSizeChange = FALSE; //BOOL bEndOfSizeChange = FALSE; TEXTMETRIC tm; dc.GetTextMetrics(&tm); while (n > 0) { /////////////////////////////////////////////////////////////////////// if (_tcsnicmp(strText, _T("<B>"), 3) == 0) // check for <b> or <B> { n -= 3; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bBold++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</B>"), 4) == 0) // check for </B> { n -= 4; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bBold) m_bBold--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<I>"), 3) == 0) // check for <I> { n -= 3; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bItalic++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</I>"), 4) == 0) // check for </I> { n -= 4; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bItalic) m_bItalic--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<U>"), 3) == 0) // check for <U> { n -= 3; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bUnderline++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</U>"), 4) == 0) // check for </U> { n -= 4; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bUnderline) m_bUnderline--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<STRIKE>"), 8) == 0) // check for <STRIKE> { n -= 8; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bStrikeThrough++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</STRIKE>"), 9) == 0) // check for </STRIKE> { n -= 9; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bStrikeThrough) m_bStrikeThrough--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<BIG>"), 5) == 0) // check for <BIG> { n -= 5; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (lf.lfHeight > 0) lf.lfHeight++; else lf.lfHeight--; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</BIG>"), 6) == 0) // check for </BIG> { n -= 6; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (lf.lfHeight > 0) lf.lfHeight--; else lf.lfHeight++; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<SMALL>"), 7) == 0) // check for <SMALL> { n -= 7; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (lf.lfHeight > 0) lf.lfHeight--; else lf.lfHeight++; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</SMALL>"), 8) == 0) // check for </SMALL> { n -= 8; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (lf.lfHeight > 0) lf.lfHeight++; else lf.lfHeight--; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<SUB>"), 5) == 0) // check for <SUB> { n -= 5; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bSubscript++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</SUB>"), 6) == 0) // check for </SUB> { n -= 6; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bSubscript) m_bSubscript--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<SUP>"), 5) == 0) // check for <SUP> { n -= 5; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); m_bSuperscript++;// = TRUE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</SUP>"), 6) == 0) // check for </SUP> { n -= 6; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); if (m_bSuperscript) m_bSuperscript--;// = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<FONT"), 5) == 0) // check for <FONT { index = strText.Find(_T('>')); if (index != -1) { CString strAttributes = strText.Mid(5, index-5); int m = strAttributes.GetLength(); strText = strText.Mid(index+1); // loop to parse FONT attributes while (m > 0) { // trim left whitespace if ((strAttributes.GetLength() > 0) && (strAttributes[0] == _T(' '))) { m--; strAttributes = strAttributes.Mid(1); continue; } /////////////////////////////////////////////////////////// if (_tcsnicmp(strAttributes, _T("COLOR"), 5) == 0) { int index2 = strAttributes.Find(_T('"')); if (index2 != -1) { m -= index2 + 1; strAttributes = strAttributes.Mid(index2+1); index2 = strAttributes.Find(_T('"')); if (index2 != -1) { CString strColor = strAttributes.Left(index2); CXNamedColors nc(strColor); crText = nc.GetRGB(); strAttributes = strAttributes.Mid(index2+1); m = strAttributes.GetLength(); } } else break; } /////////////////////////////////////////////////////////// else if (_tcsnicmp(strAttributes, _T("BGCOLOR"), 7) == 0) { int index2 = strAttributes.Find(_T('"')); if (index2 != -1) { m -= index2 + 1; strAttributes = strAttributes.Mid(index2+1); index2 = strAttributes.Find(_T('"')); if (index2 != -1) { CString strBgColor = strAttributes.Left(index2); CXNamedColors nc(strBgColor); crBackground = nc.GetRGB(); strAttributes = strAttributes.Mid(index2+1); m = strAttributes.GetLength(); } } else break; } /////////////////////////////////////////////////////////// else if (_tcsnicmp(strAttributes, _T("FACE"), 4) == 0) { int index2 = strAttributes.Find(_T('"')); if (index2 != -1) { m -= index2 + 1; strAttributes = strAttributes.Mid(index2+1); index2 = strAttributes.Find(_T('"')); if (index2 != -1) { memset(lf.lfFaceName, 0, sizeof(lf.lfFaceName)); _tcsncpy(lf.lfFaceName, strAttributes, index2); m -= index2 + 1; if (m > 0) strAttributes = strAttributes.Mid(index2+1); else strAttributes = _T(""); m = strAttributes.GetLength(); } } else break; } /////////////////////////////////////////////////////////// else if (_tcsnicmp(strAttributes, _T("SIZE"), 4) == 0) { int index2 = strAttributes.Find(_T('"')); if (index2 != -1) { m -= index2 + 1; strAttributes = strAttributes.Mid(index2+1); index2 = strAttributes.Find(_T('"')); if (index2 != -1) { int nSize = 0; nSize = _ttoi(strAttributes); lf.lfHeight -= nSize; bSizeChange = TRUE; m -= index2 + 1; if (m > 0) strAttributes = strAttributes.Mid(index2+1); else strAttributes = _T(""); m = strAttributes.GetLength(); } } else break; } else { while ((strAttributes.GetLength() > 0) && (strAttributes[0] != _T(' '))) { m--; strAttributes = strAttributes.Mid(1); } } } n -= index + 1; } continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</FONT>"), 7) == 0) // check for </FONT> { n -= 7; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); crText = prev_crText; crBackground = prev_crBackground; memcpy(&lf, &prev_lf, sizeof(lf)); if (bSizeChange) m_yStart += tm.tmDescent; bSizeChange = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<CODE>"), 6) == 0) // check for <CODE> { n -= 6; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); _tcscpy(lf.lfFaceName, _T("Courier New")); continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</CODE>"), 7) == 0) // check for </CODE> { n -= 7; index = strText.Find(_T('>')); if (index != -1) strText = strText.Mid(index+1); memcpy(&lf, &prev_lf, sizeof(lf)); continue; } /////////////////////////////////////////////////////////////////////// // <a href=www.xyz.com>XYZ Web Site</a> else if (_tcsnicmp(strText, _T("<A HREF="), 8) == 0) // check for <A HREF= { index = strText.Find(_T('>')); if (index != -1) { strAnchorText = strText.Mid(8, index-8); strText = strText.Mid(index+1); n = strText.GetLength(); m_bInAnchor = TRUE; continue; } } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("</A>"), 4) == 0) // check for </A> { strText = strText.Mid(4); n -= 4; m_bInAnchor = FALSE; continue; } /////////////////////////////////////////////////////////////////////// else if (_tcsnicmp(strText, _T("<HR"), 3) == 0) // check for <HR> { index = strText.Find(_T('>')); if (index != -1) { CString strAttributes = strText.Mid(3); //, index-3); int m = strAttributes.GetLength(); strText = strText.Mid(index+1); // loop to parse attributes while (m > 0) { // trim left whitespace if ((strAttributes.GetLength() > 0) && (strAttributes[0] == _T(' '))) { m--; strAttributes = strAttributes.Mid(1); continue; } /////////////////////////////////////////////////////////// if (_tcsnicmp(strAttributes, _T("SIZE"), 4) == 0) { int index2 = strAttributes.Find(_T('=')); if (index2 != -1) { m -= index2 + 1; strAttributes = strAttributes.Mid(index2+1); index2 = strAttributes.Find(_T('>')); if (index2 != -1) { CString strSize = strAttributes.Left(index2); m_nHorizontalRuleSize = _ttoi(strSize); strAttributes = strAttributes.Mid(index2+1); m = strAttributes.GetLength(); } } else break; } else { while ((strAttributes.GetLength() > 0) && (strAttributes[0] != _T(' '))) { m--; strAttributes = strAttributes.Mid(1); } } } n -= index + 1; } m_bHorizontalRule++;// = TRUE; str1 = _T("\r\n"); m_bGeneratedText = TRUE; } /////////////////////////////////////////////////////////////////////// // <br> or \r\n or plain text else { str1 = strText; index = str1.Find(_T('<')); if (index != -1) { if (_tcsnicmp(strText, _T("<BR>"), 4) == 0) // check for <BR> { n -= 4; str1 = _T("\r\n"); m_bGeneratedText = TRUE; strText = strText.Mid(4); } else { str1 = strText.Left(index); if (str1.GetLength() <= 0) { if (strText.GetLength() != 0) { str1 = strText[0]; index = 1; n -= 1; } } strText = strText.Mid(index); } } else { str1 = strText; strText = _T(""); } } lf.lfWeight = m_bBold ? FW_BOLD : FW_NORMAL; lf.lfUnderline = (BYTE) m_bUnderline; lf.lfItalic = (BYTE) m_bItalic; lf.lfStrikeOut = (BYTE) m_bStrikeThrough; m_font.DeleteObject(); VERIFY(m_font.CreateFontIndirect(&lf)); dc.SetTextColor(crText); //dc.SetBkColor(crBackground); dc.SetBkMode(TRANSPARENT); dc.SelectObject(&m_font); dc.GetTextMetrics(&tm); int nBaselineAdjust = tm.tmAscent / 2; if (m_bSubscript) { rect.top += nBaselineAdjust; rect.bottom += nBaselineAdjust; m_yStart += nBaselineAdjust; } if (m_bSuperscript) { rect.top -= nBaselineAdjust; rect.bottom -= nBaselineAdjust; m_yStart -= nBaselineAdjust; } nInitialXOffset = FormatText(dc.m_hDC, str1, &rect, nInitialXOffset); if (str1 == _T("\r\n")) { nInitialXOffset = 0; } if (m_bSubscript) { rect.top -= nBaselineAdjust; rect.bottom -= nBaselineAdjust; m_yStart -= nBaselineAdjust; } if (m_bSuperscript) { rect.top += nBaselineAdjust; rect.bottom += nBaselineAdjust; m_yStart += nBaselineAdjust; } if (m_bInAnchor) { SIZE size; GetTextExtentPoint32(dc.m_hDC, str1, str1.GetLength(), &size); CRect rectDraw = rect; rectDraw.bottom = rectDraw.top + size.cy; rectDraw.left = nInitialXOffset - size.cx; rectDraw.right = nInitialXOffset; // save rect for this text - save in window coordinates CRect *pRect = new CRect(rectDraw); m_AnchorRectPtrs.Add(pRect); m_AnchorUrls.Add(strAnchorText); TRACE(_T("added anchor: <%s>\n"), strAnchorText); //TRACERECT(*pRect); if (!m_bHyperlinkTimer) { m_bHyperlinkTimer = TRUE; SetTimer(1, 80, NULL); } } // draw horizontal rule if (m_bHorizontalRule) { int nPenWidth = m_nHorizontalRuleSize; CPen pen(PS_SOLID, nPenWidth, crText); CPen *pOldPen = dc.SelectObject(&pen); dc.MoveTo(rect.left-m_nLeftMargin, rect.top); dc.LineTo(rect.right+m_nRightMargin, rect.top); if (pOldPen) dc.SelectObject(pOldPen); m_yStart += nPenWidth; rect.top += nPenWidth; rect.bottom += nPenWidth; nInitialXOffset = 0; m_bHorizontalRule--; } if (!m_bGeneratedText) n -= str1.GetLength(); m_bGeneratedText = FALSE; } // Restore DC's State dc.SelectObject(pOldFont); // Do not call CStatic::OnPaint() for painting messages }
size_t Clipboard::Get(LPTSTR aBuf) // If aBuf is NULL, it returns the length of the text on the clipboard and leaves the // clipboard open. Otherwise, it copies the clipboard text into aBuf and closes // the clipboard (UPDATE: But only if the clipboard is still open from a prior call // to determine the length -- see later comments for details). In both cases, the // length of the clipboard text is returned (or the value CLIPBOARD_FAILURE if error). // If the clipboard is still open when the next MsgSleep() is called -- presumably // because the caller never followed up with a second call to this function, perhaps // due to having insufficient memory -- MsgSleep() will close it so that our // app doesn't keep the clipboard tied up. Note: In all current cases, the caller // will use MsgBox to display an error, which in turn calls MsgSleep(), which will // immediately close the clipboard. { // Seems best to always have done this even if we return early due to failure: if (aBuf) // It should be safe to do this even at its peak capacity, because caller // would have then given us the last char in the buffer, which is already // a zero terminator, so this would have no effect: *aBuf = '\0'; UINT i, file_count = 0; BOOL clipboard_contains_text = IsClipboardFormatAvailable(CF_NATIVETEXT); BOOL clipboard_contains_files = IsClipboardFormatAvailable(CF_HDROP); if (!(clipboard_contains_text || clipboard_contains_files)) return 0; if (!mIsOpen) { // As a precaution, don't give the caller anything from the clipboard // if the clipboard isn't already open from the caller's previous // call to determine the size of what's on the clipboard (no other app // can alter its size while we have it open). The is to prevent a // buffer overflow from happening in a scenario such as the following: // Caller calls us and we return zero size, either because there's no // CF_TEXT on the clipboard or there was a problem opening the clipboard. // In these two cases, the clipboard isn't open, so by the time the // caller calls us again, there's a chance (vanishingly small perhaps) // that another app (if our thread were preempted long enough, or the // platform is multiprocessor) will have changed the contents of the // clipboard to something larger than zero. Thus, if we copy that // into the caller's buffer, the buffer might overflow: if (aBuf) return 0; if (!Open()) { // Since this should be very rare, a shorter message is now used. Formerly, it was // "Could not open clipboard for reading after many timed attempts. Another program is probably holding it open." Close(CANT_OPEN_CLIPBOARD_READ); return CLIPBOARD_FAILURE; } if ( !(mClipMemNow = g_clip.GetClipboardDataTimeout(clipboard_contains_files ? CF_HDROP : CF_NATIVETEXT)) ) { // v1.0.47.04: Commented out the following that had been in effect when clipboard_contains_files==false: // Close("GetClipboardData"); // Short error message since so rare. // return CLIPBOARD_FAILURE; // This was done because there are situations when GetClipboardData can fail indefinitely. // For example, in Firefox, pulling down the Bookmarks menu then right-clicking "Bookmarks Toolbar // Folder" then selecting "Copy" puts one or more formats on the clipboard that cause this problem. // For details, search the forum for TYMED_NULL. // // v1.0.42.03: For the fix below, GetClipboardDataTimeout() knows not to try more than once // for CF_HDROP. // Fix for v1.0.31.02: When clipboard_contains_files==true, tolerate failure, which happens // as a normal/expected outcome when there are files on the clipboard but either: // 1) zero of them; // 2) the CF_HDROP on the clipboard is somehow misformatted. // If you select the parent ".." folder in WinRar then use the following hotkey, the script // would previously yield a runtime error: //#q:: //Send, ^c //ClipWait, 0.5, 1 //msgbox %Clipboard% //Return Close(); if (aBuf) *aBuf = '\0'; return CLIPBOARD_FAILURE; // Return this because otherwise, Contents() returns mClipMemNowLocked, which is NULL. } // Although GlobalSize(mClipMemNow) can yield zero in some cases -- in which case GlobalLock() should // not be attempted -- it probably can't yield zero for CF_HDROP and CF_TEXT because such a thing has // never been reported by anyone. Therefore, GlobalSize() is currently not called. if ( !(mClipMemNowLocked = (LPTSTR)GlobalLock(mClipMemNow)) ) { Close(_T("GlobalLock")); // Short error message since so rare. return CLIPBOARD_FAILURE; } // Otherwise: Update length after every successful new open&lock: // Determine the length (size - 1) of the buffer than would be // needed to hold what's on the clipboard: if (clipboard_contains_files) { if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0)) { mLength = (file_count - 1) * 2; // Init; -1 if don't want a newline after last file. for (i = 0; i < file_count; ++i) mLength += DragQueryFile((HDROP)mClipMemNowLocked, i, NULL, 0); } else mLength = 0; } else // clipboard_contains_text mLength = _tcslen(mClipMemNowLocked); if (mLength >= CLIPBOARD_FAILURE) // Can't realistically happen, so just indicate silent failure. return CLIPBOARD_FAILURE; } if (!aBuf) return mLength; // Above: Just return the length; don't close the clipboard because we expect // to be called again soon. If for some reason we aren't called, MsgSleep() // will automatically close the clipboard and clean up things. It's done this // way to avoid the chance that the clipboard contents (and thus its length) // will change while we don't have it open, possibly resulting in a buffer // overflow. In addition, this approach performs better because it avoids // the overhead of having to close and reopen the clipboard. // Otherwise: if (clipboard_contains_files) { if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0)) for (i = 0; i < file_count; ++i) { // Caller has already ensured aBuf is large enough to hold them all: aBuf += DragQueryFile((HDROP)mClipMemNowLocked, i, aBuf, 999); if (i < file_count - 1) // i.e. don't add newline after the last filename. { *aBuf++ = '\r'; // These two are the proper newline sequence that the OS prefers. *aBuf++ = '\n'; } //else DragQueryFile() has ensured that aBuf is terminated. } // else aBuf has already been terminated upon entrance to this function. } else _tcscpy(aBuf, mClipMemNowLocked); // Caller has already ensured that aBuf is large enough. // Fix for v1.0.37: Close() is no longer called here because it prevents the clipboard variable // from being referred to more than once in a line. For example: // Msgbox %Clipboard%%Clipboard% // ToolTip % StrLen(Clipboard) . Clipboard // Instead, the clipboard is later closed in other places (search on CLOSE_CLIPBOARD_IF_OPEN // to find them). The alternative to fixing it this way would be to let it reopen the clipboard // by means getting rid of the following lines above: //if (aBuf) // return 0; // However, that has the risks described in the comments above those two lines. return mLength; }
/* * See if the mouse is located on a hyperlink and, * if so, run it. */ BOOL RunHyperlink( LPCLASSDATA lpcd ) { /* * Get the hyperlink at the current mouse * position. */ TCHAR *pszLink = GetHyperlink( lpcd ); // Modified by Stephan (2005-05-28) if ( pszLink ) { // If it is not a URL if (!_tcsnicmp(pszLink, _T("c:\\"), 3) || !_tcsnicmp(pszLink, _T("d:\\"), 3) || !_tcsnicmp(pszLink, _T("\\\\"), 2) || !_tcsnicmp(pszLink, _T("%"), 1)) { TCHAR szAliasFolder[MAX_PATH], szPath[MAX_PATH]; TCHAR szModuleFileName[MAX_PATH]; TCHAR szExecParams[MAX_PATH]; LPTSTR pszLinkNoAlias = pszLink; // Resolve aliases szAliasFolder[0] = 0; if (!_tcsnicmp(pszLink, _T("%WINDIR%"), 8)) { GetWindowsDirectory(szAliasFolder, MAX_PATH); pszLinkNoAlias += 8; } else if (!_tcsnicmp(pszLink, _T("C:\\Program Files (x86)\\Common"), 29)) { _tcscpy(szAliasFolder, _T("c:\\Program Files (x86)\\Common Files")); pszLinkNoAlias += 29; } else if (!_tcsnicmp(pszLink, _T("C:\\Program Files\\Common"), 23)) { _tcscpy(szAliasFolder, _T("c:\\Program Files\\Common Files")); pszLinkNoAlias += 23; } else if (!_tcsnicmp(pszLink, _T("%ProgramFilesDir%"), 17)) { if (GetSystemDefaultLangID() & 0x07) // German _tcscpy(szAliasFolder, _T("c:\\Programme")); else _tcscpy(szAliasFolder, _T("c:\\Program Files")); pszLinkNoAlias += 17; } else if (!_tcsnicmp(pszLink, _T("%temp%"), 6)) { GetTempPath(MAX_PATH, szAliasFolder); pszLinkNoAlias += 6; } // Remove :line at the end if (_tcschr(pszLinkNoAlias, _T(':')) != _tcsrchr(pszLinkNoAlias, _T(':'))) { LPTSTR lpszSemicolon = _tcsrchr(pszLinkNoAlias, _T(':')); if (lpszSemicolon) lpszSemicolon[0] = _T('\0'); } _stprintf(szPath, _T("%s%s"), szAliasFolder, pszLinkNoAlias); GetModuleFileName(NULL, szModuleFileName, MAX_PATH); _stprintf(szExecParams, _T("-hyperlink \"%s\""), szPath); if (( int )ShellExecute( GetDesktopWindow(), NULL, szModuleFileName, szExecParams, NULL, SW_SHOWNORMAL ) <= 32 ) { OkIOError( lpcd, lpcd->hWnd, _T( "%s" ), szPath ); } } // Execute URL else { if (( int )ShellExecute( GetDesktopWindow(), NULL, pszLink, NULL, NULL, SW_SHOWNORMAL ) <= 32 ) OkIOError( lpcd, lpcd->hWnd, _T( "%s" ), pszLink ); } /* * Release the url buffer. */ FreePooled( lpcd->pMemPool, pszLink ); return TRUE; } /* * No hyperlink or memory failure... */ return FALSE; }
xpr_sint_t Thumbnail::runThread(xpr::Thread &aThread) { HWND sHwnd; xpr_uint_t sMsg; xpr_tchar_t sPath[XPR_MAX_PATH + 1]; xpr_char_t sPathA[XPR_MAX_PATH + 1]; xpr_size_t sInputBytes; xpr_size_t sOutputBytes; CSize sThumbSize; ThumbItem *sThumbItem = XPR_NULL; GFL_BITMAP *sGflBitmap = XPR_NULL; GFL_LOAD_PARAMS sGflLoadParams; xpr_uchar_t *sDibData = XPR_NULL; BITMAPINFOHEADER sBitmapInfoHeader; CBitmap *sBitmap, *sOldBitmap; ThumbImage *sThumbImage; CSize sPicSize; xpr_sint_t x, y, cx, cy; xpr_double_t sRatio; CRect sDestRect; DWORD sWait; while (true) { sWait = ::WaitForSingleObject(mEvent, INFINITE); if (mThread.isStop() == XPR_TRUE) break; if (sWait != WAIT_OBJECT_0) continue; { xpr::MutexGuard sLockGuard(mMutex); if (mThumbDeque.empty() == true) { ::ResetEvent(mEvent); continue; } sThumbItem = mThumbDeque.front(); mThumbDeque.pop_front(); if (XPR_IS_NULL(sThumbItem)) continue; } sThumbImage = XPR_NULL; sHwnd = sThumbItem->mHwnd; sMsg = sThumbItem->mMsg; sThumbSize = sThumbItem->mThumbSize; _tcscpy(sPath, sThumbItem->mPath.c_str()); sInputBytes = _tcslen(sPath) * sizeof(xpr_tchar_t); sOutputBytes = XPR_MAX_PATH * sizeof(xpr_tchar_t); XPR_TCS_TO_MBS(sPath, &sInputBytes, sPathA, &sOutputBytes); sPathA[sOutputBytes / sizeof(xpr_char_t)] = 0; XPR_TRACE(XPR_STRING_LITERAL("Thumbnail Thread, path=%s\n"), sPath); { gflGetDefaultPreviewParams(&sGflLoadParams); sGflLoadParams.Flags |= GFL_LOAD_SKIP_ALPHA | GFL_LOAD_PREVIEW_NO_CANVAS_RESIZE; sGflLoadParams.Origin = GFL_BOTTOM_LEFT; sGflLoadParams.ColorModel = GFL_BGR; sGflLoadParams.LinePadding = 4; if (sThumbItem->mLoadByExt == XPR_TRUE) sGflLoadParams.Flags |= GFL_LOAD_BY_EXTENSION_ONLY; if (gflLoadPreview(sPathA, sThumbSize.cx, sThumbSize.cy, &sGflBitmap, &sGflLoadParams, XPR_NULL) == XPR_FALSE) { // image bilinear scale sPicSize.cx = sGflBitmap->Width; sPicSize.cy = sGflBitmap->Height; x = y = 0; cx = sThumbSize.cx; cy = sThumbSize.cy; sRatio = (xpr_double_t)sPicSize.cx / (xpr_double_t)sPicSize.cy; if (sPicSize.cx >= sThumbSize.cx || sPicSize.cy >= sThumbSize.cy) { x = (sThumbSize.cx - sPicSize.cx) / 2; y = (sThumbSize.cy - sPicSize.cy) / 2; sDestRect = CRect(x, y, x+cx, y+cy); } else { x = (sThumbSize.cx - sPicSize.cx) / 2; y = (sThumbSize.cy - sPicSize.cy) / 2; sDestRect = CRect(x, y, x+sPicSize.cx, y+sPicSize.cy); } CClientDC dc(CWnd::GetDesktopWindow()); sBitmap = new CBitmap; sBitmap->CreateCompatibleBitmap(&dc, sThumbSize.cx, sThumbSize.cy); CDC sMemDC; sMemDC.CreateCompatibleDC(&dc); sOldBitmap = sMemDC.SelectObject(sBitmap); sDibData = XPR_NULL; GetDIBFromBitmap(sGflBitmap, &sBitmapInfoHeader, &sDibData); sMemDC.FillSolidRect(0, 0, sThumbSize.cx, sThumbSize.cy, RGB(255,255,255)); ::StretchDIBits( sMemDC.m_hDC, x, y, sGflBitmap->Width, sGflBitmap->Height, 0, 0, sGflBitmap->Width, sGflBitmap->Height, (sDibData != XPR_NULL) ? sDibData : sGflBitmap->Data, (BITMAPINFO *)&sBitmapInfoHeader, DIB_RGB_COLORS, SRCCOPY); sMemDC.SelectObject(sOldBitmap); sThumbImage = new ThumbImage; sThumbImage->mPath = sThumbItem->mPath; sThumbImage->mImage = sBitmap; sThumbImage->mWidth = sGflBitmap->Width; sThumbImage->mHeight = sGflBitmap->Height; sThumbImage->mDepth = sGflBitmap->BytesPerPixel * 8; GetFileLastWriteTime(sThumbItem->mPath.c_str(), &sThumbImage->mModifiedFileTime); if (XPR_IS_NOT_NULL(sDibData)) { free(sDibData); sDibData = XPR_NULL; } if (XPR_IS_NOT_NULL(sGflBitmap)) { gflFreeBitmap(sGflBitmap); sGflBitmap = XPR_NULL; } } } if (XPR_IS_NOT_NULL(sThumbImage)) { if (::PostMessage(sHwnd, sMsg, (WPARAM)sThumbItem->mCode, (LPARAM)sThumbImage) == XPR_FALSE) { if (XPR_IS_NOT_NULL(sThumbImage) && XPR_IS_NOT_NULL(sThumbImage->mImage)) { sThumbImage->mImage->DeleteObject(); XPR_SAFE_DELETE(sThumbImage->mImage); } XPR_SAFE_DELETE(sThumbImage); } } XPR_SAFE_DELETE(sThumbItem); } return 0; }
static void Update() { WndProperty* wp; TCHAR Text[100]; Angle teammateBearing = XCSoarInterface::Calculated().TeammateBearing; double teammateRange = XCSoarInterface::Calculated().TeammateRange; if (XCSoarInterface::SettingsComputer().TeamCodeRefWaypoint >= 0) { double Value = (teammateBearing - XCSoarInterface::Basic().TrackBearing). as_delta().value_degrees(); if (Value > 1) _stprintf(Text, _T("%2.0f")_T(DEG)_T(">"), Value); else if (Value < -1) _stprintf(Text, _T("<%2.0f")_T(DEG), -Value); else _tcscpy(Text, _T("<>")); } else { _tcscpy(Text, _T("---")); } wp = (WndProperty*)wf->FindByName(_T("prpRelBearing")); if (wp) { wp->SetText(Text); wp->RefreshDisplay(); } wp = (WndProperty*)wf->FindByName(_T("prpBearing")); if (wp) { wp->GetDataField()->SetAsFloat(teammateBearing.value_degrees()); wp->RefreshDisplay(); } wp = (WndProperty*)wf->FindByName(_T("prpRange")); if (wp) { wp->GetDataField()->SetAsFloat(Units::ToUserDistance(fixed(teammateRange))); wp->RefreshDisplay(); } wp = (WndProperty*)wf->FindByName(_T("prpOwnCode")); if (wp) { _tcsncpy(Text, XCSoarInterface::Calculated().OwnTeamCode, 5); Text[5] = '\0'; wp->SetText(Text); wp->RefreshDisplay(); } wp = (WndProperty*)wf->FindByName(_T("prpMateCode")); if (wp) { wp->SetText(XCSoarInterface::SettingsComputer().TeammateCode); wp->RefreshDisplay(); } wp = (WndProperty*)wf->FindByName(_T("prpFlarmLock")); if (wp) { wp->SetText(XCSoarInterface::SettingsComputer().TeamFlarmTracking ? XCSoarInterface::SettingsComputer().TeamFlarmCNTarget : _T("")); wp->RefreshDisplay(); } }
/** * \return S_OK for success, S_FALSE for failure * * Registers a client to the DIL. ClientID will have client id * which will be used for further client related calls */ HRESULT CDIL_CAN_MHS::CAN_RegisterClient(BOOL bRegister, DWORD& ClientID, char* pacClientName) { HRESULT hResult = S_FALSE; INT Index; if (bRegister) { if (sg_unClientCnt < MAX_CLIENT_ALLOWED) { Index = 0; if (!bClientExist(pacClientName, Index)) { //Currently store the client information if (_tcscmp(pacClientName, CAN_MONITOR_NODE) == 0) { //First slot is reserved to monitor node ClientID = 1; _tcscpy(sg_asClientToBufMap[0].m_acClientName, pacClientName); sg_asClientToBufMap[0].m_dwClientID = ClientID; sg_asClientToBufMap[0].m_unBufCount = 0; } else { if (!bClientExist(CAN_MONITOR_NODE, Index)) { Index = sg_unClientCnt + 1; } else { Index = sg_unClientCnt; } ClientID = dwGetAvailableClientSlot(); _tcscpy(sg_asClientToBufMap[Index].m_acClientName, pacClientName); sg_asClientToBufMap[Index].m_dwClientID = ClientID; sg_asClientToBufMap[Index].m_unBufCount = 0; } sg_unClientCnt++; hResult = S_OK; } else { ClientID = sg_asClientToBufMap[Index].m_dwClientID; hResult = ERR_CLIENT_EXISTS; } } else { hResult = ERR_NO_MORE_CLIENT_ALLOWED; } } else { if (bRemoveClient(ClientID)) { hResult = S_OK; } else { hResult = ERR_NO_CLIENT_EXIST; } } return(hResult); }
/*! \brief 安装指定的服务到服务管理器中 \param LPCTSTR pszPath :服务执行文件的全路径 \param DWORD dwServiceType:服务类型 \li SERVICE_FILE_SYSTEM_DRIVER \li SERVICE_KERNEL_DRIVER \li SERVICE_WIN32_OWN_PROCESS \li SERVICE_WIN32_SHARE_PROCESS \li SERVICE_INTERACTIVE_PROCESS \param DWORD dwStartType :开始类型 \li SERVICE_AUTO_START \li SERVICE_BOOT_START \li SERVICE_DEMAND_START \li SERVICE_DISABLED \li SERVICE_SYSTEM_START \return 类型为 BOOL 。成功返回TRUE,否则返回FALSE. \version 1.0 \author 康 林 \date 2007-6-12 21:03:45 */ BOOL CServiceManage::Install(LPCTSTR pszPath /* = NULL */, LPTSTR pszServerName /* = NULL */, LPCTSTR pszDisplayName /* = NULL */) { SC_HANDLE schService; TCHAR szPath[MAX_PATH]; if(NULL == pszPath) { if(!GetModuleFileName(NULL, szPath, MAX_PATH)) { printf("Cannot install service (%d)\n", GetLastError()); return FALSE; } } else { _tcscpy(szPath, pszPath); } // Get a handle to the SCM database. if(NULL == m_hSchSCManager) { m_hSchSCManager = OpenSCManager( NULL, // local computer NULL, // ServicesActive database SC_MANAGER_ALL_ACCESS); // full access rights if (NULL == m_hSchSCManager) { printf("OpenSCManager failed (%d)\n", GetLastError()); return FALSE; } } if(NULL == pszServerName) { pszServerName =(LPTSTR) m_szServiceName.c_str(); } // 结束 if(NULL == pszServerName) // Create the service. schService = CreateService( m_hSchSCManager, // SCM database pszServerName, // name of service pszDisplayName, // service name to display SERVICE_ALL_ACCESS, // desired access SERVICE_WIN32_OWN_PROCESS, // service type SERVICE_AUTO_START, // start type SERVICE_ERROR_NORMAL, // error control type szPath, // path to service's binary NULL, // no load ordering group NULL, // no tag identifier NULL, // no dependencies NULL, // LocalSystem account NULL); // no password if (schService == NULL) { printf("CreateService failed (%d)\n", GetLastError()); return FALSE; } else printf("Service installed successfully\n"); CloseServiceHandle(schService); }
void VNCOptions::SetFromCommandLine(LPTSTR szCmdLine) { // We assume no quoting here. // Copy the command line - we don't know what might happen to the original int cmdlinelen = _tcslen(szCmdLine); if (cmdlinelen == 0) return; TCHAR *cmd = new TCHAR[cmdlinelen + 1]; _tcscpy(cmd, szCmdLine); // Count the number of spaces // This may be more than the number of arguments, but that doesn't matter. int nspaces = 0; TCHAR *p = cmd; TCHAR *pos = cmd; while ( ( pos = _tcschr(p, ' ') ) != NULL ) { nspaces ++; p = pos + 1; } // Create the array to hold pointers to each bit of string TCHAR **args = new LPTSTR[nspaces + 1]; // replace spaces with nulls and // create an array of TCHAR*'s which points to start of each bit. pos = cmd; int i = 0; args[i] = cmd; bool inquote=false; for (pos = cmd; *pos != 0; pos++) { // Arguments are normally separated by spaces, unless there's quoting if ((*pos == ' ') && !inquote) { *pos = '\0'; p = pos + 1; args[++i] = p; } if (*pos == '"') { if (!inquote) { // Are we starting a quoted argument? args[i] = ++pos; // It starts just after the quote } else { *pos = '\0'; // Finish a quoted argument? } inquote = !inquote; } } i++; bool hostGiven = false, portGiven = false; // take in order. for (int j = 0; j < i; j++) { if ( SwitchMatch(args[j], _T("help")) || SwitchMatch(args[j], _T("?")) || SwitchMatch(args[j], _T("h"))) { ShowUsage(); PostQuitMessage(1); } else if ( SwitchMatch(args[j], _T("listen"))) { m_listening = true; } else if ( SwitchMatch(args[j], _T("restricted"))) { m_restricted = true; } else if ( SwitchMatch(args[j], _T("viewonly"))) { m_ViewOnly = true; } else if ( SwitchMatch(args[j], _T("fullscreen"))) { m_FullScreen = true; } else if ( SwitchMatch(args[j], _T("8bit"))) { m_Use8Bit = true; } else if ( SwitchMatch(args[j], _T("shared"))) { m_Shared = true; } else if ( SwitchMatch(args[j], _T("swapmouse"))) { m_SwapMouse = true; } else if ( SwitchMatch(args[j], _T("nocursor"))) { m_localCursor = NOCURSOR; } else if ( SwitchMatch(args[j], _T("dotcursor"))) { m_localCursor = DOTCURSOR; } else if ( SwitchMatch(args[j], _T("normalcursor"))) { m_localCursor = NORMALCURSOR; } else if ( SwitchMatch(args[j], _T("belldeiconify") )) { m_DeiconifyOnBell = true; } else if ( SwitchMatch(args[j], _T("emulate3") )) { m_Emul3Buttons = true; } else if ( SwitchMatch(args[j], _T("noemulate3") )) { m_Emul3Buttons = false; } else if ( SwitchMatch(args[j], _T("scale") )) { if (++j == i) { ArgError(_T("No scaling factor specified")); continue; } int numscales = _stscanf(args[j], _T("%d/%d"), &m_scale_num, &m_scale_den); if (numscales < 1) { ArgError(_T("Invalid scaling specified")); continue; } if (numscales == 1) m_scale_den = 1; // needed if you're overriding a previous setting } else if ( SwitchMatch(args[j], _T("emulate3timeout") )) { if (++j == i) { ArgError(_T("No timeout specified")); continue; } if (_stscanf(args[j], _T("%d"), &m_Emul3Timeout) != 1) { ArgError(_T("Invalid timeout specified")); continue; } } else if ( SwitchMatch(args[j], _T("emulate3fuzz") )) { if (++j == i) { ArgError(_T("No fuzz specified")); continue; } if (_stscanf(args[j], _T("%d"), &m_Emul3Fuzz) != 1) { ArgError(_T("Invalid fuzz specified")); continue; } } else if ( SwitchMatch(args[j], _T("disableclipboard") )) { m_DisableClipboard = true; } #ifdef UNDER_CE // Manual setting of palm vs hpc aspect ratio for dialog boxes. else if ( SwitchMatch(args[j], _T("hpc") )) { m_palmpc = false; } else if ( SwitchMatch(args[j], _T("palm") )) { m_palmpc = true; } else if ( SwitchMatch(args[j], _T("slow") )) { m_slowgdi = true; } #endif else if ( SwitchMatch(args[j], _T("delay") )) { if (++j == i) { ArgError(_T("No delay specified")); continue; } if (_stscanf(args[j], _T("%d"), &m_delay) != 1) { ArgError(_T("Invalid delay specified")); continue; } } else if ( SwitchMatch(args[j], _T("loglevel") )) { if (++j == i) { ArgError(_T("No loglevel specified")); continue; } if (_stscanf(args[j], _T("%d"), &m_logLevel) != 1) { ArgError(_T("Invalid loglevel specified")); continue; } } else if ( SwitchMatch(args[j], _T("console") )) { m_logToConsole = true; } else if ( SwitchMatch(args[j], _T("logfile") )) { if (++j == i) { ArgError(_T("No logfile specified")); continue; } if (_stscanf(args[j], _T("%s"), &m_logFilename) != 1) { ArgError(_T("Invalid logfile specified")); continue; } else { m_logToFile = true; } } else if ( SwitchMatch(args[j], _T("config") )) { if (++j == i) { ArgError(_T("No config file specified")); continue; } // The GetPrivateProfile* stuff seems not to like some relative paths _fullpath(m_configFilename, args[j], _MAX_PATH); if (_access(m_configFilename, 04)) { ArgError(_T("Can't open specified config file for reading.")); PostQuitMessage(1); continue; } else { Load(m_configFilename); m_configSpecified = true; } } else if ( SwitchMatch(args[j], _T("register") )) { Register(); PostQuitMessage(0); } else { TCHAR phost[256]; if (!ParseDisplay(args[j], phost, 255, &m_port)) { ShowUsage(_T("Invalid VNC server specified.")); PostQuitMessage(1); } else { _tcscpy(m_host, phost); m_connectionSpecified = true; } } } if (m_scale_num != 1 || m_scale_den != 1) m_scaling = true; // reduce scaling factors by greatest common denominator if (m_scaling) { FixScaling(); } // tidy up delete [] cmd; delete [] args; }
int InpdUpdate() { unsigned int i, j = 0; struct GameInp* pgi = NULL; unsigned char* plv = NULL; unsigned short nThisVal; if (hInpdList == NULL) { return 1; } if (LastVal == NULL) { return 1; } // Update the values of all the inputs for (i = 0, pgi = GameInp, plv = LastVal; i < nGameInpCount; i++, pgi++, plv++) { LVITEM LvItem; TCHAR szVal[16]; if (pgi->nType == 0) { continue; } if (pgi->nType & BIT_GROUP_ANALOG) { if (bRunPause) { // Update LastVal nThisVal = pgi->Input.nVal; } else { nThisVal = *pgi->Input.pShortVal; } if (bLastValDefined && (pgi->nType != BIT_ANALOG_REL || nThisVal) && pgi->Input.nVal == *((unsigned short*)plv)) { j++; continue; } *((unsigned short*)plv) = nThisVal; } else { if (bRunPause) { // Update LastVal nThisVal = pgi->Input.nVal; } else { nThisVal = *pgi->Input.pVal; } if (bLastValDefined && pgi->Input.nVal == *plv) { // hasn't changed j++; continue; } *plv = nThisVal; } switch (pgi->nType) { case BIT_DIGITAL: { if (nThisVal == 0) { szVal[0] = 0; } else { if (nThisVal == 1) { _tcscpy(szVal, _T("ON")); } else { _stprintf(szVal, _T("0x%02X"), nThisVal); } } break; } case BIT_ANALOG_ABS: { _stprintf(szVal, _T("0x%02X"), nThisVal >> 8); break; } case BIT_ANALOG_REL: { if (nThisVal == 0) { szVal[0] = 0; } if ((short)nThisVal < 0) { _stprintf(szVal, _T("%d"), ((short)nThisVal) >> 8); } if ((short)nThisVal > 0) { _stprintf(szVal, _T("+%d"), ((short)nThisVal) >> 8); } break; } default: { _stprintf(szVal, _T("0x%02X"), nThisVal); } }
DWORD WINAPI BkgPingStatusCheckThread(LPVOID lpVoid) { BBS_PING_OPTION pingOpt = {0,}; BBS_CUR_NET_INFO netInfo; BBS_PING_RESULT pingResult; BBS_ADAPTER_INFO adapterInfo; DWORD dwPingFailCount = 0; CBBS_Ping ping; TCHAR tszLiteralIP[18] = {'\0',}; memset(&pingOpt, 0, sizeof(BBS_PING_OPTION)); memset(&netInfo, 0, sizeof(BBS_CUR_NET_INFO)); memset(&pingResult, 0, sizeof(BBS_PING_RESULT)); memset(&adapterInfo, 0, sizeof(BBS_ADAPTER_INFO)); NKDbgPrintfW( _T("[NETUI] ===== [BkgPingStatusCheckThread Start] ===== \r\n") ); g_bIsOperating = TRUE; while(g_bIsOperating == TRUE) { // 1초씩 g_dwBreakInterval 만큼 쉬어준다. // 1초씩 마다 스레드가 종료 조건이 걸려있는지 확인 for(UINT i=1; i<=g_dwBreakInterval; i++) { // BreakTime Interval Sleep(1000); if(g_bIsOperating == FALSE) { return 0; } } // PIng 실패 횟수 초기화 필수! dwPingFailCount = 0; GetWlanDefaultInformation(&adapterInfo); GetCurrentNetworkInfo(adapterInfo.tszAdapterName, &netInfo); NKDbgPrintfW( _T("[NETUI] ---------- [Default Information] ---------- \r\n") ); NKDbgPrintfW( _T("[NETUI] Adapter(%s), DHCP(%d) \r\n"), adapterInfo.tszAdapterName, adapterInfo.bDHCPEnabled ); NKDbgPrintfW( _T("[NETUI] IPAddr(%s) \r\n"), adapterInfo.tszIPAddr ); NKDbgPrintfW( _T("[NETUI] DefaultGateWay(%s) \r\n"), adapterInfo.tszDefaultGateWay ); NKDbgPrintfW( _T("[NETUI] DnsAddr(%s) \r\n"), adapterInfo.tszDnsAddr ); NKDbgPrintfW( _T("[NETUI] ---------------------------------------- \r\n\r\n") ); // 아답터가 검색되었는지? if( _tcslen(adapterInfo.tszAdapterName) == 0 ) { // 아답터가 검색되지 않았다면, 기본 대기시간만큼 다시 대기 // ERROR NKDbgPrintfW( _T("[NETUI] [ERROR] Can't Find Adapter! \r\n") ); continue; } NKDbgPrintfW( _T("[NETUI] SSID : %s \r\n"), netInfo.tszSSID ); // 현재 접속된 SSID가 있을 때만 Ping 시도 if( _tcslen(netInfo.tszSSID) != 0 ) { // Custom Dest IP를 지정 되어있으면, 읽어온 값으로, 지정되지 않았다면, 기본 DefaultGateWay로 시도 if( _tcslen(g_tszCustomDestAddr) > 0 ) { _tcscpy(pingOpt.tszDestIP, g_tszCustomDestAddr); } else { _tcscpy(pingOpt.tszDestIP, adapterInfo.tszDefaultGateWay); } pingOpt.dwSendBufSize = 32; pingOpt.dwTimeOut = 1000; pingOpt.ucTos = 0; pingOpt.ucTtl = 32; NKDbgPrintfW( TEXT("[NETUI] Dest IP(%s) \r\n"), pingOpt.tszDestIP ); if( ping.InitPing(pingOpt, tszLiteralIP) == TRUE) { HKEY hKey = NULL; DWORD dwDisposition = 0; NKDbgPrintfW( TEXT("[NETUI] Literal IP(%s) \r\n"), tszLiteralIP ); for(DWORD dwLoop=0; dwLoop<g_dwMaxCheckCount; dwLoop++) { if( !ping.StartPing(&pingResult) ) { NKDbgPrintfW( TEXT("[NETUI] Ping Failed!(%d) \r\n"), pingResult.dwErrCode ); dwPingFailCount++; } else { NKDbgPrintfW( TEXT("[NETUI] Size(%d), Time(%d), TTL(%d) \r\n"), pingResult.dwDataSize, pingResult.dwTime, pingResult.ucTtl ); } // 1초씩 g_dwBreakInterval 만큼 쉬어준다. // 1초씩 마다 스레드가 종료 조건이 걸려있는지 확인 for(UINT i=1; i<=g_dwPingInterval; i++) { // Ping Interval Sleep(1000); if(g_bIsOperating == FALSE) { return 0; } } } ping.DeinitPing(); NKDbgPrintfW( TEXT("[NETUI] Max[%d] / Fail[%d] \r\n"), g_dwMaxCheckCount, dwPingFailCount ); // 최대 Ping 테스트 개수가 모두 Fail 되었을때! if( dwPingFailCount >= g_dwMaxCheckCount ) { NKDbgPrintfW( TEXT("[NETUI] Rebind Adapter! \r\n") ); if( DoNdis_RebindAdater(adapterInfo.tszAdapterName) == FALSE ) { NKDbgPrintfW( TEXT("[NETUI] DoNdis_RebindAdater ERROR!! \r\n") ); } } } else { NKDbgPrintfW( TEXT("[NETUI] Init Ping ERROR!! \r\n") ); } } else { NKDbgPrintfW( TEXT("[NETUI] isn't be connected to any SSID \r\n") ); } } return 0; }
/* gets the list of mechanisms */ int _sasl_load_plugins(const add_plugin_list_t *entrypoints, const sasl_callback_t *getpath_cb, const sasl_callback_t *verifyfile_cb) { int result; TCHAR cur_dir[PATH_MAX], full_name[PATH_MAX+2], prefix[PATH_MAX+2]; /* 1 for '\\' 1 for trailing '\0' */ TCHAR * pattern; TCHAR c; int pos; int retCode = SASL_OK; char *utf8path = NULL; TCHAR *path=NULL; int position; const add_plugin_list_t *cur_ep; struct _stat statbuf; /* filesystem entry information */ intptr_t fhandle; /* file handle for _findnext function */ struct _tfinddata_t finddata; /* data returned by _findnext() */ size_t prefix_len; /* for static plugins */ add_plugin_t *add_plugin; _sasl_plug_type type; _sasl_plug_rec *p; if (! entrypoints || ! getpath_cb || getpath_cb->id != SASL_CB_GETPATH || ! getpath_cb->proc || ! verifyfile_cb || verifyfile_cb->id != SASL_CB_VERIFYFILE || ! verifyfile_cb->proc) return SASL_BADPARAM; /* do all the static plugins first */ for (cur_ep = entrypoints; cur_ep->entryname; cur_ep++) { /* What type of plugin are we looking for? */ if (!strcmp(cur_ep->entryname, "sasl_server_plug_init")) { type = SERVER; add_plugin = (add_plugin_t *)sasl_server_add_plugin; } else if (!strcmp(cur_ep->entryname, "sasl_client_plug_init")) { type = CLIENT; add_plugin = (add_plugin_t *)sasl_client_add_plugin; } else if (!strcmp(cur_ep->entryname, "sasl_auxprop_plug_init")) { type = AUXPROP; add_plugin = (add_plugin_t *)sasl_auxprop_add_plugin; } else if (!strcmp(cur_ep->entryname, "sasl_canonuser_init")) { type = CANONUSER; add_plugin = (add_plugin_t *)sasl_canonuser_add_plugin; } else { /* What are we looking for then? */ return SASL_FAIL; } for (p = _sasl_static_plugins; p->type; p++) { if (type == p->type) result = add_plugin(p->name, p->plug); } } /* get the path to the plugins */ result = ((sasl_getpath_t *)(getpath_cb->proc))(getpath_cb->context, &utf8path); if (result != SASL_OK) return result; if (!utf8path) return SASL_FAIL; if (sizeof(TCHAR) == sizeof(char)) { path = (TCHAR*)utf8path; } else { path = _sasl_utf8_to_wchar(utf8path); if (!path) return SASL_FAIL; } if (_tcslen(path) >= PATH_MAX) { /* no you can't buffer overrun */ retCode = SASL_FAIL; goto cleanup; } position=0; do { pos=0; do { c=path[position]; position++; cur_dir[pos]=c; pos++; } while ((c!=PATHS_DELIMITER) && (c!=0)); cur_dir[pos-1]='\0'; /* : check to make sure that a valid directory name was passed in */ if (_tstat (cur_dir, &statbuf) < 0) { continue; } if ((statbuf.st_mode & S_IFDIR) == 0) { continue; } _tcscpy(prefix, cur_dir); prefix_len = _tcslen (prefix); /* : Don't append trailing \ unless required */ if (prefix[prefix_len-1] != '\\') { _tcscat(prefix,_T("\\")); prefix_len++; } pattern = prefix; /* : Check that we have enough space for "*.dll" */ if ((prefix_len + DLL_MASK_LEN) > (sizeof(prefix) / sizeof(TCHAR) - 1)) { _sasl_log(NULL, SASL_LOG_WARN, "plugin search mask is too big"); continue; } _tcscat (prefix + prefix_len, _T("*") DLL_SUFFIX); fhandle = _tfindfirst (pattern, &finddata); if (fhandle == -1) { /* no matching files */ continue; } /* : Truncate "*.dll" */ prefix[prefix_len] = '\0'; do { size_t length; void *library; char *c; char plugname[PATH_MAX]; int entries; length = _tcslen(finddata.name); if (length < 5) { /* At least <Ch>.dll */ continue; /* can not possibly be what we're looking for */ } /* : Check for overflow */ if (length + prefix_len >= PATH_MAX) continue; /* too big */ if (_tcscmp(finddata.name + (length - _tcslen(DLL_SUFFIX)), DLL_SUFFIX) != 0) { continue; } /* : Check that it is not a directory */ if ((finddata.attrib & _A_SUBDIR) == _A_SUBDIR) { continue; } /* : Construct full name from prefix and name */ _tcscpy (full_name, prefix); _tcscat (full_name, finddata.name); /* cut off .dll suffix -- this only need be approximate */ if (sizeof(TCHAR) != sizeof(char)) { if (WideCharToMultiByte(CP_UTF8, 0, finddata.name, -1, plugname, sizeof(plugname), NULL, NULL) == 0) { // in case of unicode use utf8 continue; } } else { _tcscpy((TCHAR*)plugname, finddata.name); // w/o unicode local enconding is fine } c = strchr(plugname, '.'); if (c != NULL) *c = '\0'; result = _tsasl_get_plugin (full_name, verifyfile_cb, &library); if (result != SASL_OK) { continue; } entries = 0; for (cur_ep = entrypoints; cur_ep->entryname; cur_ep++) { result = _sasl_plugin_load(plugname, library, cur_ep->entryname, cur_ep->add_plugin); if (result == SASL_OK) { ++entries; } /* If this fails, it's not the end of the world */ } if (entries == 0) { _sasl_remove_last_plugin(); } } while (_tfindnext (fhandle, &finddata) == 0); _findclose (fhandle); } while ((c!='=') && (c!=0)); cleanup: if (sizeof(TCHAR) != sizeof(char)) { sasl_FREE(path); /* It's always allocated in coversion to wchar */ } return retCode; }
static BOOL LoadCompatibilityModes(LPCOMPATIBILITYPAGE info) { BOOL Ret; LONG e; HKEY hk, hk2; TCHAR szKey[256]; ClearCItemList(info); e = RegOpenKey(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers"), &hk); if (e == ERROR_SUCCESS) { DWORD i; PCITEM lastitem = NULL; for(i = 0; (RegEnumKey(hk, i,szKey, sizeof(szKey) / sizeof(szKey[0])) == ERROR_SUCCESS); i++) { e = RegOpenKey(hk, szKey, &hk2); if (e == ERROR_SUCCESS) { DWORD dwType; e = RegQueryValueEx(hk2, NULL, 0, &dwType, NULL, NULL); if (e != ERROR_SUCCESS || (e == ERROR_SUCCESS && dwType == REG_SZ)) { PCITEM item; item = HeapAlloc(GetProcessHeap(), 0, sizeof(CITEM)); if (item != NULL) { DWORD cdb = sizeof(item->szName); /* description */ e = RegQueryValueEx(hk2, NULL, 0, NULL, (LPBYTE)item->szName, &cdb); /* make sure it is null-terminated */ if (cdb > sizeof(item->szName) - sizeof(item->szName[0])) { item->szName[(sizeof(item->szName) / sizeof(item->szName[0])) - 1] = TEXT('\0'); } if (e != ERROR_SUCCESS || cdb < sizeof(item->szName[0])) { _tcscpy(item->szName, szKey); e = ERROR_SUCCESS; } _tcscpy(item->szKeyName, szKey); info->nItems++; ReadDWORDFlag(hk2, TEXT("MajorVersion"), &item->MajorVersion, 0); ReadDWORDFlag(hk2, TEXT("MinorVersion"), &item->MinorVersion, 0); ReadDWORDFlag(hk2, TEXT("BuildNumber"), &item->BuildNumber, 0); ReadDWORDFlag(hk2, TEXT("PlatformId"), &item->PlatformId, 0); ReadDWORDFlag(hk2, TEXT("SPMajorVersion"), &item->SPMajorVersion, 0); ReadDWORDFlag(hk2, TEXT("SPMinorVersion"), &item->SPMinorVersion, 0); if (e == ERROR_SUCCESS) { item->next = NULL; if (lastitem != NULL) { lastitem->next = item; } else { info->CItems = item; } lastitem = item; } else { HeapFree(GetProcessHeap(), 0, item); } } } RegCloseKey(hk2); } if (e != ERROR_SUCCESS) { e = ERROR_SUCCESS; } } RegCloseKey(hk); } Ret = ((e == ERROR_SUCCESS || e == ERROR_NO_MORE_ITEMS) ? TRUE : FALSE); return Ret; }