Here are the examples of the csharp api System.Collections.Generic.List.Insert(int, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
594 Examples
19
View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Update(GameTime gameTime) {
base.Update(gameTime);
_Time += Engine.RawDeltaTime;
_TimeSinceCursorMove += Engine.RawDeltaTime;
bool isRebinding = Engine.Scene == null ||
Engine.Scene.Enreplacedies.FindFirst<KeyboardConfigUI>() != null ||
Engine.Scene.Enreplacedies.FindFirst<ButtonConfigUI>() != null;
if (!(Engine.Scene?.Paused ?? true) || isRebinding) {
string typing = Typing;
Active = false;
Typing = typing;
}
if (!Active && !isRebinding && Settings.ButtonChat.Button.Pressed) {
Active = true;
} else if (Active) {
Engine.Commands.Open = false;
_ControlHeld = MInput.Keyboard.Check(Keys.LeftControl) || MInput.Keyboard.Check(Keys.RightControl);
if (!MInput.Keyboard.Check(Keys.Left) && !MInput.Keyboard.Check(Keys.Right)) {
_CursorMoveFast = false;
_TimeSinceCursorMove = 0;
}
// boolean to determine if Left or Right were already held on previous frame
bool _directionHeldLast = MInput.Keyboard.PreviousState[Keys.Left] == KeyState.Down
|| MInput.Keyboard.PreviousState[Keys.Right] == KeyState.Down;
bool _cursorCanMove = true;
// conditions for the cursor to be moving:
// 1. Don't apply delays on first frame Left/Right is pressed
if (_directionHeldLast) {
// 2. Delay time depends on whether this is the initial delay or subsequent "scrolling" left or right
_cursorCanMove = _TimeSinceCursorMove > (_CursorMoveFast ? _CursorMoveDelay : _CursorInitialMoveDelay);
}
if (MInput.Keyboard.Pressed(Keys.Enter)) {
if (!string.IsNullOrWhiteSpace(Typing))
Repeat.Insert(1, Typing);
Send(Typing);
Active = false;
} else if (MInput.Keyboard.Pressed(Keys.Down) && RepeatIndex > 0) {
RepeatIndex--;
} else if (MInput.Keyboard.Pressed(Keys.Up) && RepeatIndex < Repeat.Count - 1) {
RepeatIndex++;
} else if (MInput.Keyboard.Check(Keys.Left) && _cursorCanMove && CursorIndex > 0) {
if (_ControlHeld) {
// skip over space right before the cursor, if there is one
if (Typing[_CursorIndex - 1] == ' ')
CursorIndex--;
if (CursorIndex > 0) {
int prevWord = Typing.LastIndexOf(" ", _CursorIndex - 1);
CursorIndex = (prevWord < 0) ? 0 : prevWord + 1;
}
} else {
CursorIndex--;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Check(Keys.Right) && _cursorCanMove && CursorIndex < Typing.Length) {
if (_ControlHeld) {
int nextWord = Typing.IndexOf(" ", _CursorIndex);
CursorIndex = (nextWord < 0) ? Typing.Length : nextWord + 1;
} else {
CursorIndex++;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Pressed(Keys.Home)) {
CursorIndex = 0;
} else if (MInput.Keyboard.Pressed(Keys.End)) {
CursorIndex = Typing.Length;
} else if (Input.ESC.Pressed) {
Active = false;
}
}
// Prevent menus from reacting to player input after exiting chat.
if (_ConsumeInput > 0) {
Input.MenuConfirm.ConsumeBuffer();
Input.MenuConfirm.ConsumePress();
Input.ESC.ConsumeBuffer();
Input.ESC.ConsumePress();
Input.Pause.ConsumeBuffer();
Input.Pause.ConsumePress();
_ConsumeInput--;
}
}
19
View Source File : MainWindow.xaml.ManualTab.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
void ManualSend()
{
if (machine.Mode != Machine.OperatingMode.Manual)
return;
string tosend;
tosend = TextBoxManual.Text;
machine.SendLine(tosend);
ManualCommands.Insert(0, tosend);
ManualCommandIndex = -1;
TextBoxManual.Text = "";
}
19
View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
private void RecordCommand(string command) {
m_history.Insert(0, command);
if (m_history.Count > MAX_HISTORY)
m_history.RemoveAt(m_history.Count - 1);
}
19
View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void OnInspectorGUI()
{
serializedObject.Update();
if (!initialized)
this.Init();
//Style for Tips
var foldoutTipStyle = new GUIStyle(EditorStyles.foldout);
foldoutTipStyle.fontStyle = FontStyle.Bold;
//DISPLAY VALUE
EditorGUILayout.PropertyField(serializedObject.FindProperty("DisplayValue"));
//
//=============DNA replacedET AND EDITOR============//
SerializedProperty dnareplacedet = serializedObject.FindProperty("dnareplacedet");
dnareplacedet.isExpanded = EditorGUILayout.Foldout(dnareplacedet.isExpanded, "Dynamic DNA", foldoutTipStyle);
if (dnareplacedet.isExpanded)
{
GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
EditorGUI.indentLevel++;
dnareplacedetInfoExpanded = EditorGUILayout.Foldout(dnareplacedetInfoExpanded, "INFO");
if (dnareplacedetInfoExpanded)
EditorGUILayout.HelpBox("The DynmicDNAreplacedet is the DNA this converter will apply to the skeleton. The DNA consists of names and replacedociated values. Often you display these names as 'sliders'. The values set by these sliders change an Avatar's body proportions by modifying its skeleton bones by the dna value, according to the 'DNA Converter Settings' you set in the 'DNA Converter Settings' section.", MessageType.Info);
if(dnareplacedet.objectReferenceValue == null)
{
//show a tip that people need to create or replacedign a dna replacedet
EditorGUILayout.HelpBox("Create or replacedign a DNA replacedet this converter will use", MessageType.Info);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(dnareplacedet, new GUIContent("DNA replacedet", "A DynamireplacedADnareplacedet contains a list of names that define the 'DNA' that will be used to modify the Avatars Skeleton. Often displayed in the UI as 'sliders'"));
if (EditorGUI.EndChangeCheck())
{
UpdateDnaNames();
serializedObject.ApplyModifiedProperties();
serializedObject.Update();//?
if (minimalMode)
{
//force the Avatar to update its dna and dnaconverter dictionaries
umaData.umaRecipe.ClearDna();
umaData.umaRecipe.ClearDNAConverters();
}
}
//If there is no dna replacedet replacedigned show a button to make one
if (dnareplacedet.objectReferenceValue == null)
{
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel * 15);
if (GUILayout.Button(new GUIContent("Create Dynamic DNA replacedet")))
{
var suggestedPath = replacedetDatabase.GetreplacedetPath(target);
var suggestedName = target.name + "DNAreplacedet";
var path = EditorUtility.SaveFilePanelInProject("Create a new Dynamic DNA replacedet", suggestedName, "replacedet", "some message", suggestedPath);
if (path != "")
{
var newDnareplacedet = CustomreplacedetUtility.Createreplacedet<DynamireplacedADnareplacedet>(path, false);
if (newDnareplacedet != null)
{
//set this replacedet as the used replacedet
dnareplacedet.objectReferenceValue = newDnareplacedet;
serializedObject.ApplyModifiedProperties();
createDnareplacedetName = "";
}
UpdateDnaNames();
if (minimalMode)
{
//force the Avatar to update its dna and dnaconverter dictionaries
umaData.umaRecipe.ClearDna();
umaData.umaRecipe.ClearDNAConverters();
}
}
}
GUILayout.EndHorizontal();
}
//Otherwise show the DNA replacedets Editor
else
{
if (thisDUDA == null)
{
thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
}
else if (thisDUDA.target != (DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue)
{
thisDUDA = Editor.CreateEditor((DynamireplacedADnareplacedet)dnareplacedet.objectReferenceValue, typeof(UMA.CharacterSystem.Editors.DynamireplacedADnareplacedetEditor));
}
EditorGUI.BeginChangeCheck();
thisDUDA.OnInspectorGUI();
if (EditorGUI.EndChangeCheck())
{
UpdateDnaNames();
}
}
EditorGUI.indentLevel--;
GUIHelper.EndVerticalPadded(3);
}
serializedObject.ApplyModifiedProperties();
//===========END DNA replacedET AND EDITOR============//
//
EditorGUILayout.Space();
//
//=============CONVERTER VALUES AND EDITOR=============//
SerializedProperty hashList = serializedObject.FindProperty("hashList");
SerializedProperty skeletonModifiers = serializedObject.FindProperty("skeletonModifiers");
string converterTips = "";
if (minimalMode)
{
converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. The best way to edit these modifiers is to set the DNA slider you want to adjust in the game view, to either its minimum or maximum position. Then add or edit a skeleton modifier in the list below to use that value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
}
else
{
converterTips = "Skeleton Modifiers control how the values of the DNA you set above are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. Add bones you wish to make available to modify in the 'BoneHashes' section. Then add or edit a skeleton modifier in the list below to use a given dna value to modify the skeleton. The 'Value Modifiers' part of a Skeleton Modifier, takes the incoming value, modifies it by the settings and applies it to the bone. The Min and Max values are what that result will be 'clamped' to. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this use the starting pose below instead).";
}
skeletonModifiersExpanded = EditorGUILayout.Foldout(skeletonModifiersExpanded, "DNA Converter Settings", foldoutTipStyle);
if (skeletonModifiersExpanded)
{
GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
if (!minimalMode)
{
EditorGUILayout.HelpBox("TIP: Setting up your DNA Converter's Skeleton Modifiers is much easier if you use the 'DNA Converter Bahaviour Customizer' scene as it can automatically populate the list of available bones with the ones in the generated Avatar's skeleton.", MessageType.Info);
}
EditorGUI.indentLevel++;
skeletonModifiersInfoExpanded = EditorGUILayout.Foldout(skeletonModifiersInfoExpanded, "INFO");
if (skeletonModifiersInfoExpanded)
EditorGUILayout.HelpBox(converterTips, MessageType.Info);
if (!minimalMode)//in minimal mode we dont need to show these because we will have a skeleton that we can get the bonehash list from
{
int hashListCount = hashList.arraySize;
hashList.isExpanded = EditorGUILayout.Foldout(hashList.isExpanded, new GUIContent("Bone Hashes", "These are the bones you have identified that the converter will work on. If you use the Dynamic DNA Customizer Scene these can be set automatically when you add Modifiers") );
if (hashList.isExpanded)
{
EditorGUI.indentLevel++;
extraBonesAddDelOptsExpanded = EditorGUILayout.Foldout(extraBonesAddDelOptsExpanded, "Add/Delete Bones Options");
EditorGUI.indentLevel--;
if (extraBonesAddDelOptsExpanded)
{
//make a drop area for importing bone hashes from another DynamicDnaConverter
var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their names");//cant click to pick unfortunately because this is a prefab
var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
for (int i = 0; i < dnaNamesAddOpts.Count; i++)
AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
Rect selectedAddMethodRect = dropArea;
selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
selectedBonesAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the bones to the current list, or 'Replace' them with the imported ones"), selectedBonesAddMethod, AddMethods);
ImportConverterDropArea(dropArea, selectedBonesAddMethod, AddDNAConverterHashes);
EditorGUILayout.Space();
//Clear all and Add Defaults Buttons
Rect clearAndDefaultsRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
clearAndDefaultsRect.xMin = clearAndDefaultsRect.xMin + (EditorGUI.indentLevel * 15);
var defaultsButRect = clearAndDefaultsRect;
var clearButRect = clearAndDefaultsRect;
defaultsButRect.width = clearAndDefaultsRect.width / 2;
clearButRect.xMin = defaultsButRect.xMax;
clearButRect.width = clearAndDefaultsRect.width / 2;
if (GUI.Button(defaultsButRect, new GUIContent("Add Default Hashes", "Adds the default bone hashes as used by UMA Human Male DNA")))
{
AddDefaultBoneHashes();
//once we add these we need to update the hashnames so the dropdown has the right stuff in
hashList.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
UpdateHashNames();
}
EditorGUI.BeginDisabledGroup(hashList.arraySize == 0);
if (GUI.Button(clearButRect, new GUIContent("Clear All Bone Hashes", "Clears the current Bone Hashes. Cannot be undone.")))
{
bool proceed = true;
//if there are any skeleton modifiers that are using these bone hashes warn the user that clearing this list will break them
if (skeletonModifiers.arraySize > 0)
proceed = EditorUtility.DisplayDialog("Really Clear All Bone Hashes?", "This will delete all the bone hashes in the list and make any skeleton modifiers you have added not work. Are you sure?", "Yes", "Cancel");
if (proceed)
{
(target as DynamicDNAConverterBehaviour).hashList = new List<DynamicDNAConverterBehaviour.HashLisreplacedem>();
hashList.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
UpdateHashNames();
}
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
}
//create an add field for adding new hashes
EditorGUILayout.BeginHorizontal();
//var buttonDisabled = newHashName == "";
bool canAdd = true;
bool notFoundInSkeleton = false;
bool didAdd = false;
EditorGUI.BeginChangeCheck();
newHashName = EditorGUILayout.TextField(newHashName);
if (EditorGUI.EndChangeCheck())
{
if (newHashName != "" && canAdd)
{
//buttonDisabled = false;
}
}
if (newHashName != "")
{
for (int ni = 0; ni < hashList.arraySize; ni++)
{
if (hashList.GetArrayElementAtIndex(ni).FindPropertyRelative("hashName").stringValue == newHashName)
{
canAdd = false;
//buttonDisabled = true;
}
}
//if we have a skeleton available we can also check that the bone the user is trying to add exists
if (umaData)
if (umaData.skeleton != null)
{
if (umaData.skeleton.HasBone(UMAUtils.StringToHash(newHashName)) == false)
{
canAdd = false;
//buttonDisabled = true;
notFoundInSkeleton = true;
}
}
}
//Dont disable because it stops looking like what you want to do, just make it do nothing if nothing is entered
/*if (buttonDisabled)
{
EditorGUI.BeginDisabledGroup(true);
}*/
if (GUILayout.Button("Add Bone Hash"))
{
if (canAdd)
{
var newHash = UMAUtils.StringToHash(newHashName);
(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(newHashName, newHash));
hashList.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
didAdd = true;
UpdateHashNames();
//reset the bloody text field!
EditorGUIUtility.keyboardControl = 0;
}
}
/*if (buttonDisabled)
{
EditorGUI.EndDisabledGroup();
}*/
EditorGUILayout.EndHorizontal();
if (canAdd == false)
{
if (notFoundInSkeleton == true)
{
EditorGUILayout.HelpBox("That name was not found in the skeleton. (Standard Bone names start with a capital letter in CamelCase)", MessageType.Warning);
}
else
{
EditorGUILayout.HelpBox("That name is already in use.", MessageType.Warning);
}
}
if (didAdd)
{
newHashName = "";
}
//THE ACTUAL BONE HASH LIST
GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
EditorGUILayout.LabelField("Bone Hash List (" + hashListCount + ")", EditorStyles.helpBox);
//Search Bone Hashes Controls
if (hashList.arraySize > 0)
boneHashFilter = EditorGUILayout.TextField("Search Bones", boneHashFilter);
EditorGUI.indentLevel++;
if (hashList.arraySize > 0)
{
for (int i = 0; i < hashList.arraySize; i++)
{
var thisHashEl = hashList.GetArrayElementAtIndex(i);
//Search Bone Hashes Method
if (boneHashFilter.Length >= 3)
{
if (thisHashEl.displayName.IndexOf(boneHashFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
EditorGUILayout.BeginHorizontal();
thisHashEl.isExpanded = EditorGUILayout.Foldout(thisHashEl.isExpanded, thisHashEl.displayName);
//DeleteButton
Rect hDelButR = EditorGUILayout.GetControlRect(false);
hDelButR.x = hDelButR.x + hDelButR.width - 100f;
hDelButR.width = 100f;
if (GUI.Button(hDelButR, "Delete"))
{
hashList.DeleteArrayElementAtIndex(i);
continue;
}
EditorGUILayout.EndHorizontal();
if (thisHashEl.isExpanded)
{
EditorGUI.indentLevel++;
string origName = thisHashEl.FindPropertyRelative("hashName").stringValue;
string newName = origName;
EditorGUI.BeginChangeCheck();
newName = EditorGUILayout.TextField("Hash Name", origName);
if (EditorGUI.EndChangeCheck())
{
if (newName != origName && newName != "")
{
thisHashEl.FindPropertyRelative("hashName").stringValue = newName;
int newHash = UMAUtils.StringToHash(newName);
thisHashEl.FindPropertyRelative("hash").intValue = newHash;
serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.IntField("Hash", thisHashEl.FindPropertyRelative("hash").intValue);
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
}
}
hashList.serializedObject.ApplyModifiedProperties();
EditorGUILayout.Space();
}
EditorGUI.indentLevel--;
GUIHelper.EndVerticalPadded(3);
}
}
//SKELETON MODIFIERS SECTION
skeletonModifiers.isExpanded = EditorGUILayout.Foldout(skeletonModifiers.isExpanded, "Skeleton Modifiers");
if (skeletonModifiers.isExpanded)
{
//If dnaNames is null or empty show a warning
bool showDNANamesWarning = false;
if (serializedObject.FindProperty("dnareplacedet").objectReferenceValue == null)
showDNANamesWarning = true;
else if((serializedObject.FindProperty("dnareplacedet").objectReferenceValue as DynamireplacedADnareplacedet).Names.Length == 0)
showDNANamesWarning = true;
if(showDNANamesWarning)
EditorGUILayout.HelpBox("You need to have your DNA Names set up above in order for the Skeleton Modifiers to make any modifications", MessageType.Warning);
//If bone hashes is empty show a warning
if(hashList.arraySize == 0 && !minimalMode)
EditorGUILayout.HelpBox("You need to add the bones you want the Skeleton Modifiers to be able to modify to the 'Bone Hashes' section above.", MessageType.Warning);
EditorGUI.indentLevel++;
extraSkelAddDelOptsExpanded = EditorGUILayout.Foldout(extraSkelAddDelOptsExpanded, "Add/Delete Modifier Options");
EditorGUI.indentLevel--;
if (extraSkelAddDelOptsExpanded)
{
//make a drop area for importing skeletonModifiers from another DynamicDnaConverter
var dropArea = GUILayoutUtility.GetRect(0.0f, 60.0f, GUILayout.ExpandWidth(true));
dropArea.xMin = dropArea.xMin + (EditorGUI.indentLevel * 15);
GUI.Box(dropArea, "Drag DynamicDNAConverterBahaviours here to import their Skeleton Modifiers");//cant click to pick unfortunately because this is a prefab
var AddMethods = new GUIContent[dnaNamesAddOpts.Count];
for (int i = 0; i < dnaNamesAddOpts.Count; i++)
AddMethods[i] = new GUIContent(dnaNamesAddOpts[i]);
Rect selectedAddMethodRect = dropArea;
selectedAddMethodRect.yMin = dropArea.yMax - EditorGUIUtility.singleLineHeight - 5;
selectedAddMethodRect.xMin = dropArea.xMin - ((EditorGUI.indentLevel * 10) - 10);
selectedAddMethodRect.xMax = dropArea.xMax - ((EditorGUI.indentLevel * 10) + 10);
selectedModifiersAddMethod = EditorGUI.Popup(selectedAddMethodRect, new GUIContent("On Import", "Choose whether to 'Add' the modifiers to the current list, or 'Replace' the modifiers with the imported list"), selectedModifiersAddMethod, AddMethods);
ImportConverterDropArea(dropArea, selectedModifiersAddMethod, AddDNAConverterModifiers);
//Clear all button
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel * 15);
EditorGUI.BeginDisabledGroup(skeletonModifiers.arraySize == 0);
if (GUILayout.Button("Clear All Modifiers"))
{
if (EditorUtility.DisplayDialog("Really Clear All Modifiers?", "This will delete all the skeleton modifiers in the list and cannot be undone. Are you sure?", "Yes", "Cancel"))
{
(target as DynamicDNAConverterBehaviour).skeletonModifiers = new List<DynamicDNAConverterBehaviour.SkeletonModifier>();
skeletonModifiers.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
}
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
EditorGUILayout.Space();
}
//Add new Skeleton Modifier UI
Rect addSkelButsR = EditorGUILayout.GetControlRect(false);
var addSkelLabel = addSkelButsR;
var addSkelBone = addSkelButsR;
var addSkelProp = addSkelButsR;
var addSkelAddBut = addSkelButsR;
addSkelLabel.width = 100;
addSkelAddBut.width = 70;
addSkelBone.width = addSkelProp.width = (addSkelButsR.width - (addSkelLabel.width + (addSkelAddBut.width + 5))) / 2;
addSkelBone.x = addSkelLabel.xMax;
addSkelProp.x = addSkelBone.xMax;
addSkelAddBut.x = addSkelProp.xMax + 5;
EditorGUI.LabelField(addSkelLabel, new GUIContent("Add Modifier", "Add a modifier for the selected bone in the skeleton, that will modify its 'Position', 'Rotation' or 'Scale'"));
EditorGUI.indentLevel--;
List<string> thisBoneNames = new List<string>(0);
//string[] boneNames = new string[0];
/*if(minimalMode == false)
{
bonesInSkeleton = new List<string>( hashNames.ToArray());
}
else
{
bonesInSkeleton = new List<string>(umaData.skeleton.BoneNames);
}
bonesInSkeleton.Sort();*/
//Array.Sort(boneNames);
thisBoneNames = new List<string>(bonesInSkeleton);
thisBoneNames.Insert(0, "Choose Bone");
EditorGUI.BeginChangeCheck();
selectedAddHash = EditorGUI.Popup(addSkelBone, selectedAddHash, thisBoneNames.ToArray());
string[] propertyArray = new string[] { "Position", "Rotation", "Scale" };
selectedAddProp = EditorGUI.Popup(addSkelProp, selectedAddProp, propertyArray);
if (EditorGUI.EndChangeCheck())
{
if (selectedAddHash > 0)
{
addSkelBoneName = thisBoneNames[selectedAddHash];
addSkelBoneHash = UMAUtils.StringToHash(addSkelBoneName);
}
else
{
addSkelBoneName = "";
addSkelBoneHash = 0;
canAddSkel = false;
}
}
if (addSkelBoneName != "" && addSkelBoneHash != 0)
{
canAddSkel = true;
alreadyExistedSkel = false;
//we need to check if there is already a modifier for that bone for the selected property
for (int i = 0; i < skeletonModifiers.arraySize; i++)
{
var thisSkelMod = skeletonModifiers.GetArrayElementAtIndex(i);
if (thisSkelMod.FindPropertyRelative("property").enumValueIndex == selectedAddProp && thisSkelMod.FindPropertyRelative("hash").intValue == addSkelBoneHash)
{
canAddSkel = false;
alreadyExistedSkel = true;
}
}
}
if (canAddSkel == false)
{
EditorGUI.BeginDisabledGroup(true);
}
if (GUI.Button(addSkelAddBut, "Add It!"))
{
if (minimalMode)
{
if (!hashes.Contains(addSkelBoneHash))
{
(target as DynamicDNAConverterBehaviour).hashList.Insert(0, new DynamicDNAConverterBehaviour.HashLisreplacedem(addSkelBoneName, addSkelBoneHash));
hashList.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
UpdateHashNames();
}
}
(target as DynamicDNAConverterBehaviour).skeletonModifiers.Insert(0, new DynamicDNAConverterBehaviour.SkeletonModifier(addSkelBoneName, addSkelBoneHash, (DynamicDNAConverterBehaviour.SkeletonModifier.SkeletonPropType)selectedAddProp));
skeletonModifiers.serializedObject.ApplyModifiedProperties();
serializedObject.Update();
addSkelBoneHash = 0;
addSkelBoneName = "";
selectedAddHash = 0;
EditorGUIUtility.keyboardControl = 0;
}
if (canAddSkel == false)
{
EditorGUI.EndDisabledGroup();
}
if (alreadyExistedSkel == true)
{
EditorGUILayout.HelpBox("There was already a modifier for that bone with that property. You can serach the existing modifiers to find it.", MessageType.Warning);
}
EditorGUI.indentLevel++;
//Search Filters Controls- dont show if we dont have any modifiers
EditorGUILayout.Space();
//THE ACTUAL MODIFIER LIST
GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
EditorGUILayout.LabelField("Skeleton Modifiers (" + skeletonModifiers.arraySize + ")", EditorStyles.helpBox);
if (skeletonModifiers.arraySize > 0)
{
Rect searchR = EditorGUILayout.GetControlRect();
var searchL = searchR;
var searchF = searchR;
var searchTL = searchR;
var searchTF = searchR;
searchL.width = 130;
searchF.width = (searchR.width / 3) * 2 - searchL.width;
searchF.x = searchR.x + searchL.width;
searchTL.width = 35;
searchTL.x = searchF.xMax;
searchTF.width = (searchR.width / 3) - searchTL.width + (EditorGUI.indentLevel * 15);
searchTF.x = searchTL.xMax - (EditorGUI.indentLevel * 15);
EditorGUI.LabelField(searchL, "Search Modifiers");
EditorGUI.indentLevel--;
skeletonModifiersFilter = EditorGUI.TextField(searchF, skeletonModifiersFilter);
EditorGUI.LabelField(searchTL, "By");
skeletonModifiersFilterType = EditorGUI.Popup(searchTF, skeletonModifiersFilterType, skeletonModifiersFilterTypeList);
EditorGUI.indentLevel++;
}
EditorGUI.indentLevel++;
for (int i = 0; i < skeletonModifiers.arraySize; i++)
{
var thisSkelEl = skeletonModifiers.GetArrayElementAtIndex(i);
//Search Filters Method
if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
{
if (skeletonModifiersFilterType == 1 || skeletonModifiersFilterType == 2 || skeletonModifiersFilterType == 3)
{
string thisProperty = thisSkelEl.FindPropertyRelative("property").enumNames[thisSkelEl.FindPropertyRelative("property").enumValueIndex];
if (skeletonModifiersFilterType == 1)//Position Modifiers
{
if (thisProperty.IndexOf("position", StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
else if (skeletonModifiersFilterType == 2)//Rotation Modifiers
{
if (thisProperty.IndexOf("rotation", StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
else if (skeletonModifiersFilterType == 3)//scale Modifiers
{
if (thisProperty.IndexOf("scale", StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
}
else if (skeletonModifiersFilterType == 5)//Adjust Bones
{
if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
else if (skeletonModifiersFilterType == 6)//Non Adjust Bones
{
if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) > -1)
continue;
}
}
if (skeletonModifiersFilter.Length >= 3)
{
if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA")
{
if (thisSkelEl.displayName.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) == -1)
continue;
}
else //Searches for Modifiers that use a given DNA Value- slow but super handy
{
string[] XYZ = new string[] { "X", "Y", "Z" };
SerializedProperty mods;
SerializedProperty thisMod;
int modsi;
bool _continue = true;
foreach (string xyz in XYZ)
{
mods = thisSkelEl.FindPropertyRelative("values" + xyz).FindPropertyRelative("val").FindPropertyRelative("modifiers");
for (int mi = 0; mi < mods.arraySize; mi++)
{
thisMod = mods.GetArrayElementAtIndex(mi);
modsi = thisMod.FindPropertyRelative("modifier").enumValueIndex;
if (modsi > 3)
{
if (thisMod.FindPropertyRelative("DNATypeName").stringValue.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) > -1)
_continue = false;
}
}
}
if (_continue)
{
continue;
}
}
}
Rect currentRect = EditorGUILayout.GetControlRect(false, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
//Delete button
Rect sDelButR = currentRect;
sDelButR.x = sDelButR.x + sDelButR.width - 100f;
sDelButR.width = 100f;
sDelButR.height = EditorGUIUtility.singleLineHeight;
if (GUI.Button(sDelButR, "Delete"))
{
skeletonModifiers.DeleteArrayElementAtIndex(i);
continue;
}
Rect thisSkelRect = new Rect(currentRect.xMin, currentRect.yMin, currentRect.width, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none));
_skelModPropDrawer.OnGUI(thisSkelRect, thisSkelEl, new GUIContent(thisSkelEl.displayName));
}
GUIHelper.EndVerticalPadded(3);
EditorGUI.indentLevel--;
//we want to discourage users from using the starting values to customise their models (if they have any modifiers set up
if (skeletonModifiers.arraySize > 0)
{
_skelModPropDrawer.enableSkelModValueEditing = enableSkelModValueEditing = EditorGUILayout.ToggleLeft("Enable editing of starting Value (not reccommended)", enableSkelModValueEditing);
//and make it easy to set the starting values back to the defaults
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel * 15);
if (GUILayout.Button("Reset All Starting Values to Default"))
{
for (int i = 0; i < skeletonModifiers.arraySize; i++)
{
var thisSkeModProp = skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumNames[skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumValueIndex];
if (thisSkeModProp != "")
{
if (thisSkeModProp == "Position" || thisSkeModProp == "Rotation")
{
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f;
}
if (thisSkeModProp == "Scale")
{
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f;
}
}
}
skeletonModifiers.serializedObject.ApplyModifiedProperties();
}
GUILayout.EndHorizontal();
}
EditorGUILayout.Space();
}
EditorGUILayout.Space();
serializedObject.FindProperty("overallModifiersEnabled").boolValue = EditorGUILayout.ToggleLeft("Enable Overall Modifiers", serializedObject.FindProperty("overallModifiersEnabled").boolValue);
SerializedProperty overallModifiersEnabledProp = serializedObject.FindProperty("overallModifiersEnabled");
bool overallModifiersEnabled = overallModifiersEnabledProp.boolValue;
if (overallModifiersEnabled)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedObject.FindProperty("overallScale"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("tightenBounds"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("boundsAdjust"));
//EditorGUILayout.PropertyField(serializedObject.FindProperty("heightModifiers"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("radiusAdjust"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("mreplacedModifiers"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.indentLevel--;
GUIHelper.EndVerticalPadded(3);
}
serializedObject.ApplyModifiedProperties();
//===========END CONVERTER VALUES AND EDITOR============//
//
EditorGUILayout.Space();
//
//===========BONEPOSE replacedET AND EDITOR===========//
startingPoseExpanded = EditorGUILayout.Foldout(startingPoseExpanded, "Starting Pose", foldoutTipStyle);
if (startingPoseExpanded)
{
GUIHelper.BeginVerticalPadded(3, new Color(0.75f, 0.875f, 1f, 0.3f));
EditorGUI.indentLevel++;
startingPoseInfoExpanded = EditorGUILayout.Foldout(startingPoseInfoExpanded, "INFO");
if (startingPoseInfoExpanded)
EditorGUILayout.HelpBox("The 'Starting Pose'is the initial position/rotation/scale of all the bones in this Avatar's skeleton. Use this to completely transform the mesh of your character. You could (for example) transform standard UMA characters into a backwards compatible 'Short Squat Dwarf' or a 'Bobble- headded Toon'. Optionally, you can create an UMABonePose replacedet from an FBX model using the UMA > Pose Tools > Bone Pose Builder and add the resulting replacedet here. After you have added or created a UMABonePose replacedet, you can add and edit the position, rotation and scale settings for any bone in the active character's skeleton in the 'Bone Poses' section.'.", MessageType.Info);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPose"), new GUIContent("Starting UMABonePose", "Define an replacedet that will set the starting bone poses of any Avatar using this converter"));
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
//If this gets set we need to back it up
thisDDCC.BackupConverter();
}
//Draw the poses array from the replacedet if set or show controls to create a new replacedet.
SerializedProperty bonePosereplacedet = serializedObject.FindProperty("startingPose");
if (bonePosereplacedet.objectReferenceValue != null)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPoseWeight"));
if (thisUBP == null)
{
thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
if (umaData != null)
{
((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
}
}
else if (thisUBP.target != (UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue)
{
thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePosereplacedet.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor));
((UMA.PoseTools.UMABonePoseEditor)thisUBP).dynamicDNAConverterMode = true;
if (umaData != null)
{
((UMA.PoseTools.UMABonePoseEditor)thisUBP).context = new UMA.PoseTools.UMABonePoseEditorContext();
((UMA.PoseTools.UMABonePoseEditor)thisUBP).context.activeUMA = umaData;
}
}
EditorGUI.BeginChangeCheck();
thisUBP.OnInspectorGUI();
if (EditorGUI.EndChangeCheck())
{
//Currently we dont need to do anything here as the change is picked up by DynamicDNAConverterCustomizer an this triggers an UMA update
//this may change though if we have a method in future for modifying the TPose
}
}
else
{
if (thisDDCC != null)
{
var createPosereplacedetR = EditorGUILayout.GetControlRect(false);
var createPosereplacedetRLabel = createPosereplacedetR;
var createPosereplacedetRField = createPosereplacedetR;
var createPosereplacedetRButton = createPosereplacedetR;
createPosereplacedetRLabel.width = createPosereplacedetRLabel.width / 3 + 7;
createPosereplacedetRButton.width = 70f;
createPosereplacedetRField.width = ((createPosereplacedetRField.width / 3) * 2) - 82;
createPosereplacedetRField.x = createPosereplacedetRLabel.xMax;
createPosereplacedetRButton.x = createPosereplacedetRField.xMax + 5;
EditorGUI.LabelField(createPosereplacedetRLabel, new GUIContent("New BonePose replacedet", "Create a new empty UMABonePose with the name of your choosing."));
createBonePosereplacedetName = EditorGUI.TextField(createPosereplacedetRField, createBonePosereplacedetName);
if (GUI.Button(createPosereplacedetRButton, "Create It"))//need to do the button enabled thing here
{
var newDnareplacedet = thisDDCC.CreatePosereplacedet("", createBonePosereplacedetName);
if (newDnareplacedet != null)
{
//set this replacedet as the used replacedet
bonePosereplacedet.objectReferenceValue = newDnareplacedet;
serializedObject.ApplyModifiedProperties();
createBonePosereplacedetName = "";
}
}
}
else
{
EditorGUILayout.HelpBox("Edit a character that uses this converter in the 'DynamicDna Converter Behaviour Customizer' scene and you can create a StartingPosereplacedet automatically here", MessageType.Info);
}
}
if (minimalMode && umaData.skeleton != null && bonePosereplacedet.objectReferenceValue == null)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Create Poses from Current DNA state");
EditorGUILayout.HelpBox("Create bone poses from Avatar's current dna modified state. Applies the pose and sets DNA values back to 0. Smaller margin of error equals greater accuracy but more poses to apply on DNA Update.", MessageType.Info);
if (thisDDCC != null)
{
//[Range(0.000005f, 0.0005f)]
EditorGUI.BeginChangeCheck();
var thisAccuracy = EditorGUILayout.Slider(new GUIContent("Margin Of Error","The smaller the margin of error, the more accurate the Pose will be, but it will also have more bonePoses to apply when DNA is updated"), thisDDCC.bonePoseAccuracy * 1000, 0.5f, 0.005f);
if (EditorGUI.EndChangeCheck())
{
thisDDCC.bonePoseAccuracy = thisAccuracy / 1000;
GUI.changed = false;
}
}
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel * 20);
if (GUILayout.Button(/*createFromDnaButR, */"Create Poses"))
{
if (thisDDCC != null)
{
if (thisDDCC.CreateBonePosesFromCurrentDna(createBonePosereplacedetName))
{
serializedObject.Update();
}
}
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
GUIHelper.EndVerticalPadded(3);
}
serializedObject.ApplyModifiedProperties();
//=============END BONEPOSE replacedET AND EDITOR============//
//
EditorGUILayout.Space();
}
19
View Source File : UMABonePoseEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void OnInspectorGUI()
{
serializedObject.Update();
SerializedProperty poses = serializedObject.FindProperty("poses");
if (doBoneAdd)
{
int addedIndex = poses.arraySize;
poses.InsertArrayElementAtIndex(addedIndex);
var pose = poses.GetArrayElementAtIndex(addedIndex);
SerializedProperty bone = pose.FindPropertyRelative("bone");
bone.stringValue = addBoneName;
SerializedProperty hash = pose.FindPropertyRelative("hash");
hash.intValue = UMASkeleton.StringToHash(addBoneName);
SerializedProperty position = pose.FindPropertyRelative("position");
position.vector3Value = Vector3.zero;
SerializedProperty rotation = pose.FindPropertyRelative("rotation");
rotation.quaternionValue = Quaternion.idenreplacedy;
SerializedProperty scale = pose.FindPropertyRelative("scale");
scale.vector3Value = Vector3.one;
activeBoneIndex = BAD_INDEX;
editBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
addBoneIndex = 0;
addBoneName = "";
doBoneAdd = false;
}
if (doBoneRemove)
{
poses.DeleteArrayElementAtIndex(removeBoneIndex - 1);
activeBoneIndex = BAD_INDEX;
editBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
removeBoneIndex = 0;
doBoneRemove = false;
}
// HACK
if (!dynamicDNAConverterMode)
{
sourceUMA = EditorGUILayout.ObjectField("Source UMA", sourceUMA, typeof(UMAData), true) as UMAData;
if (sourceUMA != null)
{
if (context == null)
{
context = new UMABonePoseEditorContext();
}
if (context.activeUMA != sourceUMA)
{
context.activeUMA = sourceUMA;
}
}
}
// Weight of pose on preview model
if (haveValidContext && !dynamicDNAConverterMode)
{
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
EditorGUI.BeginDisabledGroup(haveEditTarget);
previewWeight = EditorGUILayout.Slider(previewGUIContent, previewWeight, 0f, 1f);
EditorGUI.EndDisabledGroup();
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
}
GUILayout.Space(EditorGUIUtility.singleLineHeight / 2f);
// string controlName = GUI.GetNameOfFocusedControl();
// if ((controlName != null) && (controlName.Length > 0))
// Debug.Log(controlName);
// These can get corrupted by undo, so just rebuild them
string[] removeBoneOptions = new string[targetPose.poses.Length + 1];
removeBoneOptions[0] = " ";
for (int i = 0; i < targetPose.poses.Length; i++)
{
removeBoneOptions[i + 1] = targetPose.poses[i].bone;
}
string[] addBoneOptions = new string[1];
if (haveValidContext)
{
List<string> addList = new List<string>(context.boneList);
addList.Insert(0, " ");
for (int i = 0; i < targetPose.poses.Length; i++)
{
addList.Remove(targetPose.poses[i].bone);
}
addBoneOptions = addList.ToArray();
}
// List of existing bones
poses.isExpanded = EditorGUILayout.Foldout(poses.isExpanded, "Pose Bones ("+poses.arraySize+")");
if (poses.isExpanded)
{
for (int i = 0; i < poses.arraySize; i++)
{
SerializedProperty pose = poses.GetArrayElementAtIndex(i);
drawBoneIndex = i;
PoseBoneDrawer(pose);
}
}
GUILayout.Space(EditorGUIUtility.singleLineHeight);
// Controls for adding a new bone
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
if (haveValidContext)
{
EditorGUI.BeginDisabledGroup(addBoneIndex < 1);
if (GUILayout.Button(addBoneGUIContent, GUILayout.Width(90f)))
{
addBoneName = addBoneOptions[addBoneIndex];
doBoneAdd = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
addBoneIndex = EditorGUILayout.Popup(addBoneIndex, addBoneOptions);
EditorGUILayout.EndVertical();
}
else
{
EditorGUI.BeginDisabledGroup(addBoneName.Length < minBoneNameLength);
if (GUILayout.Button(addBoneGUIContent, GUILayout.Width(90f)))
{
doBoneAdd = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
addBoneName = EditorGUILayout.TextField(addBoneName);
EditorGUILayout.EndVertical();
}
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
// Controls for removing existing bone
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
EditorGUI.BeginDisabledGroup(removeBoneIndex < 1);
if (GUILayout.Button(removeBoneGUIContent, GUILayout.Width(90f)))
{
doBoneRemove = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
removeBoneIndex = EditorGUILayout.Popup(removeBoneIndex, removeBoneOptions);
EditorGUILayout.EndVertical();
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
}
19
View Source File : SkeletonModifierPropertyDrawer.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
int startingIndent = EditorGUI.indentLevel;
EditorGUI.BeginProperty(position, label, property);
var valR = new Rect(position.xMin, position.yMin, position.width, EditorGUIUtility.singleLineHeight);
string betterLabel = label.text;
if (property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] != "")
{
betterLabel += " (" + property.FindPropertyRelative("property").enumDisplayNames[property.FindPropertyRelative("property").enumValueIndex] + ")";
}
List<string> boneNames = new List<string>();
if (bonesInSkeleton != null)
{
boneNames = new List<string>(bonesInSkeleton);
}
else
{
boneNames = new List<string>(hashNames);
}
string thisHashName = property.FindPropertyRelative("hashName").stringValue;
int hashNameIndex = boneNames.IndexOf(thisHashName);
if (hashNameIndex == -1 && bonesInSkeleton != null)
{
boneNames.Insert(0, thisHashName + " (missing)");
hashNameIndex = 0;
var warningRect = new Rect((valR.xMin), valR.yMin, 20f, valR.height);
var warningIconGUI = new GUIContent("", thisHashName + " was not a bone in the Avatars Skeleton. Please choose another bone for this modifier or delete it.");
warningIconGUI.image = warningIcon;
betterLabel += " (missing)";
GUI.Label(warningRect, warningIconGUI, warningStyle);
}
property.isExpanded = EditorGUI.Foldout(valR, property.isExpanded, betterLabel, true);
if (property.isExpanded)
{
EditorGUI.indentLevel++;
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
if (boneNames.Count > 0)
{
int newHashNameIndex = hashNameIndex;
EditorGUI.BeginChangeCheck();
newHashNameIndex = EditorGUI.Popup(valR, "Hash Name", hashNameIndex, boneNames.ToArray());
if (EditorGUI.EndChangeCheck())
{
if (newHashNameIndex != hashNameIndex)
{
property.FindPropertyRelative("hashName").stringValue = boneNames[newHashNameIndex];
property.FindPropertyRelative("hash").intValue = UMAUtils.StringToHash(boneNames[newHashNameIndex]);
property.serializedObject.ApplyModifiedProperties();
}
}
}
else
{
EditorGUI.PropertyField(valR, property.FindPropertyRelative("hashName"));
}
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
EditorGUI.PropertyField(valR, property.FindPropertyRelative("property"));
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var valXR = valR;
var valYR = valR;
var valZR = valR;
valXR.width = valYR.width = valZR.width = valR.width / 3;
valYR.x = valYR.x + valXR.width;
valZR.x = valZR.x + valXR.width + valYR.width;
SerializedProperty subValsToOpen = null;
var valuesX = property.FindPropertyRelative("valuesX");
var valuesY = property.FindPropertyRelative("valuesY");
var valuesZ = property.FindPropertyRelative("valuesZ");
if (valuesX.isExpanded)
{
var valXRB = valXR;
valXRB.x = valXRB.x + (EditorGUI.indentLevel * 10f);
valXRB.width = valXRB.width - (EditorGUI.indentLevel * 10f);
EditorGUI.DrawRect(valXRB, new Color32(255, 255, 255, 100));
}
valuesX.isExpanded = EditorGUI.Foldout(valXR, valuesX.isExpanded, "ValuesX", true);
if (valuesX.isExpanded)
{
valuesY.isExpanded = false;
valuesZ.isExpanded = false;
subValsToOpen = valuesX;
}
if (valuesY.isExpanded)
{
EditorGUI.DrawRect(valYR, new Color32(255, 255, 255, 100));
}
valuesY.isExpanded = EditorGUI.Foldout(valYR, valuesY.isExpanded, "ValuesY", true);
if (valuesY.isExpanded)
{
valuesX.isExpanded = false;
valuesZ.isExpanded = false;
subValsToOpen = valuesY;
}
if (valuesZ.isExpanded)
{
EditorGUI.DrawRect(valZR, new Color32(255, 255, 255, 100));
}
valuesZ.isExpanded = EditorGUI.Foldout(valZR, valuesZ.isExpanded, "ValuesZ", true);
if (valuesZ.isExpanded)
{
valuesX.isExpanded = false;
valuesY.isExpanded = false;
subValsToOpen = valuesZ;
}
if (subValsToOpen != null)
{
valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
valR.width = valR.width - 30;
var boxR1 = valR;
boxR1.x = boxR1.x + EditorGUI.indentLevel * 10f;
boxR1.y = boxR1.y - 6;
boxR1.height = boxR1.height + 12;
//topbox
EditorGUI.DrawRect(boxR1, new Color32(255, 255, 255, 100));
var valSXR = valR;
var valSYR = valR;
var valSZR = valR;
valSXR.width = valSYR.width = valSZR.width = valR.width / 3;
valSYR.x = valSYR.x + valSXR.width;
valSZR.x = valSZR.x + valSXR.width + valSYR.width;
var subValuesVal = subValsToOpen.FindPropertyRelative("val");
var subValuesMin = subValsToOpen.FindPropertyRelative("min");
var subValuesMax = subValsToOpen.FindPropertyRelative("max");
var valSXRF = valSXR;
valSXRF.x = valSXRF.x + 38f;
valSXRF.width = valSXRF.width - 35f;
if (!enableSkelModValueEditing) EditorGUI.BeginDisabledGroup(true);
EditorGUI.LabelField(valSXR, "Value");
subValuesVal.FindPropertyRelative("value").floatValue = EditorGUI.FloatField(valSXRF, subValuesVal.FindPropertyRelative("value").floatValue);
subValuesVal.serializedObject.ApplyModifiedProperties();
if (!enableSkelModValueEditing) EditorGUI.EndDisabledGroup();
var valSYRF = valSYR;
valSYRF.x = valSYRF.x + 30f;
valSYRF.width = valSYRF.width - 30f;
EditorGUI.LabelField(valSYR, "Min");
subValuesMin.floatValue = EditorGUI.FloatField(valSYRF, subValuesMin.floatValue);
var valSZRF = valSZR;
valSZRF.x = valSZRF.x + 30f;
valSZRF.width = valSZRF.width - 30f;
EditorGUI.LabelField(valSZR, "Max");
subValuesMax.floatValue = EditorGUI.FloatField(valSZRF, subValuesMax.floatValue);
var thisModifiersProp = subValuesVal.FindPropertyRelative("modifiers");
var modifiersi = thisModifiersProp.arraySize;
valR = new Rect(valR.xMin, valR.yMax + padding + 4f, valR.width, EditorGUIUtility.singleLineHeight);
var boxR = valR;
boxR.y = boxR.y - 2f;
boxR.x = boxR.x + EditorGUI.indentLevel * 10f;
boxR.height = boxR.height + 6f + ((EditorGUIUtility.singleLineHeight + padding) * (modifiersi + 1));
//bottombox
EditorGUI.DrawRect(boxR, new Color32(255, 255, 255, 100));
EditorGUI.LabelField(valR, "Value Modifiers");
for (int i = 0; i < modifiersi; i++)
{
valR = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
var propsR = valR;
propsR.width = valR.width;
var valRBut = new Rect((propsR.width + 35f), valR.y, 20f, EditorGUIUtility.singleLineHeight);
thisSpValDrawer.OnGUI(propsR, thisModifiersProp.GetArrayElementAtIndex(i), new GUIContent(""));
if (GUI.Button(valRBut, "X"))
{
thisModifiersProp.DeleteArrayElementAtIndex(i);
}
}
var addBut = new Rect(valR.xMin, valR.yMax + padding, valR.width, EditorGUIUtility.singleLineHeight);
addBut.x = addBut.xMax - 35f;
addBut.width = 60f;
if (GUI.Button(addBut, "Add"))
{
thisModifiersProp.InsertArrayElementAtIndex(modifiersi);
}
thisModifiersProp.serializedObject.ApplyModifiedProperties();
}
}
EditorGUI.indentLevel = startingIndent;
EditorGUI.EndProperty();
}
19
View Source File : TestCustomizerDD.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void InitializeWardrobeDropDowns()
{
List<string> slotsFromAllRaces = new List<string>();
foreach (string race in characterSystem.Recipes.Keys)
{
int i = 0;
foreach (string slot in characterSystem.Recipes[race].Keys)
{
if (!slotsFromAllRaces.Contains(slot) && ((limitWardrobeOptions.Count == 0 || limitWardrobeOptions.Contains(slot)) && !hideWardrobeOptions.Contains(slot)))
{
slotsFromAllRaces.Insert(i, slot);
i++;
}
}
}
foreach (string slot in slotsFromAllRaces)
{
if (slot == "None")
continue;
if (wardrobeDropdownPanel.transform.Find(slot + "DropdownHolder") == null)
{
GameObject thisWardrobeDropdown = Instantiate(wardrobeDrodownPrefab) as GameObject;
thisWardrobeDropdown.transform.SetParent(wardrobeDropdownPanel.transform, false);
thisWardrobeDropdown.GetComponent<CSWardrobeSlotChangerDD>().customizerScript = this;
thisWardrobeDropdown.GetComponent<CSWardrobeSlotChangerDD>().wardrobeSlotToChange = slot;
thisWardrobeDropdown.name = slot + "DropdownHolder";
thisWardrobeDropdown.transform.Find("SlotLabel").GetComponent<Text>().text = slot;
thisWardrobeDropdown.GetComponent<Dropdown>().onValueChanged.AddListener(thisWardrobeDropdown.GetComponent<CSWardrobeSlotChangerDD>().ChangeWardrobeSlot);
}
}
}
19
View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
internal static void EnsureMSBuildForUnity()
{
PackageManifest manifest = null;
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return;
}
// Read the package manifest into a list of strings (for easy finding of entries)
// and then deserialize.
List<string> manifestFileLines = new List<string>();
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
manifestFileLines.Add(line);
}
// Go back to the start of the file.
manifestStream.Seek(0, 0);
// Deserialize the scoped registries portion of the package manifest.
manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
}
}
if (manifest == null)
{
Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
return;
}
// Ensure that pre-existing scoped registries are retained.
List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
{
scopedRegistries.AddRange(manifest.scopedRegistries);
}
// Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
bool needToAddRegistry = true;
foreach (ScopedRegistry registry in scopedRegistries)
{
if (registry.url == MSBuildRegistryUrl)
{
needToAddRegistry = false;
}
}
// If no entry was found, add one.
if (needToAddRegistry)
{
ScopedRegistry registry = new ScopedRegistry();
registry.name = MSBuildRegistryName;
registry.url = MSBuildRegistryUrl;
registry.scopes = MSBuildRegistryScopes;
scopedRegistries.Add(registry);
}
// Update the manifest's scoped registries, as the collection may have been modified.
manifest.scopedRegistries = scopedRegistries.ToArray();
int dependenciesStartIndex = -1;
int scopedRegistriesStartIndex = -1;
int scopedRegistriesEndIndex = -1;
int packageLine = -1;
// Presume that we need to add the MSBuild for Unity package. If this value is false,
// we will check to see if the currently configured version meets or exceeds the
// minimum requirements.
bool needToAddPackage = true;
// Attempt to find the MSBuild for Unity package entry in the dependencies collection
// This loop also identifies the dependencies collection line and the start / end of a
// pre-existing scoped registries collections
for (int i = 0; i < manifestFileLines.Count; i++)
{
if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
{
scopedRegistriesStartIndex = i;
}
if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
{
scopedRegistriesEndIndex = i;
}
if (manifestFileLines[i].Contains("\"dependencies\": {"))
{
dependenciesStartIndex = i;
}
if (manifestFileLines[i].Contains(MSBuildPackageName))
{
packageLine = i;
needToAddPackage = false;
}
}
// If no package was found add it to the dependencies collection.
if (needToAddPackage)
{
// Add the package to the collection (pad the entry with four spaces)
manifestFileLines.Insert(dependenciesStartIndex + 1, $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
}
else
{
// Replace the line that currently exists
manifestFileLines[packageLine] = $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
}
// Update the manifest file.
// First, serialize the scoped registry collection.
string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);
// Ensure that the file is truncated to ensure it is always valid after writing.
using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(outFile))
{
bool scopedRegistriesWritten = false;
// Write each line of the manifest back to the file.
for (int i = 0; i < manifestFileLines.Count; i++)
{
if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
{
// Skip these lines, they will be replaced.
continue;
}
if (!scopedRegistriesWritten && (i > 0))
{
// Trim the leading '{' and '\n' from the serialized scoped registries
serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
// Trim, the trailing '\n' and '}'
serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
// Append a trailing ',' to close the scopedRegistries node
serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
writer.WriteLine(serializedRegistriesJson);
scopedRegistriesWritten = true;
}
writer.WriteLine(manifestFileLines[i]);
}
}
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
async static Task<List<(int Rune, string Emoji)>> ParseAsync(
CancellationToken cancellationToken)
{
// insertion/sorting is done against the hex string notation and not
// the actual int32 value since the original reference impl generated
// the mappings via wget/sort -u/sed...
var runes = new List<string>();
await foreach (var _line in DownloadAsync(cancellationToken))
{
var line = _line;
var comment = line.IndexOf('#');
if (comment >= 0)
line = line.Substring(0, comment);
if (string.IsNullOrWhiteSpace(line))
continue;
var firstRune = line.IndexOf(' ');
if (firstRune > 0 &&
line[0] != '0')
{
var rune = line.Substring(0, firstRune);
var index = runes.BinarySearch(rune);
if (index < 0)
runes.Insert(~index, rune);
}
}
var emojis = new List<(int, string)>();
foreach (var runeString in runes)
{
var rune = int.Parse(runeString, NumberStyles.HexNumber);
emojis.Add((rune, char.ConvertFromUtf32(rune)));
}
return emojis;
}
19
View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
[MenuItem("Oculus/Video/Enable Native Android Video Player")]
public static void EnableNativeVideoPlayer()
{
// rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java
if (File.Exists(disabledPlayerFileName))
{
File.Move(disabledPlayerFileName, videoPlayerFileName);
File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta");
}
replacedetDatabase.Importreplacedet(videoPlayerFileName);
replacedetDatabase.Deletereplacedet(disabledPlayerFileName);
// Enable audio plugins
PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);
if (audio360 != null && audio360exo29 != null)
{
audio360.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360.SaveAndReimport();
audio360exo29.SaveAndReimport();
}
// Enable gradle build with exoplayer
EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
// create android plugins directory if it doesn't exist
if (!Directory.Exists(androidPluginsFolder))
{
Directory.CreateDirectory(androidPluginsFolder);
}
if (!File.Exists(gradleTemplatePath))
{
if (File.Exists(gradleTemplatePath + ".DISABLED"))
{
File.Move(disabledGradleTemplatePath, gradleTemplatePath);
File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath+".meta");
}
else
{
File.Copy(internalGradleTemplatePath, gradleTemplatePath);
}
replacedetDatabase.Importreplacedet(gradleTemplatePath);
}
// parse the gradle file to check the current version:
string currentFile = File.ReadAllText(gradleTemplatePath);
List<string> lines = new List<string>(currentFile.Split('\n'));
var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value;
if (gradleVersion == "2.3.0")
{
// add google() to buildscript/repositories
int buildscriptRepositories = GoToSection("buildscript.repositories", lines);
if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()");
}
// add google() and jcenter() to allprojects/repositories
int allprojectsRepositories = GoToSection("allprojects.repositories", lines);
if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()");
}
if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()");
}
}
// add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies
int dependencies = GoToSection("dependencies", lines);
if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'");
}
int android = GoToSection("android", lines);
// add compileOptions to add Java 1.8 compatibility
if (FindInScope("compileOptions", android + 1, lines) == -1)
{
int compileOptionsIndex = GetScopeEnd(android + 1, lines);
lines.Insert(compileOptionsIndex, "\t}");
lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\tcompileOptions {");
}
// add sourceSets if Version < 2018.2
#if !UNITY_2018_2_OR_NEWER
if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\"");
}
#endif
File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
}
19
View Source File : Diagnostics.cs
License : MIT License
Project Creator : acidbubbles
License : MIT License
Project Creator : acidbubbles
public static string GetHierarchy(GameObject o)
{
if (o == null)
return "{null}";
var items = new List<string>(new[] { o.name });
GameObject parent = o;
for (int i = 0; i < 100; i++)
{
parent = parent.transform.parent?.gameObject;
if (parent == null || parent == o) break;
items.Insert(0, parent.gameObject.name);
}
return string.Join(" -> ", items.ToArray());
}
19
View Source File : EpubBuilder.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast
License : GNU General Public License v3.0
Project Creator : Aeroblast
void SetCover()//等KindlePosToUri不再使用后 关系到xhtml相关变量
{
if (azw3.mobi_header.extMeta.id_value.ContainsKey(201))
{
string cover;
int off = (int)azw3.mobi_header.extMeta.id_value[201];//CoverOffset
if (azw3.mobi_header.first_res_index + off < azw3.section_count)
if (azw3.sections[azw3.mobi_header.first_res_index + off].type == "Image")
{
cover_name = AddImage(off, "Cover");
if (NeedCreateCoverDoreplacedent())
{
Log.log("[Info]Adding a cover doreplacedent.");
string t = File.ReadAllText("template\\template_cover.txt");
var (w, h) = Util.GetImageSize(imgs[img_names.IndexOf(cover_name)]);
cover = t.Replace("{❕image}", cover_name).Replace("{❕w}", w.ToString()).Replace("{❕h}", h.ToString());
string coverDoreplacedentName = "cover.xhtml";
if (renameXhtmlWithId)
{
var id = azw3.resc.spine.GetElementsByTagName("itemref")[0].Attributes.GetNamedItem("idref").Value;
coverDoreplacedentName = id + ".xhtml";
}
xhtml_names.Insert(0, coverDoreplacedentName);
XmlDoreplacedent cover_ = new XmlDoreplacedent();
cover_.LoadXml(cover);
xhtmls.Insert(0, cover_);
extraCoverDocAdded = true;
}
}
return;
}
//if (azw3.mobi_header.extMeta.id_string.ContainsKey(129)){}
Log.log("[Warn]No Cover!");
}
19
View Source File : History.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
public void Add(string path)
{
if (files.Remove(path) == true) {
files.Insert(0, path);
}
else {
if (files.Count == maxSize)
files.RemoveAt(files.Count - 1);
files.Insert(0, path);
}
if (Changed != null)
Changed(this);
}
19
View Source File : ChineseMoney.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static void GetString(long data, List<string> sc, int pos)
{
if (data == 0)
{
return;
}
sc.Insert(0, $"{Digit[Convert.ToInt32(data % 10)]}{Wei[pos]}");
GetString(data / 10, sc, pos + 1);
}
19
View Source File : ChineseMoney.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static void GetString(long data , List<string> sc , int pos)
{
if(data == 0)
{
return ;
}
sc.Insert(0 , $"{Digit[Convert.ToInt32(data % 10)]}{Wei[pos]}") ;
GetString(data / 10 , sc , pos + 1) ;
}
19
View Source File : ChineseMoney.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string InvoicePrintString(decimal money)
{
var sc = new List<string>() ;
// 金额*100,即以“分”为单位的金额
var money100 = Convert.ToInt64(money * 100m) ;
if(money100 == 0)
{
return "" ;
}
while(money100 > 0)
{
sc.Insert(0 , Digit[Convert.ToInt32(money100 % 10)].ToString()) ;
money100 /= 10 ;
}
while(sc.Count < 8)
{
sc.Insert(0 , "零") ;
}
var sb = new StringBuilder() ;
foreach(var s in sc)
{
sb.Append(" " + s) ;
}
return sb.ToString() ;
}
19
View Source File : PBXProjectData.cs
License : MIT License
Project Creator : agens-no
License : MIT License
Project Creator : agens-no
public void ReadFromStream(TextReader sr)
{
Clear();
m_RootElements = ParseContent(sr.ReadToEnd());
if (!m_RootElements.Contains("objects"))
throw new Exception("Invalid PBX project file: no objects element");
var objects = m_RootElements["objects"].AsDict();
m_RootElements.Remove("objects");
m_RootElements.SetString("objects", "OBJMARKER");
if (m_RootElements.Contains("objectVersion"))
{
m_ObjectVersion = m_RootElements["objectVersion"].replacedtring();
m_RootElements.Remove("objectVersion");
}
var allGuids = new List<string>();
string prevSectionName = null;
foreach (var kv in objects.values)
{
allGuids.Add(kv.Key);
var el = kv.Value;
if (!(el is PBXElementDict) || !el.AsDict().Contains("isa"))
{
m_UnknownObjects.values.Add(kv.Key, el);
continue;
}
var dict = el.AsDict();
var sectionName = dict["isa"].replacedtring();
if (m_Section.ContainsKey(sectionName))
{
var section = m_Section[sectionName];
section.AddObject(kv.Key, dict);
}
else
{
UnknownSection section;
if (m_UnknownSections.ContainsKey(sectionName))
section = m_UnknownSections[sectionName];
else
{
section = new UnknownSection(sectionName);
m_UnknownSections.Add(sectionName, section);
}
section.AddObject(kv.Key, dict);
// update section order
if (!m_SectionOrder.Contains(sectionName))
{
int pos = 0;
if (prevSectionName != null)
{
// this never fails, because we already added any previous unknown sections
// to m_SectionOrder
pos = m_SectionOrder.FindIndex(x => x == prevSectionName);
pos += 1;
}
m_SectionOrder.Insert(pos, sectionName);
}
}
prevSectionName = sectionName;
}
RepairStructure(allGuids);
RefreshAuxMaps();
}
19
View Source File : ServiceLocation.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public async Task<string> TryGetCDNDomain(string input)
{
var domains = input.Split('.').ToList();
domains.Insert(1, "cdn");
var combined = string.Join(".", domains);
try
{
var result = await QueryDNS(combined);
if (!result.HasError && result.Answers.Any() && await TryConnect(combined))
{
return combined;
}
return input;
}
catch
{
return input;
}
}
19
View Source File : GeneratorTools.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal static string[] AddEmbeddedAirDefense(string[] units, AmountNR airDefenseLevel, DBEntryCoalition coalitionDB, Decade decade, List<string> unitMods)
{
int airDefenseLevelInt = (int)airDefenseLevel.Get();
// No luck this time, don't add anything
if (Toolbox.RandomDouble() >= Database.Instance.Common.AirDefense.AirDefenseLevels[airDefenseLevelInt].EmbeddedChance)
return units;
// Convert the unit array to an open-ended list so that units can be added
List<string> unitsList = new List<string>(units);
// Add some air defense units
int embeddedCount = Database.Instance.Common.AirDefense.AirDefenseLevels[airDefenseLevelInt].EmbeddedUnitCount.GetValue();
for (int i = 0; i < embeddedCount; i++)
unitsList.AddRange(
coalitionDB.GetRandomUnits(Toolbox.RandomFrom(EMBEDDED_AIR_DEFENSE_FAMILIES), decade, 1, unitMods));
if (unitsList.Count == 0) return new string[0];
// Randomize unit order so embbedded air defense units are not always at the end of the group
// but keep unit #0 at its place, because the first unit of the group is used to determine the group type, and we don't want
// a artillery platoon to be named "air defense bataillon" because the first unit is a AAA.
string unit0 = unitsList[0];
unitsList.RemoveAt(0);
unitsList = unitsList.OrderBy(x => Toolbox.RandomInt()).ToList();
unitsList.Insert(0, unit0);
return unitsList.ToArray();
}
19
View Source File : DCSMissionBriefing.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal void AddItem(DCSMissionBriefingItemType briefingItemType, string briefingItem, bool insertFirst = false)
{
if (insertFirst)
Items[(int)briefingItemType].Insert(0, briefingItem);
else
Items[(int)briefingItemType].Add(briefingItem);
}
19
View Source File : GeometryExtrusionOptionsDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void DrawPropertyName(SerializedProperty property, Rect position, string selectedLayerName)
{
var parsedString = "No property selected";
var descriptionString = "No description available";
if (string.IsNullOrEmpty(selectedLayerName) || tileJsonData == null || !tileJsonData.PropertyDisplayNames.ContainsKey(selectedLayerName))
{
DrawWarningMessage(position);
}
else
{
var propertyDisplayNames = tileJsonData.PropertyDisplayNames[selectedLayerName];
_propertyNamesList = new List<string>(propertyDisplayNames);
//check if the selection is valid
var propertyString = property.FindPropertyRelative("propertyName").stringValue;
if (_propertyNamesList.Contains(propertyString))
{
//if the layer contains the current layerstring, set it's index to match
_propertyIndex = propertyDisplayNames.FindIndex(s => s.Equals(propertyString));
//create guicontent for a valid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
for (int extIdx = 0; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
var propertyNameLabel = new GUIContent { text = "Property Name", tooltip = "The name of the property in the selected Mapbox layer that will be used for extrusion" };
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(propertyNameLabel, _propertyIndex, _propertyNameContent);
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(property);
}
//set new string values based on selection
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedString];
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_propertyIndex = 0;
_propertyNamesList.Insert(0, propertyString);
//create guicontent for an invalid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
//first property gets a unique tooltip
_propertyNameContent[0] = new GUIContent
{
text = _propertyNamesList[0],
tooltip = "Unavialable in Selected Layer"
};
for (int extIdx = 1; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
var propertyNameLabel = new GUIContent { text = "Property Name", tooltip = "The name of the property in the selected Mapbox layer that will be used for extrusion" };
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(propertyNameLabel, _propertyIndex, _propertyNameContent);
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(property);
}
//set new string values based on the offset
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = "Unavailable in Selected Layer.";
}
property.FindPropertyRelative("propertyName").stringValue = parsedString;
property.FindPropertyRelative("propertyDescription").stringValue = descriptionString;
}
descriptionString = string.IsNullOrEmpty(descriptionString) ? "No description available" : descriptionString;
var propertyDescriptionPrefixLabel = new GUIContent { text = "Property Description", tooltip = "Factual information about the selected property" };
EditorGUILayout.LabelField(propertyDescriptionPrefixLabel, new GUIContent(descriptionString), (GUIStyle)"wordWrappedLabel");
}
19
View Source File : FeaturesSubLayerPropertiesDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
public void DrawLayerName(SerializedProperty property, List<string> layerDisplayNames)
{
var layerNameLabel = new GUIContent
{
text = "Data Layer",
tooltip = "The layer name from the Mapbox tileset that would be used for visualizing a feature"
};
//disable the selection if there is no layer
if (layerDisplayNames.Count == 0)
{
EditorGUILayout.LabelField(layerNameLabel, new GUIContent("No layers found: Invalid TilesetId / No Internet."), (GUIStyle)"minipopUp");
return;
}
//check the string value at the current _layerIndex to verify that the stored index matches the property string.
var layerString = property.FindPropertyRelative("layerName").stringValue;
if (layerDisplayNames.Contains(layerString))
{
//if the layer contains the current layerstring, set it's index to match
_layerIndex = layerDisplayNames.FindIndex(s => s.Equals(layerString));
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_layerIndex = 0;
layerDisplayNames.Insert(0, layerString);
if (!tileJsonData.LayerPropertyDescriptionDictionary.ContainsKey(layerString))
{
tileJsonData.LayerPropertyDescriptionDictionary.Add(layerString, new Dictionary<string, string>());
}
}
//create the display name guicontent array with an additional entry for the currently selected item
_layerTypeContent = new GUIContent[layerDisplayNames.Count];
for (int extIdx = 0; extIdx < layerDisplayNames.Count; extIdx++)
{
_layerTypeContent[extIdx] = new GUIContent
{
text = layerDisplayNames[extIdx],
};
}
//draw the layer selection popup
_layerIndex = EditorGUILayout.Popup(layerNameLabel, _layerIndex, _layerTypeContent);
var parsedString = layerDisplayNames.ToArray()[_layerIndex].Split(new string[] { tileJsonData.commonLayersKey }, System.StringSplitOptions.None)[0].Trim();
property.FindPropertyRelative("layerName").stringValue = parsedString;
}
19
View Source File : VectorFilterOptionsDrawer.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
private void DrawPropertyDropDown(SerializedProperty originalProperty, SerializedProperty filterProperty)
{
var selectedLayerName = originalProperty.FindPropertyRelative("_selectedLayerName").stringValue;
AbstractMap mapObject = (AbstractMap)originalProperty.serializedObject.targetObject;
TileJsonData tileJsonData = mapObject.VectorData.GetTileJsonData();
if (string.IsNullOrEmpty(selectedLayerName) || !tileJsonData.PropertyDisplayNames.ContainsKey(selectedLayerName))
{
DrawWarningMessage();
return;
}
var parsedString = "no property selected";
var descriptionString = "no description available";
var propertyDisplayNames = tileJsonData.PropertyDisplayNames[selectedLayerName];
_propertyNamesList = new List<string>(propertyDisplayNames);
var propertyString = filterProperty.FindPropertyRelative("Key").stringValue;
//check if the selection is valid
if (_propertyNamesList.Contains(propertyString))
{
//if the layer contains the current layerstring, set it's index to match
_propertyIndex = propertyDisplayNames.FindIndex(s => s.Equals(propertyString));
//create guicontent for a valid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
for (int extIdx = 0; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(_propertyIndex, _propertyNameContent, GUILayout.MaxWidth(150));
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
//set new string values based on selection
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedString];
}
else
{
//if the selected layer isn't in the source, add a placeholder entry
_propertyIndex = 0;
_propertyNamesList.Insert(0, propertyString);
//create guicontent for an invalid layer
_propertyNameContent = new GUIContent[_propertyNamesList.Count];
//first property gets a unique tooltip
_propertyNameContent[0] = new GUIContent
{
text = _propertyNamesList[0],
tooltip = "Unavialable in Selected Layer"
};
for (int extIdx = 1; extIdx < _propertyNamesList.Count; extIdx++)
{
var parsedPropertyString = _propertyNamesList[extIdx].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
_propertyNameContent[extIdx] = new GUIContent
{
text = _propertyNamesList[extIdx],
tooltip = tileJsonData.LayerPropertyDescriptionDictionary[selectedLayerName][parsedPropertyString]
};
}
//display popup
EditorGUI.BeginChangeCheck();
_propertyIndex = EditorGUILayout.Popup(_propertyIndex, _propertyNameContent, GUILayout.MaxWidth(150));
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
//set new string values based on the offset
parsedString = _propertyNamesList[_propertyIndex].Split(new string[] { tileJsonData.optionalPropertiesString }, System.StringSplitOptions.None)[0].Trim();
descriptionString = "Unavailable in Selected Layer.";
}
EditorGUI.BeginChangeCheck();
filterProperty.FindPropertyRelative("Key").stringValue = parsedString;
if (EditorGUI.EndChangeCheck())
{
EditorHelper.CheckForModifiedProperty(filterProperty);
}
filterProperty.FindPropertyRelative("KeyDescription").stringValue = descriptionString;
}
19
View Source File : AdditionalDefinesHelper.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void DrawMainBody()
{
EditorGUILayout.Separator();
int itemCount = m_additionalDefines.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
m_additionalDefines[ i ] = EditorGUILayout.TextField( m_additionalDefines[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_additionalDefines[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_additionalDefines[ i ] );
}
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalDefines.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
if( m_additionalDefines.Count > markedToDelete )
{
m_additionalDefines.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox( "Please add your defines without the #define keywords", MessageType.Info );
}
19
View Source File : AdditionalIncludesHelper.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void DrawMainBody()
{
EditorGUILayout.Separator();
//if( OutsideList != null && OutsideList.Count > 0 )
//{
// m_drawElements.Clear();
// EditorGUI.BeginDisabledGroup( true );
// int outsideCount = OutsideList.Count;
// for( int i = 0; i < outsideCount; i++ )
// {
// if( !m_drawElements.Contains( OutsideList[ i ] ) )
// {
// m_drawElements.Add( OutsideList[ i ] );
// EditorGUILayout.TextField( OutsideList[ i ] );
// }
// }
// EditorGUI.EndDisabledGroup();
// EditorGUILayout.Separator();
//}
int itemCount = m_additionalIncludes.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
m_additionalIncludes[ i ] = EditorGUILayout.TextField( m_additionalIncludes[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_additionalIncludes[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_additionalIncludes[ i ] );
}
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalIncludes.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
if( m_additionalIncludes.Count > markedToDelete )
{
m_additionalIncludes.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox( "Please add your includes without the #include \"\" keywords", MessageType.Info );
}
19
View Source File : AdditionalPragmasHelper.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void DrawMainBody()
{
EditorGUILayout.Separator();
int itemCount = m_additionalPragmas.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
m_additionalPragmas[ i ] = EditorGUILayout.TextField( m_additionalPragmas[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_additionalPragmas[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_additionalPragmas[ i ] );
}
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalPragmas.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
if( m_additionalPragmas.Count > markedToDelete )
{
m_additionalPragmas.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox( "Please add your pragmas without the #pragma keywords", MessageType.Info );
}
19
View Source File : AdditionalSurfaceOptionsHelper.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void DrawMainBody()
{
EditorGUILayout.Separator();
int itemCount = m_availableOptions.Count;
if( itemCount == 0 )
{
EditorGUILayout.HelpBox( "Your list is Empty!\nUse the plus button to add one.", MessageType.Info );
}
int markedToDelete = -1;
float originalLabelWidth = EditorGUIUtility.labelWidth;
for( int i = 0; i < itemCount; i++ )
{
EditorGUI.indentLevel += 1;
EditorGUIUtility.labelWidth = 62;
EditorGUILayout.BeginHorizontal();
//Option
EditorGUI.BeginChangeCheck();
m_availableOptions[ i ] = EditorGUILayout.TextField( "["+i+"] -", m_availableOptions[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_availableOptions[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_availableOptions[ i ] );
}
EditorGUIUtility.labelWidth = originalLabelWidth;
{
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_availableOptions.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel -= 1;
}
if( markedToDelete > -1 )
{
if( m_availableOptions.Count > markedToDelete )
{
m_availableOptions.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
}
19
View Source File : MasterNode.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public void DrawShaderKeywords()
{
if( m_addShaderKeywordStyle == null )
m_addShaderKeywordStyle = UIUtils.PlusStyle;
if( m_removeShaderKeywordStyle == null )
m_removeShaderKeywordStyle = UIUtils.MinusStyle;
if( m_smallAddShaderKeywordItemStyle == null )
m_smallAddShaderKeywordItemStyle = UIUtils.PlusStyle;
if( m_smallRemoveShaderKeywordStyle == null )
m_smallRemoveShaderKeywordStyle = UIUtils.MinusStyle;
EditorGUILayout.BeginHorizontal();
{
m_shaderKeywordsFoldout = EditorGUILayout.Foldout( m_shaderKeywordsFoldout, ShaderKeywordsStr );
// Add keyword
if( GUILayout.Button( string.Empty, m_addShaderKeywordStyle ) )
{
m_shaderKeywords.Insert( 0, "" );
}
//Remove keyword
if( GUILayout.Button( string.Empty, m_removeShaderKeywordStyle ) )
{
m_shaderKeywords.RemoveAt( m_shaderKeywords.Count - 1 );
}
}
EditorGUILayout.EndHorizontal();
if( m_shaderKeywordsFoldout )
{
EditorGUI.indentLevel += 1;
int itemCount = m_shaderKeywords.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label( " " );
// Add new port
if( GUILayoutButton( string.Empty, m_smallAddShaderKeywordItemStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_shaderKeywords.Insert( i, "" );
}
//Remove port
if( GUILayoutButton( string.Empty, m_smallRemoveShaderKeywordStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
m_shaderKeywords.RemoveAt( markedToDelete );
}
EditorGUI.indentLevel -= 1;
}
}
19
View Source File : TextureCoordinatesNode.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public override void DrawProperties()
{
bool guiEnabledBuffer = GUI.enabled;
EditorGUI.BeginChangeCheck();
List<string> arr = ( m_inputReferenceNode != null ) ? null : new List<string>( UIUtils.TexturePropertyNodeArr() );
if( arr != null && arr.Count > 0 )
{
arr.Insert( 0, "None" );
GUI.enabled = true;
m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId + 1, arr.ToArray() ) - 1;
}
else
{
m_referenceArrayId = -1;
GUI.enabled = false;
EditorGUILayoutPopup( Constants.AvailableReferenceStr, 0, Dummy );
}
GUI.enabled = guiEnabledBuffer;
if( EditorGUI.EndChangeCheck() )
{
m_referenceNode = UIUtils.GetTexturePropertyNode( m_referenceArrayId );
if( m_referenceNode != null )
{
m_referenceNodeId = m_referenceNode.UniqueId;
}
else
{
m_referenceNodeId = -1;
m_referenceArrayId = -1;
}
Updatereplacedle();
UpdatePorts();
}
EditorGUI.BeginChangeCheck();
m_texcoordSize = EditorGUILayoutIntPopup( Constants.AvailableUVSizesLabel, m_texcoordSize, Constants.AvailableUVSizesStr, Constants.AvailableUVSizes );
if( EditorGUI.EndChangeCheck() )
{
UpdateOutput();
}
m_textureCoordChannel = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordChannel, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
if( m_referenceArrayId > -1 )
GUI.enabled = false;
base.DrawProperties();
GUI.enabled = guiEnabledBuffer;
}
19
View Source File : TemplateAdditionalParentHelper.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void DrawMainBody()
{
EditorGUILayout.Separator();
if( m_nativeItems.Count > 0 )
{
NodeUtils.DrawNestedPropertyGroup( ref m_nativeItemsFoldout, NativeFoldoutStr, DrawNativeItems ,4);
}
int itemCount = m_additionalItems.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
m_additionalItems[ i ] = EditorGUILayout.TextField( m_additionalItems[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_additionalItems[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_additionalItems[ i ] );
m_isDirty = true;
}
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalItems.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
m_isDirty = true;
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
m_isDirty = true;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
if( m_additionalItems.Count > markedToDelete )
{
m_additionalItems.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox( m_helpBoxMessage, MessageType.Info );
}
19
View Source File : TextureCoordinatesNode.cs
License : GNU General Public License v3.0
Project Creator : alexismorin
License : GNU General Public License v3.0
Project Creator : alexismorin
public override void DrawProperties()
{
bool guiEnabledBuffer = GUI.enabled;
EditorGUI.BeginChangeCheck();
List<string> arr = ( m_inputReferenceNode != null ) ? null : new List<string>( UIUtils.TexturePropertyNodeArr() );
if( arr != null && arr.Count > 0 )
{
arr.Insert( 0, "None" );
GUI.enabled = true;
m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId + 1, arr.ToArray() ) - 1;
}
else
{
m_referenceArrayId = -1;
GUI.enabled = false;
EditorGUILayoutPopup( Constants.AvailableReferenceStr, 0, Dummy );
}
GUI.enabled = guiEnabledBuffer;
if( EditorGUI.EndChangeCheck() )
{
m_referenceNode = UIUtils.GetTexturePropertyNode( m_referenceArrayId );
if( m_referenceNode != null )
{
m_referenceNodeId = m_referenceNode.UniqueId;
}
else
{
m_referenceNodeId = -1;
m_referenceArrayId = -1;
}
Updatereplacedle();
UpdatePorts();
}
EditorGUI.BeginChangeCheck();
m_texcoordSize = EditorGUILayoutIntPopup( Constants.AvailableUVSizesLabel, m_texcoordSize, Constants.AvailableUVSizesStr, Constants.AvailableUVSizes );
if( EditorGUI.EndChangeCheck() )
{
UpdateOutput();
}
m_textureCoordChannel = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordChannel, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
if( m_referenceArrayId > -1 )
GUI.enabled = false;
base.DrawProperties();
GUI.enabled = guiEnabledBuffer;
}
19
View Source File : PythonConsole.cs
License : MIT License
Project Creator : AlexLemminG
License : MIT License
Project Creator : AlexLemminG
void ExecuteCommand (string command){
if (input.wasCanceled) {
input.ActivateInputField ();
return;
}
input.text = "";
input.ActivateInputField ();
if (command.Length != 0) {
m_previousCommands.Insert (0, command);
}
m_previousCommandSelected = -1;
m_commandExecutionInProgress = true;
bool exception = false;
try{
PythonUtils.GetEngine ().Execute (command, m_scope);
}catch(Exception e){
exception = true;
write (e.Message);
}
m_commandExecutionInProgress = false;
var commandLog = "<b>" + (exception ? "<color=#d22>" : "") + command + (exception ? "</color=#f66>" : "") + "</b>";
if(string.IsNullOrEmpty(m_log)){
m_log = commandLog;
}else{
m_log = commandLog + "\n" + m_log;
}
FlushLog ();
scroll.verticalNormalizedPosition = 0f;
}
19
View Source File : IndicatorsFactory.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<string> GetIndicatorsNames()
{
if (Directory.Exists(@"Custom") == false)
{
Directory.CreateDirectory(@"Custom");
}
if (Directory.Exists(@"Custom\Indicators") == false)
{
Directory.CreateDirectory(@"Custom\Indicators");
}
List<string> resultOne = GetFullNamesFromFolder(@"Custom\Indicators");
for (int i = 0; i < resultOne.Count; i++)
{
resultOne[i] = resultOne[i].Split('\\')[resultOne[i].Split('\\').Length - 1];
resultOne[i] = resultOne[i].Split('.')[0];
}
// resultOne.Add("Ssma");
List<string> resultTrue = new List<string>();
for (int i = 0; i < resultOne.Count; i++)
{
bool isInArray = false;
for (int i2 = 0; i2 < resultTrue.Count; i2++)
{
if (resultTrue[i2][0] > resultOne[i][0])
{
resultTrue.Insert(i2, resultOne[i]);
isInArray = true;
break;
}
}
if (isInArray == false)
{
resultTrue.Add(resultOne[i]);
}
}
return resultTrue;
}
19
View Source File : IndicatorsFactory.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<string> GetIndicatorsNames()
{
if (Directory.Exists(@"Custom") == false)
{
Directory.CreateDirectory(@"Custom");
}
if (Directory.Exists(@"Custom\Indicators") == false)
{
Directory.CreateDirectory(@"Custom\Indicators");
}
if (Directory.Exists(@"Custom\Indicators\Scripts") == false)
{
Directory.CreateDirectory(@"Custom\Indicators\Scripts");
}
List<string> resultOne = GetFullNamesFromFolder(@"Custom\Indicators\Scripts");
for (int i = 0; i < resultOne.Count; i++)
{
resultOne[i] = resultOne[i].Split('\\')[resultOne[i].Split('\\').Length - 1];
resultOne[i] = resultOne[i].Split('.')[0];
}
//resultOne.Add("Template");
List<string> resultTrue = new List<string>();
for (int i = 0; i < resultOne.Count; i++)
{
bool isInArray = false;
for (int i2 = 0; i2 < resultTrue.Count; i2++)
{
if (resultTrue[i2][0] > resultOne[i][0])
{
resultTrue.Insert(i2, resultOne[i]);
isInArray = true;
break;
}
}
if (isInArray == false)
{
resultTrue.Add(resultOne[i]);
}
}
return resultTrue;
}
19
View Source File : BotFactory.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<string> GetNamesStrategy()
{
List<string> result = new List<string>();
result.Add("SmaScreener");
result.Add("Fisher");
result.Add("Engine");
result.Add("ScreenerEngine");
result.Add("ClusterEngine");
result.Add("SmaTrendSample");
result.Add("FundBalanceDivergenceBot");
result.Add("PairTraderSimple");
result.Add("MomentumMACD");
result.Add("MarketMakerBot");
result.Add("PatternTrader");
result.Add("HighFrequencyTrader");
result.Add("EnvelopTrend");
result.Add("Williams Band");
result.Add("TwoLegArbitrage");
result.Add("ThreeSoldier");
result.Add("TimeOfDayBot");
result.Add("PriceChannelTrade");
result.Add("SmaStochastic");
result.Add("ClusterCountertrend");
result.Add("PairTraderSpreadSma");
result.Add("WilliamsRangeTrade");
result.Add("ParabolicSarTrade");
result.Add("PivotPointsRobot");
result.Add("RsiContrtrend");
result.Add("PinBarTrade");
result.Add("BbPowerTrade");
result.Add("BollingerRevers");
result.Add("BollingerTrailing");
result.Add("CciTrade");
result.Add("MacdRevers");
result.Add("MacdTrail");
result.Add("OneLegArbitrage");
result.Add("PairRsiTrade");
result.Add("PriceChannelBreak");
result.Add("PriceChannelVolatility");
result.Add("RsiTrade");
result.Add("RviTrade");
result.AddRange(BotsWithAttribute.Keys);
List<string> resultTrue = new List<string>();
for (int i = 0; i < result.Count; i++)
{
bool isInArray = false;
for (int i2 = 0; i2 < resultTrue.Count; i2++)
{
if (resultTrue[i2][0] > result[i][0])
{
resultTrue.Insert(i2, result[i]);
isInArray = true;
break;
}
}
if (isInArray == false)
{
resultTrue.Add(result[i]);
}
}
return resultTrue;
}
19
View Source File : BotFactory.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static List<string> GetScriptsNamesStrategy()
{
if (Directory.Exists(@"Custom") == false)
{
Directory.CreateDirectory(@"Custom");
}
if (Directory.Exists(@"Custom\Robots") == false)
{
Directory.CreateDirectory(@"Custom\Robots");
}
List<string> resultOne = GetFullNamesFromFolder(@"Custom\Robots");
for (int i = 0; i < resultOne.Count; i++)
{
resultOne[i] = resultOne[i].Split('\\')[resultOne[i].Split('\\').Length - 1];
resultOne[i] = resultOne[i].Split('.')[0];
}
// resultOne.Add("Ssma");
List<string> resultTrue = new List<string>();
for (int i = 0; i < resultOne.Count; i++)
{
bool isInArray = false;
for (int i2 = 0; i2 < resultTrue.Count; i2++)
{
if (resultTrue[i2][0] > resultOne[i][0])
{
resultTrue.Insert(i2, resultOne[i]);
isInArray = true;
break;
}
}
if (isInArray == false)
{
resultTrue.Add(resultOne[i]);
}
}
return resultTrue;
}
19
View Source File : SymbolResolver.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
public static IntPtr LoadImage (ref string name)
{
var pathValues = Environment.GetEnvironmentVariable("PATH");
var paths = new List<string>(pathValues == null ? new string[0] :
pathValues.Split(Path.PathSeparator));
paths.Insert(0, Directory.GetCurrentDirectory());
paths.Insert(0, Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));
foreach (var format in formats)
{
// Search the Current or specified directory for the library
string filename = string.Format(format, name);
string attempted = null;
foreach (var path in paths)
{
var fullPath = Path.Combine(path, filename);
if (File.Exists(fullPath))
{
attempted = fullPath;
break;
}
}
if (!File.Exists(attempted))
continue;
var ptr = loadImage (attempted);
if (ptr == IntPtr.Zero)
continue;
name = attempted;
return ptr;
}
return IntPtr.Zero;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
static int Main(string[] args)
{
List<string> newArgs = new List<string>(args);
newArgs.Insert(0, typeof(Program).replacedembly.Location);
int returnCode = Xunit.ConsoleClient.Program.Main(newArgs.ToArray());
Console.WriteLine("Tests finished. Press any key to exit.");
if (!Console.IsInputRedirected)
{
Console.ReadKey(true);
}
return returnCode;
}
19
View Source File : ItemIgnore.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private static void AddIgnores(IAnkhServiceProvider context, string path, List<string> ignores)
{
try
{
context.GetService<IProgressRunner>().RunModal(CommandStrings.IgnoreCaption,
delegate(object sender, ProgressWorkerArgs e)
{
SvnGetPropertyArgs pa = new SvnGetPropertyArgs();
pa.ThrowOnError = false;
SvnTargetPropertyCollection tpc;
if (e.Client.GetProperty(path, SvnPropertyNames.SvnIgnore, pa, out tpc))
{
SvnPropertyValue pv;
if (tpc.Count > 0 && null != (pv = tpc[0]) && pv.StringValue != null)
{
int n = 0;
foreach (string oldItem in pv.StringValue.Split('\n'))
{
string item = oldItem.TrimEnd('\r');
if (item.Trim().Length == 0)
continue;
// Don't add duplicates
while (n < ignores.Count && ignores.IndexOf(item, n) >= 0)
ignores.RemoveAt(ignores.IndexOf(item, n));
if (ignores.Contains(item))
continue;
ignores.Insert(n++, item);
}
}
StringBuilder sb = new StringBuilder();
bool next = false;
foreach (string item in ignores)
{
if (next)
sb.Append('\n'); // Subversion wants only newlines
else
next = true;
sb.Append(item);
}
e.Client.SetProperty(path, SvnPropertyNames.SvnIgnore, sb.ToString());
}
});
// Make sure a changed directory is visible in the PC Window
context.GetService<IFileStatusMonitor>().ScheduleMonitor(path);
}
finally
{
// Ignore doesn't bubble
context.GetService<ISvnStatusCache>().MarkDirtyRecursive(path);
}
}
19
View Source File : Host.cs
License : MIT License
Project Creator : ancientproject
License : MIT License
Project Creator : ancientproject
public static string Evolve(string code) // todo REWORK IT
{
var result = code;
var parsed = new TransformerSyntax().ManyEvolver.Parse(code);
foreach (var token in parsed.Pipe(x => Trace($"evolving :: {x}")))
{
switch (token)
{
case EmptyEvolve _:
break;
case LocalsInitEvolver local:
var dd = result.Split('\n').ToList();
dd.Insert(token.InputPosition.Line-1, $"{string.Join(" ", local.Result)}\n");
result = string.Join("\n", dd);
break;
case DefineLabels labels:
var reg = new Regex(@"\!\[~(?<alias>\w+)\]");
var usedAliases = reg.Matches(code).Select(x => x.Groups["alias"].Value).ToArray();
var compiledAliases = labels.Labels.Select(x => x.Name).ToList();
var failedFind = usedAliases.Where(x => !compiledAliases.Contains(x)).ToArray();
if (failedFind.Any())
{
var msg = $"[{string.Join(",", failedFind)}] symbols not compiled.";
Error(Warning.PrecompiledSymbolNotFound, msg);
throw new AncientEvolveException(msg);
}
result = labels.Labels.Aggregate(result, (current, aliase) =>
current.Replace($"![~{aliase.Name}]", $"0x{aliase.Hex}"));
break;
case ErrorEvolveToken error:
Error(error, code);
throw new AncientEvolveException(error.ErrorResult.ToString());
}
}
return result;
}
19
View Source File : Index.cshtml.cs
License : MIT License
Project Creator : andrewlock
License : MIT License
Project Creator : andrewlock
public IActionResult OnPost()
{
ExistingUsers = _users;
if (!ModelState.IsValid)
{
return Page();
}
if (_users.Contains(NewUser))
{
//Note, you would typically extract this to a validation attribute
//But I do it here as the users list is hard coded above
ModelState.AddModelError(nameof(NewUser), "This user already exists!");
return Page();
}
//all ok, add the user and clear the existing value
_users.Insert(0, NewUser);
return RedirectToPage();
}
19
View Source File : DynamicParameters.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType = null, int? size = null)
{
var failMessage = "Expression must be a property/field chain off of a(n) {0} instance";
failMessage = string.Format(failMessage, typeof(T).Name);
Action @throw = () => throw new InvalidOperationException(failMessage);
// Is it even a MemberExpression?
var lastMemberAccess = expression.Body as MemberExpression;
if (lastMemberAccess == null
|| (!(lastMemberAccess.Member is PropertyInfo)
&& !(lastMemberAccess.Member is FieldInfo)))
{
if (expression.Body.NodeType == ExpressionType.Convert
&& expression.Body.Type == typeof(object)
&& ((UnaryExpression)expression.Body).Operand is MemberExpression)
{
// It's got to be unboxed
lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand;
}
else
{
@throw();
}
}
// Does the chain consist of MemberExpressions leading to a ParameterExpression of type T?
MemberExpression diving = lastMemberAccess;
// Retain a list of member names and the member expressions so we can rebuild the chain.
List<string> names = new List<string>();
List<MemberExpression> chain = new List<MemberExpression>();
do
{
// Insert the names in the right order so expression
// "Post.Author.Name" becomes parameter "PostAuthorName"
names.Insert(0, diving?.Member.Name);
chain.Insert(0, diving);
var constant = diving?.Expression as ParameterExpression;
diving = diving?.Expression as MemberExpression;
if (constant != null && constant.Type == typeof(T))
{
break;
}
else if (diving == null
|| (!(diving.Member is PropertyInfo)
&& !(diving.Member is FieldInfo)))
{
@throw();
}
}
while (diving != null);
var dynamicParamName = string.Concat(names.ToArray());
// Before we get all emitty...
var lookup = string.Join("|", names.ToArray());
var cache = CachedOutputSetters<T>.Cache;
var setter = (Action<object, DynamicParameters>)cache[lookup];
if (setter != null) goto MAKECALLBACK;
// Come on let's build a method, let's build it, let's build it now!
var dm = new DynamicMethod("ExpressionParam" + Guid.NewGuid().ToString(), null, new[] { typeof(object), GetType() }, true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // [object]
il.Emit(OpCodes.Castclreplaced, typeof(T)); // [T]
// Count - 1 to skip the last member access
var i = 0;
for (; i < (chain.Count - 1); i++)
{
var member = chain[0].Member;
if (member is PropertyInfo)
{
var get = ((PropertyInfo)member).GetGetMethod(true);
il.Emit(OpCodes.Callvirt, get); // [Member{i}]
}
else // Else it must be a field!
{
il.Emit(OpCodes.Ldfld, (FieldInfo)member); // [Member{i}]
}
}
var paramGetter = GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type);
il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters]
il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName]
il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method
// GET READY
var lastMember = lastMemberAccess.Member;
if (lastMember is PropertyInfo)
{
var set = ((PropertyInfo)lastMember).GetSetMethod(true);
il.Emit(OpCodes.Callvirt, set); // SET
}
else
{
il.Emit(OpCodes.Stfld, (FieldInfo)lastMember); // SET
}
il.Emit(OpCodes.Ret); // GO
setter = (Action<object, DynamicParameters>)dm.CreateDelegate(typeof(Action<object, DynamicParameters>));
lock (cache)
{
cache[lookup] = setter;
}
// Queue the preparation to be fired off when adding parameters to the DbCommand
MAKECALLBACK:
(outputCallbacks ?? (outputCallbacks = new List<Action>())).Add(() =>
{
// Finally, prep the parameter and attach the callback to it
var targetMemberType = lastMemberAccess?.Type;
int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0;
if (parameters.TryGetValue(dynamicParamName, out ParamInfo parameter))
{
parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput;
if (parameter.AttachedParam.Size == 0)
{
parameter.Size = parameter.AttachedParam.Size = sizeToSet;
}
}
else
{
dbType = (!dbType.HasValue)
#pragma warning disable 618
? SqlMapper.LookupDbType(targetMemberType, targetMemberType?.Name, true, out SqlMapper.ITypeHandler handler)
#pragma warning restore 618
: dbType;
// CameFromTemplate property would not apply here because this new param
// Still needs to be added to the command
Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet);
}
parameter = parameters[dynamicParamName];
parameter.OutputCallback = setter;
parameter.OutputTarget = target;
});
return this;
}
19
View Source File : BuilderPlug.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public void AddOpened(string path)
{
int index = recent_files.IndexOf(path);
if (index > -1)
{
recent_files.RemoveAt(index);
}
recent_files.Insert(0, path);
ShowMenu();
for (int i = 0; i < 12 && i < recent_files.Count; i++)
{
General.Settings.WritePluginSetting("recentfiles" + i, recent_files[i]);
}
}
19
View Source File : SalesforceVisitor.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
protected override Expression VisitMethodCall(MethodCallExpression m)
{
#region Method On Querable
if (m.Method.DeclaringType == typeof(Queryable) || (m.Method.DeclaringType == typeof(AsyncQueryable)))
{
var methodName = m.Method.Name;
switch (methodName)
{
case nameof(AsyncQueryable.Take):
Take = (int) ((m.Arguments[1] as ConstantExpression).Value);
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.Skip):
Skip = (int) ((m.Arguments[1] as ConstantExpression).Value);
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.FirstAsync):
case nameof(AsyncQueryable.FirstOrDefaultAsync):
case nameof(AsyncQueryable.SingleAsync):
case nameof(AsyncQueryable.SingleOrDefaultAsync):
QueryType = (QueryTypeEnum) Enum.Parse(typeof(QueryTypeEnum), methodName);
Take = 2;
if (m.Arguments.Count > 1)
{
ConstantExpression ce = this.Visit(m.Arguments[1]) as ConstantExpression;
if (ce?.Value != null)
{
WhereExpression.Insert(0, ce.Value.ToString());
}
}
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.ToListAsync):
QueryType = QueryTypeEnum.ListAsync;
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.AnyAsync):
case nameof(AsyncQueryable.CountAsync):
QueryType = (QueryTypeEnum) Enum.Parse(typeof(QueryTypeEnum), methodName);
if (m.Arguments.Count > 1)
{
ConstantExpression ce = this.Visit(m.Arguments[1]) as ConstantExpression;
if (ce?.Value != null)
{
WhereExpression.Insert(0, ce.Value.ToString());
}
}
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.Select):
this.Visit(m.Arguments[1]);
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.Where):
if (m.Arguments.Count > 1)
{
ConstantExpression ce = this.Visit(m.Arguments[1]) as ConstantExpression;
if (ce?.Value != null)
{
WhereExpression.Insert(0, ce.Value.ToString());
}
}
this.Visit(m.Arguments[0]);
break;
case nameof(AsyncQueryable.OrderBy):
{
if (this.Visit(m.Arguments[1]) is ConstantExpression ce && ce.Value != null)
{
OrderByExpression.Insert(0, ce.Value.ToString());
}
this.Visit(m.Arguments[0]);
break;
}
case nameof(AsyncQueryable.OrderByDescending):
{
if (this.Visit(m.Arguments[1]) is ConstantExpression ce && ce.Value != null)
{
OrderByExpression.Insert(0, ce.Value.ToString() + " DESC");
}
this.Visit(m.Arguments[0]);
break;
}
default:
{
break;
}
}
}
#endregion
#region Method On string
else if (m.Method.DeclaringType == typeof(string))
{
switch (m.Method.Name)
{
case nameof(string.Contains):
{
var result = string.Format("({0} LIKE '%{1}%')",
(this.Visit(m.Object) as ConstantExpression).Value.ToString(),
(this.Visit(m.Arguments[0]) as ConstantExpression).Value.ToString().Trim('\'').Replace("%", "\\%"));
return Expression.Constant(result);
}
case nameof(string.StartsWith):
{
var result = string.Format("({0} LIKE '{1}%')",
(this.Visit(m.Object) as ConstantExpression).Value.ToString(),
(this.Visit(m.Arguments[0]) as ConstantExpression).Value.ToString().Trim('\'').Replace("%", "\\%"));
return Expression.Constant(result);
}
case nameof(string.EndsWith):
{
var result = string.Format("({0} LIKE '%{1}')",
(this.Visit(m.Object) as ConstantExpression).Value.ToString(),
(this.Visit(m.Arguments[0]) as ConstantExpression).Value.ToString().Trim('\'').Replace("%", "\\%"));
return Expression.Constant(result);
}
}
}
else if (m.Method.DeclaringType == typeof(NetCoreForceStringExtensions))
{
switch (m.Method.Name)
{
case nameof(NetCoreForceStringExtensions.Includes):
{
var result = string.Format("({0} INCLUDES('{1}'))",
(this.Visit(m.Arguments[0]) as ConstantExpression).Value.ToString(),
(this.Visit(m.Arguments[1]) as ConstantExpression).Value.ToString().Trim('\'').Replace("%", "\\%"));
return Expression.Constant(result);
}
case nameof(NetCoreForceStringExtensions.Excludes):
{
var result = string.Format("({0} EXCLUDES('{1}'))",
(this.Visit(m.Arguments[0]) as ConstantExpression).Value.ToString(),
(this.Visit(m.Arguments[1]) as ConstantExpression).Value.ToString().Trim('\'').Replace("%", "\\%"));
return Expression.Constant(result);
}
}
}
#endregion
return m;
}
19
View Source File : Options.cs
License : MIT License
Project Creator : aolszowka
License : MIT License
Project Creator : aolszowka
public void Insert (int index, string item) {values.Insert (index, item);}
19
View Source File : IgnoredRoutesConfiguration.cs
License : Apache License 2.0
Project Creator : AppMetrics
License : Apache License 2.0
Project Creator : AppMetrics
public void Insert(int index, string item)
{
_regexList.Insert(index, GetRegex(item));
_stringListImplementation.Insert(index, item);
}
19
View Source File : GenerateAppService.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
private string GetNaviLocation(int channelId)
{
List<string> channelNames = new List<string>();
var channel = ChannelManagerCache.GetChannel(channelId);
if (channel != null)
{
string href = $"/channel/{channel.id}";
if (!string.IsNullOrEmpty(channel.channel_href))
{
href = channel.channel_href;
}
string channelHref = $"<a href='{href}'>{channel.channel_name}</a>";
channelNames.Insert(0, channelHref);
int channelPid = channel.parent_id;
while (channelPid > 0)
{
channel= ChannelManagerCache.GetChannel(channelPid);
if (channel != null)
{
string channelHref2 = "<a href='/index.html'>首页</a>";
if (channel.channel_index != "首页")
{
if (!string.IsNullOrEmpty(channel.channel_href))
{
href = channel.channel_href;
}
channelHref2 = $"<a href='{href}'>{channel.channel_name}</a>";
}
channelNames.Insert(0,channelHref2);
channelPid = channel.parent_id;
}
}
}
if (channelNames.Count == 0)
{
return "<a href='/index.html'>首页</a>";
}
return string.Join('>', channelNames);
}
19
View Source File : SpectralFeaturesExtractor.cs
License : MIT License
Project Creator : ar1st0crat
License : MIT License
Project Creator : ar1st0crat
public void AddFeature(string name, Func<float[], float[], float> algorithm)
{
FeatureCount++;
FeatureDescriptions.Insert(_extractors.Count, name);
_extractors.Add(algorithm);
}
19
View Source File : HtmlFormatter.cs
License : MIT License
Project Creator : arbelatech
License : MIT License
Project Creator : arbelatech
private string GetStyleDefaults(string[] prefixes, bool usesPrefixes)
{
Func<string, string> prefix = cls =>
{
if (!string.IsNullOrEmpty(cls))
cls = "." + cls;
return string.Join(", ", prefixes.Select(arg => (!string.IsNullOrEmpty(arg) ? arg + " " : "") + cls));
};
var lines = _cssToStyleMap
.Where(kvp => kvp.Key != null && kvp.Value != null)
.Select(kvp => Tuple.Create(kvp.Value.Depth, kvp.Value.TokenType, kvp.Key, kvp.Value.StyleRules))
.OrderBy(t => t.Item1)
.Select(s => $"{prefix(s.Item3)} {{ {s.Item4} }} /* {s.Item2} */")
.ToList();
if (usesPrefixes && !Options.NoBackground && _style.BackgroundColor != null)
{
var textStyle = "";
if (_tokenToClreplacedMap.Contains(TokenTypes.Text))
{
textStyle = " " + _cssToStyleMap[_tokenToClreplacedMap[TokenTypes.Text]].StyleRules;
}
lines.Insert(0, $"{prefix("")} {{ background: {_style.BackgroundColor}; {textStyle} }}");
}
if (_style.HighlightColor != null)
{
lines.Insert(0, $"{prefix("")}.hll {{ background-color: {_style.HighlightColor} }}");
}
return string.Join("\n", lines);
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
public static int Main(string[] args)
{
bool showHelp = false;
bool rebuildAllModules = false;
bool showUsage = false;
bool reboot = false;
bool installUnsigned = false;
bool installReferences = false;
bool deleteFiles = false;
bool deleteModules = false;
bool isCommandLine = false;
List<string> filesToOpen = new List<string>();
List<string> modulesToInstall = new List<string>();
List<string> modulesToUninstall = new List<string>();
bool clean = false;
bool cleanCache = false;
bool fetchreplacedets = false;
bool showWelcome = false;
bool showFilereplacedociations = false;
bool moduleCreator = false;
bool startNewProcess = false;
int delay = 0;
string keyOutputPrefix = null;
string globalSettingName = null;
string globalSettingValue = null;
bool logExceptions = false;
OptionSet argParser = new OptionSet()
{
{ "h|help", "Print this message and exit.", v => { showHelp = v != null; } },
{ "rebuild-all-modules", "Recompile all installed modules from the stored source code.", v => { rebuildAllModules = v != null; } },
{ "i|install=", "Install a module from a module.json.zip file and close the program (unless the -b/--boot option is also specified). This option can be specified multiple times.", v => { modulesToInstall.Add(v); } },
{ "install-references", "When installing modules, also install the module's additional references, if available.", v => { installReferences = v != null; } },
{ "install-unsigned", "Allow installing modules without a signature or with an invalid signature.", v => { installUnsigned = v != null; } },
{ "u|uninstall=", "Uninstall the module with the specified id and close the program (unless the -b/--boot option is also specified). If modules are being uninstalled and installed at the same time, the modules will be uninstalled first, then the program will be rebooted and the new modules installed. This option can be specified multiple times.", v => { modulesToUninstall.Add(v); } },
{ "b|boot", "Reboot the program after the specified module(s) have been installed or uninstalled.", v => { reboot = v != null; } },
{ "d|delete", "Deletes the tree files after opening them.", v => { deleteFiles = v != null; } },
{ "delete-modules", "Deletes the module files after installing them.", v => { deleteModules = v != null; } },
{ "w|wait=", "Wait for the specified number of milliseconds before doing anything.", v => { delay = int.Parse(v); } },
{ "clean", "Export all the currently installed modules, then uninstall all of them, delete the compiled module cache, and reinstall them.", v => { clean = v != null; } },
{ "fetch-replacedets", "When exporting currently installed modules, fetch the replacedets from their remote location, rather than retrieving them from the cache.", v => { fetchreplacedets = v != null; } },
{ "clean-cache", "Delete the compiled module cache. This will also remove all replacedets. You probably want to use the --clean command, instead.", v => { cleanCache = v != null; } },
{ "k|key=", "Create a public/private RSA key pair to be used when signing modules.", v => { keyOutputPrefix = v; } },
{ "welcome", "Show the welcome window.", v => { showWelcome = v != null; } },
{ "file-replacedociations", "Show the file replacedociations window.", v => { showFilereplacedociations = v != null; } },
{ "module-creator", "Start with the module creator window.", v => { moduleCreator = v != null; } },
{ "set-global={/}{=}", "Set the value of a global setting.", (n, v) => { globalSettingName = n; globalSettingValue = v; } },
{ "new-process", "Start a new process, even if another instance of TreeViewer is already running.", (v) => { startNewProcess = v != null; } },
{ "log-exceptions", "Log all handled and unhandles exceptions to the console.", (v) => { logExceptions = v != null; } },
};
List<string> unrecognised = argParser.Parse(args);
if (showWelcome || showFilereplacedociations)
{
moduleCreator = false;
}
if (unrecognised.Contains("--4e83aefc-1b77-4144-aa81-dc55cbca0329"))
{
WaitingForRebootAfterAdmin = true;
unrecognised.Remove("--4e83aefc-1b77-4144-aa81-dc55cbca0329");
}
if (unrecognised.Count > 0)
{
List<string> reallyUnrecognised = new List<string>();
for (int i = 0; i < unrecognised.Count; i++)
{
if (unrecognised[i].StartsWith("-"))
{
reallyUnrecognised.Add(unrecognised[i]);
}
else
{
filesToOpen.Add(unrecognised[i]);
}
}
if (reallyUnrecognised.Count > 0)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Unrecognised argument" + (reallyUnrecognised.Count > 1 ? "s" : "") + ": " + reallyUnrecognised.Aggregate((a, b) => a + " " + b));
showUsage = true;
}
}
if (showUsage || showHelp)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("TreeViewer version {0}", Version);
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Usage:");
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine(" TreeViewer {-h|--help}");
ConsoleWrapperUI.WriteLine(" TreeViewer [options...] [tree_file, [tree_file_2, ...]]");
ConsoleWrapperUI.WriteLine(" TreeViewer [-b] -i <module_file.json.zip> [-i <module_file_2.json.zip> ...]");
ConsoleWrapperUI.WriteLine(" TreeViewer [-b] -u <module_ID> [-u <module_ID_2> ...]");
}
if (showHelp)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Options:");
ConsoleWrapperUI.WriteLine();
argParser.WriteOptionDescriptions(Console.Out);
return 0;
}
if (showUsage)
{
return 64;
}
if (delay > 0)
{
ConsoleWrapperUI.EnableConsole();
System.Threading.Thread.Sleep(delay);
}
if (logExceptions)
{
System.Diagnostics.Stopwatch runTime = System.Diagnostics.Stopwatch.StartNew();
AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
{
long elapsed = runTime.ElapsedMilliseconds;
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Exception (first chance): " + e.Exception.GetType().Name + " @ T+" + TimeSpan.FromMilliseconds(elapsed).ToString());
ConsoleWrapperUI.WriteLine("\t" + e.Exception.Message.Replace("\n", "\n\t"));
ConsoleWrapperUI.WriteLine("\tin " + e.Exception.Source);
ConsoleWrapperUI.WriteLine("\t" + e.Exception.StackTrace.Replace("\n", "\n\t"));
ConsoleWrapperUI.WriteLine();
};
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
long elapsed = runTime.ElapsedMilliseconds;
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Exception (unhandled): " + e.ExceptionObject.GetType().Name + " @ T+" + TimeSpan.FromMilliseconds(elapsed).ToString());
if (e.ExceptionObject is Exception ex)
{
ConsoleWrapperUI.WriteLine("\t " + ex.Message.Replace("\n", "\n\t"));
ConsoleWrapperUI.WriteLine("\tin " + ex.Source);
ConsoleWrapperUI.WriteLine("\t" + ex.StackTrace.Replace("\n", "\n\t"));
ConsoleWrapperUI.WriteLine();
}
else
{
ConsoleWrapperUI.WriteLine("\t Unknown exception type!");
ConsoleWrapperUI.WriteLine();
}
if (e.IsTerminating)
{
ConsoleWrapperUI.WriteLine("Shutting down due to the exception!");
ConsoleWrapperUI.WriteLine();
}
};
ConsoleWrapperUI.EnableConsole();
try
{
throw new Exception("Making sure that the exception log system works.");
}
catch { }
}
// Force loading the System.Threading.Tasks.Parallel replacedembly
Parallel.For(0, 0, (i) => { });
List<string> pipeClientArgument = new List<string>();
if (deleteFiles)
{
pipeClientArgument.Add("::DeleteFiles");
}
else
{
pipeClientArgument.Add("::NoDeleteFiles");
}
pipeClientArgument.AddRange(from el in filesToOpen select System.IO.Path.GetFullPath(el));
if (NamedPipes.TryStartClient(pipeClientArgument.ToArray(), startNewProcess))
{
if (!startNewProcess)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Another instance of TreeViewer is already running. That instance has been signalled.");
ConsoleWrapperUI.WriteLine("Run TreeViewer with the --new-process switch to force a new process to spawn.");
ConsoleWrapperUI.WriteLine();
return 0;
}
}
else
{
NamedPipes.StartServer();
}
if (!string.IsNullOrEmpty(keyOutputPrefix))
{
try
{
CryptoUtils.CreateKeyPair(keyOutputPrefix);
return 0;
}
catch (Exception ex)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tAn error has occurred while generating the RSA key pair!");
ConsoleWrapperUI.WriteLine("\t\t" + ex.Message);
ConsoleWrapperUI.WriteLine();
return 1;
}
}
VectSharp.SVG.Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(VectSharp.SVG.Parser.ParseSVGURI);
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
if (!string.IsNullOrEmpty(globalSettingName))
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Loading installed modules...");
ConsoleWrapperUI.WriteLine();
_ = Modules.LoadInstalledModules(true, null);
try
{
GlobalSettings.SetSetting(globalSettingName, globalSettingValue);
GlobalSettings.SaveSettings();
if (!string.IsNullOrEmpty(globalSettingValue))
{
ConsoleWrapperUI.WriteLine("\tGlobal setting \"" + globalSettingName + "\" has been successfully changed to \"" + globalSettingValue + "\"!");
ConsoleWrapperUI.WriteLine();
}
else
{
ConsoleWrapperUI.WriteLine("\tGlobal setting \"" + globalSettingName + "\" has been reset to the default value!");
ConsoleWrapperUI.WriteLine();
}
return 0;
}
catch (Exception ex)
{
ConsoleWrapperUI.WriteLine("\tAn error has occurred while setting the global setting!");
ConsoleWrapperUI.WriteLine("\t\t" + ex.Message);
ConsoleWrapperUI.WriteLine();
return 1;
}
}
if (rebuildAllModules)
{
Modules.RebuildAllModules();
}
if (clean)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Loading installed modules...");
ConsoleWrapperUI.WriteLine();
_ = Modules.LoadInstalledModules(false, null);
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tExporting all currently installed modules...");
ConsoleWrapperUI.WriteLine();
List<string> exportedModules = ExportAllModules(fetchreplacedets);
ConsoleWrapperUI.WriteLine("\tResetting installed module database...");
System.IO.File.WriteAllText(Modules.ModuleListPath, "[]");
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tRebooting...");
ConsoleWrapperUI.WriteLine();
List<string> newArgs = new List<string>();
if (isCommandLine)
{
newArgs.Add("-c");
}
if (deleteFiles)
{
newArgs.Add("-d");
}
if (reboot)
{
newArgs.Add("-b");
}
newArgs.Add("--clean-cache");
if (installReferences)
{
newArgs.Add("--install-references");
}
if (installUnsigned)
{
newArgs.Add("--install-unsigned");
}
for (int i = 0; i < exportedModules.Count; i++)
{
newArgs.Add("-i");
newArgs.Add(exportedModules[i]);
}
newArgs.Add("--delete-modules");
newArgs.AddRange(filesToOpen);
Reboot(newArgs.ToArray(), false);
return 0;
}
if (modulesToUninstall.Count > 0)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Loading installed modules...");
ConsoleWrapperUI.WriteLine();
_ = Modules.LoadInstalledModules(false, null);
ConsoleWrapperUI.WriteLine();
for (int i = 0; i < modulesToUninstall.Count; i++)
{
try
{
ModuleMetadata.Uninstall(modulesToUninstall[i]);
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tModule {0} uninstalled successfully!", modulesToUninstall[i]);
ConsoleWrapperUI.WriteLine();
}
catch (Exception ex)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tCould not uninstall module {0}!", modulesToUninstall[i]);
ConsoleWrapperUI.WriteLine("\t\t" + ex.Message);
ConsoleWrapperUI.WriteLine();
return 1;
}
}
if (reboot || modulesToInstall.Count > 0 || cleanCache)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tRebooting...");
ConsoleWrapperUI.WriteLine();
List<string> newArgs = new List<string>();
if (isCommandLine)
{
newArgs.Add("-c");
}
if (deleteFiles)
{
newArgs.Add("-d");
}
if (reboot)
{
newArgs.Add("-b");
}
if (cleanCache)
{
newArgs.Add("--clean-cache");
}
if (deleteModules)
{
newArgs.Add("--delete-modules");
}
if (installReferences)
{
newArgs.Add("--install-references");
}
if (installUnsigned)
{
newArgs.Add("--install-unsigned");
}
for (int i = 0; i < modulesToInstall.Count; i++)
{
newArgs.Add("-i");
newArgs.Add(modulesToInstall[i]);
}
newArgs.AddRange(filesToOpen);
Reboot(newArgs.ToArray(), false);
return 0;
}
else
{
return 0;
}
}
if (cleanCache)
{
try
{
System.IO.Directory.Delete(Modules.ModulePath, true);
System.IO.Directory.CreateDirectory(Modules.ModulePath);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(Modules.ModulePath, "replacedets"));
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(Modules.ModulePath, "libraries"));
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tModule cache cleaned!");
ConsoleWrapperUI.WriteLine();
if (!reboot && modulesToInstall.Count == 0)
{
return 0;
}
}
catch (Exception ex)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tCould not clean the module cache!");
ConsoleWrapperUI.WriteLine("\t\t" + ex.Message);
ConsoleWrapperUI.WriteLine();
return 1;
}
}
if (modulesToInstall.Count > 0)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("Loading installed modules...");
ConsoleWrapperUI.WriteLine();
_ = Modules.LoadInstalledModules(false, null);
ConsoleWrapperUI.WriteLine();
for (int i = 0; i < modulesToInstall.Count; i++)
{
try
{
ModuleMetadata.Install(modulesToInstall[i], installUnsigned, installReferences);
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tModule {0} installed successfully!", modulesToInstall[i]);
ConsoleWrapperUI.WriteLine();
if (deleteModules)
{
try
{
System.IO.File.Delete(modulesToInstall[i]);
}
catch { }
}
}
catch (Exception ex)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tCould not install module {0}!", modulesToInstall[i]);
ConsoleWrapperUI.WriteLine("\t\t" + ex.Message);
ConsoleWrapperUI.WriteLine();
return 1;
}
}
if (reboot)
{
ConsoleWrapperUI.WriteLine();
ConsoleWrapperUI.WriteLine("\tRebooting...");
ConsoleWrapperUI.WriteLine();
List<string> newArgs = new List<string>();
if (isCommandLine)
{
newArgs.Add("-c");
}
if (deleteFiles)
{
newArgs.Add("-d");
}
newArgs.AddRange(filesToOpen);
Reboot(newArgs.ToArray(), false);
return 0;
}
else
{
return 0;
}
}
filesToOpen.Insert(0, showWelcome.ToString());
filesToOpen.Insert(1, showFilereplacedociations.ToString());
filesToOpen.Insert(2, moduleCreator.ToString());
filesToOpen.Insert(3, deleteFiles.ToString());
BuildAvaloniaApp().StartWithClreplacedicDesktopLifetime(filesToOpen.ToArray());
return 0;
}
See More Examples