Example #1
0
static int isowavParseCueFile()
{
	TCHAR  szLine[1024];
	TCHAR  szFile[1024];
	TCHAR* s;
	TCHAR* t;
	FILE*  h;
	int    track = 0;
	int    length;

	isowavTOC->FirstTrack = 1;
	isowavTOC->LastTrack  = 1;

	isowavTOC->TrackData[0].Address[1] = 0;
	isowavTOC->TrackData[0].Address[2] = 2;
	isowavTOC->TrackData[0].Address[3] = 0;

	h = _tfopen(CDEmuImage, _T("rt"));
	if (h == NULL) {
		return 1;
	}

	while (1) {
		if (_fgetts(szLine, sizeof(szLine), h) == NULL) {
			break;
		}

		length = _tcslen(szLine);
		// get rid of the linefeed at the end
		while (length && (szLine[length - 1] == _T('\r') || szLine[length - 1] == _T('\n'))) {
			szLine[length - 1] = 0;
			length--;
		}

		s = szLine;

		// file info
		if ((t = LabelCheck(s, _T("FILE"))) != 0) {
			s = t;

			TCHAR* szQuote;

			// read filename
			QuoteRead(&szQuote, NULL, s);

			_sntprintf(szFile, ExtractFilename(CDEmuImage) - CDEmuImage, _T("%s"), CDEmuImage);
			_sntprintf(szFile + (ExtractFilename(CDEmuImage) - CDEmuImage), 1024 - (ExtractFilename(CDEmuImage) - CDEmuImage), _T("\\%s"), szQuote);

			continue;
		}

		// track info
		if ((t = LabelCheck(s, _T("TRACK"))) != 0) {
			s = t;

			// track number
			track = _tcstol(s, &t, 10);

			if (track < 1 || track > MAXIMUM_NUMBER_TRACKS) {
				fclose(h);
				return 1;
			}

			if (track < isowavTOC->FirstTrack) {
				isowavTOC->FirstTrack = track;
			}
			if (track > isowavTOC->LastTrack) {
				isowavTOC->LastTrack = track;
			}
			isowavTOC->TrackData[track - 1].TrackNumber = track;

			isowavTOC->TrackData[track - 1].Filename = (TCHAR*)malloc((_tcslen(szFile) + 1) * sizeof(TCHAR));
			if (isowavTOC->TrackData[track - 1].Filename == NULL) {
				fclose(h);
				return 1;
			}
			_tcscpy(isowavTOC->TrackData[track - 1].Filename, szFile);

			s = t;

			// type of track

			if ((t = LabelCheck(s, _T("MODE1/2048"))) != 0) {
				isowavTOC->TrackData[track - 1].Control = 4;

				continue;
			}
			if ((t = LabelCheck(s, _T("AUDIO"))) != 0) {
				isowavTOC->TrackData[track - 1].Control = 0;

				continue;
			}

			fclose(h);
			return 1;
		}

		// pregap
		if ((t = LabelCheck(s, _T("PREGAP"))) != 0) {
			s = t;

			int M, S, F;

			// pregap M
			M = _tcstol(s, &t, 10);
			s = t + 1;
			// pregap S
			S = _tcstol(s, &t, 10);
			s = t + 1;
			// pregap F
			F = _tcstol(s, &t, 10);

			if (M < 0 || M > 100 || S < 0 || S > 59 || F < 0 || F > 74) {
				fclose(h);
				return 1;
			}

			isowavTOC->TrackData[track - 1].Address[1] = M;
			isowavTOC->TrackData[track - 1].Address[2] = S;
			isowavTOC->TrackData[track - 1].Address[3] = F;

			continue;
		}
	}

	fclose(h);

	return isowavGetTrackSizes();
}
Example #2
0
/** ini_getl()
 * \param Section     the name of the section to search for
 * \param Key         the name of the entry to find the value of
 * \param DefValue    the default value in the event of a failed read
 * \param Filename    the name of the .ini file to read from
 *
 * \return            the value located at Key
 */
long ini_getl(const TCHAR *Section, const TCHAR *Key, long DefValue, const TCHAR *Filename)
{
  TCHAR buff[64];
  int len = ini_gets(Section, Key, __T(""), buff, sizearray(buff), Filename);
  return (len == 0) ? DefValue : _tcstol(buff, NULL, 10);
}
Example #3
0
bool LoadCupTask(LPCTSTR szFileName) {
    LockTaskData();

    mapCode2Waypoint_t mapWaypoint;

    ClearTask();
    size_t idxTP = 0;
    bool bTakeOff = true;
    bool bLoadComplet = true;
    bool bLastInvalid=true;

    TCHAR szString[READLINE_LENGTH + 1];
    TCHAR TpCode[NAME_SIZE + 1];

    szString[READLINE_LENGTH] = _T('\0');
    TpCode[NAME_SIZE] = _T('\0');

    memset(szString, 0, sizeof (szString)); // clear Temp Buffer
    WAYPOINT newPoint = {0};
    WAYPOINT* WPtoAdd=NULL;

    enum {
        none, Waypoint, TaskTp, Option
    } FileSection = none;
    FILE * stream = _tfopen(szFileName, _T("rt"));
    if (stream) {
        charset cs = charset::unknown;
        while (ReadStringX(stream, READLINE_LENGTH, szString, cs)) {

            if ((FileSection == none) && ((_tcsncmp(_T("name,code,country"), szString, 17) == 0) ||
                    (_tcsncmp(_T("Title,Code,Country"), szString, 18) == 0))) {
                FileSection = Waypoint;
                continue;
            } else if ((FileSection == Waypoint) && (_tcscmp(szString, _T("-----Related Tasks-----")) == 0)) {
                FileSection = TaskTp;
                continue;
            }

            TCHAR *pToken = NULL;
            TCHAR *pWClast = NULL;

            switch (FileSection) {
                case Waypoint:
                    memset(&newPoint, 0, sizeof(newPoint));
                    if (ParseCUPWayPointString(szString, &newPoint)) {
                        mapWaypoint[newPoint.Name] = newPoint;
                    }
                    break;
                case TaskTp:
                    // 1. Description
                    //       First column is the description of the task. If filled it should be double quoted.
                    //       If left empty, then SeeYou will determine the task type on runtime.
                    if ((pToken = strsep_r(szString, TEXT(","), &pWClast)) == NULL) {
                        UnlockTaskData();
                        return false;
                    }

                    // 2. and all successive columns, separated by commas
                    //       Each column represents one waypoint name double quoted. The waypoint name must be exactly the
                    //       same as the Long name of a waypoint listed above the Related tasks.
                    WPtoAdd=NULL;
                    while (bLoadComplet && (pToken = strsep_r(NULL, TEXT(","), &pWClast)) != NULL) {
                        if (idxTP < MAXTASKPOINTS) {
                            _tcsncpy(TpCode, pToken, NAME_SIZE);
                            CleanCupCode(TpCode);
                            mapCode2Waypoint_t::iterator It = mapWaypoint.find(TpCode);
                            if(!ISGAAIRCRAFT) {
                                if (It != mapWaypoint.end()) {
                                    if (bTakeOff) {
                                        // skip TakeOff Set At Home Waypoint
                                        int ix = FindOrAddWaypoint(&(It->second),false);
                                        if (ix>=0) {
                                            #if 0 // REMOVE
                                            // We must not change HomeWaypoint without user knowing!
                                            // The takeoff and homewaypoint are independent from task.
                                            // In addition, this is a bug because on next run the index is invalid
                                            // and we have no more HowWaypoint!
                                            HomeWaypoint = ix;
                                            #endif
                                            bTakeOff = false;
                                        }
                                        #if BUGSTOP
                                        else LKASSERT(0); // .. else is unmanaged, TODO
                                        #endif
                                    } else {
                                        int ix =  FindOrAddWaypoint(&(It->second),false);
                                        if (ix>=0) Task[idxTP++].Index = ix;
                                        #if BUGSTOP
                                        else LKASSERT(0); // .. else is unmanaged, TODO
                                        #endif
                                    }
                                    bLastInvalid=false;
                                } else {
                                    // An invalid takeoff, probably a "???" , which we ignore
                                    #if TESTBENCH
                                    if (bTakeOff) StartupStore(_T("....... CUP Takeoff not found: <%s>\n"),TpCode);
                                    #endif
                                    // in any case bTakeOff now is false
                                    bTakeOff=false;
                                    bLastInvalid=true;
                                }
                            } else { //ISGAIRRCRAFT
                                if(It != mapWaypoint.end()) {
                                    if(WPtoAdd!=NULL) {
                                        //add what we found in previous cycle: it was not the last one
                                        int ix = FindOrAddWaypoint(WPtoAdd,false); 
                                        if (ix>=0) Task[idxTP++].Index = ix;
                                        #if BUGSTOP
                                        else LKASSERT(0); // .. else is unmanaged, TODO
                                        #endif
                                    }
                                    if (bTakeOff) { //it's the first: may be we have a corresponding airfield
                                        //look for departure airfield and add it
                                        int ix = FindOrAddWaypoint(&(It->second),true); 
                                        if (ix>=0) {
                                            Task[idxTP++].Index = ix;
                                            bTakeOff = false;
                                        } 
                                        #if BUGSTOP
                                        else LKASSERT(0); // .. else is unmanaged, TODO
                                        #endif
                                    } else WPtoAdd=&(It->second); //store it for next cycle (may be it is the last one)
                                }
                            }
                        } else {
                            bLoadComplet = false;
                        }
                    }
                    if(ISGAAIRCRAFT) { //For GA: check if we have an airport corresponding to the last WP
                        if(WPtoAdd!=NULL) { //if we have the last one (probably an airfield) still to add...
                            if(idxTP<MAXTASKPOINTS) {
                                int ix=FindOrAddWaypoint(WPtoAdd,true); //look for arrival airport and add it
                                if (ix>=0) {
                                    Task[idxTP++].Index= ix;
                                }
                                #if BUGSTOP
                                else LKASSERT(0); // .. else is unmanaged, TODO
                                #endif
                            }
                            else bLoadComplet=false;
                        }
                    }
                    FileSection = Option;
                break;
                case Option:
                    if ((pToken = strsep_r(szString, TEXT(","), &pWClast)) != NULL) {
                        if (_tcscmp(pToken, _T("Options")) == 0) {
                            while ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) != NULL) {
                                if (_tcsstr(pToken, _T("NoStart=")) == pToken) {
                                    // Opening of start line
                                    PGNumberOfGates = 1;
                                    StrToTime(pToken + 8, &PGOpenTimeH, &PGOpenTimeM);
                                } else if (_tcsstr(pToken, _T("TaskTime=")) == pToken) {
                                    // Designated Time for the task
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("WpDis=")) == pToken) {
                                    // Task distance calculation. False = use fixes, True = use waypoints
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("NearDis=")) == pToken) {
                                    // Distance tolerance
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("NearAlt=")) == pToken) {
                                    // Altitude tolerance
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("MinDis=")) == pToken) {
                                    // Uncompleted leg. 
                                    // False = calculate maximum distance from last observation zone.
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("RandomOrder=")) == pToken) {
                                    // if true, then Random order of waypoints is checked
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("MaxPts=")) == pToken) {
                                    // Maximum number of points
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("BeforePts=")) == pToken) {
                                    // Number of mandatory waypoints at the beginning. 1 means start line only, two means
                                    //      start line plus first point in task sequence (Task line).
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("AfterPts=")) == pToken) {
                                    // Number of mandatory waypoints at the end. 1 means finish line only, two means finish line
                                    //      and one point before finish in task sequence (Task line).
                                    // TODO :
                                } else if (_tcsstr(pToken, _T("Bonus=")) == pToken) {
                                    // Bonus for crossing the finish line         
                                    // TODO :
                                }
                            }
                        } else if (_tcsstr(pToken, _T("ObsZone=")) == pToken) {
                            TCHAR *sz = NULL;
                            CupObsZoneUpdater TmpZone;
                            TmpZone.mIdx = _tcstol(pToken + 8, &sz, 10);
                            if (TmpZone.mIdx < MAXSTARTPOINTS) {
                                while ((pToken = strsep_r(NULL, TEXT(","), &pWClast)) != NULL) {
                                    if (_tcsstr(pToken, _T("Style=")) == pToken) {
                                        // Direction. 0 - Fixed value, 1 - Symmetrical, 2 - To next point, 3 - To previous point, 4 - To start point
                                        TmpZone.mType = _tcstol(pToken + 6, &sz, 10);
                                    } else if (_tcsstr(pToken, _T("R1=")) == pToken) {
                                        // Radius 1
                                        TmpZone.mR1 = ReadLength(pToken + 3);
                                    } else if (_tcsstr(pToken, _T("A1=")) == pToken) {
                                        // Angle 1 in degrees
                                        TmpZone.mA1 = _tcstod(pToken + 3, &sz);
                                    } else if (_tcsstr(pToken, _T("R2=")) == pToken) {
                                        // Radius 2
                                        TmpZone.mR2 = ReadLength(pToken + 3);
                                    } else if (_tcsstr(pToken, _T("A2=")) == pToken) {
                                        // Angle 2 in degrees
                                        TmpZone.mA2 = _tcstod(pToken + 3, &sz);
                                    } else if (_tcsstr(pToken, _T("A12=")) == pToken) {
                                        // Angle 12
                                        TmpZone.mA12 = _tcstod(pToken + 4, &sz);
                                    } else if (_tcsstr(pToken, _T("Line=")) == pToken) {
                                        // true For Line Turmpoint type 
                                        // Exist only for start an Goalin LK
                                        TmpZone.mLine = (_tcstol(pToken + 5, &sz, 10) == 1);
                                    }
                                }
                                TmpZone.UpdateTask();
                            }
                        }
                    }
                    break;
                case none:
                default:
                    break;
            }
            memset(szString, 0, sizeof (szString)); // clear Temp Buffer
        }
        fclose(stream);
    }
    if(!ISGAAIRCRAFT) {
        // Landing don't exist in LK Task Systems, so Remove It;
        if ( bLoadComplet && !bLastInvalid ) {
            RemoveTaskPoint(getFinalWaypoint());
        }
    }
    UnlockTaskData();
    for (mapCode2Waypoint_t::iterator It = mapWaypoint.begin(); It != mapWaypoint.end(); ++It) {
        if (It->second.Comment) {
            free(It->second.Comment);
        }
        if (It->second.Details) {
            free(It->second.Details);
        }
    }
    mapWaypoint.clear();

    return ValidTaskPoint(0);
}
Example #4
0
	void CLabelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
	{
		if( _tcscmp(pstrName, _T("align")) == 0 ) {
			if( _tcsstr(pstrValue, _T("left")) != NULL ) {
				m_uTextStyle &= ~(DT_CENTER | DT_RIGHT | DT_SINGLELINE);
				m_uTextStyle |= DT_LEFT;
			}
			if( _tcsstr(pstrValue, _T("center")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_RIGHT );
				m_uTextStyle |= DT_CENTER;
			}
			if( _tcsstr(pstrValue, _T("right")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_CENTER | DT_SINGLELINE);
				m_uTextStyle |= DT_RIGHT;
			}
		}
		else if( _tcscmp(pstrName, _T("valign")) == 0 ) {
			if( _tcsstr(pstrValue, _T("top")) != NULL ) {
				m_uTextStyle &= ~(DT_BOTTOM | DT_VCENTER);
				m_uTextStyle |= (DT_TOP | DT_SINGLELINE);
			}
			if( _tcsstr(pstrValue, _T("center")) != NULL ) {
				m_uTextStyle &= ~(DT_TOP | DT_BOTTOM );            
				m_uTextStyle |= (DT_VCENTER | DT_SINGLELINE);
			}
			if( _tcsstr(pstrValue, _T("bottom")) != NULL ) {
				m_uTextStyle &= ~(DT_TOP | DT_VCENTER);
				m_uTextStyle |= (DT_BOTTOM | DT_SINGLELINE);
			}
		}
		else if( _tcscmp(pstrName, _T("endellipsis")) == 0 ) {
			if( _tcscmp(pstrValue, _T("true")) == 0 ) m_uTextStyle |= DT_END_ELLIPSIS;
			else m_uTextStyle &= ~DT_END_ELLIPSIS;
		}    
		else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("disabledtextcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetDisabledTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textpadding")) == 0 ) {
			RECT rcTextPadding = { 0 };
			LPTSTR pstr = NULL;
			rcTextPadding.left = _tcstol(pstrValue, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.top = _tcstol(pstr + 1, &pstr, 10);    ASSERT(pstr);    
			rcTextPadding.right = _tcstol(pstr + 1, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);    
			SetTextPadding(rcTextPadding);
		}
		else if( _tcscmp(pstrName, _T("showhtml")) == 0 ) SetShowHtml(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("autocalcwidth")) == 0 ) {
			SetAutoCalcWidth(_tcscmp(pstrValue, _T("true")) == 0);
		}
		else CControlUI::SetAttribute(pstrName, pstrValue);
	}
Example #5
0
// -----------------------------------------------------------------------------
// Feedback intensity dialog
static BOOL CALLBACK PhosphorProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam)	// LPARAM lParam
{
	static int nPrevIntensity;
	static int nPrevSaturation;

	switch (Msg) {
		case WM_INITDIALOG: {
			TCHAR szText[16];
			nPrevIntensity = nVidFeedbackIntensity;
			nPrevSaturation = nVidFeedbackOverSaturation;
			nExitStatus = 0;

			WndInMid(hDlg, hScrnWnd);

			// Initialise sliders
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETRANGE, (WPARAM)0, (LPARAM)MAKELONG(0, 255));
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETPAGESIZE, (WPARAM)0, (LPARAM)8);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)127);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)63);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)31);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)15);

			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETRANGE, (WPARAM)0, (LPARAM)MAKELONG(0, 127));
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETPAGESIZE, (WPARAM)0, (LPARAM)4);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)63);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)31);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)15);

			// Set slider to current values
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nVidFeedbackIntensity);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nVidFeedbackOverSaturation);

			// Set the edit control to current values
			_stprintf(szText, _T("%i"), nVidFeedbackIntensity);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);
			_stprintf(szText, _T("%i"), nVidFeedbackOverSaturation);
			SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);

			return TRUE;
		}
		case WM_COMMAND: {
			switch (HIWORD(wParam)) {
				case BN_CLICKED: {
					if (LOWORD(wParam) == IDOK) {
						nExitStatus = 1;
						SendMessage(hDlg, WM_CLOSE, 0, 0);
					}
					if (LOWORD(wParam) == IDCANCEL) {
						nExitStatus = -1;
						SendMessage(hDlg, WM_CLOSE, 0, 0);
					}
					break;
				}
				case EN_UPDATE: {
					if (nExitStatus == 0) {
						TCHAR szText[16] = _T("");
						bool bValid = 1;

						switch (LOWORD(wParam)) {
							case IDC_PHOSPHOR_1_EDIT:
								if (SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_EDIT, WM_GETTEXTLENGTH, (WPARAM)0, (LPARAM)0) < 16) {
									SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_EDIT, WM_GETTEXT, (WPARAM)16, (LPARAM)szText);
								}

								// Scan string in the edit control for illegal characters
								for (int i = 0; szText[i]; i++) {
									if (!_istdigit(szText[i])) {
										bValid = 0;
										break;
									}
								}

								if (bValid) {
									nVidFeedbackIntensity = _tcstol(szText, NULL, 0);
									if (nVidFeedbackIntensity < 0) {
										nVidFeedbackIntensity = 0;
									} else {
										if (nVidFeedbackIntensity > 255) {
											nVidFeedbackIntensity = 255;
										}
									}

									// Set slider to current value
									SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nVidFeedbackIntensity);
								}
								break;
							case IDC_PHOSPHOR_2_EDIT:
								if (SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_EDIT, WM_GETTEXTLENGTH, (WPARAM)0, (LPARAM)0) < 16) {
									SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_EDIT, WM_GETTEXT, (WPARAM)16, (LPARAM)szText);
								}

								// Scan string in the edit control for illegal characters
								for (int i = 0; szText[i]; i++) {
									if (!_istdigit(szText[i])) {
										bValid = 0;
										break;
									}
								}

								if (bValid) {
									nVidFeedbackOverSaturation = _tcstol(szText, NULL, 0);
									if (nVidFeedbackOverSaturation < 0) {
										nVidFeedbackOverSaturation = 0;
									} else {
										if (nVidFeedbackOverSaturation > 255) {
											nVidFeedbackOverSaturation = 255;
										}
									}

									// Set slider to current value
									SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nVidFeedbackOverSaturation);

									// Update the screen
									if (bVidOkay) {
										VidPaint(2);
									}
								}
								break;
						}
					}
					break;
				}
			}
			break;
		}

		case WM_HSCROLL: {
			switch (LOWORD(wParam)) {
				case TB_BOTTOM:
				case TB_ENDTRACK:
				case TB_LINEDOWN:
				case TB_LINEUP:
				case TB_PAGEDOWN:
				case TB_PAGEUP:
				case TB_THUMBPOSITION:
				case TB_THUMBTRACK:
				case TB_TOP: {
					if (nExitStatus == 0) {
						TCHAR szText[16];

						// Update the contents of the edit control
						switch (GetDlgCtrlID((HWND)lParam)) {
							case IDC_PHOSPHOR_1_SLIDER:
								nVidFeedbackIntensity = SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_SLIDER, TBM_GETPOS, (WPARAM)0, (LPARAM)0);
								_stprintf(szText, _T("%i"), nVidFeedbackIntensity);
								SendDlgItemMessage(hDlg, IDC_PHOSPHOR_1_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);
								break;
							case IDC_PHOSPHOR_2_SLIDER:
								nVidFeedbackOverSaturation = SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_SLIDER, TBM_GETPOS, (WPARAM)0, (LPARAM)0);
								_stprintf(szText, _T("%i"), nVidFeedbackOverSaturation);
								SendDlgItemMessage(hDlg, IDC_PHOSPHOR_2_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);
								break;
						}
					}
					break;
				}
			}
			break;
		}

		case WM_CLOSE:
			if (nExitStatus != 1) {
				nVidFeedbackIntensity = nPrevIntensity;
				nVidFeedbackOverSaturation = nPrevSaturation;
			}
			EndDialog(hDlg, 0);
			break;
	}

	return 0;
}
Example #6
0
int parseArguments(int argc, _TCHAR* argv[], encodingParameters *params)
{
	int i;
	for(i=1;i<argc;i++) {
		if(!_tcscmp(argv[i],_T("--fastest"))) params->overallQuality = kQualityFastest;
		else if(!_tcscmp(argv[i],_T("--fast"))) params->overallQuality = kQualityFast;
		else if(!_tcscmp(argv[i],_T("--normal"))) params->overallQuality = kQualityNormal;
		else if(!_tcscmp(argv[i],_T("--high"))) params->overallQuality = kQualityHigh;
		else if(!_tcscmp(argv[i],_T("--highest"))) params->overallQuality = kQualityHighest;
		else if(!_tcscmp(argv[i],_T("--quiet"))) params->quiet = true;
		else if(!_tcscmp(argv[i],_T("--cbr"))) {
			params->mode = kConfigCBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--abr"))) {
			params->mode = kConfigABR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--cvbr"))) {
			params->mode = kConfigConstrainedVBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 8) params->modeQuality = 8;
				else if(params->modeQuality > 1280) params->modeQuality = 1280;
			}
		}
		else if(!_tcscmp(argv[i],_T("--tvbr"))) {
			params->mode = kConfigTrueVBR;
			if(++i<argc) {
				params->modeQuality = _tstoi(argv[i]);
				if(params->modeQuality < 0) params->modeQuality = 0;
				else if(params->modeQuality > 127) params->modeQuality = 127;
			}
		}
		else if(!_tcscmp(argv[i],_T("--samplerate"))) {
			if(++i<argc) {
				if(!_tcscmp(argv[i],_T("auto"))) params->outSamplerate = 0;
				else if(!_tcscmp(argv[i],_T("keep"))) params->outSamplerate = 1;
				else params->outSamplerate = _tstoi(argv[i]);
				if(params->outSamplerate < 0) params->outSamplerate = 0;
			}
		}
		else if(!_tcscmp(argv[i],_T("--title"))) {
			if(++i<argc) params->metadata.title = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--album"))) {
			if(++i<argc) params->metadata.album = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--artist"))) {
			if(++i<argc) params->metadata.artist = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--albumartist"))) {
			if(++i<argc) params->metadata.albumArtist = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--composer"))) {
			if(++i<argc) params->metadata.composer = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--grouping"))) {
			if(++i<argc) params->metadata.group = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--genre"))) {
			if(++i<argc) params->metadata.genre = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--date"))) {
			if(++i<argc) params->metadata.date = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--comment"))) {
			if(++i<argc) params->metadata.comment = tCharToUTF8Str(argv[i]);
		}
		else if(!_tcscmp(argv[i],_T("--track"))) {
			if(++i<argc) {
				_TCHAR *ptr;
				params->metadata.track = _tcstol(argv[i],&ptr,10);
				if(*ptr == _T('/')) params->metadata.totalTrack = _tcstol(ptr+1,&ptr,10);
			}
		}
		else if(!_tcscmp(argv[i],_T("--disc"))) {
			if(++i<argc) {
				_TCHAR *ptr;
				params->metadata.disc = _tcstol(argv[i],&ptr,10);
				if(*ptr == _T('/')) params->metadata.totalDisc = _tcstol(ptr+1,&ptr,10);
			}
		}
		else if(!_tcscmp(argv[i],_T("--compilation"))) {
			params->metadata.compilation = true;
		}
		else if(!_tcscmp(argv[i],_T("--ignorelength"))) {
			params->ignoreLength = true;
		}
		else if(!_tcscmp(argv[i],_T("--he"))) {
			params->highEfficiency = true;
		}
		else if(!_tcsncmp(argv[i],_T("--"),2)) {}
		else {
			if(!params->inFile) {
				params->inFile = argv[i];
				if(!_tcscmp(argv[i],_T("-"))) params->readFromStdin = true;
			}
			else if(!params->outFile) params->outFile = argv[i];
		}
	}
	if(!params->inFile) return -1;
	if(params->highEfficiency) {
		if(params->mode < 3) params->mode = (codecConfig)(params->mode + 4);
		else {
			fprintf(stderr,"Warning: HE-AAC encoder cannot be used with true VBR mode - disabled.\n");
			params->highEfficiency = false;
		}
	}
	return 0;
}
Example #7
0
bool
WaypointReaderSeeYou::ParseLine(const TCHAR* line, const unsigned linenum,
                              Waypoints &waypoints)
{
  TCHAR ctemp[4096];
  const TCHAR *params[20];
  static const unsigned int max_params = ARRAY_SIZE(params);
  size_t n_params;

  const unsigned iName = 0;
  const unsigned iLatitude = 3, iLongitude = 4, iElevation = 5;
  const unsigned iStyle = 6, iRWDir = 7, iRWLen = 8;
  const unsigned iFrequency = 9, iDescription = 10;

  static bool ignore_following;
  if (linenum == 0)
    ignore_following = false;

  // If (end-of-file or comment)
  if (line[0] == '\0' || line[0] == 0x1a ||
      _tcsstr(line, _T("**")) == line ||
      _tcsstr(line, _T("*")) == line)
    // -> return without error condition
    return true;

  if (_tcslen(line) >= ARRAY_SIZE(ctemp))
    /* line too long for buffer */
    return false;

  // Skip first line if it doesn't begin with a quotation character
  // (usually the field order line)
  if (linenum == 0 && line[0] != _T('\"'))
    return true;

  // If task marker is reached ignore all following lines
  if (_tcsstr(line, _T("-----Related Tasks-----")) == line)
    ignore_following = true;
  if (ignore_following)
    return true;

  // Get fields
  n_params = ExtractParameters(line, ctemp, params, max_params, true, _T('"'));

  // Check if the basic fields are provided
  if (iName >= n_params)
    return false;
  if (iLatitude >= n_params)
    return false;
  if (iLongitude >= n_params)
    return false;

  GeoPoint location;

  // Latitude (e.g. 5115.900N)
  if (!ParseAngle(params[iLatitude], location.latitude, true))
    return false;

  // Longitude (e.g. 00715.900W)
  if (!ParseAngle(params[iLongitude], location.longitude, false))
    return false;

  location.Normalize(); // ensure longitude is within -180:180

  Waypoint new_waypoint(location);
  new_waypoint.file_num = file_num;
  new_waypoint.original_id = 0;

  // Name (e.g. "Some Turnpoint")
  if (*params[iName] == _T('\0'))
    return false;
  new_waypoint.name = params[iName];

  // Elevation (e.g. 458.0m)
  /// @todo configurable behaviour
  if ((iElevation >= n_params ||
      !ParseAltitude(params[iElevation], new_waypoint.elevation)) &&
      !CheckAltitude(new_waypoint))
    return false;

  // Style (e.g. 5)
  /// @todo include peaks with peak symbols etc.
  if (iStyle < n_params)
    ParseStyle(params[iStyle], new_waypoint);

  // Frequency & runway direction/length (for airports and landables)
  // and description (e.g. "Some Description")
  if (new_waypoint.IsLandable()) {
    if (iFrequency < n_params)
      new_waypoint.radio_frequency = RadioFrequency::Parse(params[iFrequency]);

    // Runway length (e.g. 546.0m)
    fixed rwlen = fixed_minus_one;
    if (iRWLen < n_params && ParseDistance(params[iRWLen], rwlen) &&
        positive(rwlen))
      new_waypoint.runway.SetLength(uround(rwlen));

    if (iRWDir < n_params && *params[iRWDir]) {
      TCHAR *end;
      int direction =_tcstol(params[iRWDir], &end, 10);
      if (end == params[iRWDir] || direction < 0 || direction > 360 ||
          (direction == 0 && !positive(rwlen)))
        direction = -1;
      else if (direction == 360)
        direction = 0;
      if (direction >= 0)
        new_waypoint.runway.SetDirectionDegrees(direction);
    }
  }

  if (iDescription < n_params)
    new_waypoint.comment = params[iDescription];

  waypoints.Append(new_waypoint);
  return true;
}
Example #8
0
BOOL NMEAParser::RMC(TCHAR *String, TCHAR **params, size_t nparams, NMEA_INFO *pGPS)
{
  TCHAR *Stop;
  static bool logbaddate=true;
  double speed=0;

  gpsValid = !NAVWarn(params[1][0]);

  GPSCONNECT = TRUE;    
  RMCAvailable=true; // 100409

  #ifdef PNA
  if (DeviceIsGM130) {

	double ps = GM130BarPressure();
	RMZAltitude = (1 - pow(fabs(ps / QNH),  0.190284)) * 44307.69;
	// StartupStore(_T("....... Pressure=%.0f QNH=%.2f Altitude=%.1f\n"),ps,QNH,RMZAltitude);

	RMZAvailable = TRUE;

	UpdateBaroSource(pGPS, BARO__GM130, NULL,   RMZAltitude);
  }
  if (DeviceIsRoyaltek3200) {
	if (Royaltek3200_ReadBarData()) {
		double ps = Royaltek3200_GetPressure();
		RMZAltitude = (1 - pow(fabs(ps / QNH),  0.190284)) * 44307.69;

		#if 0
		pGPS->TemperatureAvailable=true;
		pGPS->OutsideAirTemperature = Royaltek3200_GetTemperature();
		#endif
	}

	RMZAvailable = TRUE;

	UpdateBaroSource(pGPS, BARO__ROYALTEK3200,  NULL,  RMZAltitude);

  }
  #endif // PNA

  if (!activeGPS) {
	// Before ignoring anything else, commit RMZ altitude otherwise it will be ignored!
	if(RMZAvailable) {
		UpdateBaroSource(pGPS, isFlarm? BARO__RMZ_FLARM:BARO__RMZ, NULL, RMZAltitude);
	}
	return TRUE;
  }

  // if no valid fix, we dont get speed either!
  if (gpsValid)
  {
	// speed is in knots, 2 = 3.7kmh
	speed = StrToDouble(params[6], NULL);
  }
  
  pGPS->NAVWarning = !gpsValid;

  // say we are updated every time we get this,
  // so infoboxes get refreshed if GPS connected
  // the RMC sentence marks the start of a new fix, so we force the old data to be saved for calculations
        // note that Condor sends no date..
        if ((_tcslen(params[8]) <6) && !DevIsCondor) {
		#if TESTBENCH
		StartupStore(_T(".... RMC date field empty, skip sentence!\n"));
		#endif
		return TRUE;
	}

	// Even with no valid position, we let RMC set the time and date if valid
	long gy, gm, gd;
	gy = _tcstol(&params[8][4], &Stop, 10) + 2000;   
	params[8][4] = '\0';
	gm = _tcstol(&params[8][2], &Stop, 10); 
	params[8][2] = '\0';
	gd = _tcstol(&params[8][0], &Stop, 10); 

	// SeeYou PC is sending NMEA sentences with RMC date 2072-02-27
	if ( ((gy > 1980) && (gy <2100) ) && (gm != 0) && (gd != 0) ) { 
		pGPS->Year = gy;
		pGPS->Month = gm;
		pGPS->Day = gd;

force_advance:
		RMCtime = StrToDouble(params[0],NULL);
#ifndef OLD_TIME_MODIFY
		double ThisTime = TimeModify(params[0], pGPS, StartDay);
#else
		double ThisTime = TimeModify(RMCtime, pGPS);
#endif
		// RMC time has priority on GGA and GLL etc. so if we have it we use it at once
		if (!TimeHasAdvanced(ThisTime, pGPS)) {
			#if DEBUGSEQ
			StartupStore(_T("..... RMC time not advanced, skipping \n")); // 31C
			#endif
			return FALSE;
		}
			
	}  else {
		if (DevIsCondor) {
			#if DEBUGSEQ
			StartupStore(_T(".. Condor not sending valid date, using 1.1.2012%s"),NEWLINE);
			#endif
			gy=2012; gm=1; gd=1;
			goto force_advance;
		}

		if (gpsValid && logbaddate) { // 091115
			StartupStore(_T("------ NMEAParser:RMC Receiving an invalid or null DATE from GPS%s"),NEWLINE);
			StartupStore(_T("------ NMEAParser: Date received is y=%ld m=%ld d=%ld%s"),gy,gm,gd,NEWLINE); // 100422
			StartupStore(_T("------ This message will NOT be repeated. %s%s"),WhatTimeIsIt(),NEWLINE);
			DoStatusMessage(MsgToken(875));
			logbaddate=false;
		}
		gy=2012; gm=2; gd=30;	// an impossible date!
		goto force_advance;
		 
	}

  if (gpsValid) { 
	double tmplat;
	double tmplon;

	tmplat = MixedFormatToDegrees(StrToDouble(params[2], NULL));
	tmplat = NorthOrSouth(tmplat, params[3][0]);
	  
	tmplon = MixedFormatToDegrees(StrToDouble(params[4], NULL));
	tmplon = EastOrWest(tmplon,params[5][0]);
  
	if (!((tmplat == 0.0) && (tmplon == 0.0))) {
		pGPS->Latitude = tmplat;
		pGPS->Longitude = tmplon;
	}
  
	pGPS->Speed = KNOTSTOMETRESSECONDS * speed;
  
	if (pGPS->Speed>trackbearingminspeed) {
		pGPS->TrackBearing = AngleLimit360(StrToDouble(params[7], NULL));
	}
  } // gpsvalid 091108

#ifdef WIN32
  // As soon as we get a fix for the first time, set the
  // system clock to the GPS time.
  static bool sysTimeInitialised = false;
  
  if (!pGPS->NAVWarning && (gpsValid)) {
	if (SetSystemTimeFromGPS) {
		if (!sysTimeInitialised) {
			if ( ( pGPS->Year > 1980 && pGPS->Year<2100) && ( pGPS->Month > 0) && ( pGPS->Hour > 0)) {
        
				sysTimeInitialised =true; // Attempting only once
				SYSTEMTIME sysTime;
				// ::GetSystemTime(&sysTime);
				int hours = (int)pGPS->Hour;
				int mins = (int)pGPS->Minute;
				int secs = (int)pGPS->Second;
				sysTime.wYear = (unsigned short)pGPS->Year;
				sysTime.wMonth = (unsigned short)pGPS->Month;
				sysTime.wDay = (unsigned short)pGPS->Day;
				sysTime.wHour = (unsigned short)hours;
				sysTime.wMinute = (unsigned short)mins;
				sysTime.wSecond = (unsigned short)secs;
				sysTime.wMilliseconds = 0;
				::SetSystemTime(&sysTime);
			}
		}
	}
  }
#else
#warning "Set system clock to the GPS time not implemented."
#endif

  if(RMZAvailable) {
	UpdateBaroSource(pGPS, BARO__RMZ, NULL,  RMZAltitude);
  }
  if (!GGAAvailable) {
	// update SatInUse, some GPS receiver dont emmit GGA sentance
	if (!gpsValid) { 
		pGPS->SatellitesUsed = 0;
	} else {
		pGPS->SatellitesUsed = -1;
	}
  }
  
  if ( !GGAAvailable || (GGAtime == RMCtime)  )  {
	#if DEBUGSEQ
	StartupStore(_T("... RMC trigger gps, GGAtime==RMCtime\n")); // 31C
	#endif
	TriggerGPSUpdate(); 
  }

  return TRUE;

} // END RMC
Example #9
0
STDMETHODIMP_(void) CConsoleObject::OnNavigateComplete2(IDispatch* dispatch, VARIANT* url)
{
	Log(LOG_FUNC, _T("CConsoleObject::NavigateComplete2(url=%s)\n"), url->bstrVal);

	HRESULT hr;

	/*
	 * Get the IDispatchEx of the global script object
	 */

	CComQIPtr<IWebBrowser2> webBrowser2 = dispatch;
	if (!webBrowser2) return;

	CComPtr<IDispatch> documentDispatch;
	hr = webBrowser2->get_Document(&documentDispatch);
	if (FAILED(hr)) return;

	CComQIPtr<IHTMLDocument> document = documentDispatch;
	if (!document) {
		Log(LOG_ERROR, _T("QI IHTMLDocument failed\n"));
		return;
	}

	CComPtr<IDispatch> scriptDispatch;
	hr = document->get_Script(&scriptDispatch);
	if (FAILED(hr)) {
		Log(LOG_ERROR, _T("get_Script() failed\n"));
		return;
	}

	CComQIPtr<IDispatchEx> scriptDispEx = scriptDispatch;
	if (!scriptDispEx) {
		Log(LOG_ERROR, _T("QI IDispatchEx failed\n"));
		return;
	}

	/*
	 * Determine IE version.
	 * Use console67 to avoid name collision with the Developer Tools of IE8.
	 */

	CRegKey regKey;
	long versionNumber = LONG_MAX; // fail safe
	LONG regError;

	regError = regKey.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer"), KEY_READ);
	if (regError == ERROR_SUCCESS) {
		TCHAR versionString[128];
		ULONG size = sizeof(versionString);

		regError = regKey.QueryStringValue(_T("Version"), versionString, &size);
		if (regError == ERROR_SUCCESS) {
			versionString[size - 1] = _T('\0');

			TCHAR* dot = NULL;
			versionNumber = _tcstol(versionString, &dot, 10);
		}
	}

	_bstr_t console67Name(_T("console"));
	if (regError != ERROR_SUCCESS || versionNumber >= 8) {
		console67Name += _T("67");
	}

	_variant_t me(this, true);
	hr = scriptDispEx.PutPropertyAlways(console67Name, &me);
	if (FAILED(hr)) {
		Log(LOG_ERROR, _T("Put(\"console67\") failed: 0x%x\n"), hr);
		return;
	}

	/*CComQIPtr<IHTMLDocument2> document2 = documentDispatch;
	if (!document2) return;

	CComPtr<IHTMLWindow2> htmlWindow2;
	hr = document2->get_parentWindow(&htmlWindow2);
	if (FAILED(hr)) return;
	
	_bstr_t script =
		_T("this.Function;\n")
		_T("var aaa = new Function();\n");
	_variant_t dummy;
	hr = htmlWindow2->execScript(script, _bstr_t(_T("JavaScript")), &dummy);
	if (FAILED(hr)) {
		Log(LOG_ERROR, _T("NavigateComplete2(): execScript() failed: 0x%x\n"), hr);
		return;
	}*/

	DUMP_IDISPATCH(this);

	Log(LOG_FUNC, _T("CConsoleObject::NavigateComplete2() end\n"));
}
Example #10
0
	void CLabelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
	{
		if( _tcscmp(pstrName, _T("align")) == 0 ) {
			if( _tcsstr(pstrValue, _T("left")) != NULL ) {
				m_uTextStyle &= ~(DT_CENTER | DT_RIGHT | DT_SINGLELINE);
				m_uTextStyle |= DT_LEFT;
			}
			if( _tcsstr(pstrValue, _T("center")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_RIGHT );
				m_uTextStyle |= DT_CENTER;
			}
			if( _tcsstr(pstrValue, _T("right")) != NULL ) {
				m_uTextStyle &= ~(DT_LEFT | DT_CENTER | DT_SINGLELINE);
				m_uTextStyle |= DT_RIGHT;
			}
		}
		else if (_tcscmp(pstrName, _T("valign")) == 0)
		{
		    if (_tcsstr(pstrValue, _T("top")) != NULL) {
		        m_uTextStyle &= ~(DT_BOTTOM | DT_VCENTER);
		        m_uTextStyle |= (DT_TOP | DT_SINGLELINE);
		    }
		    if (_tcsstr(pstrValue, _T("vcenter")) != NULL) {
		        m_uTextStyle &= ~(DT_TOP | DT_BOTTOM);
		        m_uTextStyle |= (DT_VCENTER | DT_SINGLELINE);
		    }
		    if (_tcsstr(pstrValue, _T("bottom")) != NULL) {
		        m_uTextStyle &= ~(DT_TOP | DT_VCENTER);
		        m_uTextStyle |= (DT_BOTTOM | DT_SINGLELINE);
		    }
		}
		else if( _tcscmp(pstrName, _T("endellipsis")) == 0 ) {
			if( _tcscmp(pstrValue, _T("true")) == 0 ) m_uTextStyle |= DT_END_ELLIPSIS;
			else m_uTextStyle &= ~DT_END_ELLIPSIS;
		}    
		else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("disabledtextcolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetDisabledTextColor(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textpadding")) == 0 ) {
			RECT rcTextPadding = { 0 };
			LPTSTR pstr = NULL;
			rcTextPadding.left = _tcstol(pstrValue, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.top = _tcstol(pstr + 1, &pstr, 10);    ASSERT(pstr);    
			rcTextPadding.right = _tcstol(pstr + 1, &pstr, 10);  ASSERT(pstr);    
			rcTextPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);    
			SetTextPadding(rcTextPadding);
		}
		else if( _tcscmp(pstrName, _T("showhtml")) == 0 ) SetShowHtml(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledeffect")) == 0 ) SetEnabledEffect(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledluminous")) == 0 ) SetEnabledLuminous(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("luminousfuzzy")) == 0 ) SetLuminousFuzzy((float)_tstof(pstrValue));
		else if( _tcscmp(pstrName, _T("gradientangle")) == 0 ) SetGradientAngle(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("enabledstroke")) == 0 ) SetEnabledStroke(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("enabledshadow")) == 0 ) SetEnabledShadow(_tcscmp(pstrValue, _T("true")) == 0);
		else if( _tcscmp(pstrName, _T("gradientlength")) == 0 ) SetGradientLength(_ttoi(pstrValue));
		else if( _tcscmp(pstrName, _T("shadowoffset")) == 0 ){
			LPTSTR pstr = NULL;
			int offsetx = _tcstol(pstrValue, &pstr, 10);	ASSERT(pstr);    
			int offsety = _tcstol(pstr + 1, &pstr, 10);		ASSERT(pstr);
			SetShadowOffset(offsetx,offsety);
		}
		else if( _tcscmp(pstrName, _T("textcolor1")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextColor1(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textshadowcolora")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextShadowColorA(clrColor);
		}
		else if( _tcscmp(pstrName, _T("textshadowcolorb")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetTextShadowColorB(clrColor);
		}
		else if( _tcscmp(pstrName, _T("strokecolor")) == 0 ) {
			if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
			LPTSTR pstr = NULL;
			DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
			SetStrokeColor(clrColor);
		}
		else CControlUI::SetAttribute(pstrName, pstrValue);
	}
Example #11
0
void controlUC::setAttribute(PCWSTR pstrName, PCWSTR pstrValue)
{
	if( _tcscmp(pstrName, L"pos") == 0 ) {
		RECT rcPos = { 0 };
		PWSTR pstr = NULL;
		rcPos.left = _tcstol(pstrValue, &pstr, 10);  assert(pstr);    
		rcPos.top = _tcstol(pstr + 1, &pstr, 10);    assert(pstr);    
		rcPos.right = _tcstol(pstr + 1, &pstr, 10);  assert(pstr);    
		rcPos.bottom = _tcstol(pstr + 1, &pstr, 10); assert(pstr);    
		SIZE szXY = {rcPos.left >= 0 ? rcPos.left : rcPos.right, rcPos.top >= 0 ? rcPos.top : rcPos.bottom};
		setFixedXY(szXY);
		setFixedWidth(rcPos.right - rcPos.left);
		setFixedHeight(rcPos.bottom - rcPos.top);
	}
	else if( _tcscmp(pstrName, L"relativepos") == 0 ) {
		SIZE szMove,szZoom;
		PWSTR pstr = NULL;
		szMove.cx = _tcstol(pstrValue, &pstr, 10);  assert(pstr);    
		szMove.cy = _tcstol(pstr + 1, &pstr, 10);    assert(pstr);    
		szZoom.cx = _tcstol(pstr + 1, &pstr, 10);  assert(pstr);    
		szZoom.cy = _tcstol(pstr + 1, &pstr, 10); assert(pstr); 
		setRelativePos(szMove,szZoom);
	}
	else if( _tcscmp(pstrName, L"padding") == 0 ) {
		RECT rcPadding = { 0 };
		PWSTR pstr = NULL;
		rcPadding.left = _tcstol(pstrValue, &pstr, 10);  assert(pstr);    
		rcPadding.top = _tcstol(pstr + 1, &pstr, 10);    assert(pstr);    
		rcPadding.right = _tcstol(pstr + 1, &pstr, 10);  assert(pstr);    
		rcPadding.bottom = _tcstol(pstr + 1, &pstr, 10); assert(pstr);    
		setPadding(rcPadding);
	}
	else if( _tcscmp(pstrName, L"bkcolor") == 0 || _tcscmp(pstrName, L"bkcolor1") == 0 ) {
		while( *pstrValue > L'\0' && *pstrValue <= L' ')  pstrValue = ::CharNext(pstrValue);
		if( *pstrValue == L'#') pstrValue = ::CharNext(pstrValue);
		PWSTR pstr = NULL;
		DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
		setBkColor(clrColor);
	}
	else if( _tcscmp(pstrName, L"bordercolor") == 0 ) {
		if( *pstrValue == L'#') pstrValue = ::CharNext(pstrValue);
		PWSTR pstr = NULL;
		DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
		setBorderColor(clrColor);
	}
	else if( _tcscmp(pstrName, L"focusbordercolor") == 0 ) {
		if( *pstrValue == L'#') pstrValue = ::CharNext(pstrValue);
		PWSTR pstr = NULL;
		DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
		setFocusBorderColor(clrColor);
	}
	else if( _tcscmp(pstrName, L"bordersize") == 0 ) setBorderSize(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"borderround") == 0 ) {
		SIZE cxyRound = { 0 };
		PWSTR pstr = NULL;
		cxyRound.cx = _tcstol(pstrValue, &pstr, 10);  assert(pstr);    
		cxyRound.cy = _tcstol(pstr + 1, &pstr, 10);    assert(pstr);     
		setBorderRound(cxyRound);
	}
	else if( _tcscmp(pstrName, L"width") == 0 ) setFixedWidth(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"height") == 0 ) setFixedHeight(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"minwidth") == 0 ) setMinWidth(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"minheight") == 0 ) setMinHeight(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"maxwidth") == 0 ) setMaxWidth(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"maxheight") == 0 ) setMaxHeight(_ttoi(pstrValue));
	else if( _tcscmp(pstrName, L"name") == 0 ) setName(pstrValue);
	else if( _tcscmp(pstrName, L"text") == 0 ) setText(pstrValue);
	else if( _tcscmp(pstrName, L"tooltip") == 0 ) setToolTip(pstrValue);
	else if( _tcscmp(pstrName, L"userdata") == 0 ) setUserData(pstrValue);
	else if( _tcscmp(pstrName, L"enabled") == 0 ) setEnabled(_tcscmp(pstrValue, L"true") == 0);
	else if( _tcscmp(pstrName, L"mouse") == 0 ) setMouseEnabled(_tcscmp(pstrValue, L"true") == 0);
	else if( _tcscmp(pstrName, L"visible") == 0 ) setVisible(_tcscmp(pstrValue, L"true") == 0);
	else if( _tcscmp(pstrName, L"float") == 0 ) setFloat(_tcscmp(pstrValue, L"true") == 0);
	else if( _tcscmp(pstrName, L"shortcut") == 0 ) setShortcut(pstrValue[0]);
	else if( _tcscmp(pstrName, L"menu") == 0 ) setContextMenuUsed(_tcscmp(pstrValue, L"true") == 0);
}
Example #12
0
static INT32 StringToInp(struct GameInp* pgi, TCHAR* s)
{
	TCHAR* szRet = NULL;

	SKIP_WS(s);											// skip whitespace
	szRet = LabelCheck(s, _T("undefined"));
	if (szRet) {
		pgi->nInput = 0;
		return 0;
	}

	szRet = LabelCheck(s, _T("constant"));
	if (szRet) {
		pgi->nInput = GIT_CONSTANT;
		s = szRet;
		pgi->Input.Constant.nConst=(UINT8)_tcstol(s, &szRet, 0);
		*(pgi->Input.pVal) = pgi->Input.Constant.nConst;
		return 0;
	}

	szRet = LabelCheck(s, _T("switch"));
	if (szRet) {
		pgi->nInput = GIT_SWITCH;
		s = szRet;
		pgi->Input.Switch.nCode = (UINT16)_tcstol(s, &szRet, 0);
		return 0;
	}

	// Analog using mouse axis:
	szRet = LabelCheck(s, _T("mouseaxis"));
	if (szRet) {
		pgi->nInput = GIT_MOUSEAXIS;
		return StringToMouseAxis(pgi, szRet);
	}
	// Analog using joystick axis:
	szRet = LabelCheck(s, _T("joyaxis-neg"));
	if (szRet) {
		pgi->nInput = GIT_JOYAXIS_NEG;
		return StringToJoyAxis(pgi, szRet);
	}
	szRet = LabelCheck(s, _T("joyaxis-pos"));
	if (szRet) {
		pgi->nInput = GIT_JOYAXIS_POS;
		return StringToJoyAxis(pgi, szRet);
	}
	szRet = LabelCheck(s, _T("joyaxis"));
	if (szRet) {
		pgi->nInput = GIT_JOYAXIS_FULL;
		return StringToJoyAxis(pgi, szRet);
	}

	// Analog using keyboard slider
	szRet = LabelCheck(s, _T("slider"));
	if (szRet) {
		s = szRet;
		pgi->nInput = GIT_KEYSLIDER;
		pgi->Input.Slider.SliderAxis.nSlider[0] = 0;	// defaults
		pgi->Input.Slider.SliderAxis.nSlider[1] = 0;	//

		pgi->Input.Slider.SliderAxis.nSlider[0] = (UINT16)_tcstol(s, &szRet, 0);
		s = szRet;
		if (s == NULL) {
			return 1;
		}
		pgi->Input.Slider.SliderAxis.nSlider[1] = (UINT16)_tcstol(s, &szRet, 0);
		s = szRet;
		if (s == NULL) {
			return 1;
		}
		szRet = SliderInfo(pgi, s);
		s = szRet;
		if (s == NULL) {								// Get remaining slider info
			return 1;
		}
		return 0;
	}

	// Analog using joystick slider
	szRet = LabelCheck(s, _T("joyslider"));
	if (szRet) {
		s = szRet;
		pgi->nInput = GIT_JOYSLIDER;
		pgi->Input.Slider.JoyAxis.nJoy = 0;				// defaults
		pgi->Input.Slider.JoyAxis.nAxis = 0;			//

		pgi->Input.Slider.JoyAxis.nJoy = (UINT8)_tcstol(s, &szRet, 0);
		s = szRet;
		if (s == NULL) {
			return 1;
		}
		pgi->Input.Slider.JoyAxis.nAxis = (UINT8)_tcstol(s, &szRet, 0);
		s = szRet;
		if (s == NULL) {
			return 1;
		}
		szRet = SliderInfo(pgi, s);						// Get remaining slider info
		s = szRet;
		if (s == NULL) {
			return 1;
		}
		return 0;
	}

	return 1;
}
Example #13
0
/// <summary>
/// Draw the chart according to user selection and display it in the ChartViewer.
/// </summary>
/// <param name="viewer">The ChartViewer object to display the chart.</param>
void CFinancedemoDlg::drawChart(CChartViewer *viewer)
{
    // In this demo, we just assume we plot up to the latest time. So endDate is now.
    double endDate = Chart::chartTime2((int)time(0));

    // If the trading day has not yet started (before 9:30am), or if the end date is on
    // on Sat or Sun, we set the end date to 4:00pm of the last trading day     
    while ((fmod(endDate, 86400) < 9 * 3600 + 30 * 60) || 
        (Chart::getChartWeekDay(endDate) == 0)
        || (Chart::getChartWeekDay(endDate) == 6))
        endDate = endDate - fmod(endDate, 86400) - 86400 + 16 * 3600;

     // The duration selected by the user
    int durationInDays = (int)_tcstol((const TCHAR *)m_TimeRange.GetItemDataPtr(
        m_TimeRange.GetCurSel()), 0, 0);

    // Compute the start date by subtracting the duration from the end date.
    double startDate;
    if (durationInDays >= 30)
    {
        // More or equal to 30 days - so we use months as the unit
        int YMD = Chart::getChartYMD(endDate);
        int startMonth = (YMD / 100) % 100 - durationInDays / 30;
        int startYear = YMD / 10000;
        while (startMonth < 1)
        {
            --startYear;
            startMonth += 12;
        }
        startDate = Chart::chartTime(startYear, startMonth, 1);
    }
    else
    {
        // Less than 30 days - use day as the unit. The starting point of the axis is
        // always at the start of the day (9:30am). Note that we use trading days, so
        // we skip Sat and Sun in counting the days.
        startDate = endDate - fmod(endDate, 86400) + 9 * 3600 + 30 * 60;
        for (int i = 1; i < durationInDays; ++i)
        {
            if (Chart::getChartWeekDay(startDate) == 1)
                startDate -= 3 * 86400;
            else
                startDate -= 86400;
        }
    }

    // The first moving average period selected by the user.
    CString avgText;
    m_MovAvg1.GetWindowText(avgText);
    m_avgPeriod1 = (int)_tcstol(avgText, 0, 0);
    if (m_avgPeriod1 < 0)
        m_avgPeriod1 = 0;
    if (m_avgPeriod1 > 300)
        m_avgPeriod1 = 300;

    // The second moving average period selected by the user.
    m_MovAvg2.GetWindowText(avgText);
    m_avgPeriod2 = (int)_tcstol(avgText, 0, 0);
    if (m_avgPeriod2 < 0)
        m_avgPeriod2 = 0;
    if (m_avgPeriod2 > 300)
        m_avgPeriod2 = 300;

    // We need extra leading data points in order to compute moving averages.
    int extraPoints = (m_avgPeriod1 > m_avgPeriod2) ? m_avgPeriod1 : m_avgPeriod2;
    if (extraPoints < 25)
        extraPoints = 25;

    // The data series we want to get.
    CString tickerKey = 
        (const TCHAR *)m_TickerSymbol.GetItemDataPtr(m_TickerSymbol.GetCurSel());

    // In this demo, we can get 15 min, daily, weekly or monthly data depending on
    // the time range.
    int resolution;
    if (durationInDays <= 10) 
    {
        // 10 days or less, we assume 15 minute data points are available
        resolution = 900;

        // We need to adjust the startDate backwards for the extraPoints. We assume 
        // 6.5 hours trading time per day, and 5 trading days per week.
        double dataPointsPerDay = 6.5 * 3600 / resolution;
        double adjustedStartDate = startDate - fmod(startDate, 86400) - 
            (int)(extraPoints / dataPointsPerDay * 7 / 5 + 2.9999999) * 86400;

        // Get the required 15 min data
        get15MinData(tickerKey, adjustedStartDate, endDate);
    }
    else if (durationInDays >= 4.5 * 360)
    {
        // 4 years or more - use monthly data points.
        resolution = 30 * 86400;
            
        // Adjust startDate backwards to cater for extraPoints
        int YMD = Chart::getChartYMD(startDate);
        int adjustedMonth = (YMD / 100) % 100 - extraPoints;
        int adjustedYear = YMD / 10000;
        while (adjustedMonth < 1)
        {
            --adjustedYear;
            adjustedMonth += 12;
        }
        double adjustedStartDate = Chart::chartTime(adjustedYear, adjustedMonth, 1);
        
        // Get the required monthly data
        getMonthlyData(tickerKey, adjustedStartDate, endDate);
    }
    else if (durationInDays >= 1.5 * 360)
    {
        // 1 year or more - use weekly points. 
        resolution = 7 * 86400;
 
        //Note that we need to add extra points by shifting the starting weeks backwards
        double adjustedStartDate = startDate - (extraPoints * 7 + 6) * 86400;
            
        // Get the required weekly data
        getWeeklyData(tickerKey, adjustedStartDate, endDate);
    }
    else
    {
        // Default - use daily points
        resolution = 86400;
            
        // Adjust startDate backwards to cater for extraPoints. We multiply the days 
        // by 7/5 as we assume 1 week has 5 trading days.
        double adjustedStartDate = startDate - fmod(startDate, 86400) - 
            ((extraPoints * 7 + 4) / 5 + 2) * 86400;

        // Get the required daily data
        getDailyData(tickerKey, adjustedStartDate, endDate);
    }
    
    // We now confirm the actual number of extra points (data points that are before
    // the start date) as inferred using actual data from the database.
    for (extraPoints = 0; extraPoints < m_noOfPoints; ++extraPoints)
    {
        if (m_timeStamps[extraPoints] >= startDate)
            break;
    }

    // Check if there is any valid data
    if (extraPoints >= m_noOfPoints)
    {
        // No data - just display the no data message.
        MultiChart errMsg(400, 50);
        errMsg.addTitle(Chart::TopLeft, "No data available for the specified time period", 
            "arial.ttf", 10);
        viewer->setChart(&errMsg);
        return;
    }

    // In some finance chart presentation style, even if the data for the latest day 
    // is not fully available, the axis for the entire day will still be drawn, where
    // no data will appear near the end of the axis.
    int extraTrailingPoints = 0;
    if (resolution <= 86400)
    {
        // Add extra points to the axis until it reaches the end of the day. The end
        // of day is assumed to be 16:00 (it depends on the stock exchange).
        double lastTime = m_timeStamps[m_noOfPoints - 1];
        int extraTrailingPoints = (int)((16 * 3600 - fmod(lastTime, 86400)) / resolution);
        if (extraTrailingPoints > 0)
        {
            double *extendedTimeStamps = new double[m_noOfPoints + extraTrailingPoints];
            memcpy(extendedTimeStamps, m_timeStamps, sizeof(double) * m_noOfPoints);
            for (int i = 0; i < extraTrailingPoints; ++i)
                extendedTimeStamps[m_noOfPoints + i] = lastTime + resolution * (i + 1);
            delete[] m_timeStamps;
            m_timeStamps = extendedTimeStamps;
        }
    }

    //
    // At this stage, all data is available. We can draw the chart as according to 
    // user input.
    //

    //
    // Determine the chart size. In this demo, user can select 4 different chart sizes.
    // Default is the large chart size.
    //
    int width = 780;
    int mainHeight = 250;
    int indicatorHeight = 80;

    CString selectedSize = (const TCHAR *)m_ChartSize.GetItemDataPtr(m_ChartSize.GetCurSel());
    if (selectedSize == _T("S"))
    {
        // Small chart size
        width = 450;
        mainHeight = 160;
        indicatorHeight = 60;
    }
    else if (selectedSize == _T("M"))
    {
        // Medium chart size
        width = 620;
        mainHeight = 210;
        indicatorHeight = 65;
    }
    else if (selectedSize == _T("H"))
    {
        // Huge chart size
        width = 1000;
        mainHeight = 320;
        indicatorHeight = 90;
    }

    // Create the chart object using the selected size
    FinanceChart m(width);

    // Set the data into the chart object
    m.setData(DoubleArray(m_timeStamps, m_noOfPoints + extraTrailingPoints), 
        DoubleArray(m_highData, m_noOfPoints), DoubleArray(m_lowData, m_noOfPoints), 
        DoubleArray(m_openData, m_noOfPoints), DoubleArray(m_closeData, m_noOfPoints),
        DoubleArray(m_volData, m_noOfPoints), extraPoints);

    //
    // We configure the title of the chart. In this demo chart design, we put the
    // company name as the top line of the title with left alignment.
    //
    CString companyName;
    m_TickerSymbol.GetLBText(m_TickerSymbol.GetCurSel(), companyName);
    m.addPlotAreaTitle(Chart::TopLeft, TCHARtoUTF8(companyName));

    // We displays the current date as well as the data resolution on the next line.
    const char *resolutionText = "";
    if (resolution == 30 * 86400)
        resolutionText = "Monthly";
    else if (resolution == 7 * 86400)
        resolutionText = "Weekly";
    else if (resolution == 86400)
        resolutionText = "Daily";
    else if (resolution == 900)
        resolutionText = "15-min";

    char buffer[1024];
    sprintf(buffer, "<*font=arial.ttf,size=8*>%s - %s chart", 
        m.formatValue(Chart::chartTime2((int)time(0)), "mmm dd, yyyy"), resolutionText);
    m.addPlotAreaTitle(Chart::BottomLeft, buffer);

    // A copyright message at the bottom left corner the title area
    m.addPlotAreaTitle(Chart::BottomRight, 
        "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering");

    //
    // Set the grid style according to user preference. In this simple demo user
    // interface, the user can enable/disable grid lines. The grid line colors are
    // hard coded to 0xdddddd (light grey), and the plot area background color is 
    // hard coded to 0xfffff0 (pale yellow).
    //
    int vGridColor = m_VGrid.GetCheck() ? 0xdddddd : Chart::Transparent;
    int hGridColor = m_HGrid.GetCheck() ? 0xdddddd : Chart::Transparent;
    m.setPlotAreaStyle(0xfffff0, hGridColor, vGridColor, hGridColor, vGridColor);

    //
    // Set log or linear scale according to user preference
    //
    m.setLogScale(m_LogScale.GetCheck() != 0);

    //
    // Add the first techical indicator according. In this demo, we draw the first
    // indicator on top of the main chart.
    //
    addIndicator(&m, (const TCHAR *)m_Indicator1.GetItemDataPtr(m_Indicator1.GetCurSel()), 
        indicatorHeight);

    // Add the main chart
    m.addMainChart(mainHeight);

    //
    // Draw the main chart depending on the chart type the user has selected
    //
    CString selectedType = (const TCHAR *)m_ChartType.GetItemDataPtr(m_ChartType.GetCurSel());
    if (selectedType == _T("Close"))
        m.addCloseLine(0x40);
    else if (selectedType == _T("TP"))
        m.addTypicalPrice(0x40);
    else if (selectedType == _T("WC"))
        m.addWeightedClose(0x40);
    else if (selectedType == _T("Median"))
        m.addMedianPrice(0x40);

    //
    // Add moving average lines.
    //
    addMovingAvg(&m, (const TCHAR *)m_AvgType1.GetItemDataPtr(m_AvgType1.GetCurSel()), 
        m_avgPeriod1, 0x663300);
    addMovingAvg(&m, (const TCHAR *)m_AvgType2.GetItemDataPtr(m_AvgType2.GetCurSel()), 
        m_avgPeriod2, 0x9900ff);

    //
    // Draw the main chart if the user has selected CandleStick or OHLC. We
    // draw it here to make sure it is drawn behind the moving average lines
    // (that is, the moving average lines stay on top.)
    //
    if (selectedType == _T("CandleStick"))
        m.addCandleStick(0x33ff33, 0xff3333);
    else if (selectedType == _T("OHLC"))
        m.addHLOC(0x8000, 0x800000);

    //
    // Add price band/channel/envelop to the chart according to user selection
    //
    CString selectedBand = (const TCHAR *)m_Band.GetItemDataPtr(m_Band.GetCurSel());
    if (selectedBand == _T("BB"))
        m.addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);
    else if (selectedBand == _T("DC"))
        m.addDonchianChannel(20, 0x9999ff, 0xc06666ff);
    else if (selectedBand == _T("Envelop"))
        m.addEnvelop(20, 0.1, 0x9999ff, 0xc06666ff);

    //
    // Add volume bars to the main chart if necessary
    //
    if (m_Volume.GetCheck())
        m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);

    //
    // Add additional indicators as according to user selection.
    //
    addIndicator(&m, (const TCHAR *)m_Indicator2.GetItemDataPtr(m_Indicator2.GetCurSel()), 
        indicatorHeight);
    addIndicator(&m, (const TCHAR *)m_Indicator3.GetItemDataPtr(m_Indicator3.GetCurSel()), 
        indicatorHeight);
    addIndicator(&m, (const TCHAR *)m_Indicator4.GetItemDataPtr(m_Indicator4.GetCurSel()), 
        indicatorHeight);

    // Set the chart to the viewer
    viewer->setChart(&m);

    // Set image map (for tool tips) to the viewer
    sprintf(buffer, "title='%s {value|G}'", m.getToolTipDateFormat());
    viewer->setImageMap(m.getHTMLImageMap("", "", buffer));
}
Example #14
0
LRESULT CPropDlg::OnPropertyChanged(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
	ATLTRACE(_T("CPropDlg::OnPropertyChanged()\n"));
	const int getLen = 127;
	_TCHAR buf[128] = _T("");
	_TCHAR *bufend;

	int nVal = 0;
	switch(m_nCurSel)
	{
	case 0: // Fire
		break;
	case 1: // Decay
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nDecay )
		{
			m_nDecay = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 2: // Flammability
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nFlammability )
		{
			m_nFlammability = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 3: // Maximum Heat
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nMaxHeat )
		{
			m_nMaxHeat = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 4: // Spread Rate
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nSpreadRate )
		{
			m_nSpreadRate = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 5: // Size
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nSize )
		{
			m_nSize = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 6: // Smoothness
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nSmoothness )
		{
			m_nSmoothness = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 7: // Distribution
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nDistribution )
		{
			m_nDistribution = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	case 8: // Chaos
		GetDlgItemText(IDC_EDIT1, buf, getLen);
		nVal = _tcstol(buf,&bufend,10);
		if( nVal != m_nChaos )
		{
			m_nChaos = nVal;
			::EnableWindow(GetDlgItem(IDC_APPLY),TRUE);
		}
		break;
	}
	return 0;
}
Example #15
0
FlarmId
FlarmId::Parse(const TCHAR *input, TCHAR **endptr_r)
{
  return FlarmId(_tcstol(input, endptr_r, 16));
}
Example #16
0
static BOOL FLYSEN(PDeviceDescriptor_t d, TCHAR *String, NMEA_INFO *pGPS)
{

    TCHAR ctemp[80];
    double vtas;
    static int offset=-1;

    GPSCONNECT=true;

    // firmware 3.31h no offset
    // firmware 3.32  1 offset
    // Determine firmware version, assuming it will not change in the session!
    if (offset<0) {
        NMEAParser::ExtractParameter(String,ctemp,8);
        if ( (_tcscmp(ctemp,_T("A"))==0) || (_tcscmp(ctemp,_T("V"))==0))
            offset=0;
        else {
            NMEAParser::ExtractParameter(String,ctemp,9);
            if ( (_tcscmp(ctemp,_T("A"))==0) || (_tcscmp(ctemp,_T("V"))==0))
                offset=1;
            else
                return TRUE;
        }
    }

    // VOID GPS SIGNAL
    NMEAParser::ExtractParameter(String,ctemp,8+offset);
    if (_tcscmp(ctemp,_T("V"))==0) {
        pGPS->NAVWarning=true;
        // GPSCONNECT=false; // 121127 NO!!
        goto label_nogps;
    }
    // ------------------------

    double tmplat;
    double tmplon;

    NMEAParser::ExtractParameter(String,ctemp,1+offset);
    tmplat = MixedFormatToDegrees(StrToDouble(ctemp, NULL));
    NMEAParser::ExtractParameter(String,ctemp,2+offset);
    tmplat = NorthOrSouth(tmplat, ctemp[0]);

    NMEAParser::ExtractParameter(String,ctemp,3+offset);
    tmplon = MixedFormatToDegrees(StrToDouble(ctemp, NULL));
    NMEAParser::ExtractParameter(String,ctemp,4+offset);
    tmplon = EastOrWest(tmplon,ctemp[0]);

    if (!((tmplat == 0.0) && (tmplon == 0.0))) {
        pGPS->Latitude = tmplat;
        pGPS->Longitude = tmplon;
        pGPS->NAVWarning=false;
    }

    // GPS SPEED
    NMEAParser::ExtractParameter(String,ctemp,6+offset);
    pGPS->Speed = StrToDouble(ctemp,NULL)/10;

    // TRACK BEARING
    if (pGPS->Speed>1.0) {
        NMEAParser::ExtractParameter(String,ctemp,5+offset);
        pGPS->TrackBearing = AngleLimit360(StrToDouble(ctemp, NULL));
    }

    // HGPS
    NMEAParser::ExtractParameter(String,ctemp,7+offset);
    pGPS->Altitude = StrToDouble(ctemp,NULL);

    // ------------------------
label_nogps:

    // SATS
    NMEAParser::ExtractParameter(String,ctemp,9+offset);
    pGPS->SatellitesUsed = (int) StrToDouble(ctemp,NULL);

    // DATE
    // Firmware 3.32 has got the date
    if (offset>0) {
        NMEAParser::ExtractParameter(String,ctemp,0);
        long gy, gm, gd;
        TCHAR *Stop;
        gy = _tcstol(&ctemp[4], &Stop, 10) + 2000;
        ctemp[4] = '\0';
        gm = _tcstol(&ctemp[2], &Stop, 10);
        ctemp[2] = '\0';
        gd = _tcstol(&ctemp[0], &Stop, 10);

        if ( ((gy > 1980) && (gy <2100) ) && (gm != 0) && (gd != 0) ) {
            pGPS->Year = gy;
            pGPS->Month = gm;
            pGPS->Day = gd;
        }
    }

    // TIME
    // ignoring 00:00.00
    // We need to manage UTC time
#ifndef OLD_TIME_MODIFY
    static int StartDay=-1;
    if (pGPS->SatellitesUsed>0) {
        NMEAParser::ExtractParameter(String,ctemp,0+offset);
        pGPS->Time = TimeModify(ctemp, pGPS, StartDay);
    }
    // TODO : check if TimeHasAdvanced check is needed (cf. Parser.cpp)
#else
    NMEAParser::ExtractParameter(String,ctemp,0+offset);
    double fixTime = StrToDouble(ctemp,NULL);

    static  int day_difference=0, previous_months_day_difference=0;
    static int startday=-1;

    if (fixTime>0 && pGPS->SatellitesUsed>0) {
        double hours, mins,secs;
        hours = fixTime / 10000;
        pGPS->Hour = (int)hours;
        mins = fixTime / 100;
        mins = mins - (pGPS->Hour*100);
        pGPS->Minute = (int)mins;
        secs = fixTime - (pGPS->Hour*10000) - (pGPS->Minute*100);
        pGPS->Second = (int)secs;

        fixTime = secs + (pGPS->Minute*60) + (pGPS->Hour*3600);

        if ((startday== -1) && (pGPS->Day != 0)) {
            if (offset)
                StartupStore(_T(". FLYSEN First GPS DATE: %d-%d-%d%s"), pGPS->Year, pGPS->Month, pGPS->Day,NEWLINE);
            else
                StartupStore(_T(". FLYSEN No Date, using PNA GPS DATE: %d-%d-%d%s"), pGPS->Year, pGPS->Month, pGPS->Day,NEWLINE);
            startday = pGPS->Day;
            day_difference=0;
            previous_months_day_difference=0;
        }
        if (startday != -1) {
            if (pGPS->Day < startday) {
                // detect change of month (e.g. day=1, startday=26)
                previous_months_day_difference=day_difference+1;
                day_difference=0;
                startday = pGPS->Day;
                StartupStore(_T(". FLYSEN Change GPS DATE to NEW MONTH: %d-%d-%d  (%d days running)%s"),
                             pGPS->Year, pGPS->Month, pGPS->Day,previous_months_day_difference,NEWLINE);
            }
            if ( (pGPS->Day-startday)!=day_difference) {
                StartupStore(_T(". FLYSEN Change GPS DATE: %d-%d-%d%s"), pGPS->Year, pGPS->Month, pGPS->Day,NEWLINE);
            }

            day_difference = pGPS->Day-startday;
            if ((day_difference+previous_months_day_difference)>0) {
                fixTime += (day_difference+previous_months_day_difference) * 86400;
            }
        }
        pGPS->Time = fixTime;
    }
#endif

    // HPA from the pressure sensor
    //   NMEAParser::ExtractParameter(String,ctemp,10+offset);
    //   double ps = StrToDouble(ctemp,NULL)/100;
    //   pGPS->BaroAltitude = (1 - pow(fabs(ps / QNH),  0.190284)) * 44307.69;

    // HBAR 1013.25
    NMEAParser::ExtractParameter(String,ctemp,11+offset);
    double palt=StrToDouble(ctemp,NULL);
    UpdateBaroSource( pGPS, 0,d, AltitudeToQNHAltitude(palt));

    // VARIO
    NMEAParser::ExtractParameter(String,ctemp,12+offset);
    pGPS->Vario = StrToDouble(ctemp,NULL)/100;

    // TAS
    NMEAParser::ExtractParameter(String,ctemp,13+offset);
    vtas=StrToDouble(ctemp,NULL)/10;
    pGPS->IndicatedAirspeed = vtas/AirDensityRatio(palt);
    pGPS->TrueAirspeed = vtas;
    if (pGPS->IndicatedAirspeed >0)
        pGPS->AirspeedAvailable = TRUE;
    else
        pGPS->AirspeedAvailable = FALSE;

    // ignore n.14 airspeed source

    // OAT
    NMEAParser::ExtractParameter(String,ctemp,15+offset);
    pGPS->OutsideAirTemperature = StrToDouble(ctemp,NULL);
    pGPS->TemperatureAvailable=TRUE;

    // ignore n.16 baloon temperature

    // BATTERY PERCENTAGES
    NMEAParser::ExtractParameter(String,ctemp,17+offset);
    pGPS->ExtBatt1_Voltage = StrToDouble(ctemp,NULL)+1000;
    NMEAParser::ExtractParameter(String,ctemp,18+offset);
    pGPS->ExtBatt2_Voltage = StrToDouble(ctemp,NULL)+1000;



    pGPS->VarioAvailable = TRUE;

    // currently unused in LK, but ready for next future
    TriggerVarioUpdate();
    TriggerGPSUpdate();

    return TRUE;
}
Example #17
0
/* libcall(const libname[], const funcname[], const typestring[], ...)
 *
 * Loads the DLL or shared library if not yet loaded (the name comparison is
 * case sensitive).
 *
 * typestring format:
 *    Whitespace is permitted between the types, but not inside the type
 *    specification. The string "ii[4]&u16s" is equivalent to "i i[4] &u16 s",
 *    but the latter is easier on the eye.
 *
 * types:
 *    i = signed integer, 16-bit in Windows 3.x, else 32-bit in Win32 and Linux
 *    u = unsigned integer, 16-bit in Windows 3.x, else 32-bit in Win32 and Linux
 *    f = IEEE floating point, 32-bit
 *    p = packed string
 *    s = unpacked string
 *    The difference between packed and unpacked strings is only relevant when
 *    the parameter is passed by reference (see below).
 *
 * pass-by-value and pass-by-reference:
 *    By default, parameters are passed by value. To pass a parameter by
 *    reference, prefix the type letter with an "&":
 *    &i = signed integer passed by reference
 *    i = signed integer passed by value
 *    Same for '&u' versus 'u' and '&f' versus 'f'.
 *
 *    Arrays are passed by "copy & copy-back". That is, libcall() allocates a
 *    block of dynamic memory to copy the array into. On return from the foreign
 *    function, libcall() copies the array back to the abstract machine. The
 *    net effect is similar to pass by reference, but the foreign function does
 *    not work in the AMX stack directly. During the copy and the copy-back
 *    operations, libcall() may also transform the array elements, for example
 *    between 16-bit and 32-bit elements. This is done because Pawn only
 *    supports a single cell size, which may not fit the required integer size
 *    of the foreign function.
 *
 *    See "element ranges" for the syntax of passing an array.
 *
 *    Strings may either be passed by copy, or by "copy & copy-back". When the
 *    string is an output parameter (for the foreign function), the size of the
 *    array that will hold the return string must be indicated between square
 *    brackets behind the type letter (see "element ranges"). When the string
 *    is "input only", this is not needed --libcall() will determine the length
 *    of the input string itself.
 *
 *    The tokens 'p' and 's' are equivalent, but 'p[10]' and 's[10]' are not
 *    equivalent: the latter syntaxes determine whether the output from the
 *    foreign function will be stored as a packed or an unpacked string.
 *
 * element sizes:
 *    Add an integer behind the type letter; for example, 'i16' refers to a
 *    16-bit signed integer. Note that the value behind the type letter must
 *    be either 8, 16 or 32.
 *
 *    You should only use element size specifiers on the 'i' and 'u' types. That
 *    is, do not use these specifiers on 'f', 's' and 'p'.
 *
 * element ranges:
 *    For passing arrays, the size of the array may be given behind the type
 *    letter and optional element size. The token 'u[4]' indicates an array of
 *    four unsigned integers, which are typically 32-bit. The token 'i16[8]'
 *    is an array of 8 signed 16-bit integers. Arrays are always passed by
 *    "copy & copy-back"
 *
 * When compiled as Unicode, this library converts all strings to Unicode
 * strings.
 *
 * The calling convention for the foreign functions is assumed:
 * -  "__stdcall" for Win32,
 * -  "far pascal" for Win16
 * -  and the GCC default for Unix/Linux (_cdecl)
 *
 * C++ name mangling of the called function is not handled (there is no standard
 * convention for name mangling, so there is no portable way to convert C++
 * function names to mangled names). Win32 name mangling (used by default by
 * Microsoft compilers on functions declared as __stdcall) is also not handled.
 *
 * Returns the value of the called function.
 */
static cell AMX_NATIVE_CALL n_libcall(AMX *amx, const cell *params)
{
  const TCHAR *libname, *funcname, *typestring;
  MODLIST *item;
  int paramidx, typeidx, idx;
  PARAM ps[MAXPARAMS];
  cell *cptr,result;
  LIBFUNC LibFunc;

  amx_StrParam(amx, params[1], libname);
  item = findlib(&ModRoot, amx, libname);
  if (item == NULL)
    item = addlib(&ModRoot, amx, libname);
  if (item == NULL) {
    amx_RaiseError(amx, AMX_ERR_NATIVE);
    return 0;
  } /* if */

  /* library is loaded, get the function */
  amx_StrParam(amx, params[2], funcname);
  LibFunc=(LIBFUNC)SearchProcAddress(item->inst, funcname);
  if (LibFunc==NULL) {
    amx_RaiseError(amx, AMX_ERR_NATIVE);
    return 0;
  } /* if */

  #if defined HAVE_DYNCALL_H
    /* (re-)initialize the dyncall library */
    if (dcVM==NULL) {
      dcVM=dcNewCallVM(4096);
      dcMode(dcVM,DC_CALL_C_X86_WIN32_STD);
    } /* if */
    dcReset(dcVM);
  #endif

  /* decode the parameters */
  paramidx=typeidx=0;
  amx_StrParam(amx, params[3], typestring);
  while (paramidx < MAXPARAMS && typestring[typeidx]!=__T('\0')) {
    /* skip white space */
    while (typestring[typeidx]!=__T('\0') && typestring[typeidx]<=__T(' '))
      typeidx++;
    if (typestring[typeidx]==__T('\0'))
      break;
    /* save "pass-by-reference" token */
    ps[paramidx].type=0;
    if (typestring[typeidx]==__T('&')) {
      ps[paramidx].type=BYREF;
      typeidx++;
    } /* if */
    /* store type character */
    ps[paramidx].type |= (unsigned char)typestring[typeidx];
    typeidx++;
    /* set default size, then check for an explicit size */
    #if defined __WIN32__ || defined _WIN32 || defined WIN32
      ps[paramidx].size=32;
    #elif defined _Windows
      ps[paramidx].size=16;
    #endif
    if (_istdigit(typestring[typeidx])) {
      ps[paramidx].size=(unsigned char)_tcstol(&typestring[typeidx],NULL,10);
      while (_istdigit(typestring[typeidx]))
        typeidx++;
    } /* if */
    /* set default range, then check for an explicit range */
    ps[paramidx].range=1;
    if (typestring[typeidx]=='[') {
      ps[paramidx].range=_tcstol(&typestring[typeidx+1],NULL,10);
      while (typestring[typeidx]!=']' && typestring[typeidx]!='\0')
        typeidx++;
      ps[paramidx].type |= BYREF; /* arrays are always passed by reference */
      typeidx++;                  /* skip closing ']' too */
    } /* if */
    /* get pointer to parameter */
    amx_GetAddr(amx,params[paramidx+4],&cptr);
    switch (ps[paramidx].type) {
    case 'i': /* signed integer */
    case 'u': /* unsigned integer */
    case 'f': /* floating point */
      assert(ps[paramidx].range==1);
      ps[paramidx].v.val=(int)*cptr;
      break;
    case 'i' | BYREF:
    case 'u' | BYREF:
    case 'f' | BYREF:
      ps[paramidx].v.ptr=cptr;
      if (ps[paramidx].range>1) {
        /* convert array and pass by address */
        ps[paramidx].v.ptr = fillarray(amx, &ps[paramidx], cptr);
      } /* if */
      break;
    case 'p':
    case 's':
    case 'p' | BYREF:
    case 's' | BYREF:
      if (ps[paramidx].type=='s' || ps[paramidx].type=='p') {
        int len;
        /* get length of input string */
        amx_StrLen(cptr,&len);
        len++;            /* include '\0' */
        /* check max. size */
        if (len<ps[paramidx].range)
          len=ps[paramidx].range;
        ps[paramidx].range=len;
      } /* if */
      ps[paramidx].v.ptr=malloc(ps[paramidx].range*sizeof(TCHAR));
      if (ps[paramidx].v.ptr==NULL)
        return amx_RaiseError(amx, AMX_ERR_NATIVE);
      amx_GetString((char *)ps[paramidx].v.ptr,cptr,sizeof(TCHAR)>1,UNLIMITED);
      break;
    default:
      /* invalid parameter type */
      return amx_RaiseError(amx, AMX_ERR_NATIVE);
    } /* switch */
    paramidx++;
  } /* while */
  if ((params[0]/sizeof(cell)) - 3 != (size_t)paramidx)
    return amx_RaiseError(amx, AMX_ERR_NATIVE); /* format string does not match number of parameters */

  #if defined HAVE_DYNCALL_H
    for (idx = 0; idx < paramidx; idx++) {
      if ((ps[idx].type=='i' || ps[idx].type=='u' || ps[idx].type=='f') && ps[idx].range==1) {
        switch (ps[idx].size) {
        case 8:
          dcArgChar(dcVM,(unsigned char)(ps[idx].v.val & 0xff));
          break;
        case 16:
          dcArgShort(dcVM,(unsigned short)(ps[idx].v.val & 0xffff));
          break;
        default:
          dcArgLong(dcVM,ps[idx].v.val);
        } /* switch */
      } else {
        dcArgPointer(dcVM,ps[idx].v.ptr);
      } /* if */
    } /* for */
    result=(cell)dcCallPointer(dcVM,(void*)LibFunc);
  #else /* HAVE_DYNCALL_H */
    /* push the parameters to the stack (left-to-right in 16-bit; right-to-left
     * in 32-bit)
     */
#if defined __WIN32__ || defined _WIN32 || defined WIN32
    for (idx=paramidx-1; idx>=0; idx--) {
#else
    for (idx=0; idx<paramidx; idx++) {
#endif
      if ((ps[idx].type=='i' || ps[idx].type=='u' || ps[idx].type=='f') && ps[idx].range==1) {
        switch (ps[idx].size) {
        case 8:
          push((unsigned char)(ps[idx].v.val & 0xff));
          break;
        case 16:
          push((unsigned short)(ps[idx].v.val & 0xffff));
          break;
        default:
          push(ps[idx].v.val);
        } /* switch */
      } else {
        push(ps[idx].v.ptr);
      } /* if */
    } /* for */

    /* call the function; all parameters are already pushed to the stack (the
     * function should remove the parameters from the stack)
     */
    result=LibFunc();
  #endif /* HAVE_DYNCALL_H */

  /* store return values and free allocated memory */
  for (idx=0; idx<paramidx; idx++) {
    switch (ps[idx].type) {
    case 'p':
    case 's':
      free(ps[idx].v.ptr);
      break;
    case 'p' | BYREF:
    case 's' | BYREF:
      amx_GetAddr(amx,params[idx+4],&cptr);
      amx_SetString(cptr,(char *)ps[idx].v.ptr,ps[idx].type==('p'|BYREF),sizeof(TCHAR)>1,UNLIMITED);
      free(ps[idx].v.ptr);
      break;
    case 'i':
    case 'u':
    case 'f':
      assert(ps[idx].range==1);
      break;
    case 'i' | BYREF:
    case 'u' | BYREF:
    case 'f' | BYREF:
      amx_GetAddr(amx,params[idx+4],&cptr);
      if (ps[idx].range==1) {
        /* modify directly in the AMX (no memory block was allocated */
        switch (ps[idx].size) {
        case 8:
          *cptr= (ps[idx].type==('i' | BYREF)) ? (long)((signed char)*cptr) : (*cptr & 0xff);
          break;
        case 16:
          *cptr= (ps[idx].type==('i' | BYREF)) ? (long)((short)*cptr) : (*cptr & 0xffff);
          break;
        } /* switch */
      } else {
        int i;
        for (i=0; i<ps[idx].range; i++) {
          switch (ps[idx].size) {
          case 8:
            *cptr= (ps[idx].type==('i' | BYREF)) ? ((signed char*)ps[idx].v.ptr)[i] : ((unsigned char*)ps[idx].v.ptr)[i];
            break;
          case 16:
            *cptr= (ps[idx].type==('i' | BYREF)) ? ((short*)ps[idx].v.ptr)[i] : ((unsigned short*)ps[idx].v.ptr)[i];
            break;
          default:
            *cptr= (ps[idx].type==('i' | BYREF)) ? ((long*)ps[idx].v.ptr)[i] : ((unsigned long*)ps[idx].v.ptr)[i];
          } /* switch */
        } /* for */
        free((char *)ps[idx].v.ptr);
      } /* if */
      break;
    default:
      assert(0);
    } /* switch */
  } /* for */

  return result;
}

/* bool: libfree(const libname[]="")
 * When the name is an empty string, this function frees all libraries (for this
 * abstract machine). The name comparison is case sensitive.
 * Returns true if one or more libraries were freed.
 */
static cell AMX_NATIVE_CALL n_libfree(AMX *amx, const cell *params)
{
  const TCHAR *libname;
  amx_StrParam(amx,params[1],libname);
  return freelib(&ModRoot,amx,libname) > 0;
}

#else /* HAVE_DYNCALL_H || WIN32_FFI */

static cell AMX_NATIVE_CALL n_libcall(AMX *amx, const cell *params)
{
  (void)amx;
  (void)params;
  return 0;
}
Example #18
0
bool
WaypointReaderSeeYou::ParseLine(const TCHAR* line, const unsigned linenum,
                              Waypoints &waypoints)
{
  enum {
    iName = 0,
    iLatitude = 3,
    iLongitude = 4,
    iElevation = 5,
    iStyle = 6,
    iRWDir = 7,
    iRWLen = 8,
    iFrequency = 9,
    iDescription = 10,
  };

  if (linenum == 0)
    ignore_following = false;

  // If (end-of-file or comment)
  if (StringIsEmpty(line) ||
      StringStartsWith(line, _T("**")) ||
      StringStartsWith(line, _T("*")))
    // -> return without error condition
    return true;

  TCHAR ctemp[4096];
  if (_tcslen(line) >= ARRAY_SIZE(ctemp))
    /* line too long for buffer */
    return false;

  // Skip first line if it doesn't begin with a quotation character
  // (usually the field order line)
  if (linenum == 0 && line[0] != _T('\"'))
    return true;

  // If task marker is reached ignore all following lines
  if (_tcsstr(line, _T("-----Related Tasks-----")) == line)
    ignore_following = true;
  if (ignore_following)
    return true;

  // Get fields
  const TCHAR *params[20];
  size_t n_params = ExtractParameters(line, ctemp, params,
                                      ARRAY_SIZE(params), true, _T('"'));

  // Check if the basic fields are provided
  if (iName >= n_params ||
      iLatitude >= n_params ||
      iLongitude >= n_params)
    return false;

  Waypoint new_waypoint;

  // Latitude (e.g. 5115.900N)
  if (!ParseAngle(params[iLatitude], new_waypoint.location.latitude, true))
    return false;

  // Longitude (e.g. 00715.900W)
  if (!ParseAngle(params[iLongitude], new_waypoint.location.longitude, false))
    return false;

  new_waypoint.location.Normalize(); // ensure longitude is within -180:180

  new_waypoint.file_num = file_num;
  new_waypoint.original_id = 0;

  // Name (e.g. "Some Turnpoint")
  if (*params[iName] == _T('\0'))
    return false;
  new_waypoint.name = params[iName];

  // Elevation (e.g. 458.0m)
  /// @todo configurable behaviour
  if ((iElevation >= n_params ||
      !ParseAltitude(params[iElevation], new_waypoint.elevation)) &&
      !CheckAltitude(new_waypoint))
    return false;

  // Style (e.g. 5)
  if (iStyle < n_params)
    ParseStyle(params[iStyle], new_waypoint.type);

  new_waypoint.flags.turn_point = true;

  // Frequency & runway direction/length (for airports and landables)
  // and description (e.g. "Some Description")
  if (new_waypoint.IsLandable()) {
    if (iFrequency < n_params)
      new_waypoint.radio_frequency = RadioFrequency::Parse(params[iFrequency]);

    // Runway length (e.g. 546.0m)
    fixed rwlen = fixed(-1);
    if (iRWLen < n_params && ParseDistance(params[iRWLen], rwlen) &&
        positive(rwlen))
      new_waypoint.runway.SetLength(uround(rwlen));

    if (iRWDir < n_params && *params[iRWDir]) {
      TCHAR *end;
      int direction =_tcstol(params[iRWDir], &end, 10);
      if (end == params[iRWDir] || direction < 0 || direction > 360 ||
          (direction == 0 && !positive(rwlen)))
        direction = -1;
      else if (direction == 360)
        direction = 0;
      if (direction >= 0)
        new_waypoint.runway.SetDirectionDegrees(direction);
    }
  }

  if (iDescription < n_params) {
    /*
     * This convention was introduced by the OpenAIP
     * project (http://www.openaip.net/), since no waypoint type
     * exists for thermal hotspots.
     */
    if (StringStartsWith(params[iDescription], _T("Hotspot")))
      new_waypoint.type = Waypoint::Type::THERMAL_HOTSPOT;

    new_waypoint.comment = params[iDescription];
  }

  waypoints.Append(std::move(new_waypoint));
  return true;
}
Example #19
0
//#define CUPDEBUG
bool ParseCUPWayPointString(TCHAR *String,WAYPOINT *Temp)
{
  TCHAR ctemp[(COMMENT_SIZE*2)+1]; // must be bigger than COMMENT_SIZE!
  TCHAR *pToken;
  TCHAR TempString[READLINE_LENGTH+1];
  TCHAR OrigString[READLINE_LENGTH+1];
  TCHAR Tname[NAME_SIZE+1];
  int flags=0;

  unsigned int i, j;
  bool ishome=false; // 100310

  // strtok does not return empty fields. we create them here with special char
  #define DUMCHAR	'|'

  Temp->Visible = true; // default all waypoints visible at start
  Temp->FarVisible = true;
  Temp->Format = LKW_CUP;
  Temp->Number = WayPointList.size();

  Temp->FileNum = globalFileNum;

  #if BUGSTOP
  // This should never happen
  LKASSERT(_tcslen(String) < sizeof(OrigString));
  #endif
  LK_tcsncpy(OrigString, String,READLINE_LENGTH);  
  // if string is too short do nothing
  if (_tcslen(OrigString)<11) return false;

  #ifdef CUPDEBUG
  StartupStore(_T("OLD:<%s>%s"),OrigString,NEWLINE);
  #endif

  for (i=0,j=0; i<_tcslen(OrigString); i++) {

	// skip last comma, and avoid overruning the end
	if (  (i+1)>= _tcslen(OrigString)) break;
	if ( (OrigString[i] == _T(',')) && (OrigString[i+1] == _T(',')) ) {
		TempString[j++] = _T(',');
		TempString[j++] = _T(DUMCHAR);
		continue;
	} 
	/* we need terminations for comments
	if ( OrigString[i] == _T('\r') ) continue;
	if ( OrigString[i] == _T('\n') ) continue; 
	*/

	TempString[j++] = OrigString[i];
  }
  TempString[j] = _T('\0');

  #ifdef CUPDEBUG
  StartupStore(_T("NEW:<%s>%s"),TempString,NEWLINE);
  #endif
  // ---------------- NAME ----------------
  pToken = _tcstok(TempString, TEXT(","));
  if (pToken == NULL) return false;

  if (_tcslen(pToken)>NAME_SIZE) {
	pToken[NAME_SIZE-1]= _T('\0');
  }

  _tcscpy(Temp->Name, pToken); 
  CleanCupCode(Temp->Name);

  #ifdef CUPDEBUG
  StartupStore(_T("   CUP NAME=<%s>%s"),Temp->Name,NEWLINE);
  #endif


  // ---------------- CODE ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;

  if (_tcslen(pToken)>CUPSIZE_CODE) pToken[CUPSIZE_CODE-1]= _T('\0');
  _tcscpy(Temp->Code, pToken); 
  for (i=_tcslen(Temp->Code)-1; i>1; i--) if (Temp->Code[i]==' ') Temp->Code[i]=0; else break;
  _tcscpy(Tname,Temp->Code);
  for (j=0, i=0; i<_tcslen(Tname); i++) 
	//if (Tname[i]!='\"') Temp->Code[j++]=Tname[i];
	if ( (Tname[i]!='\"') && (Tname[i]!=DUMCHAR) ) Temp->Code[j++]=Tname[i]; Temp->Code[j]= _T('\0');

  if (_tcslen(Temp->Code)>5) { // 100310
	if (  _tcscmp(Temp->Code,_T("LKHOME")) == 0 ) {
		StartupStore(_T(". Found LKHOME inside CUP waypoint <%s>%s"),Temp->Name,NEWLINE);
		ishome=true;
	}
  }
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP CODE=<%s>%s"),Temp->Code,NEWLINE);
  #endif

        
  // ---------------- COUNTRY ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  LK_tcsncpy(Temp->Country,pToken,CUPSIZE_COUNTRY);
  if (_tcslen(Temp->Country)>3) {
	Temp->Country[3]= _T('\0');
  }
  if ((_tcslen(Temp->Country) == 1) && Temp->Country[0]==DUMCHAR) Temp->Country[0]=_T('\0');

  #ifdef CUPDEBUG
  StartupStore(_T("   CUP COUNTRY=<%s>%s"),Temp->Country,NEWLINE);
  #endif


  // ---------------- LATITUDE  ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;

  Temp->Latitude = CUPToLat(pToken);

  if((Temp->Latitude > 90) || (Temp->Latitude < -90)) {
	return false;
  }
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP LATITUDE=<%f>%s"),Temp->Latitude,NEWLINE);
  #endif


  // ---------------- LONGITUDE  ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  Temp->Longitude  = CUPToLon(pToken);
  if((Temp->Longitude  > 180) || (Temp->Longitude  < -180)) {
	return false;
  }
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP LONGITUDE=<%f>%s"),Temp->Longitude,NEWLINE);
  #endif



  // ---------------- ELEVATION  ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  Temp->Altitude = ReadAltitude(pToken);
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP ELEVATION=<%f>%s"),Temp->Altitude,NEWLINE);
  #endif
  if (Temp->Altitude == -9999){
	  Temp->Altitude=0;
  }


  // ---------------- STYLE  ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  
  Temp->Style = (int)_tcstol(pToken,NULL,10);
  switch(Temp->Style) {
	case 2:				// airfield grass
	case 4:				// glider site
	case 5:				// airfield solid
		flags = AIRPORT;
		flags += LANDPOINT;
		break;
	case 3:				// outlanding
		flags = LANDPOINT;
		break;
	default:
		flags = TURNPOINT;
		break;
  }
  if (ishome) flags += HOME;
  Temp->Flags = flags;

  #ifdef CUPDEBUG
  StartupStore(_T("   CUP STYLE=<%d> flags=%d %s"),Temp->Style,Temp->Flags,NEWLINE);
  #endif

  // ---------------- RWY DIRECTION   ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  if ((_tcslen(pToken) == 1) && (pToken[0]==DUMCHAR))
	Temp->RunwayDir=-1;
  else
	Temp->RunwayDir = (int)AngleLimit360(_tcstol(pToken, NULL, 10));
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP RUNWAY DIRECTION=<%d>%s"),Temp->RunwayDir,NEWLINE);
  #endif


  // ---------------- RWY LENGTH   ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  if ((_tcslen(pToken) == 1) && (pToken[0]==DUMCHAR))
	Temp->RunwayLen = -1;
  else
	Temp->RunwayLen = (int)ReadLength(pToken);
  #ifdef CUPDEBUG
  StartupStore(_T("   CUP RUNWAY LEN=<%d>%s"),Temp->RunwayLen,NEWLINE);
  #endif



  // ---------------- AIRPORT FREQ   ------------------
  pToken = _tcstok(NULL, TEXT(","));
  if (pToken == NULL) return false;
  if (_tcslen(pToken)>CUPSIZE_FREQ) pToken[CUPSIZE_FREQ-1]= _T('\0');
  _tcscpy(Temp->Freq, pToken); 
  TrimRight(Temp->Freq);
  _tcscpy(Tname,Temp->Freq);
  for (j=0, i=0; i<_tcslen(Tname); i++) 
	if ( (Tname[i]!='\"') && (Tname[i]!=DUMCHAR) ) Temp->Freq[j++]=Tname[i];
  Temp->Freq[j]= _T('\0');

  #ifdef CUPDEBUG
  StartupStore(_T("   CUP FREQ=<%s>%s"),Temp->Freq,NEWLINE);
  #endif


  // ---------------- COMMENT   ------------------
  pToken = _tcstok(NULL, TEXT("\n\r"));
  if (pToken != NULL) {

	if (_tcslen(pToken)>=COMMENT_SIZE) pToken[COMMENT_SIZE-1]= _T('\0');

	// remove trailing spaces and CR LF
	_tcscpy(ctemp, pToken); 
	for (i=_tcslen(ctemp)-1; i>1; i--) {
		if ( (ctemp[i]==' ') || (ctemp[i]=='\r') || (ctemp[i]=='\n') ) ctemp[i]=0;
		else
			break;
	}

	// now remove " " (if there)
	for (j=0, i=0; i<_tcslen(ctemp); i++) 
		if (ctemp[i]!='\"') ctemp[j++]=ctemp[i];
	ctemp[j]= _T('\0');
	if (_tcslen(ctemp) >0 ) {
		if (Temp->Comment) {
			free(Temp->Comment);
		}
		Temp->Comment = (TCHAR*)malloc((_tcslen(ctemp)+1)*sizeof(TCHAR));
		if (Temp->Comment) _tcscpy(Temp->Comment, ctemp);
	}

	#ifdef CUPDEBUG
	StartupStore(_T("   CUP COMMENT=<%s>%s"),Temp->Comment,NEWLINE);
	#endif
  } else {
	Temp->Comment=NULL; // useless
  }

  if(Temp->Altitude <= 0) {
	WaypointAltitudeFromTerrain(Temp);
  } 

  if (Temp->Details) {
	free(Temp->Details);
  }

  return true;
}
Example #20
0
void CUDSMainWnd::SendContinuosFrames( unsigned char abByteArr[],mPSTXSELMSGDATA psTxCanMsgUds, UDS_INTERFACE FInterface)
{

    CString Length;
    CString omTempByte;
    CString omByteStrTemp;
    int numberofFrames =0;                      // It will indicate how many multiples frames have been sent
    int c_numberOfTaken = numberOfTaken+2;      // The consecutive Messages will contain one byte more that the FirstFrame

    int i = aux_Finterface + c_numberOfTaken/2;         // aux_Finterface it's used to indicate that i must be bigger if we're in extended Addressing
    if (TotalLength*2<c_numberOfTaken)          // It only enters here once, at the end when the last message of the multiple frames has to be sent when
    {
        i = TotalLength+aux_Finterface;         // the number of frames that has to be sent is less than c_numberOfTaken
    }
    while (DatatoSend.GetLength())                          // While there is remaining data that has to be sent
    {
        omByteStrTemp = DatatoSend.Left(c_numberOfTaken);   //I take the part of the message that is going to be sent in the current Frame
        //while(FWait_SendingFrame){}                           // Wait if something is being sent in this moment

        while (omByteStrTemp.GetLength())
        {
            omTempByte = omByteStrTemp.Right(NO_OF_CHAR_IN_BYTE);
            abByteArr[i--] = (BYTE)_tcstol(omTempByte, L'\0', 16);              // It fills the array
            omByteStrTemp = omByteStrTemp.Left(omByteStrTemp.GetLength() - NO_OF_CHAR_IN_BYTE);
        }
        psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;                  // Consecutive Frames can always have 8 bytes
        abByteArr[initialByte]= ConsecutiveFrame;                   // Put the initial Byte of the consecutive frames in a long request
        SendSimpleDiagnosticMessage();                              // Send the current Message

        DatatoSend = DatatoSend.Right(((UINT)TotalLength*2)-c_numberOfTaken);        // DatatoSend will contain the rest of the bytes that hasn't been sent yet.
        TotalLength = (((UINT)TotalLength*2)-c_numberOfTaken)/2;
        ConsecutiveFrame++;
        if (ConsecutiveFrame == 0x30)
        {
            ConsecutiveFrame=0x20;    // Requirement from the ISO TP
        }
        numberofFrames++;

        if (numberofFrames == BSizE)        // It enters here when I've reached the quantity of Blocks settled by the ECU in the flow Control
        {
            FWaitFlow = TRUE;               // Now it has to wait for the Flow control again
            numberofFrames = 0;
            c_dDiffTime =0;
            return ;                        // Now it has to wait for another FlowControl
        }
        else
        {
            for(c_dDiffTime =0,c_unPreviousTime =-1 ; c_dDiffTime <=STMin; CalculateDiffTime()) {}      // Wait for the STMin Time settled by the ECU in the flow Control
        }
        c_unPreviousTime = -1;              //ReStart the variables for the timmings
        c_dDiffTime = 0;

        i = aux_Finterface + c_numberOfTaken/2;             // it must be a bigger number in the case of extended addressing-> aux_Finterface to control this.
        if (TotalLength*2<c_numberOfTaken)                  // It only enters here once, at the end when the last message of the multiple frames has to be sent when
        {
            i = TotalLength+aux_Finterface;                 // the number of frames that has to be sent is less than c_numberOfTaken
        }
    }
    m_omSendButton.EnableWindow(TRUE);      // It only enters here when it has sent all the msg
    // In the case that this function cannot be completed there is a timer as default to activate the SEND button
}
/*
 * The sequence of entries in array must match with what java layer expect (6 informations
 * per USB device). If a particular USB attribute is not set in descriptor or can not be
 * obtained "---" is placed in its place.
 *
 * Returns array of USB device's information found, empty array if no USB device is found,
 * NULL if an error occurs (additionally throws exception).
 */
jobjectArray list_usb_devices(JNIEnv *env, jint vendor_to_match) {

	int x = 0;
	int i = 0;
	int vid = 0;
	BOOL ret = FALSE;
	DWORD error_code = 0;
	DWORD size = 0;
	TCHAR *ptrend;
	DWORD usb_member_index = 0;
	HDEVINFO usb_dev_info_set;
	SP_DEVINFO_DATA usb_dev_instance;
	DEVPROPTYPE proptype;
	DWORD regproptype;
	TCHAR buffer[1024];
	TCHAR charbuffer[1024];

	struct jstrarray_list list = { 0 };
	jstring usb_dev_info;
	jclass strClass = NULL;
	jobjectArray usbDevicesFound = NULL;

	init_jstrarraylist(&list, 50);

	/* get information set for all usb devices matching the GUID */
	usb_dev_info_set = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
	if (usb_dev_info_set == INVALID_HANDLE_VALUE) {
		SetupDiDestroyDeviceInfoList(usb_dev_info_set);
		free_jstrarraylist(&list);
		throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
		return NULL;
	}

	/* enumerate all devices in this information set */
	usb_member_index = 0;
	while (1) {
		ZeroMemory(&usb_dev_instance, sizeof(usb_dev_instance));
		usb_dev_instance.cbSize = sizeof(usb_dev_instance);

		/* from information set, get device by index */
		ret = SetupDiEnumDeviceInfo(usb_dev_info_set, usb_member_index, &usb_dev_instance);
		if (ret == FALSE) {
			error_code = GetLastError();
			if (error_code == ERROR_NO_MORE_ITEMS) {
				break;
			}
			else {
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				free_jstrarraylist(&list);
				throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(error_code), NULL);
				return NULL;
			}
		}

		/* for this device find its instance ID (USB\VID_04D8&PID_00DF\000098037)
		 * this is the variable 'Device Instance Path' in device manager. */
		memset(buffer, '\0', sizeof(buffer));
		ret = SetupDiGetDeviceInstanceId(usb_dev_info_set, &usb_dev_instance, buffer, sizeof(buffer), &size);
		if (ret == FALSE) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
			return NULL;
		}

		/* USB-IF vendor ID, extract and match, if matched continue further otherwise loop back */
		x = 0;
		while (buffer[x] != '\0') {
			if((buffer[x] == 'V') && (buffer[x + 1] == 'I') && (buffer[x + 2] == 'D') && (buffer[x + 3] == '_')) {
				break;
			}
			x++;
		}
		x = x + 4;
		i = 0;
		while (buffer[x] != '&') {
			charbuffer[i] = buffer[x];
			i++;
			x++;
		}
		charbuffer[i] = '\0'; /* indicate end of string */

		vid = (int)_tcstol(charbuffer, &ptrend, 16);

		if(vendor_to_match != 0) {
			/* we need to apply filter for identify specific vendor */
			if(vid != vendor_to_match) {
				usb_member_index++;
				continue;
			}
		}

		usb_dev_info = (*env)->NewString(env, charbuffer, (jsize) _tcslen(charbuffer));
		if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) {
			(*env)->ExceptionClear(env);
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 3, 0, E_NEWSTRSTR);
			return NULL;
		}
		insert_jstrarraylist(&list, usb_dev_info);

		/* USB product ID */
		x = 6;
		while (buffer[x] != '\0') {
			if ((buffer[x] == 'P') && (buffer[x + 1] == 'I') && (buffer[x + 2] == 'D') && (buffer[x + 3] == '_')) {
				break;
			}
			x++;
		}
		x = x + 4;
		i = 0;
		while (buffer[x] != '\\') {
			charbuffer[i] = buffer[x];
			i++;
			x++;
		}
		charbuffer[i] = '\0';

		usb_dev_info = (*env)->NewString(env, charbuffer, (jsize) _tcslen(charbuffer));
		if ((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) {
			(*env)->ExceptionClear(env);
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 3, 0, E_NEWSTRSTR);
			return NULL;
		}
		insert_jstrarraylist(&list, usb_dev_info);

		/* SERIAL NUMBER */
		x++;
		i = 0;
		while (buffer[x] != '\0') {
			charbuffer[i] = buffer[x];
			i++;
			x++;
		}
		charbuffer[i] = '\0';

		usb_dev_info = (*env)->NewString(env, charbuffer, (jsize) _tcslen(charbuffer));
		if ((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) {
			(*env)->ExceptionClear(env);
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 3, 0, E_NEWSTRSTR);
			return NULL;
		}
		insert_jstrarraylist(&list, usb_dev_info);
		
		/* PRODUCT
			(idProduct field of USB device descriptor) */
		memset(buffer, '\0', sizeof(buffer));
		ret = SetupDiGetDeviceProperty(usb_dev_info_set, &usb_dev_instance, &DEVPKEY_Device_BusReportedDeviceDesc, &proptype, (BYTE *)buffer, sizeof(buffer), &size, 0);
		if (ret == FALSE) {
			/* fallback to SPDRP_DEVICEDESC if DEVPKEY_Device_BusReportedDeviceDesc fails */
			ret = SetupDiGetDeviceRegistryProperty(usb_dev_info_set, &usb_dev_instance, SPDRP_DEVICEDESC, &regproptype, (BYTE *)buffer, sizeof(buffer), &size);
			if (ret == FALSE) {
				/* if second attempt fails, throw error, we need to investigate drivers/firmware etc */
				SetupDiDestroyDeviceInfoList(usb_dev_info_set);
				free_jstrarraylist(&list);
				throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
				return NULL;
			}
			usb_dev_info = (*env)->NewString(env, buffer, (jsize)_tcslen(buffer));
			insert_jstrarraylist(&list, usb_dev_info);
		}else {
			usb_dev_info = (*env)->NewString(env, buffer, (jsize)_tcslen(buffer));
			insert_jstrarraylist(&list, usb_dev_info);
		}

		/* MANUFACTURER */
		memset(buffer, '\0', sizeof(buffer));
		ret = SetupDiGetDeviceProperty(usb_dev_info_set, &usb_dev_instance, &DEVPKEY_Device_Manufacturer, &proptype, (BYTE *)buffer, sizeof(buffer), &size, 0);
		if (ret == FALSE) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
			return NULL;
		}
		usb_dev_info = (*env)->NewString(env, buffer, (jsize) _tcslen(buffer));
		insert_jstrarraylist(&list, usb_dev_info);

		/* LOCATION (Location paths + Location info, get separately and then create a single string) */
		memset(buffer, '\0', sizeof(buffer));
		ret = SetupDiGetDeviceRegistryProperty(usb_dev_info_set, &usb_dev_instance, SPDRP_LOCATION_PATHS, &regproptype, (BYTE *)buffer, sizeof(buffer), &size);
		if (ret == FALSE) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
			return NULL;
		}

		memset(charbuffer, '\0', sizeof(charbuffer));
		ret = SetupDiGetDeviceRegistryProperty(usb_dev_info_set, &usb_dev_instance, SPDRP_LOCATION_INFORMATION, &regproptype, (BYTE *)charbuffer, sizeof(charbuffer), &size);
		if (ret == FALSE) {
			SetupDiDestroyDeviceInfoList(usb_dev_info_set);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL);
			return NULL;
		}

		i = 0;
		x = (int)_tcslen(buffer);
		buffer[x] = '-';
		x++;
		for (i = 0; i < (int)_tcslen(charbuffer); i++) {
			buffer[x] = charbuffer[i];
			x++;
		}
		buffer[x] = '\0';

		usb_dev_info = (*env)->NewString(env, buffer, (jsize)_tcslen(buffer));
		insert_jstrarraylist(&list, usb_dev_info);

		/* loop to get next USB device */
		usb_member_index++;
	}

	SetupDiDestroyDeviceInfoList(usb_dev_info_set);

	strClass = (*env)->FindClass(env, JAVALSTRING);
	if((strClass == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) {
		(*env)->ExceptionClear(env);
		free_jstrarraylist(&list);
		throw_serialcom_exception(env, 3, 0, E_FINDCLASSSSTRINGSTR);
		return NULL;
	}

	usbDevicesFound = (*env)->NewObjectArray(env, (jsize)list.index, strClass, NULL);
	if((usbDevicesFound == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) {
		(*env)->ExceptionClear(env);
		free_jstrarraylist(&list);
		throw_serialcom_exception(env, 3, 0, E_NEWOBJECTARRAYSTR);
		return NULL;
	}

	for (x = 0; x < list.index; x++) {
		(*env)->SetObjectArrayElement(env, usbDevicesFound, x, list.base[x]);
		if ((*env)->ExceptionOccurred(env)) {
			(*env)->ExceptionClear(env);
			free_jstrarraylist(&list);
			throw_serialcom_exception(env, 3, 0, E_SETOBJECTARRAYSTR);
			return NULL;
		}
	}

	free_jstrarraylist(&list);
	return usbDevicesFound;
}
Example #22
0
void CUDSMainWnd::PrepareDiagnosticMessage(CString omByteStr,mPSTXSELMSGDATA psTxCanMsgUds, unsigned char abByteArr[], UINT ByteArrLen)
{
    memset(abByteArr, 0, ByteArrLen);               // Initialize the array to zero
    omByteStr.Replace(" ","");
    int i_counter =0;
    UINT LengthStr = omByteStr.GetLength();
    UINT Result;
    if ( LengthStr%2 != 0)
    {
        CString LastString = "0" + omByteStr.Right(1);
        omByteStr= omByteStr.Left(omByteStr.GetLength() - 1);
        omByteStr = omByteStr+ LastString;

    }
    Result = LengthStr / 2 + LengthStr % 2;
    TotalLength = Result;
    m_omSendButton.EnableWindow(FALSE);  //I have to disable the sendButton everytime that I press SEND
    // If it's a long request I need it
    // If it's a long response I've to restart it  and receive all the bytes
    // If it's a simple response: the response could take more time or it could be a 0x78 resp

    m_nTimer = SetTimer(ID_TIMER_SEND_BUTTON,P2_Time , NULL);               // Time to wait to enable the send button again

    switch (fInterface)
    {
        case INTERFACE_NORMAL_11:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= FALSE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }

                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_EXTENDED_11:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= FALSE;
            ByteArrLen = ByteArrLen-2;
            abByteArr[0] = TargetAddress;
            if (Result>6)                                                           // Long Request - The limit of a simple request for extended is 6 because the byte that contains the TA.
            {
                m_omSendButton.EnableWindow(FALSE);
                m_nTimer = SetTimer(ID_TIMER_SEND_BUTTON, P2_Time , NULL);          // Start Timer to wait to enable by default the send button again

                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface);

            }
            else                                             // Short request
            {
                i_counter = Result+1;
                abByteArr[1] = Result;
                Result = Result+2;
                CString omTempByte;
                while (omByteStr.GetLength())               // Take all the bytes that will be parte of the simple message
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_NORMAL_ISO_29:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= TRUE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
        case INTERFACE_NORMAL_J1939_29:
        {
            psTxCanMsgUds->m_psTxMsg->m_ucEXTENDED= TRUE;
            ByteArrLen = ByteArrLen-1;
            if (Result>7)                            // Long Request
            {
                int f =SendFirstFrame(omByteStr,abByteArr,psTxCanMsgUds,fInterface );

            }
            else                                     // Short request
            {
                i_counter = (int) Result;
                abByteArr[0] = Result;
                Result++;                            // Result must be increased to make the size array bigger
                CString omTempByte;
                while (omByteStr.GetLength())
                {
                    omTempByte = omByteStr.Right(NO_OF_CHAR_IN_BYTE);
                    abByteArr[i_counter--] = (BYTE)_tcstol(omTempByte, L'\0', 16);
                    omByteStr = omByteStr.Left(omByteStr.GetLength() - NO_OF_CHAR_IN_BYTE);
                }
                if(fMsgSize)
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = 8;
                }
                else
                {
                    psTxCanMsgUds->m_psTxMsg->m_ucDataLen = Result;
                }
                SendSimpleDiagnosticMessage();
            }
        }
        break;
    }
}
Example #23
0
double CUPToLon(TCHAR *temp)
{
  TCHAR *dot, td;
  TCHAR tdeg[4], tmin[4], tsec[5];
  double degrees, mins, secs;
  unsigned int slen;
  bool east=false;

  // longit can be 01234.5X
  if (_tcslen(temp)<8 || _tcslen(temp)>10) return -9999;

  // check there is a dot, to be sure
  dot = _tcschr(temp,'.');
  if(!dot) return -9999;
  *dot = _T('\0');
  dot++;

  _tcscpy(tsec,dot);
  slen=_tcslen(tsec);
  // seconds are 0X minimum including the letter
  if (slen<2 || slen>4) return -9999;
  td= tsec[slen-1];

  if ( (td != _T('E')) && ( td != _T('W')) ) return -9999;
  if ( td == _T('E') ) east=true;

  td='\0';

  tdeg[0]=temp[0];
  tdeg[1]=temp[1];
  tdeg[2]=temp[2];
  tdeg[3]=_T('\0');

  tmin[0]=temp[3];
  tmin[1]=temp[4];
  tmin[2]=_T('\0');

  degrees = (double)_tcstol(tdeg, NULL, 10);
  mins     = (double)_tcstol(tmin, NULL, 10);
  secs     = (double)_tcstol(tsec, NULL, 10);

  // if seconds are only a decimal, for example 3 , they really are 300
  switch (slen) {
	case 2:
		// 3X
		secs*=100;
		break;
	case 3:
		// 33X
		secs*=10;
		break;
	default:
		break;
  }

  mins += secs / 1000.0;
  degrees += mins / 60.0;

  if (!east) degrees *= -1;

  return degrees;
}
Example #24
0
long StringToIntDflt(const TCHAR *String, long Default){
  if (String == NULL || String[0] == '\0')
    return(Default);
  return(_tcstol(String, NULL, 0));        
}
Example #25
0
static BOOL CALLBACK CPUClockProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM)	// LPARAM lParam
{
	switch (Msg) {
		case WM_INITDIALOG: {
			TCHAR szText[16];
			nExitStatus = 0;

			WndInMid(hDlg, hScrnWnd);

			// Initialise slider
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETRANGE, (WPARAM)0, (LPARAM)MAKELONG(0x80, 0x0200));
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETLINESIZE, (WPARAM)0, (LPARAM)0x05);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETPAGESIZE, (WPARAM)0, (LPARAM)0x10);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)0x0100);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)0x0120);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)0x0140);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETTIC, (WPARAM)0, (LPARAM)0x0180);

			// Set slider to current value
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nBurnCPUSpeedAdjust);

			// Set the edit control to current value
			_stprintf(szText, _T("%i"), nBurnCPUSpeedAdjust * 100 / 256);
			SendDlgItemMessage(hDlg, IDC_CPUCLOCK_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);

			return TRUE;
		}
		case WM_COMMAND: {
			switch (HIWORD(wParam)) {
				case BN_CLICKED: {
					if (LOWORD(wParam) == IDOK) {
						nExitStatus = 1;
						SendMessage(hDlg, WM_CLOSE, 0, 0);
					}
					if (LOWORD(wParam) == IDCANCEL) {
						nExitStatus = -1;
						SendMessage(hDlg, WM_CLOSE, 0, 0);
					}
					break;
				}
				case EN_UPDATE: {
					if (nExitStatus == 0) {
						TCHAR szText[16] = _T("");
						bool bValid = 1;
						int nValue;

						if (SendDlgItemMessage(hDlg, IDC_CPUCLOCK_EDIT, WM_GETTEXTLENGTH, (WPARAM)0, (LPARAM)0) < 16) {
							SendDlgItemMessage(hDlg, IDC_CPUCLOCK_EDIT, WM_GETTEXT, (WPARAM)16, (LPARAM)szText);
						}

						// Scan string in the edit control for illegal characters
						for (int i = 0; szText[i]; i++) {
							if (!_istdigit(szText[i])) {
								bValid = 0;
								break;
							}
						}

						if (bValid) {
							nValue = _tcstol(szText, NULL, 0);
							if (nValue < 25) {
								nValue = 25;
							} else {
								if (nValue > 400) {
									nValue = 400;
								}
							}

							nValue = (int)((double)nValue * 256.0 / 100.0 + 0.5);

							// Set slider to current value
							SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_SETPOS, (WPARAM)true, (LPARAM)nValue);
						}
					}
					break;
				}
			}
			break;
		}

		case WM_HSCROLL: {
			switch (LOWORD(wParam)) {
				case TB_BOTTOM:
				case TB_ENDTRACK:
				case TB_LINEDOWN:
				case TB_LINEUP:
				case TB_PAGEDOWN:
				case TB_PAGEUP:
				case TB_THUMBPOSITION:
				case TB_THUMBTRACK:
				case TB_TOP: {
					if (nExitStatus == 0) {
						TCHAR szText[16];
						int nValue;

						// Update the contents of the edit control
						nValue = SendDlgItemMessage(hDlg, IDC_CPUCLOCK_SLIDER, TBM_GETPOS, (WPARAM)0, (LPARAM)0);
						nValue = (int)((double)nValue * 100.0 / 256.0 + 0.5);
						_stprintf(szText, _T("%i"), nValue);
						SendDlgItemMessage(hDlg, IDC_CPUCLOCK_EDIT, WM_SETTEXT, (WPARAM)0, (LPARAM)szText);
					}
					break;
				}
			}
			break;
		}

		case WM_CLOSE:
			if (nExitStatus == 1) {
				TCHAR szText[16] = _T("");

				SendDlgItemMessage(hDlg, IDC_CPUCLOCK_EDIT, WM_GETTEXT, (WPARAM)16, (LPARAM)szText);
				nBurnCPUSpeedAdjust = _tcstol(szText, NULL, 0);
				if (nBurnCPUSpeedAdjust < 25) {
					nBurnCPUSpeedAdjust = 25;
				} else {
					if (nBurnCPUSpeedAdjust > 400) {
						nBurnCPUSpeedAdjust = 400;
					}
				}

				nBurnCPUSpeedAdjust = (int)((double)nBurnCPUSpeedAdjust * 256.0 / 100.0 + 0.5);
			}
			EndDialog(hDlg, 0);
			break;
	}

	return 0;
}
Example #26
0
int ProjectProperties::ReadProps(CTGitPath path)
{
	if (gitconfig)
		git_config_free(gitconfig);

	git_config_new(&gitconfig);
	CString adminDirPath;
	if (g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, adminDirPath))
	{
		CStringA configFile = CUnicodeUtils::GetUTF8(adminDirPath) + "config";
		git_config_add_file_ondisk(gitconfig, configFile, 5, FALSE);
	}

	if (!g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
	{
		CStringA configFile = CUnicodeUtils::GetUTF8(g_Git.m_CurrentDir) + "\\.tgitconfig";
		git_config_add_file_ondisk(gitconfig, configFile, 4, FALSE);
	}
	else
	{
		CString tmpFile = GetTempFile();
		CTGitPath path(_T(".tgitconfig"));
		if (g_Git.GetOneFile(_T("HEAD"), path, tmpFile) == 0)
		{
			CStringA configFile = CUnicodeUtils::GetUTF8(tmpFile);
			git_config_add_file_ondisk(gitconfig, configFile, 4, FALSE);
		}
	}

	CStringA globalConfigA = CUnicodeUtils::GetUTF8(g_Git.GetGitGlobalConfig());
	git_config_add_file_ondisk(gitconfig, globalConfigA.GetBuffer(), 3, FALSE);
	globalConfigA.ReleaseBuffer();
	CStringA globalXDGConfigA = CUnicodeUtils::GetUTF8( g_Git.GetGitGlobalXDGConfig());
	git_config_add_file_ondisk(gitconfig, globalXDGConfigA.GetBuffer(), 2, FALSE);
	globalXDGConfigA.ReleaseBuffer();
	CStringA systemConfigA = CUnicodeUtils::GetUTF8(g_Git.ms_LastMsysGitDir + _T("\\..\\etc\\gitconfig"));
	git_config_add_file_ondisk(gitconfig, systemConfigA.GetBuffer(), 1, FALSE);
	systemConfigA.ReleaseBuffer();
	giterr_clear();

	CString sPropVal;

	GetStringProps(this->sLabel,BUGTRAQPROPNAME_LABEL);
	GetStringProps(this->sMessage,BUGTRAQPROPNAME_MESSAGE);
	nBugIdPos = sMessage.Find(L"%BUGID%");
	GetStringProps(this->sUrl,BUGTRAQPROPNAME_URL);

	GetBOOLProps(this->bWarnIfNoIssue,BUGTRAQPROPNAME_WARNIFNOISSUE);
	GetBOOLProps(this->bNumber,BUGTRAQPROPNAME_NUMBER);
	GetBOOLProps(this->bAppend,BUGTRAQPROPNAME_APPEND);

	GetStringProps(sProviderUuid, BUGTRAQPROPNAME_PROVIDERUUID);
	GetStringProps(sProviderUuid64, BUGTRAQPROPNAME_PROVIDERUUID64);
	GetStringProps(sProviderParams, BUGTRAQPROPNAME_PROVIDERPARAMS);

	GetBOOLProps(this->bWarnNoSignedOffBy, PROJECTPROPNAME_WARNNOSIGNEDOFFBY);

	GetStringProps(sPropVal, BUGTRAQPROPNAME_LOGREGEX);

	sCheckRe = sPropVal;
	if (sCheckRe.Find('\n')>=0)
	{
		sBugIDRe = sCheckRe.Mid(sCheckRe.Find('\n')).Trim();
		sCheckRe = sCheckRe.Left(sCheckRe.Find('\n')).Trim();
	}
	if (!sCheckRe.IsEmpty())
	{
		sCheckRe = sCheckRe.Trim();
	}

	if (GetStringProps(sPropVal, PROJECTPROPNAME_LOGWIDTHLINE) == 0)
	{
		CString val;
		val = sPropVal;
		if (!val.IsEmpty())
			nLogWidthMarker = _ttoi(val) + 2; // HACK, + 2 needed
	}

	if (GetStringProps(sPropVal, PROJECTPROPNAME_PROJECTLANGUAGE) == 0)
	{
		CString val;
		val = sPropVal;
		if (!val.IsEmpty())
		{
			LPTSTR strEnd;
			lProjectLanguage = _tcstol(val, &strEnd, 0);
		}
	}

	if (GetStringProps(sPropVal, PROJECTPROPNAME_LOGMINSIZE) == 0)
	{
		CString val;
		val = sPropVal;
		if (!val.IsEmpty())
			nMinLogSize = _ttoi(val);
	}

	return 0;
}
Example #27
0
BOOL JsonPlugin::SetDirectory(PCTSTR dir, int iOpMode)
{
    tstring path;
    if(!_tcscmp(dir, _T(".."))) // go to updir (..)
    {
        path = CurrentDir;
        TCHAR* pSlash = _tcsrchr(CurrentDir, '/');
        if(pSlash)
        {
            path = path.substr(0, pSlash - CurrentDir);
        }
        return GoToPath(path.c_str());
    }

    // First, try the name immediately
    if(curObject->IsObject())
    {
        auto mem = curObject->FindMember((PWSTR)WideFromOem(dir));
        if(mem != curObject->MemberEnd())
        {
            if(!mem->value.IsObject() && !mem->value.IsArray())
                return FALSE;
            curObject = &mem->value;
            _tcsncat(CurrentDir, _T("/"), _countof(CurrentDir));
            size_t l = _tcslen(CurrentDir);
            EncodeToBuf(CurrentDir + l, dir, _countof(CurrentDir) - l);
            CurrentDir[_countof(CurrentDir) - 1] = 0;
            return TRUE;
        }
    }
    else if(curObject->IsArray()) //try the value immediately
    {
        PTSTR end;
        long index = _tcstol(dir, &end, 10);
        if(*end == 0)
        {
            auto val = &(*curObject)[index];
            if(!val->IsObject() && !val->IsArray())
                return FALSE;
            curObject = val;
            _tcsncat(CurrentDir, _T("/"), _countof(CurrentDir));
            _tcsncat(CurrentDir, dir, _countof(CurrentDir));
            CurrentDir[_countof(CurrentDir) - 1] = 0;
            return TRUE;
        }
    }

    // Then, try without converting backslashes to slashes (there may be a name with backslashes)
    if(dir[0] != '/') //relative path, add CurrentDir first
    {
        path = CurrentDir;
        path += _T("/");
    }

    if(_tcscmp(dir, _T("/")))
        path += dir;

    if(GoToPath(path.c_str()))
        return TRUE;

    // Convert \ to / and retry
    path.clear();
    tstring tdir(dir);

    for(size_t i = 0; i < tdir.size(); i++)
        if(tdir[i] == '\\')
            tdir[i] = '/';

    if(tdir[0] != '/') //relative path, add CurrentDir first
    {
        path = CurrentDir;
        path += _T("/");
    }
    if(_tcscmp(tdir.c_str(), _T("/")))
        path += tdir;

    return GoToPath(path.c_str());
} //SetDirectory
Example #28
0
INT ExecuteIf(PARSED_COMMAND *Cmd)
{
    INT result = FALSE; /* when set cause 'then' clause to be executed */
    LPTSTR param;
    LPTSTR Left = NULL, Right;

    if (Cmd->If.LeftArg)
    {
        Left = DoDelayedExpansion(Cmd->If.LeftArg);
        if (!Left)
            return 1;
    }
    Right = DoDelayedExpansion(Cmd->If.RightArg);
    if (!Right)
    {
        cmd_free(Left);
        return 1;
    }

    if (Cmd->If.Operator == IF_CMDEXTVERSION)
    {
        /* IF CMDEXTVERSION n: check if Command Extensions version
         * is greater or equal to n */
        DWORD n = _tcstoul(Right, &param, 10);
        if (*param != _T('\0'))
        {
            error_syntax(Right);
            cmd_free(Right);
            return 1;
        }
        result = (2 >= n);
    }
    else if (Cmd->If.Operator == IF_DEFINED)
    {
        /* IF DEFINED var: check if environment variable exists */
        result = (GetEnvVarOrSpecial(Right) != NULL);
    }
    else if (Cmd->If.Operator == IF_ERRORLEVEL)
    {
        /* IF ERRORLEVEL n: check if last exit code is greater or equal to n */
        INT n = _tcstol(Right, &param, 10);
        if (*param != _T('\0'))
        {
            error_syntax(Right);
            cmd_free(Right);
            return 1;
        }
        result = (nErrorLevel >= n);
    }
    else if (Cmd->If.Operator == IF_EXIST)
    {
        BOOL IsDir;
        INT Size;
        WIN32_FIND_DATA f;
        HANDLE hFind;

        /* IF EXIST filename: check if file exists (wildcards allowed) */
        StripQuotes(Right);

        Size = _tcslen(Right);
        IsDir = (Right[Size - 1] == '\\');
        if (IsDir)
            Right[Size - 1] = 0;


        hFind = FindFirstFile(Right, &f);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            if (IsDir)
            {
                result = ((f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);
            }
            else
            {
                result = TRUE;
            }
            FindClose(hFind);
        }

        if (IsDir)
            Right[Size - 1] = '\\';
    }
    else
    {
        /* Do case-insensitive string comparisons if /I specified */
        INT (*StringCmp)(LPCTSTR, LPCTSTR) =
            (Cmd->If.Flags & IFFLAG_IGNORECASE) ? _tcsicmp : _tcscmp;

        if (Cmd->If.Operator == IF_STRINGEQ)
        {
            /* IF str1 == str2 */
            result = StringCmp(Left, Right) == 0;
        }
        else
        {
            result = GenericCmp(StringCmp, Left, Right);
            switch (Cmd->If.Operator)
            {
            case IF_EQU: result = (result == 0); break;
            case IF_NEQ: result = (result != 0); break;
            case IF_LSS: result = (result < 0); break;
            case IF_LEQ: result = (result <= 0); break;
            case IF_GTR: result = (result > 0); break;
            case IF_GEQ: result = (result >= 0); break;
            }
        }
    }

    cmd_free(Left);
    cmd_free(Right);

    if (result ^ ((Cmd->If.Flags & IFFLAG_NEGATE) != 0))
    {
        /* full condition was true, do the command */
        return ExecuteCommand(Cmd->Subcommands);
    }
    else
    {
        /* full condition was false, do the "else" command if there is one */
        if (Cmd->Subcommands->Next)
            return ExecuteCommand(Cmd->Subcommands->Next);
        return 0;
    }
}
Example #29
0
/**
 * name:	 DlgProc_EditPhone()
 * desc:	 dialog procedure
 *
 * return:	 0 or 1
 **/
INT_PTR CALLBACK DlgProc_Phone(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	LPCBEXITEM cbi = (LPCBEXITEM)GetUserData(hDlg);
	static int noRecursion = 0;

	switch (msg) {
	case WM_INITDIALOG:
		{
			UINT i, item, countryCount;
			LPIDSTRLIST	pCountries;
			HWND hCombo = GetDlgItem(hDlg, EDIT_COUNTRY);

			cbi = (LPCBEXITEM)lParam;
			if (!cbi) return FALSE;
			SetUserData(hDlg, lParam);

			SendDlgItemMessage(hDlg, IDC_HEADERBAR, WM_SETICON, 0, (LPARAM)IcoLib_GetIcon(ICO_DLG_PHONE, TRUE));
			if (db_get_b(NULL, MODNAME, SET_ICONS_BUTTONS, 1)) {
				SendDlgItemMessage(hDlg, IDOK, BM_SETIMAGE, IMAGE_ICON, (LPARAM)IcoLib_GetIcon(ICO_BTN_OK));
				SendDlgItemMessage(hDlg, IDCANCEL, BM_SETIMAGE, IMAGE_ICON, (LPARAM)IcoLib_GetIcon(ICO_BTN_CANCEL));
			}

			// translate Userinfo buttons
			{
				TCHAR szButton[MAX_PATH];
				HWND hBtn;

				hBtn = GetDlgItem(hDlg, IDOK);
				GetWindowText(hBtn, szButton, _countof(szButton));
				SetWindowText(hBtn, TranslateTS(szButton));
				hBtn = GetDlgItem(hDlg, IDCANCEL);
				GetWindowText(hBtn, szButton, _countof(szButton));
				SetWindowText(hBtn, TranslateTS(szButton));
			}
			if (*cbi->pszVal) SetWindowText(hDlg, LPGENT("Edit phone number"));
			if (cbi->wFlags & CBEXIF_SMS) CheckDlgButton(hDlg, CHECK_SMS, BST_CHECKED);
			TranslateDialogDefault(hDlg);

			EnableWindow(GetDlgItem(hDlg, IDOK), *cbi->pszVal);
			SendDlgItemMessage(hDlg, EDIT_AREA, EM_LIMITTEXT, 31, 0);
			SendDlgItemMessage(hDlg, EDIT_NUMBER, EM_LIMITTEXT, 63, 0);
			SendDlgItemMessage(hDlg, EDIT_CATEGORY, EM_LIMITTEXT, cbi->ccCat - 1, 0);
			SendDlgItemMessage(hDlg, EDIT_PHONE, EM_LIMITTEXT, cbi->ccVal - 1, 0);

			GetCountryList(&countryCount, &pCountries);
			for (i = 0; i < countryCount; i++) {
				if (pCountries[i].nID == 0 || pCountries[i].nID == 0xFFFF) continue;
				item = SendMessage(hCombo, CB_ADDSTRING, NULL, (LPARAM)pCountries[i].ptszTranslated);
				SendMessage(hCombo, CB_SETITEMDATA, item, pCountries[i].nID);
			}

			SetDlgItemText(hDlg, EDIT_PHONE, cbi->pszVal);
			SetDlgItemText(hDlg, EDIT_CATEGORY, cbi->pszCat);
			EnableWindow(GetDlgItem(hDlg, EDIT_CATEGORY), !(cbi->wFlags & CBEXIF_CATREADONLY));
		}
		return TRUE;

	case WM_CTLCOLORSTATIC:
		SetBkColor((HDC)wParam, RGB(255, 255, 255));
		return (INT_PTR)GetStockObject(WHITE_BRUSH);

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
			case IDOK:
				if (HIWORD(wParam) == BN_CLICKED) {
					TCHAR szText[MAXDATASIZE];
					int errorPos;

					if (!GetDlgItemText(hDlg, EDIT_PHONE, szText, _countof(szText)) || !CheckPhoneSyntax(szText, cbi->pszVal, cbi->ccVal, errorPos) || errorPos > -1) {
						MsgErr(hDlg, TranslateT("The phone number should start with a + and consist of\nnumbers, spaces, brackets and hyphens only."));
						break;
					}
					// save category string
					GetDlgItemText(hDlg, EDIT_CATEGORY, cbi->pszCat, cbi->ccCat);

					// save SMS flag
					if ((int)IsDlgButtonChecked(hDlg, CHECK_SMS) != ((cbi->wFlags & CBEXIF_SMS) == CBEXIF_SMS))
						cbi->wFlags ^= CBEXIF_SMS;
				}
				//fall through
			case IDCANCEL:
				if (HIWORD(wParam) == BN_CLICKED) 
					EndDialog(hDlg, wParam);
				break;

		case EDIT_COUNTRY:
			if (HIWORD(wParam) != CBN_SELCHANGE)
				break;

		case EDIT_AREA:
		case EDIT_NUMBER:
			if (LOWORD(wParam) != EDIT_COUNTRY && HIWORD(wParam) != EN_CHANGE) break;
			if (noRecursion) break;
			EnableWindow(GetDlgItem(hDlg, IDOK), TRUE);
			{
				TCHAR szPhone[MAXDATASIZE], szArea[32], szData[64];
				int	 nCurSel = SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_GETCURSEL, 0, 0);
				UINT	nCountry = (nCurSel != CB_ERR) ? SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_GETITEMDATA, nCurSel, 0) : 0;

				GetDlgItemText(hDlg, EDIT_AREA, szArea, _countof(szArea));
				GetDlgItemText(hDlg, EDIT_NUMBER, szData, _countof(szData));
				mir_sntprintf(szPhone, _T("+%u (%s) %s"), nCountry, szArea, szData);
				noRecursion = 1;
				SetDlgItemText(hDlg, EDIT_PHONE, szPhone);
				noRecursion = 0;
			}
			break;

		case EDIT_PHONE:
			if (HIWORD(wParam) != EN_UPDATE) break;
			if (noRecursion) break;
			noRecursion = 1;
			{
				TCHAR szText[MAXDATASIZE], *pText = 0, *pArea, *pNumber;
				bool isValid = true;
				GetDlgItemText(hDlg, EDIT_PHONE, szText, _countof(szText));
				if (szText[0] != '+')
					isValid = false;
				if (isValid) {
					int country = _tcstol(szText + 1, &pText, 10);
					if (pText - szText > 4)
						isValid = false;
					else {
						int i;
						for (i = SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_GETCOUNT, 0, 0) - 1; i >= 0; i--) {
							if (country == SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_GETITEMDATA, i, 0)) {
								SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_SETCURSEL, i, 0);
								break;
							}
						}
						if (i < 0)
							isValid = false;
					}
				}
				if (isValid) {
					pArea = pText + _tcscspn(pText, _T("0123456789"));
					pText = pArea + _tcsspn(pArea, _T("0123456789"));
					if (*pText) {
						*pText = '\0';
						pNumber = pText + 1 + _tcscspn(pText + 1, _T("0123456789"));
						SetDlgItemText(hDlg, EDIT_NUMBER, pNumber);
					}
					SetDlgItemText(hDlg, EDIT_AREA, pArea);
				}
				if (!isValid) {
					SendDlgItemMessage(hDlg, EDIT_COUNTRY, CB_SETCURSEL, -1, 0);
					SetDlgItemText(hDlg, EDIT_AREA, _T(""));
					SetDlgItemText(hDlg, EDIT_NUMBER, _T(""));
				}
			}
			noRecursion = 0;
			EnableWindow(GetDlgItem(hDlg, IDOK), GetWindowTextLength(GetDlgItem(hDlg, EDIT_PHONE)));
			break;
		}
		break;
	}
	return FALSE;
}
Example #30
0
void CComboBoxUI::PaintStatusImage(HDC hDC)
{
    if (m_sArrowImage.IsEmpty())
        CComboUI::PaintStatusImage(hDC);
    else
    {
        // get index
        if( IsFocused() ) m_uButtonState |= UISTATE_FOCUSED;
        else m_uButtonState &= ~ UISTATE_FOCUSED;
        if( !IsEnabled() ) m_uButtonState |= UISTATE_DISABLED;
        else m_uButtonState &= ~ UISTATE_DISABLED;

        int nIndex = 0;
        if ((m_uButtonState & UISTATE_DISABLED) != 0)
            nIndex = 4;
        else if ((m_uButtonState & UISTATE_PUSHED) != 0)
            nIndex = 2;
        else if ((m_uButtonState & UISTATE_HOT) != 0)
            nIndex = 1;
        else if ((m_uButtonState & UISTATE_FOCUSED) != 0)
            nIndex = 3;

        // make modify string
        CDuiString sModify = m_sArrowImage;

        int nPos1 = sModify.Find(_T("source"));
        int nPos2 = sModify.Find(_T("'"), nPos1 + 7);
        if (nPos2 == -1) return; //first
        int nPos3 = sModify.Find(_T("'"), nPos2 + 1);
        if (nPos3 == -1) return; //second

        CDuiRect rcBmpPart;
        LPTSTR lpszValue = NULL;
        rcBmpPart.left = _tcstol(sModify.GetData() + nPos2 + 1, &lpszValue, 10);
        ASSERT(lpszValue);
        rcBmpPart.top = _tcstol(lpszValue + 1, &lpszValue, 10);
        ASSERT(lpszValue);
        rcBmpPart.right = _tcstol(lpszValue + 1, &lpszValue, 10);
        ASSERT(lpszValue);
        rcBmpPart.bottom = _tcstol(lpszValue + 1, &lpszValue, 10);
        ASSERT(lpszValue);

        m_nArrowWidth = rcBmpPart.GetWidth() / 5;
        rcBmpPart.left += nIndex * m_nArrowWidth;
        rcBmpPart.right = rcBmpPart.left + m_nArrowWidth;

        CDuiRect rcDest(0, 0, m_rcItem.right - m_rcItem.left, m_rcItem.bottom - m_rcItem.top);
        rcDest.Deflate(GetBorderSize(), GetBorderSize());
        rcDest.left = rcDest.right - m_nArrowWidth;

        CDuiString sSource = sModify.Mid(nPos1, nPos3 + 1 - nPos1);
        CDuiString sReplace;
        sReplace.SmallFormat(_T("source='%d,%d,%d,%d' dest='%d,%d,%d,%d'"),
                             rcBmpPart.left, rcBmpPart.top, rcBmpPart.right, rcBmpPart.bottom,
                             rcDest.left, rcDest.top, rcDest.right, rcDest.bottom);

        sModify.Replace(sSource, sReplace);

        // draw image
        if (!DrawImage(hDC, m_sArrowImage, sModify))
            m_sNormalImage.Empty();
    }
}