Inheritance: MonoBehaviour
Exemple #1
0
 public StruTemplateLibGeneralViewModel()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     globalInfo    = GlobalInfo.GetInstance();
     proUtils      = ProjectUtils.GetInstance();
 }
Exemple #2
0
    public void BtnOnClick()
    {
        Vector3 point = getLocation();

        GPS = new Vector2(point.x, point.y);

        Debug.Log("当前距离:::" + GlobalInfo.Distance(GPS.y, GPS.x, float.Parse(locationY), float.Parse(locationX)) * 1000);
        if (GlobalInfo.Distance(GPS.y, GPS.x, float.Parse(locationY), float.Parse(locationX)) * 1000 < limitdistance)
        {
            foreach (var item in VersionFilesItems.Where(item => item.extName == "mp4"))
            {
                Debug.Log(item.filename);
                if (item.filename.Contains("qionghaixingcheng"))
                {
                    GlobalInfo.VideoURL2D = PublicAttribute.LocalFilePath + "/Panorama/1/" + item.filename;
                }
                else
                {
                    VideoURL = PublicAttribute.LocalFilePath + "/Panorama/1/" + item.filename;
                    Debug.Log(VideoURL);
                }
            }

            foreach (var item in VersionFilesItems.Where(item => item.extName == "vsz"))
            {
                Debug.Log(item.localPath);
                StartCoroutine(LoadAssets(item.localPath));
            }
        }
        else
        {
            mainUISet._inst.ShowUI(mainUISet.UIname.change, 1);
        }
    }
Exemple #3
0
    public static List <ProductsInventoryResultJson.ProductsInventoryResult> GetProdustsInventoryInfo()
    {
        int PageSise         = 40;
        int currentPageIndex = 1;
        var QueryResult      = new List <ProductsInventoryResultJson.ProductsInventoryResult>();

        string result = GlobalInfo.GetProdustsInventoryInfoString(PageSise, currentPageIndex);
        var    jobj   = (ProductsInventoryResultJson.Rootobject)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ProductsInventoryResultJson.Rootobject));


        QueryResult.AddRange(jobj.Translate());

        int totalProductsCount = jobj.response.count;

        while (totalProductsCount > PageSise * currentPageIndex)
        {
            currentPageIndex++;
            result = GetProdustsInventoryInfoString(PageSise, currentPageIndex);
            jobj   = (ProductsInventoryResultJson.Rootobject)Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ProductsInventoryResultJson.Rootobject));

            QueryResult.AddRange(jobj.Translate());
        }



        return(QueryResult);
    }
Exemple #4
0
    public void ReturnChampSelect()
    {
        StaticData.Reset();
        GlobalInfo.Reset();

        SceneManager.LoadScene("MenuPlayer");
    }
Exemple #5
0
    public string GetDPManagedPropertyType(GlobalInfo all)
    {
        string property_type = Annotations.GetValue("ManagedPropertyType");

        if (property_type != null)
        {
            return(property_type);
        }

        property_type = Annotations.GetValue("PropertyType");

        if (property_type == null)
        {
            return(null);
        }

        switch (property_type)
        {
        case "char*":
            property_type = "string"; break;

        case "gint32":
            property_type = "int"; break;
        }

        if (IsDPNullable)
        {
            return("Nullable<" + property_type + ">");
        }
        else
        {
            return(property_type);
        }
    }
        /// <summary>
        /// 删除命令
        /// </summary>
        /// <param name="menu"></param>
        public override void Command4(SubMenuBase menu)
        {
            var struCalsList = GlobalInfo.GetInstance().StruCalsParas;

            if (struCalsList == null)
            {
                return;
            }

            int index = struCalsList.FindIndex(item => item.TowerName == menu.Title.Trim());

            if (index == -1)
            {
                return;
            }

            struCalsList.RemoveAt(index);

            if (parentVm == null)
            {
                return;
            }

            parentVm.SelectedModuleInfo.MenuItems.Add(menu);

            parentVm.MenuItems = new ObservableCollection <SubMenuBase>(parentVm.SelectedModuleInfo.MenuItems);
        }
Exemple #7
0
    void Awake()
    {
        config = UFE_Config;
        if (config.fps > 0)
        {
            Time.fixedDeltaTime        = (float)1 / (float)config.fps;
            Time.timeScale             = config.gameSpeed;
            QualitySettings.vSyncCount = 0;
        }

        SetLanguage("English");

        Camera.main.audio.loop = true;

        if (config.startGameImmediately)
        {
            config.player1Character = config.p1CharStorage;
            config.player2Character = config.p2CharStorage;
            StartGame(0);
        }
        else
        {
            StartIntro(0);
        }
    }
Exemple #8
0
 GlobalInfo globalInfo;//获取文件保存地址
 public GeneralInsulatorViewModule()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     ExportCommand = new DelegateCommand(doExportData);
     globalInfo    = GlobalInfo.GetInstance();
 }
        GlobalInfo globalInfo;//获取文件保存地址
        public StruCalsLibExtralLoadViewModel()
        {
            this.DataSource = new ObservableCollection <StruCalsLibExtralLoad>(struCalsLibExtralLoadDataService.GetList());

            ExportCommand = new DelegateCommand(doExportData);
            globalInfo    = GlobalInfo.GetInstance();
        }
Exemple #10
0
    /**
     * Attempts to log the user in based on the provided login info. If the info
     * is valid, the user either proceeds to the main page of the
     * self-assessment quiz.
     */
    public void OnClickLogin()
    {
        // Try to log in
        if (GlobalInfo.login(usernameInput.GetComponent <UnityEngine.UI.Text> ().text,
                             passwordInput.GetComponent <UnityEngine.UI.Text> ().text))
        {
            // If the login is successful, stash the login info
            GlobalInfo.storedUserName = usernameInput.GetComponent <UnityEngine.UI.Text> ().text;
            GlobalInfo.storedPassword = passwordInput.GetComponent <UnityEngine.UI.Text> ().text;

            // Proceed to either the main page or the quiz
            if (Database.get_student(GlobalInfo.storedUserName).has_finished_quiz)
            {
                Application.LoadLevel("3 Main Page");
            }
            else
            {
                Application.LoadLevel("2 Self-Assesment");
            }
        }
        else
        {
            Debug.Log("Login Failed");
        }
    }
Exemple #11
0
 GlobalInfo globalInfo;//获取文件保存地址
 public RigidJumperInsulatorViewModel()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     ExportCommand = new DelegateCommand(doExportData);
     globalInfo    = GlobalInfo.GetInstance();
 }
Exemple #12
0
    public void Moving()
    {
        //Debug.Log(player.forward);
        Vector3 forward = player.forward * movement.z; //двигаемся вперед/назад относительно того куда смотрит игрок
        Vector3 right   = player.right * movement.x;   //двигаемся влево/вправо относительно того куда смотрит игрок

        if (!GlobalInfo.CheckWallRun())
        {
            if (GlobalInfo.CheckGround())
            {
                body.MovePosition(body.position + forward * speed * Time.fixedDeltaTime);//осуществялем передвижение вперед/назад
            }
            else
            {
                body.MovePosition(body.position + forward * speedMove / 2 * Time.fixedDeltaTime);//осуществялем передвижение вперед/назад
            }
            //Debug.Log("Move");
        }
        else
        {
            jumps = 0;
        }
        if (GlobalInfo.CheckGround())
        {
            body.MovePosition(body.position + right * speed * Time.fixedDeltaTime);//осуществялем передвижение влево/вправо
        }
        else
        {
            body.MovePosition(body.position + right * speedMove / 2 * Time.fixedDeltaTime);//осуществялем передвижение влево/вправо
        }
    }
 GlobalInfo globalInfo;//获取文件保存地址
 public SpacerViewModel()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     ExportCommand = new DelegateCommand(doExportData);
     globalInfo    = GlobalInfo.GetInstance();
 }
        public bool ZoneLostTick()
        {
            if (_RegisterTicks)
            {
                _TicksSinceZoneReclaim++;
            }

            if (Dangerous && !Capture && _TicksSinceZoneReclaim == 2)
            {
                InitBlip(false);
                Inactive  = false;
                Spawned   = false;
                Dangerous = false;

                if (Convert.ToInt32(TerroristsAmount * 1.5) <= 100)
                {
                    TerroristsAmount = Convert.ToInt32(TerroristsAmount * 1.5);
                }
                else
                {
                    TerroristsAmount = 100;
                }

                _TicksSinceZoneReclaim = 0;
                _RegisterTicks         = false;
                GlobalInfo.CapturedZonesNames.Remove(GroupName);
                GlobalInfo.SaveCapturedZones();

                Screen.ShowSubtitle(GroupName + " zone was lost - terrorists are now stronger !", 10000);
                return(true);
            }

            return(false);
        }
        public void ZoneReclaimedTick()
        {
            if (!Dangerous && Inactive && GlobalInfo.GeneralRandomInstance.Next(0, 50) == 0)
            {
                MarkBlipAsDangerous();
                Spawned   = false;
                Inactive  = false;
                Dangerous = true;

                if (Convert.ToInt32(TerroristsAmount * 0.8) > 5)
                {
                    TerroristsAmount = Convert.ToInt32(TerroristsAmount * 0.8);
                }
                else
                {
                    TerroristsAmount = 5;
                }

                FighterCfg     = ReclaimerCfg;
                _RegisterTicks = true;

                GlobalInfo.CapturedZonesNames.Remove(GroupName);
                GlobalInfo.SaveCapturedZones();

                Screen.ShowSubtitle(GroupName + " zone is being reclaimed !", 8000);
            }
        }
Exemple #16
0
 GlobalInfo globalInfo;//获取文件保存地址
 public EarthWire_InternetViewModel()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     ExportCommand = new DelegateCommand(doExportData);
     globalInfo    = GlobalInfo.GetInstance();
 }
Exemple #17
0
        GlobalInfo globalInfo;//获取文件保存地址
        public StruCalsLibBaseDataViewModel()
        {
            OverhangingTower = new Tower();
            TensionTower     = new Tower();

            ExportCommand = new DelegateCommand(doExportData);
            globalInfo    = GlobalInfo.GetInstance();


            IList <StruCalsLibBaseData>        baseList   = baseService.GetList();   //基本信息列表
            IList <StruCalsLibBaseData_Detail> detailList = detailService.GetList(); //明细信息列表

            //页面返回结果
            StruCalsLibBaseData Overhangingbase = baseList.Where(item => item.BaseCategory == "悬垂塔基础参数").SingleOrDefault();
            StruCalsLibBaseData Tensionbase     = baseList.Where(item => item.BaseCategory == "耐张塔基础参数").SingleOrDefault();

            //悬垂塔
            OverhangingTower.BaseData    = Overhangingbase;
            OverhangingTower.GB50545Data = detailList.Where(item => item.ParentId == Overhangingbase.Id && item.Category == "GB50545-2010").SingleOrDefault();
            OverhangingTower.DLT5551Data = detailList.Where(item => item.ParentId == Overhangingbase.Id && item.Category == "DLT5551-2018").SingleOrDefault();
            //耐张塔
            TensionTower.BaseData    = Tensionbase;
            TensionTower.GB50545Data = detailList.Where(item => item.ParentId == Tensionbase.Id && item.Category == "GB50545-2010").SingleOrDefault();
            TensionTower.DLT5551Data = detailList.Where(item => item.ParentId == Tensionbase.Id && item.Category == "DLT5551-2018").SingleOrDefault();
        }
        public override void Command2(SubMenuBase menu)
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                Filter = "Result Files (*.calc)|*.calc",
            };

            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            GlobalInfo globalInfo = GlobalInfo.GetInstance();

            //StruCalsParas中塔位数据,是在点击这个塔位的页面后才加载的GlobalInfo中,
            //下面代码针对的是,没有打开这个塔位的页面而直接进行计算的情况
            if (globalInfo.StruCalsParas.Where(item => item.TowerName == ((SubMenuBase)menu).Title && item.SequenceName == ((StrCalsModuleSubMenu)menu).Sequence).Count() <= 0)
            {
                if (((StrCalsModuleSubMenu)menu).Sequence == "")
                {
                    ProjectUtils.GetInstance().ReadStruCalsTowerParas(((SubMenuBase)menu).Title);
                }
                else
                {
                    ProjectUtils.GetInstance().ReadStruCalsTowerParas(((SubMenuBase)menu).Title, ((StrCalsModuleSubMenu)menu).Sequence);
                }
            }

            StruCalsParasCompose paras = globalInfo.StruCalsParas.Where(para => para.TowerName == ((SubMenuBase)menu).Title && para.SequenceName == ((StrCalsModuleSubMenu)menu).Sequence).FirstOrDefault();

            if (paras == null)
            {
                return;
            }

            ConvertSpecToWorkCondition(paras.Template, paras.WorkConditions, true);
            string path = saveFileDialog.FileName.Substring(0, saveFileDialog.FileName.Length - 5);

            for (int i = 0; i < paras.HPSettingsParas.Count(); i++)
            {
                LoadComposeBase loadCompose;

                if (paras.BaseParas.Type == TowerTypeEnum.LineTower)
                {
                    loadCompose = new LoadComposeLineTower(paras.BaseParas, paras.LineParas.ToArray(), paras.HPSettingsParas[i], paras.Template, paras.ElectricalLoadFilePath);
                }
                else if (paras.BaseParas.Type == TowerTypeEnum.LineCornerTower)
                {
                    loadCompose = new LoadComposeLineCornerTower(paras.BaseParas, paras.LineParas.ToArray(), paras.HPSettingsParas[i], paras.Template, paras.ElectricalLoadFilePath);
                }
                //剩下的都属于耐张塔
                else
                {
                    loadCompose = new LoadComposeTensionTower(paras.BaseParas, paras.LineParas.ToArray(), paras.HPSettingsParas[i], paras.Template, paras.ElectricalLoadFilePath);
                }

                paras.ResultPointLoad.AddRange(loadCompose.LoadCaculate(path));
            }
        }
Exemple #19
0
 public AppStateMachine(GlobalInfo globalInfo, AudioAnalyzerForm audioAnalyzerForm)
 {
     _boardStatus            = BoardStatus.Disconnect;
     _analyzeStatus          = AnalyzeStatus.Idle;
     this._globalInfo        = globalInfo;
     this._audioAnalyzerForm = audioAnalyzerForm;
     this._taskRunning       = false;
 }
        public static GlobalInfo DecryptGlobalInfo(string globalInfo)
        {
            var serialize = new JavaScriptSerializer();

            GlobalInfo newObjectGlobal = serialize.Deserialize <GlobalInfo>(Encryption.Decrypt(globalInfo));

            return(newObjectGlobal);
        }
Exemple #21
0
        protected override void InitializeData()
        {
            SaveXmlCommand   = new DelegateCommand(SaveXml);
            DBFImportCommand = new DelegateCommand(DBFImport);

            //this.SelectedItems = new ObservableCollection<TowerStrData>(TowerStrDataReader.ReadLoadFile(filePath));//获取本地已保存信息
            this.SelectedItems = new ObservableCollection <TowerStrData>(GlobalInfo.GetInstance().GetLocalTowerStrs());
        }
    private LayerMask mask = (1 << 11) | (1 << 13) | (1 << 16) | (1 << 17); //hookable, blue, wall, box layers

    void Start()
    {
        rb             = GetComponent <Rigidbody2D>();
        global         = GameObject.Find("info").GetComponent <GlobalInfo>();
        ground_checker = GameObject.Find("GroundChecker").GetComponent <GroundChecker>();
        left           = GameObject.Find("Left").GetComponent <WallChecker>();
        right          = GameObject.Find("Right").GetComponent <WallChecker>();
    }
 GlobalInfo globalInfo;//获取文件保存地址
 public WeatherCondition_InternetViewModel()
 {
     doSearch();
     SearchCommand = new DelegateCommand(doSearch);
     ExportCommand = new DelegateCommand(doExportData);
     //ExportCommand = new DelegateCommand(doCheckData);
     globalInfo = GlobalInfo.GetInstance();
 }
Exemple #24
0
 private void OnClickECTowerParaMenu(SubMenuBase vm)
 {
     if (GlobalInfo.GetInstance().GetElecCalsTowerParasList().Count == 0)
     {
         System.Windows.MessageBox.Show("本地没有保存任何铁塔配置参数!");
         return;
     }
     OnSelectedMenuChanged(vm);
 }
Exemple #25
0
    public void LoadMenu()
    {
        StaticData.Reset();
        GlobalInfo.Reset();
        Time.timeScale   = 1;
        StaticData.pause = false;

        SceneManager.LoadScene("Login");
    }
Exemple #26
0
        /// <summary>
        /// Runs "test" script: see <see cref="RunScript(string, bool)"/>.
        /// </summary>
        /// <param name="globalInfo">The global information object.</param>
        /// <param name="scriptMustExist">
        /// False to only emit a warning and return false if the script doesn't exist instead of
        /// throwing an exception.
        /// </param>
        /// <returns>False if the script doesn't exist (<paramref name="scriptMustExist"/> is false), otherwise true.</returns>
        public void RunTest()
        {
            var key = DirectoryPath.AppendPart("test");

            if (!GlobalInfo.CheckCommitMemoryKey(key))
            {
                RunScript("test", false, true);
                GlobalInfo.WriteCommitMemoryKey(key);
            }
        }
Exemple #27
0
    public void ReturnToTitle()
    {
        Time.timeScale = 1;
        int score = digitDisplay.displaynumber;

        GlobalInfo.ReportScore(score);
        GlobalInfo.deathCount = 0;
        SceneManager.LoadScene("ResultMenu");
        flag = true;
    }
Exemple #28
0
        public StruCalsLibExtralLoadViewModel()
        {
            var libParas = GlobalInfo.GetInstance().GetStruCalsLibParas();

            if (libParas == null)
            {
                return;
            }

            WireExtraLoadParas = new ObservableCollection <StruCalsLibWireExtraLoadParas>(libParas.WireExtraLoadParas);
        }
        public StruCalsLibIceCoverModuleVodel()
        {
            var libParas = GlobalInfo.GetInstance().GetStruCalsLibParas();

            if (libParas == null)
            {
                return;
            }

            IceCoverParas = new ObservableCollection <StruCalsLibIceCoverParas>(libParas.IceCoverParas);
        }
Exemple #30
0
        public StruCalsLibBaseDataViewModel()
        {
            var libParas = GlobalInfo.GetInstance().GetStruCalsLibParas();

            if (libParas == null)
            {
                return;
            }

            OverhangingTowerParas = libParas.OverhangingTowerBaseParas;
            TensionTowerParas     = libParas.TensionTowerBaseParas;
        }
Exemple #31
0
	public void Write (StringBuilder text, SignatureType type, GlobalInfo info)
	{
		if (IsConst && (type == SignatureType.Native || type == SignatureType.NativeC))
			text.Append ("const ");

		if (type != SignatureType.Native && type != SignatureType.NativeC) {
			if (IsRef && !IsReturnType)
				text.Append ("ref ");
			if (IsOut && !IsReturnType)
				text.Append ("out ");
		}

		if (type == SignatureType.NativeC && info.IsEnum (Value)) {
			text.Append (GetPrettyType ().Replace (Value.Replace ("*", ""), "int"));
		} else if (type == SignatureType.Native || type == SignatureType.NativeC) {
			text.Append (GetPrettyType ());
		} else {
			text.Append (GetManagedType ());
		}
	}
Exemple #32
0
	static void WriteImplMethod (MethodInfo cmethod, MethodInfo cppmethod, StringBuilder text, GlobalInfo info)
	{
		bool is_void = cmethod.ReturnType.Value == "void";
		bool is_ctor = cmethod.IsConstructor;
		bool is_static = cmethod.IsStatic;
		bool is_dtor = cmethod.IsDestructor;
		bool check_instance = !is_static && !is_ctor;
		bool check_error = false;

		foreach (ParameterInfo parameter in cmethod.Parameters) {
			if (parameter.ParameterType.Value == "MoonError*") {
				check_error = true;
				break;
			}
		}

		cmethod.ReturnType.Write (text, SignatureType.NativeC, info);
		text.AppendLine ();
		text.Append (cmethod.Name);
		cmethod.Parameters.Write (text, SignatureType.NativeC, false);
		text.AppendLine ("");
		text.AppendLine ("{");

		if (is_ctor) {
			TypeInfo type = cppmethod.ParentType;
			bool use_factory = false;

			if (!cppmethod.Annotations.ContainsKey ("SkipFactories")) {
				do {
					if (type.Name == "EventObject") {
						use_factory = true;
						break;
					}

					MemberInfo m = null;
					if (type.Base != null && type.Base.Value != null && info.Children.TryGetValue (type.Base.Value, out m))
						type = (TypeInfo) m;
					else
						break;
				} while (type != null);
			}

			if (use_factory)
				text.Append ("\treturn MoonManagedFactory::Create");
			else
				text.Append ("\treturn new ");
			text.Append (cmethod.Parent.Name);
			cmethod.Parameters.Write (text, SignatureType.NativeC, true);
			text.AppendLine (";");
		} else if (is_dtor) {
			text.AppendLine ("\tdelete instance;");
		} else {
			if (check_instance) {
				text.AppendLine ("\tif (instance == NULL)");

				if (cmethod.ReturnType.Value == "void") {
					text.Append ("\t\treturn");
				} else if (cmethod.ReturnType.Value.Contains ("*")) {
					text.Append ("\t\treturn NULL");
				} else if (cmethod.ReturnType.Value == "Type::Kind") {
					text.Append ("\t\treturn Type::INVALID");
				} else if (cmethod.ReturnType.Value == "bool") {
					text.Append ("\t\treturn false");
				} else if (cmethod.ReturnType.Value == "Point") {
					text.Append ("\t\treturn Point (0, 0)");
				} else {
					text.AppendLine ("\t\t// Need to find a proper way to get the default value for the specified type and return that if instance is NULL.");
					text.Append ("\t\treturn");
					text.Append (" (");
					text.Append (cmethod.ReturnType.Value);
					text.Append (") 0");
				}
				text.AppendLine (";");

				text.AppendLine ("\t");
			}

			if (check_error) {
				text.AppendLine ("\tif (error == NULL)");
				text.Append ("\t\tg_warning (\"Moonlight: Called ");
				text.Append (cmethod.Name);
				text.AppendLine (" () with error == NULL.\");");
			}

			text.Append ("\t");
			if (!is_void)
				text.Append ("return ");

			if (is_static) {
				text.Append (cmethod.Parent.Name);
				text.Append ("::");
			} else {
				text.Append ("instance->");
				cmethod.Parameters [0].DisableWriteOnce = true;
			}
			text.Append (cppmethod.Name);
			cmethod.Parameters.Write (text, SignatureType.NativeC, true);
			text.AppendLine (";");
		}

		text.AppendLine ("}");
	}
Exemple #33
0
	static void WriteHeaderMethod (MethodInfo cmethod, MethodInfo cppmethod, StringBuilder text, GlobalInfo info)
	{
		Log.WriteLine ("Writing header: {0}::{1} (Version: '{2}', GenerateManaged: {3})",
		               cmethod.Parent.Name, cmethod.Name,
		               cmethod.Annotations.GetValue ("Version"),
		               cmethod.Annotations.ContainsKey ("GenerateManaged"));

		if (cmethod.Annotations.ContainsKey ("GeneratePInvoke"))
			text.AppendLine ("/* @GeneratePInvoke */");
		cmethod.ReturnType.Write (text, SignatureType.NativeC, info);
		if (!cmethod.ReturnType.IsPointer)
			text.Append (" ");
		text.Append (cmethod.Name);
		cmethod.Parameters.Write (text, SignatureType.NativeC, false);
		text.AppendLine (";");
	}
Exemple #34
0
	public bool NeedsQualifiedGetValue (GlobalInfo all)
	{
		foreach (MemberInfo child in Children.Values) {
			if (child is FieldInfo && child.Name == "ValueProperty")
				return true;
		}
		if (Base != null)
			return ((TypeInfo)all.Children[Base.Value]).NeedsQualifiedGetValue (all);
		return false;
	}
Exemple #35
0
	public string GetDPManagedPropertyType (GlobalInfo all)
	{
		string property_type = Annotations.GetValue ("ManagedPropertyType");

		if (property_type != null)
			return property_type;

		property_type = Annotations.GetValue ("PropertyType");

		if (property_type == null)
			return null;

		switch (property_type) {
		case "char*":
			property_type = "string"; break;
		case "gint32":
			property_type = "int"; break;
		}

		if (IsDPNullable)
			return "Nullable<" + property_type + ">";
		else
			return property_type;
	}
Exemple #36
0
	static List<FieldInfo> TopoSortedProperties (GlobalInfo all, List<TypeInfo> types)
	{
		Dictionary<TypeInfo,TypeEdgeCount> typeHash = new Dictionary<TypeInfo,TypeEdgeCount>();

		List<TypeInfo> remainingTypes = new List<TypeInfo>();

		foreach (TypeInfo type in types) {
			typeHash.Add (type, new TypeEdgeCount (type));
			remainingTypes.Add (type);
		}

		// build up edges for our graph
		foreach (TypeInfo type in typeHash.Keys) {

			// every property defines an edge from the declaring type to the property type
			foreach (FieldInfo prop in type.Properties) {
				if (string.IsNullOrEmpty (prop.DPDefaultValue))
					continue;

				TypeInfo propType = prop.GetDPPropertyType (all);
				if (propType == type)
					continue;
				if (typeHash.ContainsKey (propType) && !typeHash[propType].Inbound.Contains (type)) {
					typeHash[propType].Inbound.Add (type);
					typeHash[type].Outbound.Add (propType);
				}
			}

			// every base class has an edge to subclass
			// (this is kind of a hack to deal with
			// property types which are listed as base
			// types when the default values are
			// subclasses.

			TypeInfo ourType = type;
			TypeReference baseRef = ourType.Base;
			while (baseRef != null && !string.IsNullOrEmpty (baseRef.Value)) {
				TypeInfo baseType = (TypeInfo) all.Children [baseRef.Value];
				if (baseType == null)
					break;
				if (typeHash.ContainsKey (baseType) && !typeHash[baseType].Outbound.Contains (ourType)) {
					typeHash[baseType].Outbound.Add (ourType);
					typeHash[ourType].Inbound.Add (baseType);
				}
				ourType = baseType;
				if (!typeHash.ContainsKey (ourType))
					break;
				baseRef = ourType.Base;
			}
		}

		List<TypeInfo> sorted = new List<TypeInfo>();
		List<TypeInfo> roots = new List<TypeInfo>();

		foreach (TypeEdgeCount tec in typeHash.Values) {
			if (tec.Inbound.Count == 0)
				roots.Add (tec.Type);
		}

		while (roots.Count > 0) {
			TypeInfo type = roots[0];
			roots.RemoveAt (0);

			sorted.Add (type);
			remainingTypes.Remove (type);

			foreach (TypeInfo targetType in typeHash[type].Outbound) {
				if (!typeHash.ContainsKey (targetType))
					continue;
				typeHash[targetType].Inbound.Remove (type);
				if (typeHash[targetType].Inbound.Count == 0) {
					roots.Add (targetType);
				}
			}
		}

		if (remainingTypes.Count > 0) {
			throw new Exception (string.Format ("cycle in the DO/DP graph ({0} types left)", remainingTypes.Count));
		}

		List<FieldInfo> fields = new List<FieldInfo>();
		foreach (TypeInfo type in sorted) {
			foreach (FieldInfo field in type.Properties)
				fields.Insert (0, field);
		}
		return fields;
	}
Exemple #37
0
	static void GenerateManagedDOs (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string class_dir = Path.Combine (base_dir, "class");
		string sys_win_dir = Path.Combine (Path.Combine (class_dir, "System.Windows"), "System.Windows");
		string filename = Path.Combine (sys_win_dir, "DependencyObject.g.cs");
		string previous_namespace = "";
		StringBuilder text = new StringBuilder ();
		List<TypeInfo> types = all.GetDependencyObjects ();

		Helper.WriteWarningGenerated (text);
		text.AppendLine ("using Mono;");
		text.AppendLine ("using System;");
		text.AppendLine ("using System.Collections.Generic;");
		text.AppendLine ("using System.Windows;");
		text.AppendLine ("using System.Windows.Controls;");
		text.AppendLine ("using System.Windows.Documents;");
		text.AppendLine ("using System.Windows.Ink;");
		text.AppendLine ("using System.Windows.Input;");
		text.AppendLine ("using System.Windows.Markup;");
		text.AppendLine ("using System.Windows.Media;");
		text.AppendLine ("using System.Windows.Media.Media3D;");
		text.AppendLine ("using System.Windows.Media.Animation;");
		text.AppendLine ("using System.Windows.Shapes;");
		text.AppendLine ();

		for (int i = 0; i < types.Count; i++) {
			TypeInfo type = types [i];
			bool call_initialize = type.Annotations.ContainsKey ("CallInitialize");
			string ns;

			ns = type.Namespace;

			if (string.IsNullOrEmpty (ns)) {
				Console.WriteLine ("The type '{0}' in {1} does not have a namespace annotation.", type.FullName, Path.GetFileName (type.Header));
				continue;
			}

			if (ns == "None") {
				//Console.WriteLine ("The type '{0}''s Namespace annotation is 'None'.", type.FullName);
				continue;
			}

			string check_ns = Path.Combine (Path.Combine (Path.Combine (class_dir, "System.Windows"), ns), type.ManagedName.Replace ("`1", "") + ".cs");
			if (!File.Exists (check_ns))
				throw new Exception (string.Format ("The file {0} does not exist, did you annotate the class with the wrong namespace?", check_ns));

			if (previous_namespace != ns) {
				if (previous_namespace != string.Empty) {
					text.AppendLine ("}");
					text.AppendLine ();
				}
				text.Append ("namespace ");
				text.Append (ns);
				text.AppendLine (" {");
				previous_namespace = ns;
			} else {
				text.AppendLine ();
			}

			if (type.ContentProperty != null)
				text.AppendFormat ("\t[ContentProperty (\"{0}\")]\n", type.ContentProperty);
			text.Append ("\tpartial class ");
			text.Append (type.ManagedName.Replace ("`1", "<T>"));
			text.AppendLine (" {");

			// Public ctor
			if (!string.IsNullOrEmpty (type.C_Constructor)) {
				string access = "Public";
				foreach (MemberInfo member in type.Children.Values) {
					MethodInfo method = member as MethodInfo;

					if (method == null || !method.IsConstructor || method.IsStatic)
						continue;

					if (method.Parameters.Count != 0)
						continue;

					if (method.Annotations.ContainsKey ("ManagedAccess"))
						access = method.Annotations.GetValue ("ManagedAccess");
					break;
				}


				text.Append ("\t\t");
				Helper.WriteAccess (text, access);
				text.Append (" ");
				text.Append (type.ManagedName.Replace ("`1", ""));
				text.Append (" () : base (SafeNativeMethods.");
				text.Append (type.C_Constructor);
				text.Append (" (), true)");
				if (call_initialize) {
					text.AppendLine ();
					text.AppendLine ("\t\t{");
					text.AppendLine ("\t\t\tInitialize ();");
					text.AppendLine ("\t\t}");
				} else {
					text.AppendLine (" {}");
				}
			}

			// Internal ctor
			text.Append ("\t\tinternal ");
			text.Append (type.ManagedName.Replace ("`1", ""));
			text.Append (" (IntPtr raw, bool dropref) : base (raw, dropref)");
			if (call_initialize) {
				text.AppendLine ();
				text.AppendLine ("\t\t{");
				text.AppendLine ("\t\t\tInitialize ();");
				text.AppendLine ("\t\t}");
			} else {
				text.AppendLine (" {}");
			}

			text.AppendLine ("\t}");
		}
		text.AppendLine ("}");

		Helper.WriteAllText (filename, text.ToString ());
	}
Exemple #38
0
	static void GenerateManagedEvents (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string class_dir = Path.Combine (base_dir, "class");
		string sys_win_dir = Path.Combine (Path.Combine (class_dir, "System.Windows"), "System.Windows");
		string filename = Path.Combine (sys_win_dir, "Events.g.cs");
		string previous_namespace = "";
		List<TypeInfo> sorted_types = new List<TypeInfo>  ();
		StringBuilder text = new StringBuilder ();
		Dictionary <TypeInfo, List<FieldInfo>> types = new Dictionary<TypeInfo,List<FieldInfo>> ();

		foreach (FieldInfo field in all.Events) {
			TypeInfo parent = field.Parent as TypeInfo;
			List <FieldInfo> fields;
			string managed_parent = field.Annotations.GetValue ("ManagedDeclaringType");

			if (!field.IsEvent || !field.GenerateManagedEvent)
				continue;

			if (managed_parent != null) {
				parent = all.Children [managed_parent] as TypeInfo;

				if (parent == null)
					throw new Exception (string.Format ("Could not find the type '{0}' set as ManagedDeclaringType of '{1}'", managed_parent, field.FullName));
			}

			if (parent == null)
				throw new Exception (string.Format ("The field '{0}' does not have its parent set.", field.FullName));

			if (!types.TryGetValue (parent, out fields)) {
				fields = new List<FieldInfo> ();
				types.Add (parent, fields);
				sorted_types.Add (parent);
			}
			fields.Add (field);
		}

		Helper.WriteWarningGenerated (text);
		text.AppendLine ("using Mono;");
		text.AppendLine ("using System;");
		text.AppendLine ("using System.Collections.Generic;");
		text.AppendLine ("using System.ComponentModel;");
		text.AppendLine ("using System.Windows;");
		text.AppendLine ("using System.Windows.Controls;");
		text.AppendLine ("using System.Windows.Documents;");
		text.AppendLine ("using System.Windows.Ink;");
		text.AppendLine ("using System.Windows.Input;");
		text.AppendLine ("using System.Windows.Markup;");
		text.AppendLine ("using System.Windows.Media;");
		text.AppendLine ("using System.Windows.Media.Animation;");
		text.AppendLine ("using System.Windows.Navigation;");
		text.AppendLine ("using System.Windows.Shapes;");
		text.AppendLine ();

		text.AppendLine ("namespace Mono {");
		text.AppendLine ("\tinternal static class EventIds {");
		foreach (TypeInfo t in all.Children.SortedTypesByKind) {
			if (t.GetEventCount () == 0)
				continue;


			foreach (FieldInfo field in t.Events) {
				text.Append ("\t\tpublic const int ");
				text.Append (t.Name);
				text.Append ("_");
				text.Append (field.EventName);
				text.Append ("Event = ");
				text.Append (t.GetEventId (field));
				text.AppendLine (";");
			}
		}
		text.AppendLine ("\t}");

		text.AppendLine ("\tinternal static partial class Events {");
		text.AppendLine ("\t\tpublic static UnmanagedEventHandler CreateDispatcherFromEventId (int eventId, Delegate value) {");
		text.AppendLine ("\t\t\tswitch (eventId) {");

		foreach (TypeInfo t in all.Children.SortedTypesByKind) {
			if (t.GetEventCount () == 0)
				continue;


			foreach (FieldInfo field in t.Events) {
				if (field.GenerateManagedEventField == false)
					continue;
				text.Append ("\t\t\t\tcase EventIds.");
				text.Append (t.Name);
				text.Append ("_");
				text.Append (field.EventName);
				text.Append ("Event: return Events.");

				text.Append (GetDispatcherMethodName(field.EventDelegateType));
				text.Append (" ((");
				text.Append (field.EventDelegateType);
				text.Append (") value)");
				text.AppendLine (";");
			}
		}
		text.AppendLine ("\t\t\t\tdefault: throw new NotSupportedException ();");
		text.AppendLine ("\t\t\t}");
		text.AppendLine ("\t\t}");
		text.AppendLine ("\t}");

		text.AppendLine ("}");

		sorted_types.Sort (new Members.MembersSortedByManagedFullName <TypeInfo> ());
		for (int i = 0; i < sorted_types.Count; i++) {
			TypeInfo type = sorted_types [i];
			List<FieldInfo> fields = types [type];
			TypeInfo parent = type;
			string ns;

			ns = parent.Namespace;

			if (string.IsNullOrEmpty (ns)) {
				Console.WriteLine ("The type '{0}' in {1} does not have a namespace annotation.", parent.FullName, parent.Header);
				continue;
			}

			if (type.Annotations.ContainsKey ("ManagedEvents")) {
				string event_mode = type.Annotations.GetValue ("ManagedEvents");
				switch (event_mode) {
				case "None":
				case "Manual":
					continue;
				case "Generate":
					break;
				default:
					throw new Exception (string.Format ("Invalid value '{0}' for ManagedEvents in '{1}'", event_mode, type.FullName));
				}
			}

			if (ns == "None") {
				Console.WriteLine ("'{0}''s Namespace = 'None', this type should have set @ManagedEvents=Manual to not create events.", type.FullName);
				continue;
			}

			string check_ns = Path.Combine (Path.Combine (Path.Combine (class_dir, "System.Windows"), ns), parent.Name + ".cs");
			if (!File.Exists (check_ns))
				throw new Exception (string.Format ("The file {0} does not exist, did you annotate the class with the wrong namespace?", check_ns));

			if (previous_namespace != ns) {
				if (previous_namespace != string.Empty) {
					text.AppendLine ("}");
					text.AppendLine ();
				}
				text.Append ("namespace ");
				text.Append (ns);
				text.AppendLine (" {");
				previous_namespace = ns;
			} else {
				text.AppendLine ();
			}
			text.Append ("\tpartial class ");
			text.Append (parent.ManagedName);
			text.AppendLine (" {");

			fields.Sort (new Members.MembersSortedByName <FieldInfo> ());


			foreach (FieldInfo field in fields) {
				if (!field.IsEvent)
					continue;

				text.AppendLine ();

				if (field.Annotations.ContainsKey ("Browsable")) {
					text.Append ("\t\t[EditorBrowsable (EditorBrowsableState.");
					text.Append (field.Annotations.GetValue ("Browsable"));
					text.AppendLine (")]");
				}

				// property accessor
				text.Append ("\t\t");
				Helper.WriteAccess (text, field.GetManagedAccessorAccess ());
				text.Append (" event ");
				text.Append (field.EventDelegateType);
				text.Append (" ");
				text.Append (field.EventName);
				text.AppendLine (" {");

				// property getter
				text.Append ("\t\t\t");
				if (field.GetManagedAccessorAccess () != field.GetManagedGetterAccess ()) {
					Helper.WriteAccess (text, field.GetManagedGetterAccess ());
					text.Append (" ");
				}

				text.Append ("add { RegisterEvent (EventIds.");
				text.Append (field.ParentType.Name);
				text.Append ("_");
				text.Append (field.EventName);
				text.Append ("Event, value, Events.");
				text.Append (GetDispatcherMethodName(field.EventDelegateType));
				text.Append (" (value)");
				text.AppendLine ("); }");

				text.Append ("\t\t\t");
				text.Append ("remove { UnregisterEvent (EventIds.");
				text.Append (field.ParentType.Name);
				text.Append ("_");
				text.Append (field.EventName);
				text.Append ("Event, value);");
				text.AppendLine (" }");

				text.AppendLine ("\t\t}");

				if (field.GenerateManagedEventField) {
					if (field.Annotations.ContainsKey ("Browsable")) {
						text.Append ("\t\t[EditorBrowsable (EditorBrowsableState.");
						text.Append (field.Annotations.GetValue ("Browsable"));
						text.AppendLine (")]");
					}
					text.Append ("\t\t");
					text.Append (string.Format ("public static readonly RoutedEvent {0}Event = new RoutedEvent (EventIds.{1}_{2}Event);", field.EventName, field.ParentType.Name, field.EventName));
					text.AppendLine ();
				}
			}

			text.AppendLine ("\t}");
		}

		text.AppendLine ("}");

		Helper.WriteAllText (filename, text.ToString ());
	}
Exemple #39
0
	static void GeneratePInvokes (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		List <MethodInfo> methods = new List<MethodInfo> ();
		StringBuilder text = new StringBuilder ();
		string NativeMethods_cs;

		NativeMethods_cs = File.ReadAllText (Path.Combine (base_dir, "class/System.Windows/Mono/NativeMethods.cs".Replace ('/', Path.DirectorySeparatorChar)));

		methods = all.CPPMethodsToBind;

		foreach (MemberInfo info in all.Children.Values) {
			MethodInfo minfo = info as MethodInfo;
			if (minfo == null)
				continue;
			if (!minfo.Annotations.ContainsKey ("GeneratePInvoke"))
				continue;
			foreach (MethodInfo mi in methods) {
				if (mi.CMethod.Name == minfo.Name) {
					minfo = null;
					break;
				}
			}
			if (minfo == null)
				continue;
			//Console.WriteLine ("Added: {0} IsSrc: {1} IsPlugin: {2} Header: {3}", minfo.Name, minfo.IsSrcMember, minfo.IsPluginMember, minfo.Header);
			methods.Add (minfo);
		}

		Helper.WriteWarningGenerated (text);
		text.AppendLine ("using System;");
		text.AppendLine ("using System.Windows;");
		text.AppendLine ("using System.Runtime.InteropServices;");
		text.AppendLine ("");
		text.AppendLine ("namespace Mono {");

		text.AppendLine ("\tinternal static partial class SafeNativeMethods {");
		text.AppendLine ("\t\t/* moonplugin methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsPluginMember && IsSafe (method);
		});
		text.AppendLine ("\t");
		text.AppendLine ("\t\t/* libmoon methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsSrcMember && IsSafe (method);
		});
		text.AppendLine ("\t}");

		text.AppendLine ("\tinternal static partial class NativeMethods {");
		text.AppendLine ("\t\t/* moonplugin methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsPluginMember && !IsSafe (method);
		});
		text.AppendLine ("\t");
		text.AppendLine ("\t\t/* libmoon methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsSrcMember && !IsSafe (method);
		});
		text.AppendLine ("\t}");

		text.AppendLine ("}");
		Helper.WriteAllText (Path.Combine (base_dir, "class/System.Windows/Mono/GeneratedPInvokes.cs".Replace ('/', Path.DirectorySeparatorChar)), text.ToString ());
	}
Exemple #40
0
	static void GenerateTypeH (GlobalInfo all)
	{
		const string file = "src/type.h";
		StringBuilder text;
		string contents = File.ReadAllText (file + ".in");

		contents = contents.Replace ("/*DO_KINDS*/", all.Children.GetKindsForEnum ().ToString ());

		text = new StringBuilder ();

		Helper.WriteWarningGenerated (text);

		contents = text.ToString () + contents;

		Helper.WriteAllText (file, contents);
	}
Exemple #41
0
	static void WriteFactoryHeaderMethod (MethodInfo cmethod, MethodInfo cppmethod, StringBuilder text, GlobalInfo info, bool ensure)
	{
		text.Append ("\t static ");
		cmethod.ReturnType.Write (text, SignatureType.NativeC, info);
		text.AppendFormat ("Create{0}", cmethod.Parent.Name);
		cmethod.Parameters.Write (text, SignatureType.NativeC, false);
		text.Append (" { ");
		text.AppendFormat ("{0}* o = new {0}", cmethod.Parent.Name);
		cmethod.Parameters.Write (text, SignatureType.NativeC, true);
		text.Append ("; ");
		if (ensure)
			text.Append ("o->EnsureManagedPeer (); ");
		text.Append ("return o;");
		text.AppendLine (" }");
	}
 private GlobalInfo/*!*/ GetGlobalInfo(string/*!*/ name) {
     GlobalInfo global;
     if (!_globals.TryGetValue(name, out global)) {
         _globals[name] = global = new GlobalInfo(
             _globals.Count,
             Ast.ArrayIndex(
                 _globalArray,
                 Ast.Constant(_globals.Count)
             )
         );
     }
     return global;
 }
Exemple #43
0
	static void GenerateManagedWeakRefs (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string class_dir = Path.Combine (base_dir, "class");
		string sys_win_dir = Path.Combine (Path.Combine (class_dir, "System.Windows"), "System.Windows");
		string filename = Path.Combine (sys_win_dir, "WeakRefs.g.cs");

		StringBuilder text = new StringBuilder ();

		Helper.WriteWarningGenerated (text);
		text.AppendLine ();
		text.AppendLine ("using System;");
		text.AppendLine ("namespace Mono {");
		text.AppendLine ("\tinternal enum WeakRefs {");
		text.AppendLine ("\t\tInvalid = 0,");
		foreach (TypeInfo t in all.Children.SortedTypesByKind) {

			foreach (FieldInfo field in t.WeakRefs) {
				text.Append ("\t\t");
				text.Append (t.Name);
				text.Append ("_");
				text.Append (field.Name.Replace ("WeakRef", ""));
				text.Append (" = ");
				text.Append (t.GetWeakRefId (field));
				text.AppendLine (",");
			}
		}

		text.AppendLine ("\t}");
		text.AppendLine ("}");

		Helper.WriteAllText (filename, text.ToString ());
	}
Exemple #44
0
	static void GeneratePInvokes (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		List <MethodInfo> methods = new List<MethodInfo> ();
		StringBuilder text = new StringBuilder ();
		string NativeMethods_cs;

		NativeMethods_cs = File.ReadAllText (Path.Combine (base_dir, "class/System.Windows/Mono/NativeMethods.cs".Replace ('/', Path.DirectorySeparatorChar)));

		methods = all.CPPMethodsToBind;

		foreach (MemberInfo info in all.Children.Values) {
			MethodInfo minfo = info as MethodInfo;
			if (minfo == null)
				continue;
			if (!minfo.Annotations.ContainsKey ("GeneratePInvoke"))
				continue;
			if (minfo.ParentType == null) {
				// having this as an error would be annoying if the error is in a generated header
				// since we'd error out the first time the generator is run, but not the second
				// Make it more visible instead (red)
				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine ("C method: {0} must be a static C++ method to properly namespace it. A pinvoke will not be generated.", minfo.Name);
				Console.ResetColor ();
				continue;
			}
			foreach (MethodInfo mi in methods) {
				if (mi.CMethod.Name == minfo.Name) {
					minfo = null;
					break;
				}
			}
			if (minfo == null)
				continue;
			//Console.WriteLine ("Added: {0} IsSrc: {1} IsPlugin: {2} Header: {3}", minfo.Name, minfo.IsSrcMember, minfo.IsPluginMember, minfo.Header);
			methods.Add (minfo);
		}

		Helper.WriteWarningGenerated (text);
		text.AppendLine ("using System;");
		text.AppendLine ("using System.Windows;");
		text.AppendLine ("using System.Windows.Interop;");
		text.AppendLine ("using System.Runtime.InteropServices;");
		text.AppendLine ("");
		text.AppendLine ("namespace Mono {");

		text.AppendLine ("\tinternal static partial class SafeNativeMethods {");
		text.AppendLine ("\t\t/* moonplugin methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsPluginMember && IsSafe (method);
		});
		text.AppendLine ("\t");
		text.AppendLine ("\t\t/* libmoon methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsSrcMember && IsSafe (method);
		});
		text.AppendLine ("\t}");

		text.AppendLine ("\tinternal static partial class NativeMethods {");
		text.AppendLine ("\t\t/* moonplugin methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsPluginMember && !IsSafe (method);
		});
		text.AppendLine ("\t");
		text.AppendLine ("\t\t/* libmoon methods */");
		text.AppendLine ("\t");
		WriteMethods (all, NativeMethods_cs, text, delegate (MethodInfo method) {
			return method.IsSrcMember && !IsSafe (method);
		});
		text.AppendLine ("\t}");

		text.AppendLine ("}");
		Helper.WriteAllText (Path.Combine (base_dir, "class/System.Windows/Mono/GeneratedPInvokes.cs".Replace ('/', Path.DirectorySeparatorChar)), text.ToString ());
	}
Exemple #45
0
	static void GenerateTypeStaticCpp (GlobalInfo all)
	{
		string header;
		List<string> headers = new List<string> ();

		StringBuilder text = new StringBuilder ();

		Helper.WriteWarningGenerated (text);

		text.AppendLine ("#include <config.h>");
		text.AppendLine ();
		text.AppendLine ("#include <stdlib.h>");

		headers.Add ("factory.h");
		headers.Add ("cbinding.h");
		foreach (TypeInfo t in all.Children.SortedTypesByKind) {
			if (t.C_Constructor == string.Empty || t.C_Constructor == null || !t.GenerateCBindingCtor) {
				//Console.WriteLine ("{0} does not have a C ctor", t.FullName);
				if (t.GetTotalEventCount () == 0)
					continue;
			}

			if (string.IsNullOrEmpty (t.Header)) {
			//	Console.WriteLine ("{0} does not have a header", t.FullName);
				continue;
			}

			//Console.WriteLine ("{0}'s header is {1}", t.FullName, t.Header);

			header = Path.GetFileName (t.Header);
			if (!headers.Contains (header))
				headers.Add (header);
		}

		// Loop through all the classes and check which headers
		// are needed for the c constructors
		text.AppendLine ("");
		headers.Sort ();
		foreach (string h in headers) {
			text.Append ("#include \"");
			text.Append (h);
			text.AppendLine ("\"");
		}
		text.AppendLine ();
		text.AppendLine ("namespace Moonlight {");
		text.AppendLine ();

		foreach (TypeInfo t in all.Children.SortedTypesByKind) {
			if (t.GetEventCount () == 0)
				continue;


			foreach (FieldInfo field in t.Events) {
				text.Append ("const int ");
				text.Append (t.Name);
				text.Append ("::");
				text.Append (field.EventName);
				text.Append ("Event = ");
				text.Append (t.GetEventId (field));
				text.AppendLine (";");
			}
		}

		// Create the arrays of event names for the classes which have events
		text.AppendLine ("");
		foreach (TypeInfo t in all.Children.SortedTypesByKind) {

			if (t.Events.Count > 0) {
				text.Append ("const char *");
				text.Append (t.KindName);
				text.Append ("_Events [] = { ");

				foreach (FieldInfo field in t.Events) {
					text.Append ("\"");
					text.Append (field.EventName);
					text.Append ("\", ");
				}

				text.AppendLine ("NULL };");
			}

			if (t.Interfaces.Count > 0) {
				text.Append ("const Type::Kind ");
				text.Append (t.KindName);
				text.Append ("_Interfaces[] = { ");

				for (int i = 0; i < t.Interfaces.Count; i ++) {
					text.Append ("Type::");
					text.Append (t.Interfaces[i].KindName);
					if (i < t.Interfaces.Count - 1)
						text.Append (", ");
				}

				text.AppendLine (" };");
			}
		}

		// Create the array of type data
		text.AppendLine ("");
		text.AppendLine ("void");
		text.AppendLine ("Types::RegisterNativeTypes ()");
		text.AppendLine ("{");
		text.AppendLine ("\tDeployment *deployment = Deployment::GetCurrent ();");
		text.AppendLine ("\ttypes [(int) Type::INVALID] = new Type (deployment, Type::INVALID, Type::INVALID, false, false, false, NULL, 0, 0, NULL, 0, NULL, false, NULL, NULL );");
		text.AppendLine ("\ttypes [(int) Type::ENUM] = new Type (deployment, Type::ENUM, Type::OBJECT, false, false, false, \"Enum\", 0, 0, NULL, 0, NULL, false, NULL, NULL );");

		foreach (TypeInfo type in all.Children.SortedTypesByKind) {
			MemberInfo member;
			TypeInfo parent = null;
			string events = "NULL";
			string interfaces = "NULL";

			if (!type.Annotations.ContainsKey ("IncludeInKinds"))
				continue;

			if (type.Base != null && type.Base.Value != null && all.Children.TryGetValue (type.Base.Value, out member))
				parent = (TypeInfo) member;

			if (type.Events != null && type.Events.Count != 0)
				events = type.KindName + "_Events";

			if (type.Interfaces.Count != 0)
				interfaces = type.KindName + "_Interfaces";

			string parentKind;
			if (type.KindName == "OBJECT") {
				parentKind = "INVALID";
			} else {
				if (parent != null)
					parentKind = parent.KindName;
				else if (type.IsEnum)
					parentKind = "ENUM";
				else
					parentKind = "OBJECT";
			}

			text.AppendLine (string.Format (@"	types [(int) {0}] = new Type (deployment, {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13});",
							"Type::" + type.KindName,
							"Type::" + parentKind,
							type.IsEnum ? "true" : "false",
							type.IsValueType || type.IsEnum ? "true" : "false",
							type.IsInterface ? "true" : "false",
							"\"" + type.Name + "\"",
							type.GetEventCount (),
							type.GetTotalEventCount (),
							events,
							type.Interfaces.Count,
							interfaces,
							type.DefaultCtorVisible || type.IsValueType || type.IsEnum ? "true" : "false",
							((type.C_Constructor != null && type.GenerateCBindingCtor && (all.GetDependencyObjects ().Contains (type) || type.Name == "DependencyObject"))
							 ? (type.ConstructorSkipsFactories
							    ? string.Concat ("(create_inst_func *) ", type.C_Constructor)
							    : string.Concat ("(create_inst_func *) MoonUnmanagedFactory::Create", type.Name))
							 : "NULL"),
							type.ContentProperty != null ? string.Concat ("\"", type.ContentProperty, "\"") : "NULL"
							)
					 );
		}

		text.AppendLine ("\ttypes [(int) Type::LASTTYPE] = new Type (deployment, Type::LASTTYPE, Type::INVALID, false, false, false, NULL, 0, 0, NULL, 0, NULL, false, NULL, NULL);");

		text.AppendLine ("}");

		text.AppendLine ();

		text.AppendLine ("};");
		text.AppendLine ();

		Helper.WriteAllText ("src/type-generated.cpp", text.ToString ());
	}
Exemple #46
0
 void Start()
 {
     // Find global knowledge
     global = GameObject.Find("GlobalKnowledge").GetComponent<GlobalInfo>();
 }
Exemple #47
0
	static void GenerateValueH (GlobalInfo all)
	{
		const string file = "src/value.h";
		StringBuilder result = new StringBuilder ();

		Helper.WriteWarningGenerated (result);

		using (StreamReader reader = new StreamReader (file + ".in")) {
			string line;
			line = reader.ReadLine ();
			while (line != null) {
				if (line.Contains ("/*DO_FWD_DECLS*/")) {
					foreach (TypeInfo type in all.Children.SortedTypesByKind) {
						if (!type.Annotations.ContainsKey("IncludeInKinds") ||
						    type.Annotations.ContainsKey("SkipValue") ||
						    type.IsNested ||
						    type.IsStruct ||
						    type.IsEnum)
							continue;

						if (type.IsStruct) {
							forward_decls.Append ("struct ");
						} else {
							forward_decls.Append ("class ");
						}
						forward_decls.Append (type.Name);
						forward_decls.AppendLine (";");
					}
					forward_decls.AppendLine ();
					result.Append (forward_decls.ToString ());
				} else if (line.Contains ("/*DO_AS*/")) {
					foreach (TypeInfo type in all.Children.SortedTypesByKind) {
						if (!type.Annotations.ContainsKey("IncludeInKinds") ||
						    type.Annotations.ContainsKey("SkipValue") ||
						    type.IsNested ||
						    type.IsStruct ||
						    type.IsEnum)
							continue;

						//do_as.AppendLine (string.Format ("	{1,-30} As{0} () {{ checked_get_subclass (Type::{2}, {0}) }}", type.Name, type.Name + "*", type.KindName));

						result.Append ('\t');
						result.Append (type.Name);
						result.Append ("*");
						result.Append (' ', 40 - type.Name.Length);
						result.Append ("As");
						result.Append (type.Name);
						result.Append (" (Types *types = NULL) const { checked_get_subclass (Type::");
						result.Append (type.KindName);
						result.Append (", ");
						result.Append (type.Name);
						result.Append (") }");
						result.AppendLine ();
					}
					foreach (TypeInfo type in all.Children.SortedTypesByKind) {
						if (!type.IsEnum || !type.Annotations.ContainsKey ("IncludeInKinds"))
							continue;
						
						result.AppendFormat ("\t{0} As{0} () const\t", type.Name);
						result.Append ("\t{ ");
						result.Append ("checked_get_exact (Type::");
						result.Append (type.KindName);
						result.AppendFormat (", ({0}) -1, ({0}) u.i32);", type.Name);
						result.Append ("\t}");
						result.AppendLine ();
					}
					result.AppendLine ();
				} else {
					result.AppendLine (line);
				}
				line = reader.ReadLine ();
			}
		}

		Helper.WriteAllText (file, result.ToString ());
	}
Exemple #48
0
	static void WriteImplMethod (MethodInfo cmethod, MethodInfo cppmethod, StringBuilder text, GlobalInfo info)
	{
		bool is_void = cmethod.ReturnType.Value == "void";
		bool is_ctor = cmethod.IsConstructor;
		bool is_static = cmethod.IsStatic;
		bool is_dtor = cmethod.IsDestructor;
		bool check_instance = !is_static && !is_ctor;
		bool check_error = false;

		foreach (ParameterInfo parameter in cmethod.Parameters) {
			if (parameter.ParameterType.Value == "MoonError*") {
				check_error = true;
				break;
			}
		}

		cmethod.ReturnType.Write (text, SignatureType.NativeC, info);
		text.AppendLine ();
		text.Append (cmethod.Name);
		cmethod.Parameters.Write (text, SignatureType.NativeC, false);
		text.AppendLine ("");
		text.AppendLine ("{");

		if (is_ctor) {
			text.Append ("\treturn new ");
			text.Append (cmethod.Parent.Name);
			cmethod.Parameters.Write (text, SignatureType.NativeC, true);
			text.AppendLine (";");
		} else if (is_dtor) {
			text.AppendLine ("\tdelete instance;");
		} else {
			if (check_instance) {
				text.AppendLine ("\tif (instance == NULL)");

				if (cmethod.ReturnType.Value == "void") {
					text.Append ("\t\treturn");
				} else if (cmethod.ReturnType.Value.Contains ("*")) {
					text.Append ("\t\treturn NULL");
				} else if (cmethod.ReturnType.Value == "Type::Kind") {
					text.Append ("\t\treturn Type::INVALID");
				} else if (cmethod.ReturnType.Value == "bool") {
					text.Append ("\t\treturn false");
				} else if (cmethod.ReturnType.Value == "Point") {
					text.Append ("\t\treturn Point (0, 0)");
				} else {
					text.AppendLine ("\t\t// Need to find a proper way to get the default value for the specified type and return that if instance is NULL.");
					text.Append ("\t\treturn");
					text.Append (" (");
					text.Append (cmethod.ReturnType.Value);
					text.Append (") 0");
				}
				text.AppendLine (";");

				text.AppendLine ("\t");
			}

			if (check_error) {
				text.AppendLine ("\tif (error == NULL)");
				text.Append ("\t\tg_warning (\"Moonlight: Called ");
				text.Append (cmethod.Name);
				text.AppendLine (" () with error == NULL.\");");
			}

			text.Append ("\t");
			if (!is_void)
				text.Append ("return ");

			if (is_static) {
				text.Append (cmethod.Parent.Name);
				text.Append ("::");
			} else {
				text.Append ("instance->");
				cmethod.Parameters [0].DisableWriteOnce = true;
			}
			text.Append (cppmethod.Name);
			cmethod.Parameters.Write (text, SignatureType.NativeC, true);
			text.AppendLine (";");
		}

		text.AppendLine ("}");
	}
Exemple #49
0
	static void WriteMethods (GlobalInfo all, string NativeMethods_cs, StringBuilder text, Func<MethodInfo,bool> func)
	{
		List <MethodInfo> methods = all.CPPMethodsToBind;

		foreach (MethodInfo method in methods) {
			if (!func (method) || !method.Annotations.ContainsKey ("GeneratePInvoke"))
				continue;
			WritePInvokeMethod (NativeMethods_cs, method, text, method.IsPluginMember ? "moonplugin" : "moon");
			text.AppendLine ();
		}
	}
Exemple #50
0
	static string CreateValue (GlobalInfo all, FieldInfo field, string default_value)
	{
		if (default_value.StartsWith ("new "))
			return string.Format ("Value::CreateUnrefPtr ({0})", default_value);
		else if (field.GetDPPropertyType (all).IsEnum)
			return string.Format ("new Value ((gint32) {0}, Type::{1})", default_value, field.GetDPPropertyType (all).KindName);
		else
			return string.Format ("new Value ({0})", default_value);
	}
Exemple #51
0
	static void GenerateJSBindings (GlobalInfo all)
	{
		List<MethodInfo> methods;
		methods = all.JSMethodsToBind;
		StringBuilder mappings = new StringBuilder ();
		StringBuilder header = new StringBuilder ();
		StringBuilder body = new StringBuilder ();

		MemberInfo current = null;
		Dictionary<string, List<MethodInfo>> types = new Dictionary<string, List<MethodInfo>> ();

		foreach (MemberInfo m in methods) {
			MethodInfo method = (MethodInfo) m;
			string name = method.Annotations.GetValue ("GenerateJSBinding");
			if (name == null)
				name = method.Name;
			mappings.AppendLine ("\tMoonId_" + method.Parent.Name + "_" + name + ",");

			if (current != method.Parent) {
				current = method.Parent;
			}
			if (!types.ContainsKey (current.Name))
				types.Add (current.Name, new List<MethodInfo>());
			types[current.Name].Add (method);
		}


		foreach (KeyValuePair<string, List<MethodInfo>> t in types) {
			string parent = t.Key;

			header.AppendLine ("/*** Moonlight" + parent + "Class *********/");

			header.AppendLine ("struct Moonlight" + parent + "Type : MoonlightDependencyObjectType {");
			header.AppendLine ("\tMoonlight" + parent + "Type ();");
			header.AppendLine ("};");
			header.AppendLine ();
			header.AppendLine ("extern Moonlight" + parent + "Type *Moonlight" + parent + "Class;");
			header.AppendLine ();
			header.AppendLine ("struct Moonlight" + parent + "Object : MoonlightDependencyObjectObject {");
			header.AppendLine ("\tMoonlight" + parent + "Object (NPP instance) : MoonlightDependencyObjectObject (instance)");
			header.AppendLine ("\t{");
			header.AppendLine ("\t\tmoonlight_type = Type::" + parent.ToUpper() + ";");
			header.AppendLine ("\t}");
			header.AppendLine ();
			header.AppendLine ("\tvirtual bool Invoke (int id, NPIdentifier name,");
			header.AppendLine ("\t\tconst NPVariant *args, guint32 argCount, NPVariant *result);");
			header.AppendLine ();
			header.AppendLine ("};");

			body.AppendLine ();
			body.AppendLine ("/*** Moonlight" + parent + "Class *********/");
			body.AppendLine ();
			body.AppendLine ("static NPObject *");
			body.AppendLine ("moonlight_" + parent.ToLower() + "_allocate (NPP instance, NPClass *klass)");
			body.AppendLine ("{");
			body.AppendLine ("	return new Moonlight" + parent + "Object (instance);");
			body.AppendLine ("}");
			body.AppendLine ();
			body.AppendLine ("static const MoonNameIdMapping moonlight_" + parent.ToLower() + "_mapping[] = {");

			for (int i = 0; i < t.Value.Count; i++) {
				MethodInfo method = t.Value[i];
				string name = method.Annotations.GetValue ("GenerateJSBinding");
				if (name == null)
					name = method.Name;
				string id = "MoonId_" + parent + "_" + name;
				body.Append ("	{ \"" + name.ToLower () + "\", " + id + " }");

				if (i < t.Value.Count - 1)
					body.Append (",");
				body.AppendLine ("");

			}

			body.AppendLine ("};");
			body.AppendLine ("");
			body.AppendLine ("bool");
			body.AppendLine ("Moonlight" + parent + "Object::Invoke (int id, NPIdentifier name,");
			body.AppendLine ("				   const NPVariant *args, guint32 argCount,");
			body.AppendLine ("				   NPVariant *result)");
			body.AppendLine ("{");
			body.AppendLine ("	" + parent + " *dob = (" + parent + " *) GetDependencyObject ();");
			body.AppendLine ("");
			body.AppendLine ("	switch (id) {");

			foreach (MethodInfo method in t.Value) {
				string name = method.Annotations.GetValue ("GenerateJSBinding");
				if (name == null)
					name = method.Name;
				string id = "MoonId_" + parent + "_" + name;
				body.AppendLine ("\t\tcase " + id + ": {");

				bool errorcheck = false;
				string argcodes = "";
				List<string> args = new List<string>();
				List<string> parms = new List<string>();
				for (int i = 0; i < method.Parameters.Count; i++) {
					ParameterInfo parameter = method.Parameters[i];

					if (parameter.ParameterType.Value == "MoonError*") {
						errorcheck = true;
					} else {
						argcodes += parameter.ParameterType.GetNPType ();

						switch (parameter.ParameterType.GetNPType ()) {
							case "i":
								args.Add ("\t\t\tint arg" + i + " = NPVARIANT_TO_INT32 (args[" + i + "]);");
								parms.Add ("arg" + i);
								break;
							case "s":
								args.Add ("\t\t\tchar *arg" + i + " = STRDUP_FROM_VARIANT (args[" + i + "]);");
								parms.Add ("arg" + i);
								break;
							case "o":
								args.Add ("\t\t\tNPObject *obj" + i + " = NPVARIANT_TO_OBJECT (args[" + i + "]);");
								args.Add ("\t\t\tif (!npobject_is_dependency_object (obj" + i + "))");
								args.Add ("\t\t\t\tTHROW_JS_EXCEPTION (\"" + name + "\");");
								args.Add ("\t\t\tDependencyObject *arg" + i + " = ((MoonlightDependencyObjectObject *) obj" + i + ")->GetDependencyObject();");
								parms.Add ("(" + parameter.ParameterType.WriteFormatted () + ") arg" + i);
								break;
							case "d":
								args.Add ("\t\t\tdouble arg" + i + " = NPVARIANT_AS_DOUBLE (args[" + i + "]);");
								parms.Add ("arg" + i);
								break;
							case "b":
								args.Add ("\t\t\tbool arg" + i + " = NPVARIANT_TO_BOOLEAN (args[" + i + "]);");
								parms.Add ("arg" + i);
								break;
						}
					}
				}

				if (argcodes != "") {
					body.AppendLine ("\t\t\tif (!check_arg_list (\"" + argcodes + "\", argCount, args))");
					body.AppendLine ("\t\t\t\tTHROW_JS_EXCEPTION (\"" + name + "\");");
				}

				if (errorcheck) {
					body.AppendLine ("\t\t\tMoonError err;");
					parms.Add ("&err");
				}

				if (args.Count > 0)
					body.AppendLine (String.Join ("\n", args.ToArray()));

				body.Append ("\t\t\t");

				if (method.ReturnType.GetNPType () != "v") {
					method.ReturnType.WriteFormatted (body);
					if (!method.ReturnType.IsPointer)
						body.Append (" ");
					body.AppendLine ("ret = dob->" + method.Name + " (" + String.Join (", ", parms.ToArray ()) + ");");
				} else
					body.AppendLine ("dob->" + method.Name + " (" + String.Join (", ", parms.ToArray ()) + ");");

				for (int i = 0; i < method.Parameters.Count; i++) {
					ParameterInfo parameter = method.Parameters[i];
					if (parameter.ParameterType.GetNPType () == "s")
						body.AppendLine ("g_free (arg" + i + ");");
				}

				if (errorcheck)
					body.AppendLine ("\t\t\tif (err.number != 0) THROW_JS_EXCEPTION (err.message);");

				switch (method.ReturnType.GetNPType ()) {
					case "i":
						body.AppendLine ("\t\t\tINT32_TO_NPVARIANT (ret, *result);");
						break;
					case "s":
						body.AppendLine ("\t\t\tstring_to_npvariant (ret, *result);");
						break;
					case "o":
						string strobj = "EventObjectCreateWrapper (GetPlugin (), ret)";
						
						if (method.ReturnType.IsPointer) {
							body.AppendLine ("\t\t\tif (ret) {");
							
							if (method.ReturnType.IsMoonNpType) {
								string strname = method.ReturnType.GetPlainType();
								body.AppendLine (String.Format ("\t\t\t\tMoonlight{0} *{1} = (Moonlight{0} *) MOON_NPN_CreateObject (GetInstance (), Moonlight{0}Class);", strname, strname.ToLower()));
								body.AppendLine (String.Format ("\t\t\t\t{0}->{0} = {1}ret;", strname.ToLower()));
								strobj = strname.ToLower();
							}
							
							body.AppendLine ("\t\t\t\tOBJECT_TO_NPVARIANT (" + strobj + ", *result);");
							body.AppendLine ("\t\t\t} else");
							body.AppendLine ("\t\t\t\tNULL_TO_NPVARIANT (*result);");
						} else {
							// this will be something like a Point.
							string strname = method.ReturnType.GetPlainType();
							body.AppendLine (String.Format ("\t\t\tMoonlight{0} *{1} = (Moonlight{0} *) MOON_NPN_CreateObject (GetInstance (), Moonlight{0}Class);", strname, strname.ToLower()));
							body.AppendLine (String.Format ("\t\t\t{0}->{0} = ret;", strname.ToLower()));
							strobj = strname.ToLower();
							
							body.AppendLine ("\t\t\tOBJECT_TO_NPVARIANT (" + strobj + ", *result);");
						}
						break;
					case "d":
						body.AppendLine ("\t\t\tDOUBLE_TO_NPVARIANT (ret, *result);");
						break;
					case "b":
						body.AppendLine ("\t\t\tBOOLEAN_TO_NPVARIANT (ret, *result);");
						break;
					case "v":
						body.AppendLine ("\t\t\tVOID_TO_NPVARIANT (*result);");
						break;
				}

				body.AppendLine ("\t\t\treturn true;");
				body.AppendLine ("\t\t\tbreak;");
				body.AppendLine ("\t\t}");
			}

			body.AppendLine ("\t}");
			body.AppendLine ();

			body.AppendLine ("\treturn MoonlightDependencyObjectObject::Invoke (id, name, args, argCount, result);");
			body.AppendLine ("}");
			body.AppendLine ();

			body.AppendLine ("Moonlight" + parent + "Type::Moonlight" + parent + "Type ()");
			body.AppendLine ("{");
			body.AppendLine ("	AddMapping (moonlight_" + parent.ToLower() + "_mapping, G_N_ELEMENTS (moonlight_" + parent.ToLower() + "_mapping));");
			body.AppendLine ();
			body.AppendLine ("	allocate = moonlight_" + parent.ToLower() + "_allocate;");
			body.AppendLine ("}");
		}




		string file = "plugin/plugin-class.h";

		string contents = File.ReadAllText (file + ".in");
		contents = contents.Replace ("/*MAP_IDS*/", mappings.ToString());
		contents = contents.Replace ("/*MAP_HEADERS*/", header.ToString());

		StringBuilder text = new StringBuilder ();
		Helper.WriteWarningGenerated (text);
		contents = text.ToString () + contents;
		Helper.WriteAllText (file, contents);

		file = "plugin/plugin-class.g.cpp";
		contents = File.ReadAllText (file + ".in");
		contents = contents.Replace ("/*MAP_BODY*/", body.ToString());

		text = new StringBuilder ();
		Helper.WriteWarningGenerated (text);
		contents = text.ToString () + contents;
		Helper.WriteAllText (file, contents);
	}
Exemple #52
0
	static GlobalInfo GetTypes2 ()
	{
		string srcdir = Path.Combine (Environment.CurrentDirectory, "src");
		string plugindir = Path.Combine (Environment.CurrentDirectory, "plugin");
		string paldir = Path.Combine (srcdir, "pal");
		string palgtkdir = Path.Combine (paldir, "gtk");
		List<string> all_files = new List<string> ();

		all_files.AddRange (Directory.GetFiles (srcdir, "*.h"));
		all_files.AddRange (Directory.GetFiles (plugindir, "*.h"));
		all_files.AddRange (Directory.GetFiles (paldir, "*.h"));
		all_files.AddRange (Directory.GetFiles (palgtkdir, "*.h"));

		RemoveExcludedSrcFiles (srcdir, plugindir, paldir, all_files);

		Tokenizer tokenizer = new Tokenizer (all_files.ToArray ());
		GlobalInfo all = new GlobalInfo ();

		tokenizer.Advance (false);

		try {
			while (ParseMembers (all, tokenizer)) {
				try {
					tokenizer.Accept (Token2Type.Punctuation, "}");
					tokenizer.Accept (Token2Type.Punctuation, ";");
				} catch {}
			}
		} catch (Exception ex) {
			throw new Exception (string.Format ("{0}({1}): {2}", tokenizer.CurrentFile, tokenizer.CurrentLine, ex.Message), ex);
		}

		// Add all the manual types
		TypeInfo t;
		TypeInfo IComparableInfo;
		TypeInfo IFormattableInfo;
		TypeInfo IConvertibleInfo;
		TypeInfo IEquatableBoolInfo;
		TypeInfo IComparableBoolInfo;
		TypeInfo IEquatableDoubleInfo;
		TypeInfo IComparableDoubleInfo;
		TypeInfo IEquatableFloatInfo;
		TypeInfo IComparableFloatInfo;
		TypeInfo IEquatableCharInfo;
		TypeInfo IComparableCharInfo;
		TypeInfo IEquatableIntInfo;
		TypeInfo IComparableIntInfo;
		TypeInfo IEquatableLongInfo;
		TypeInfo IComparableLongInfo;
		TypeInfo IEquatableStringInfo;
		TypeInfo IComparableStringInfo;
		TypeInfo IEquatableTimeSpanInfo;
		TypeInfo IComparableTimeSpanInfo;
		TypeInfo IEquatableUintInfo;
		TypeInfo IComparableUintInfo;
		TypeInfo IEquatableUlongInfo;
		TypeInfo IComparableUlongInfo;

		all.Children.Add (new TypeInfo ("object", "OBJECT", "INVALID", true, true));

		all.Children.Add (IComparableInfo = new TypeInfo ("IComparable", "ICOMPARABLE", "OBJECT", true, true, false, true));
		all.Children.Add (IFormattableInfo = new TypeInfo ("IFormattable", "IFORMATTABLE", "OBJECT", true, true, false, true));
		all.Children.Add (IConvertibleInfo = new TypeInfo ("IConvertible", "ICONVERTIBLE", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableBoolInfo = new TypeInfo ("IEquatable<bool>", "IEQUATABLE_BOOL", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableBoolInfo = new TypeInfo ("IComparable<bool>", "ICOMPARABLE_BOOL", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableDoubleInfo = new TypeInfo ("IEquatable<double>", "IEQUATABLE_DOUBLE", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableDoubleInfo = new TypeInfo ("IComparable<double>", "ICOMPARABLE_DOUBLE", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableFloatInfo = new TypeInfo ("IEquatable<float>", "IEQUATABLE_FLOAT", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableFloatInfo = new TypeInfo ("IComparable<float>", "ICOMPARABLE_FLOAT", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableCharInfo = new TypeInfo ("IEquatable<char>", "IEQUATABLE_CHAR", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableCharInfo = new TypeInfo ("IComparable<char>", "ICOMPARABLE_CHAR", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableIntInfo = new TypeInfo ("IEquatable<int>", "IEQUATABLE_INT", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableIntInfo = new TypeInfo ("IComparable<int>", "ICOMPARABLE_INT", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableLongInfo = new TypeInfo ("IEquatable<long>", "IEQUATABLE_LONG", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableLongInfo = new TypeInfo ("IComparable<long>", "ICOMPARABLE_LONG", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableStringInfo = new TypeInfo ("IEquatable<string>", "IEQUATABLE_STRING", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableStringInfo = new TypeInfo ("IComparable<string>", "ICOMPARABLE_STRING", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableTimeSpanInfo = new TypeInfo ("IEquatable<TimeSpan>", "IEQUATABLE_TIMESPAN", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableTimeSpanInfo = new TypeInfo ("IComparable<TimeSpan>", "ICOMPARABLE_TIMESPAN", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableUintInfo = new TypeInfo ("IEquatable<uint>", "IEQUATABLE_UINT", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableUintInfo = new TypeInfo ("IComparable<uint>", "ICOMPARABLE_UINT", "OBJECT", true, true, false, true));

		all.Children.Add (IEquatableUlongInfo = new TypeInfo ("IEquatable<ulong>", "IEQUATABLE_ULONG", "OBJECT", true, true, false, true));
		all.Children.Add (IComparableUlongInfo = new TypeInfo ("IComparable<ulong>", "ICOMPARABLE_ULONG", "OBJECT", true, true, false, true));

		all.Children.Add (t = new TypeInfo ("bool", "BOOL", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableBoolInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableBoolInfo);

		all.Children.Add (t = new TypeInfo ("float", "FLOAT", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableFloatInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableFloatInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("double", "DOUBLE", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableDoubleInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableDoubleInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("guint64", "UINT64", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableUlongInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableUlongInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("gint64", "INT64", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableLongInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableLongInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("guint32", "UINT32", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableUintInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableUintInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("gint32", "INT32", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableIntInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableIntInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("char*", "STRING", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableStringInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableStringInfo);
		t.Interfaces.Add (IFormattableInfo);

		all.Children.Add (t = new TypeInfo ("TimeSpan", "TIMESPAN", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableTimeSpanInfo);
		t.Interfaces.Add (IEquatableTimeSpanInfo);

		all.Children.Add (t = new TypeInfo ("char", "CHAR", "OBJECT", true, true, true, false));
		t.Interfaces.Add (IComparableInfo);
		t.Interfaces.Add (IComparableCharInfo);
		t.Interfaces.Add (IConvertibleInfo);
		t.Interfaces.Add (IEquatableCharInfo);

		all.Children.Add (new TypeInfo ("NPObj", "NPOBJ", "OBJECT", true, true, true, false));
		all.Children.Add (new TypeInfo ("System.Windows.Markup.XmlLanguage", "XMLLANGUAGE", "OBJECT", true, true));

		// Set IncludeInKinds for all types which inherit from EventObject
		foreach (MemberInfo member in all.Children.Values) {
			TypeInfo type = member as TypeInfo;
			if (type == null)
				continue;
			if (type.Name == "EventObject")
				type.Annotations ["IncludeInKinds"] = null;

			TypeReference bR = type.Base;
			MemberInfo m;
			TypeInfo b;
			while (bR != null) {
				if (bR.Value == "EventObject") {
					member.Annotations ["IncludeInKinds"] = null;
				}

				if (!all.Children.TryGetValue (bR.Value, out m))
					break;

				b = m as TypeInfo;
				if (b != null)
					bR = b.Base;
				else
					bR = null;
			}
		}

		return all;
	}
Exemple #53
0
	static void GenerateManagedDPs (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string class_dir = Path.Combine (base_dir, "class");
		string sys_win_dir = Path.Combine (Path.Combine (class_dir, "System.Windows"), "System.Windows");
		string filename = Path.Combine (sys_win_dir, "DependencyProperty.g.cs");
		string previous_namespace = "";
		List<TypeInfo> sorted_types = new List<TypeInfo>  ();
		StringBuilder text = new StringBuilder ();
		Dictionary <TypeInfo, List<FieldInfo>> types = new Dictionary<TypeInfo,List<FieldInfo>> ();

		foreach (FieldInfo field in all.DependencyProperties) {
			TypeInfo parent = field.Parent as TypeInfo;
			List <FieldInfo> fields;
			string managed_parent = field.Annotations.GetValue ("ManagedDeclaringType");

			if (field.Annotations.GetValue ("GenerateManagedDP") == "false")
				continue;

			if (managed_parent != null) {
				parent = all.Children [managed_parent] as TypeInfo;

				if (parent == null)
					throw new Exception (string.Format ("Could not find the type '{0}' set as ManagedDeclaringType of '{1}'", managed_parent, field.FullName));
			}

			if (parent == null)
				throw new Exception (string.Format ("The field '{0}' does not have its parent set.", field.FullName));

			if (!types.TryGetValue (parent, out fields)) {
				fields = new List<FieldInfo> ();
				types.Add (parent, fields);
				sorted_types.Add (parent);
			}
			fields.Add (field);
		}

		Helper.WriteWarningGenerated (text);
		text.AppendLine ("using Mono;");
		text.AppendLine ("using System;");
		text.AppendLine ("using System.ComponentModel;");
		text.AppendLine ("using System.Collections.Generic;");
		text.AppendLine ("using System.Windows;");
		text.AppendLine ("using System.Windows.Controls;");
		text.AppendLine ("using System.Windows.Documents;");
		text.AppendLine ("using System.Windows.Ink;");
		text.AppendLine ("using System.Windows.Input;");
		text.AppendLine ("using System.Windows.Markup;");
		text.AppendLine ("using System.Windows.Media;");
		text.AppendLine ("using System.Windows.Media.Media3D;");
		text.AppendLine ("using System.Windows.Media.Animation;");
		text.AppendLine ("using System.Windows.Media.Effects;");
		text.AppendLine ("using System.Windows.Shapes;");
		text.AppendLine ();

		text.AppendLine ("#pragma warning disable 414 // The private field 'X' is assigned but its value is never used");
		text.AppendLine ("#pragma warning disable 169 // The private property 'X' is never used");
		text.AppendLine ();

		sorted_types.Sort (new Members.MembersSortedByManagedFullName <TypeInfo> ());
		for (int i = 0; i < sorted_types.Count; i++) {
			TypeInfo type = sorted_types [i];
			List<FieldInfo> fields = types [type];
			TypeInfo parent = type;
			string ns;

			ns = parent.Namespace;

			if (string.IsNullOrEmpty (ns)) {
				Console.WriteLine ("The type '{0}' in {1} does not have a namespace annotation.", parent.FullName, parent.Header);
				continue;
			}

			if (type.Annotations.ContainsKey ("ManagedDependencyProperties")) {
				string dp_mode = type.Annotations.GetValue ("ManagedDependencyProperties");
				switch (dp_mode) {
				case "None":
				case "Manual":
					continue;
				case "Generate":
					break;
				default:
					throw new Exception (string.Format ("Invalid value '{0}' for ManagedDependencyProperties in '{1}'", dp_mode, type.FullName));
				}
			}

			if (ns == "None") {
				Console.WriteLine ("'{0}''s Namespace = 'None', this type should have set @ManagedDependencyProperties=Manual to not create DPs.", type.FullName);
				continue;
			}

			string check_ns = Path.Combine (Path.Combine (Path.Combine (class_dir, "System.Windows"), ns), parent.Name + ".cs");
			if (!File.Exists (check_ns))
				throw new Exception (string.Format ("The file {0} does not exist, did you annotate the class with the wrong namespace?", check_ns));

			if (previous_namespace != ns) {
				if (previous_namespace != string.Empty) {
					text.AppendLine ("}");
					text.AppendLine ();
				}
				text.Append ("namespace ");
				text.Append (ns);
				text.AppendLine (" {");
				previous_namespace = ns;
			} else {
				text.AppendLine ();
			}
			text.Append ("\tpartial class ");
			text.Append (parent.ManagedName);
			text.AppendLine (" {");

			fields.Sort (new Members.MembersSortedByName <FieldInfo> ());

			// The DP registration
			foreach (FieldInfo field in fields) {
				bool conv_int_to_double = field.GetDPManagedPropertyType (all) == "int" && field.GetDPPropertyType (all).Name == "double";

				if (field.Annotations.ContainsKey ("Browsable")) {
					text.Append ("\t\t[EditorBrowsable (EditorBrowsableState.");
					text.Append (field.Annotations.GetValue ("Browsable"));
					text.AppendLine (")]");
				}

				text.Append ("\t\t");
				Helper.WriteAccess (text, field.GetManagedFieldAccess ());
				text.Append (" static readonly DependencyProperty ");
				text.Append (field.Name);
				text.Append (" = DependencyProperty.Lookup (Kind.");
				text.Append (field.ParentType.KindName);
				text.Append (", \"");
				text.Append (field.GetDependencyPropertyName ());
				text.Append ("\", typeof (");
				if (conv_int_to_double)
					text.Append ("double");
				else
					text.Append (field.GetDPManagedPropertyType (all));
				text.AppendLine ("));");
			}

			foreach (FieldInfo field in fields) {
				bool conv_int_to_double = field.GetDPManagedPropertyType (all) == "int" && field.GetDPPropertyType (all).Name == "double";

				if (field.IsDPAttached || !field.GenerateManagedAccessors)
					continue;

				text.AppendLine ();


				if (field.Annotations.ContainsKey ("Browsable")) {
					text.Append ("\t\t[EditorBrowsable (EditorBrowsableState.");
					text.Append (field.Annotations.GetValue ("Browsable"));
					text.AppendLine (")]");
				}

				// property accessor
				text.Append ("\t\t");
				Helper.WriteAccess (text, field.GetManagedAccessorAccess ());
				text.Append (" ");
				text.Append (field.GetDPManagedPropertyType (all));
				text.Append (" ");
				text.Append (field.GetDependencyPropertyName ());
				text.AppendLine (" {");

				// property getter
				text.Append ("\t\t\t");
				if (field.GetManagedAccessorAccess () != field.GetManagedGetterAccess ()) {
					Helper.WriteAccess (text, field.GetManagedGetterAccess ());
					text.Append (" ");
				}

				text.Append ("get { return (");
				text.Append (field.GetDPManagedPropertyType (all));
				if (conv_int_to_double)
					text.Append (") (double");
				text.Append (") GetValue (");
				text.Append (field.Name);
				text.AppendLine ("); }");

				// property setter
				if (!field.IsDPReadOnly) {
					text.Append ("\t\t\t");
					if (field.GetManagedAccessorAccess () != field.GetManagedSetterAccess ()) {
						Helper.WriteAccess (text, field.GetManagedSetterAccess ());
						text.Append (" ");
					}
					text.Append ("set { SetValue (");
					text.Append (field.Name);
					text.AppendLine (", value); }");
				}
				text.AppendLine ("\t\t}");
			}

			text.AppendLine ("\t}");
		}
		text.AppendLine ("}");

		Helper.WriteAllText (filename, text.ToString ());
	}
Exemple #54
0
	public void GenerateTypes_G (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string class_dir = Path.Combine (base_dir, "class");
		string moon_moonlight_dir = Path.Combine (class_dir, "System.Windows");
		List<TypeInfo> types = new List<TypeInfo> (all.GetDependencyObjects ());

		StringBuilder text = new StringBuilder ();

		Helper.WriteWarningGenerated (text);

		text.AppendLine ("using Mono;");
		text.AppendLine ("using System;");
		text.AppendLine ("using System.Reflection;");
		text.AppendLine ("using System.Collections.Generic;");
		text.AppendLine ("");
		text.AppendLine ("namespace Mono {");
		text.AppendLine ("\tpartial class Types {");
		text.AppendLine ("\t\tprivate void CreateNativeTypes ()");
		text.AppendLine ("\t\t{");
		text.AppendLine ("\t\t\tType t;");
		text.AppendLine ("\t\t\ttry {");

		foreach (MemberInfo m in all.Children.Values) {
			TypeInfo t = m as TypeInfo;
			if (t == null)
				continue;
			if (types.Contains (t))
				continue;
			types.Add (t);
		}

		types.Sort (new Members.MembersSortedByManagedFullName <TypeInfo> ());

		for (int i = 0; i < types.Count; i++) {
			TypeInfo t = types [i];
			string type = t.ManagedName;

			if (String.IsNullOrEmpty (t.Namespace) || t.Namespace == "None" || t.Name.StartsWith ("MoonWindow"))
				continue;

			type = type.Replace ("`1", "<>");

			//Log.WriteLine ("Found Kind.{0} in {1} which result in type: {2}.{3}", kind, file, ns, type);

			text.Append ("\t\t\t\tt = typeof (");
			text.Append (t.Namespace);
			text.Append (".");
			text.Append (type);
			text.AppendLine ("); ");

			text.Append ("\t\t\t\tAddBuiltinType (t, new ManagedType (t, Kind.");
			text.Append (t.KindName);
			text.AppendLine ("));");
		}

		// now handle the primitive types
		output_native_type_delegate f = delegate (string t, string k) {
			text.Append ("\t\t\t\tt = typeof (");
			text.Append (t);
			text.AppendLine (");");


			text.Append ("\t\t\t\tAddBuiltinType (t, new ManagedType (t, Kind.");
			text.Append (k);
			text.AppendLine ("));");
		};

		f ("char", "CHAR");
		f ("object", "OBJECT");
		f ("bool", "BOOL");
		f ("double", "DOUBLE");
		f ("float", "FLOAT");
		f ("ulong", "UINT64");
		f ("long", "INT64");
		f ("uint", "UINT32");
		f ("int", "INT32");
		f ("string", "STRING");
		f ("TimeSpan", "TIMESPAN");
		f ("Enum", "ENUM");

		f ("System.Windows.Application", "APPLICATION");
		f ("System.Windows.Thickness", "THICKNESS");
		f ("System.Windows.CornerRadius", "CORNERRADIUS");
		f ("System.Windows.PropertyPath", "PROPERTYPATH");
		f ("System.Windows.Point", "POINT");
		f ("System.Windows.Rect", "RECT");
		f ("System.Windows.Size", "SIZE");
		f ("System.Windows.FontStretch", "FONTSTRETCH");
		f ("System.Windows.FontWeight", "FONTWEIGHT");
		f ("System.Windows.FontStyle", "FONTSTYLE");
		f ("System.Windows.Documents.TextSelection", "TEXTSELECTION");
		f ("System.Windows.Documents.TextPointer", "TEXTPOINTER");
		f ("System.Windows.Media.FontFamily", "FONTFAMILY");
		f ("System.Windows.Markup.XmlLanguage", "XMLLANGUAGE");
		f ("System.Windows.Input.Cursor", "CURSORTYPE");
		f ("System.Windows.Messaging.LocalMessageReceiver", "LOCALMESSAGERECEIVER");
		f ("System.Windows.Messaging.LocalMessageSender", "LOCALMESSAGESENDER");

		text.AppendLine ("\t\t\t} catch (Exception ex) {");
		text.AppendLine ("\t\t\t\tConsole.WriteLine (\"There was an error while loading native types: \" + ex.ToString ());");
		text.AppendLine ("\t\t\t}");
		text.AppendLine ("\t\t}");
		text.AppendLine ("\t}");
		text.AppendLine ("}");

		Log.WriteLine ("typeandkidngen done");

		Helper.WriteAllText (Path.Combine (Path.Combine (moon_moonlight_dir, "Mono"), "Types.g.cs"), text.ToString ());
	}
Exemple #55
0
	static void GenerateDPs (GlobalInfo all)
	{
		string base_dir = Environment.CurrentDirectory;
		string moon_dir = Path.Combine (base_dir, "src");
// 		int version_previous = 0;
		StringBuilder text = new StringBuilder ();
		List<FieldInfo> fields = all.DependencyProperties;
		List<string> headers = new List<string> ();

		List<TypeInfo> types = new List<TypeInfo> ();
		foreach (FieldInfo field in fields) {
			if (!types.Contains ((TypeInfo)field.Parent))
				types.Add ((TypeInfo)field.Parent);
		}
		fields = TopoSortedProperties (all, types);

		headers.Add ("dependencyproperty.h");
		headers.Add ("validators.h");
		headers.Add ("provider.h");
		headers.Add ("color.h");
		headers.Add ("managedtypeinfo.h");
		foreach (FieldInfo field in fields) {
			string h;
			if (string.IsNullOrEmpty (field.Header))
				continue;
			h = Path.GetFileName (field.Header);

			if (!headers.Contains (h))
				headers.Add (h);
		}

		Helper.WriteWarningGenerated (text);
		text.AppendLine ();
		text.AppendLine ("#include <config.h>");
		text.AppendLine ();
		headers.Sort ();
		foreach (string h in headers) {
			text.Append ("#include \"");
			text.Append (h);
			text.AppendLine ("\"");
		}
		text.AppendLine ("namespace Moonlight {");
		text.AppendLine ();
		text.AppendLine ("void");
		text.AppendLine ("Types::RegisterNativeProperties ()");
		text.AppendLine ("{");

		for (int i = 0; i < fields.Count; i++) {
			FieldInfo field = fields [i];
			TypeInfo type = field.ParentType;
			TypeInfo propertyType = null;
			string default_value = field.DPDefaultValue;
			bool has_default_value = !string.IsNullOrEmpty (default_value);
			string autocreator = field.DPAutoCreator;
			bool is_nullable = field.IsDPNullable;
			bool is_attached = field.IsDPAttached;
			bool is_readonly = field.IsDPReadOnly;
			bool is_always_change = field.IsDPAlwaysChange;
			string validator = field.DPValidator;
			bool is_full = is_attached || is_readonly || is_always_change || validator != null || autocreator != null || is_nullable;

			propertyType = field.GetDPPropertyType (all);

			text.Append ("\t");

			if (propertyType == null) {
				text.Append ("// (no PropertyType was found for this DependencyProperty) ");
			} else {
				headers.Add (propertyType.Header);
			}

			text.Append ("DependencyProperty::Register");
			if (is_full)
				text.Append ("Full");

			text.Append (" (");
			text.Append ("this, ");
			text.Append ("Type::");
			text.Append (type.KindName);
			text.Append (", \"");

			text.Append (field.GetDependencyPropertyName ());
			text.Append ("\"");
			text.Append (", ");

			text.Append (field.IsCustom ? "true" : "false");
			text.Append (", ");

			if (has_default_value) {
				text.Append (CreateValue (all, field, default_value));
			} else if (is_full) {
				text.Append ("NULL");
			}

			if ((has_default_value || is_full))
				text.Append (", ");

			if (propertyType != null) {
				text.Append ("Type::");
				text.Append (propertyType.KindName);
			} else if (!has_default_value) {
				text.Append ("Type::INVALID");
				Console.WriteLine ("{0} does not define its property type.", field.FullName);
			}

			if (is_full) {
				text.Append (", ");
				text.Append (is_attached ? "true" : "false");
				text.Append (", ");
				text.Append (is_readonly ? "true" : "false");
				text.Append (", ");
				text.Append (is_always_change ? "true" : "false");
				text.Append (", ");
				text.Append ("NULL");
				text.Append (", ");
				text.Append (validator != null ? ("Validators::" + validator) : "NULL");
				text.Append (", ");
				text.Append (autocreator != null
					     ? (autocreator.Contains("::") ? autocreator : "AutoCreators::" + autocreator)
					     : "NULL");
				text.Append (", ");
				text.Append (is_nullable ? "true" : "false");
			}

			text.AppendLine (");");
		}

		text.AppendLine ();
		foreach (var field in fields) {
			foreach (var metadataOverride in field.MetadataOverrides) {
				text.AppendFormat ("\tthis->GetProperty ({0}::{1})->AddDefaultValueOverride (Type::{2}, {3});",
				                   field.Parent.Name,
				                   field.Name,
				                   metadataOverride.Key,
				                   CreateValue (all, field, metadataOverride.Value));
				text.AppendLine ();
			}
			if (field.HasHiddenDefaultValue) {
				text.AppendFormat ("\tthis->GetProperty ({0}::{1})->SetHasHiddenDefaultValue (true);{2}",
				                   field.Parent.Name,
				                   field.Name,
				                   Environment.NewLine);
			}
		}
		text.AppendLine ("}");
		text.AppendLine ();

		// Static initializers
		for (int i = 0; i < fields.Count; i++) {
			FieldInfo field = fields [i];
			text.Append ("const int ");
			text.Append (field.Parent.Name);
			text.Append ("::");
			text.Append (field.Name);
			text.Append (" = ");
			text.Append (i);
			text.AppendLine (";");
		}
		text.AppendLine ();

		// C++ Accessors
		for (int i = 0; i < fields.Count; i++) {
			FieldInfo field = fields [i];
			TypeInfo prop_type;
			string prop_type_str;
			string value_str;
			string prop_default = null;
			bool both = field.Annotations.ContainsKey ("GenerateAccessors");
			bool setter = both || field.Annotations.ContainsKey ("GenerateSetter");
			bool getter = both || field.Annotations.ContainsKey ("GenerateGetter");
			bool is_attached = field.IsDPAttached;
			bool nullable_setter = setter && field.IsDPNullable;
			bool doing_nullable_setter = false;

			if (!setter && !getter)
				continue;

			prop_type = field.GetDPPropertyType (all);

			switch (prop_type.Name) {
			case "char*":
				prop_type_str = "const char *";
				value_str = "String";
				break;
			case "int":
			case "gint32":
				value_str = "Int32";
				prop_type_str = prop_type.Name;
				prop_default = "0";
				break;
			case "double":
				value_str = "Double";
				prop_type_str = prop_type.Name;
				prop_default = "0.0";
				break;
			case "bool":
				prop_type_str = prop_type.Name;
				value_str = "Bool";
				prop_default = "false";
				break;
			case "char":
				prop_type_str = "gunichar";
				value_str = "Char";
				prop_default = "0";
				break;
			case "object":
				prop_type_str = "Value *";
				prop_default = "NULL";
				value_str = null;
				break;
			default:
				prop_type_str = prop_type.Name;
				value_str = prop_type.Name;
				break;
			}

			if (field.Annotations.ContainsKey ("IsConstPropertyType"))
				prop_type_str = "const " + prop_type_str;

			string GetterName = string.Format ("{0}::Get{1}", field.ParentType.Name, field.GetDependencyPropertyName());
			string SetterName = string.Format ("{0}::Set{1}", field.ParentType.Name, field.GetDependencyPropertyName());

			if (getter) {
				text.Append (prop_type_str);
				if (field.IsDPNullable || (prop_type.IsClass || prop_type.IsStruct))
					text.Append (" *");
				text.AppendLine ();
				text.Append (GetterName);
				if (is_attached)
					text.AppendLine (" (DependencyObject *obj)");
				else
					text.AppendLine (" ()");
				text.AppendLine ("{");


				if (value_str == null) {
					text.Append ("\treturn ");
				} else if (is_attached) {
					text.Append ("\tValue *value = (!obj) ? NULL : ");
				} else {
					text.Append ("\tValue *value = ");
				}

				text.AppendFormat ("{0}{1}GetValue ({2}::{3});\n",
						   is_attached ? "obj->" : "",
						   field.ParentType.NeedsQualifiedGetValue(all) ? "DependencyObject::" : "",
						   field.ParentType.Name, field.Name);

//				if (is_attached) {
//					text.AppendFormat ("\tif (!value) value = Deployment::GetCurrent ()->GetTypes ()->GetProperty ({0}::{1})->GetDefaultValue(obj->GetType ()->GetKind ());\n",
//							   field.ParentType.Name, field.Name);
//				}

				if (value_str == null) {
					// Skip this
				} else if (field.IsDPNullable || (prop_type.IsClass || prop_type.IsStruct || prop_type.Name == "char*")) {
					text.Append ("\treturn value ? ");
					if (prop_type.IsEnum) {
						text.AppendFormat ("({0}) value->As{0}() : ({0}) 0", prop_type.Name);
					} else {
						if (!field.IsDPNullable && (/*prop_type.IsStruct || */prop_default != null))
						    if (string.IsNullOrEmpty (prop_default))
							throw new NotImplementedException (
								string.Format ("Generation of DependencyProperties with struct values ({0}.{1})",
									       field.ParentType.Name, field.Name));

						text.AppendFormat ("value->As{0}{1} () : {2}",
								   field.IsDPNullable && !(prop_type.IsStruct || prop_type.IsClass) ? "Nullable" : "",
								   value_str,
								   !field.IsDPNullable && prop_default != null ? prop_default : "NULL");
					}
				} else {
					// Value cannot be null, so don't need to check for it
					text.Append ("\treturn ");
					if (prop_type.IsEnum) {
						text.AppendFormat ("value->As{0} ()", prop_type.Name);
					} else {
						text.AppendFormat ("value->As{0} ()", value_str);
					}
				}

				if (value_str != null)
					text.AppendLine (";");
				text.AppendLine ("}");
				text.AppendLine ();
			}

		 do_nullable_setter:
			if (setter) {
				text.AppendLine ("void");
				text.Append (SetterName);
				text.Append (" (");
				if (is_attached)
					text.Append ("DependencyObject *obj, ");
				text.Append (prop_type_str);
				if (prop_type.Name != "char*")
					text.Append (' ');
				if (!nullable_setter && (prop_type.IsClass || prop_type.IsStruct))
					text.Append ('*');
				text.AppendLine ("value)");

				text.AppendLine ("{");
				if (is_attached)
					text.AppendLine ("\tif (!obj) return;");
				if (doing_nullable_setter) {
					text.AppendLine ("\tif (!value)");
					text.Append ("\t\t");
					text.AppendFormat ("{0}{1}SetValue ({2}::{3}, NULL);\n",
							   is_attached ? "obj->" : "",
							   field.ParentType.NeedsQualifiedGetValue(all) ? "DependencyObject::" : "",
							   field.ParentType.Name, field.Name);
					text.AppendLine ("\telse");
					text.Append ("\t\t");
					text.AppendFormat ("{0}{1}SetValue ({2}::{3}, Value (*value));\n",
							   is_attached ? "obj->" : "",
							   field.ParentType.NeedsQualifiedGetValue(all) ? "DependencyObject::" : "",
							   field.ParentType.Name, field.Name);
				} else {
					if (!nullable_setter && prop_type.IsStruct)
						text.AppendLine ("\tif (!value) return;");
					text.Append ("\t");
					text.AppendFormat ("{0}{1}SetValue ({2}::{3}, ",
							   is_attached ? "obj->" : "",
							   field.ParentType.NeedsQualifiedGetValue(all) ? "DependencyObject::" : "",
							   field.ParentType.Name, field.Name);

					if (prop_type.Name == "guint64" || prop_type.Name == "TimeSpan") {
						text.AppendFormat ("Value (value, Type::{0}));\n",
								   prop_type.KindName);
					}
					else if (prop_type.Name == "char") {
						text.AppendLine ("Value (value, Type::CHAR));");
					}
					else if ((value_str == null) || (!nullable_setter && prop_type.IsStruct)) {
						text.AppendLine ("Value (*value));");
					}
					else if (prop_type.IsClass) {
						text.AppendLine ("Value (value));");
					}
					else if (prop_type.IsEnum) {
						text.AppendFormat ("Value ((gint32) value, Type::{0}));", prop_type.KindName);
						text.AppendLine ();
					} else {
						text.AppendLine ("Value (value));");
					}
				}
				text.AppendLine ("}");
				text.AppendLine ();
			}

			if (nullable_setter) {
				if (!prop_type.IsStruct)
					prop_type_str += " *";
				nullable_setter = false;
				doing_nullable_setter = true;
				goto do_nullable_setter;
			}
		}

		text.AppendLine ("};");
		Helper.WriteAllText (Path.Combine (moon_dir, "dependencyproperty.g.cpp"), text.ToString ());

	}
Exemple #56
0
	private static void GenerateCBindings (GlobalInfo info, string dir)
	{
		List<MethodInfo> methods;
		StringBuilder header = new StringBuilder ();
		StringBuilder impl = new StringBuilder ();
		List <string> headers = new List<string> ();
		List <string> classes = new List<string> ();
		List <string> structs = new List<string> ();

		string last_type = string.Empty;

		methods = info.CPPMethodsToBind;

		Helper.WriteWarningGenerated (header);;
		Helper.WriteWarningGenerated (impl);

		header.AppendLine ("#ifndef __MOONLIGHT_C_BINDING_H__");
		header.AppendLine ("#define __MOONLIGHT_C_BINDING_H__");
		header.AppendLine ();
		header.AppendLine ("#include <glib.h>");
		header.AppendLine ("#include <cairo.h>");
		header.AppendLine ();
		header.AppendLine ("#include \"pal.h\"");
		header.AppendLine ("#include \"pal/gtk/window-gtk.h\"");
		header.AppendLine ("#include \"enums.h\"");
		header.AppendLine ();
		header.AppendLine ("namespace Moonlight {");
		foreach (MemberInfo member in info.Children.Values) {
			TypeInfo type = member as TypeInfo;
			if (type == null)
				continue;

			if (type.IsClass) {
				if (!classes.Contains (type.Name))
					classes.Add (type.Name);
			} else if (type.IsStruct) {
				if (!structs.Contains (type.Name))
					structs.Add (type.Name);
			}
		}

		foreach (MemberInfo method in methods) {
			string h;

			if (method.ParentType != null) {
				TypeInfo type = method.ParentType;
				if (type.IsClass) {
					if (!classes.Contains (type.Name))
						classes.Add (type.Name);
				} else if (type.IsStruct) {
					if (!structs.Contains (type.Name))
						structs.Add (type.Name);
				}
			}

			if (string.IsNullOrEmpty (method.Header))
				continue;
			if (!method.Header.StartsWith (dir))
				continue;

			h = Path.GetFileName (method.Header);

			if (!headers.Contains (h))
				headers.Add (h);
		}
		header.AppendLine (forward_decls.ToString ());
		classes.Sort ();
		structs.Sort ();
		foreach (string c in classes) {
			header.Append ("class ");
			header.Append (c);
			header.AppendLine (";");
		}
		header.AppendLine ();
		foreach (string s in structs) {
			header.Append ("struct ");
			header.Append (s);
			header.AppendLine (";");
		}
		header.AppendLine ();
		header.AppendLine (cbinding_requisites.ToString ());

		header.AppendLine ();
		header.AppendLine ("G_BEGIN_DECLS");
		header.AppendLine ();

		impl.AppendLine ("#include <config.h>");
		impl.AppendLine ();
		impl.AppendLine ("#include <stdio.h>");
		impl.AppendLine ("#include <stdlib.h>");
		impl.AppendLine ();
		impl.AppendLine ("#include \"cbinding.h\"");
		if (!dir.Contains ("plugin"))
			impl.AppendLine ("#include \"factory.h\"");
		impl.AppendLine ();
		headers.Sort ();
		foreach (string h in headers) {
			impl.Append ("#include \"");
			impl.Append (h);
			impl.AppendLine ("\"");
		}

		impl.AppendLine ();
		impl.AppendLine ("namespace Moonlight {");

		foreach (MemberInfo member in methods) {
			MethodInfo method = (MethodInfo) member;

			if (!method.Header.StartsWith (dir))
				continue;

			if (last_type != method.Parent.Name) {
				last_type = method.Parent.Name;
				foreach (StringBuilder text in new StringBuilder [] {header, impl}) {
					text.AppendLine ("/**");
					text.Append (" * ");
					text.AppendLine (last_type);
					text.AppendLine (" **/");
				}
			}

			WriteHeaderMethod (method.CMethod, method, header, info);
			header.AppendLine ();

			WriteImplMethod (method.CMethod, method, impl, info);
			impl.AppendLine ();
			impl.AppendLine ();
		}

		header.AppendLine ();
		header.AppendLine ("G_END_DECLS");
		header.AppendLine ();
		header.AppendLine ("};");
		header.AppendLine ("#endif");

		impl.AppendLine ("");
		impl.AppendLine ("};");

		Helper.WriteAllText (Path.Combine (dir, "cbinding.h"), header.ToString ());
		Helper.WriteAllText (Path.Combine (dir, "cbinding.cpp"), impl.ToString ());
	}
Exemple #57
0
	public TypeInfo GetDPPropertyType (GlobalInfo all)
	{
		string property_type = DPPropertyType;
		TypeInfo propertyType = null;

		if (!string.IsNullOrEmpty (property_type)) {
			if (all.Children.ContainsKey (property_type)) {
				propertyType = (TypeInfo) all.Children [property_type];
			} else {
				Console.WriteLine ("{0}'s PropertyType '{1}' was not recognized. Do not use the Kind value, but the real type name.", FullName, property_type);
			}
		} else {
			Console.WriteLine ("{0} does not have a PropertyType defined.", FullName);
		}

		return propertyType;
	}
Exemple #58
0
	public static void GenerateCBindings (GlobalInfo info)
	{
		string base_dir = Environment.CurrentDirectory;
		string plugin_dir = Path.Combine (base_dir, "plugin");
		string moon_dir = Path.Combine (base_dir, "src");

		GenerateCBindings (info, moon_dir);
		GenerateCBindings (info, plugin_dir);
	}
Exemple #59
0
	/// <summary>
	/// Grants buffs and grounded-check based on the platform the player collides.
	/// </summary>
	/// <param name="p_platType">P_plat type.</param>
	void PlatformCollision(GlobalInfo.PlaformType p_platType)
	{
		if (isPaused)
			return;

		if (p_platType == GlobalInfo.PlaformType.WHITE || p_platType == GlobalInfo.PlaformType.LOCKED_WHITE)
		{
			_groundedFlag = true;
			return;
		}
		else if (p_platType == GlobalInfo.PlaformType.BLACK)
			return;

		else if (p_platType == GlobalInfo.PlaformType.RED || p_platType == GlobalInfo.PlaformType.LOCKED_RED)
		{
			_groundedFlag = true;
			_redBuffActive = true;
			_redBuffTimer = 0.0f;
		}
		else if (p_platType == GlobalInfo.PlaformType.BLUE || p_platType == GlobalInfo.PlaformType.LOCKED_BLUE)
		{
			_groundedFlag = true;
			_blueBuffActive = true;
			_blueBuffTimer = 0.0f;
		}
		else if (p_platType == GlobalInfo.PlaformType.GREEN || p_platType == GlobalInfo.PlaformType.LOCKED_GREEN)
		{
			_groundedFlag = true;
			if (!_greenBuffActive)
			{
				_greenBuffActive = true;
				_greenBuffTimer = 0.0f;
				InvertGravity();
			}
		}
	}
Exemple #60
0
	public static void GenerateFactories (GlobalInfo info)
	{
		string base_dir = Environment.CurrentDirectory;
		string dir = Path.Combine (base_dir, "src/");

		List<MethodInfo> methods;
		StringBuilder header = new StringBuilder ();
		List <string> headers = new List<string> ();

		methods = info.AllCtors;

		Helper.WriteWarningGenerated (header);;

		header.AppendLine ("#ifndef __MOONLIGHT_FACTORY_H__");
		header.AppendLine ("#define __MOONLIGHT_FACTORY_H__");
		header.AppendLine ();
		header.AppendLine ("#include <glib.h>");
		header.AppendLine ("#include <cairo.h>");
		header.AppendLine ();

		foreach (MemberInfo method in methods) {
			string h;

			if (string.IsNullOrEmpty (method.Header))
				continue;
			if (!method.Header.StartsWith (dir))
				continue;

			h = method.Header.Substring (dir.Length);

			if (!headers.Contains (h) &&
			    h != "pipeline-ui.h" &&
			    h != "pipeline-nocodec-ui.h" &&
			    !h.Contains ("pal/")) {
				headers.Add (h);
			}
		}
		headers.Sort ();
		foreach (string h in headers) {
			header.Append ("#include \"");
			header.Append (h);
			header.AppendLine ("\"");
		}

		header.AppendLine ("namespace Moonlight {");

		header.AppendLine ();
		header.AppendLine ("class MoonUnmanagedFactory {");
		header.AppendLine ("public:");
		header.AppendLine ();

		foreach (MemberInfo member in methods) {
			MethodInfo method = (MethodInfo) member;

			if (!method.Header.StartsWith (dir))
				continue;

			if (method.CMethod.IsConstructor) {
				TypeInfo type = method.ParentType;
				bool emit = false;
				bool ensure = false;

				do {
					if (type.Name == "EventObject") {
						emit = true;
						break;
					}
					else if (type.Name == "DependencyObject") {
						emit = true;
						ensure = true;
						break;
					}

					MemberInfo m = null;
					if (type.Base != null && type.Base.Value != null && info.Children.TryGetValue (type.Base.Value, out m))
						type = (TypeInfo) m;
					else
						break;
				} while (type != null);

				if (emit && !method.Annotations.ContainsKey ("SkipFactories")) {
					WriteFactoryHeaderMethod (method.CMethod, method, header, info, ensure);

					header.AppendLine ();
				}
			}
		}

		header.AppendLine ("};");
		header.AppendLine ();
		header.AppendLine ("class MoonManagedFactory {");
		header.AppendLine ("public:");
		header.AppendLine ();

		foreach (MemberInfo member in methods) {
			MethodInfo method = (MethodInfo) member;

			if (!method.Header.StartsWith (dir))
				continue;

			if (method.CMethod.IsConstructor) {
				TypeInfo type = method.ParentType;
				bool emit = false;

				do {
					if (type.Name == "EventObject") {
						emit = true;
						break;
					}

					MemberInfo m = null;
					if (type.Base != null && type.Base.Value != null && info.Children.TryGetValue (type.Base.Value, out m))
						type = (TypeInfo) m;
					else
						break;
				} while (type != null);

				if (emit && !method.Annotations.ContainsKey ("SkipFactories")) {
					WriteFactoryHeaderMethod (method.CMethod, method, header, info, false);

					header.AppendLine ();
				}
			}
		}

		header.AppendLine ("};");
		header.AppendLine ();
		header.AppendLine ("};");
		header.AppendLine ();
		header.AppendLine ("#endif");

		Helper.WriteAllText (Path.Combine (dir, "factory.h"), header.ToString ());
	}