<commit_before>
#include "FlareList.h"
#include "../../Flare.h"

#include "../../Game/FlareGame.h"
#include "../../Game/FlareGameTools.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"

#include "../../Spacecrafts/Subsystems/FlareSimulatedSpacecraftWeaponsSystem.h"

#define LOCTEXT_NAMESPACE "FlareList"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareList::Construct(const FArguments& InArgs)
{
	// Data
	MenuManager = InArgs._MenuManager;
	UseCompactDisplay = InArgs._UseCompactDisplay;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	AFlarePlayerController* PC = MenuManager->GetPC();
	OnItemSelected = InArgs._OnItemSelected;
	HasShips = false;

	// Build structure
	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Left)
	[
		SNew(SBox)
		.WidthOverride(Theme.ContentWidth)
		[
			SNew(SVerticalBox)

			// Filters
			+ SVerticalBox::Slot()
			.AutoHeight()
			.HAlign(HAlign_Fill)
			.Padding(Theme.TitlePadding)
			[
				SNew(SHorizontalBox)

				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				[
					SAssignNew(Title, STextBlock)
					.Text(InArgs._Title)
					.TextStyle(&FFlareStyleSet::GetDefaultTheme().SubTitleFont)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowStationsButton, SFlareButton)
					.Text(LOCTEXT("ShowStations", "Stations"))
					.HelpText(LOCTEXT("ShowStationsInfo", "Show stations in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowMilitaryButton, SFlareButton)
					.Text(LOCTEXT("ShowMilitary", "Military"))
					.HelpText(LOCTEXT("ShowMilitaryInfo", "Show military ships in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowFreightersButton, SFlareButton)
					.Text(LOCTEXT("ShowFreighters", "Freighters"))
					.HelpText(LOCTEXT("ShowFreightersInfo", "Show freighters in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]
			]

			// Box
			+ SVerticalBox::Slot()
			.AutoHeight()
			.HAlign(HAlign_Fill)
			[
				SNew(SVerticalBox)

				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(UFlareGameTools::AddLeadingSpace(LOCTEXT("NothingSpaced", "No objects.\n\n"), 3))
					.TextStyle(&FFlareStyleSet::GetDefaultTheme().TextFont)
					.Visibility(this, &SFlareList::GetNoObjectsVisibility)
				]

				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SAssignNew(WidgetList, SListView< TSharedPtr<FInterfaceContainer> >)
					.ListItemsSource(&FilteredObjectList)
					.SelectionMode(ESelectionMode::Single)
					.OnGenerateRow(this, &SFlareList::GenerateTargetInfo)
					.OnSelectionChanged(this, &SFlareList::OnTargetSelected)
				]
			]
		]
	];

	// Set filters
	ShowStationsButton->SetActive(true);
	ShowMilitaryButton->SetActive(true);
	ShowFreightersButton->SetActive(true);
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareList::AddFleet(UFlareFleet* Fleet)
{
	ObjectList.AddUnique(FInterfaceContainer::New(Fleet));
}

void SFlareList::AddShip(UFlareSimulatedSpacecraft* Ship)
{
	HasShips = true;
	ObjectList.AddUnique(FInterfaceContainer::New(Ship));
}

void SFlareList::RefreshList()
{
	struct FSortBySize
	{
		FORCEINLINE bool operator()(const TSharedPtr<FInterfaceContainer> PtrA, const TSharedPtr<FInterfaceContainer> PtrB) const
		{
			FCHECK(PtrA.IsValid());
			FCHECK(PtrB.IsValid());

			// Fleets
			if (PtrA->FleetPtr)
			{
				if (PtrB->FleetPtr)
				{
					UFlareFleet* PlayerFleet = PtrA->FleetPtr->GetGame()->GetPC()->GetPlayerFleet();

					if (PtrA->FleetPtr == PlayerFleet)
					{
						return true;
					}
					else if (PtrB->FleetPtr == PlayerFleet)
					{
						return false;
					}
					else
					{
						return (PtrA->FleetPtr->GetShips().Num() > PtrB->FleetPtr->GetShips().Num());
					}
				}
				else
				{
					return true;
				}
			}
			else if (PtrB->FleetPtr)
			{
				return false;
			}

			// Stations
			else
			{
				UFlareSimulatedSpacecraft* A = PtrA->SpacecraftPtr;
				UFlareSimulatedSpacecraft* B = PtrB->SpacecraftPtr;

				if (A->IsPlayerShip() != B->IsPlayerShip())
				{
					return A->IsPlayerShip();
				}
				else if (A->IsStation() && B->IsStation())
				{
					if (A->GetDescription()->IsSubstation && !B->GetDescription()->IsSubstation)
					{
						return true;
					}
					else if (!A->GetDescription()->IsSubstation && B->GetDescription()->IsSubstation)
					{
						return false;
					}
					else if (A->GetDescription()->GetCapacity() != B->GetDescription()->GetCapacity())
					{
						return A->GetDescription()->GetCapacity() > B->GetDescription()->GetCapacity();
					}
					else
					{
						return A->GetDescription()->Mass > B->GetDescription()->Mass;
					}
				}
				else if (A->IsStation() && !B->IsStation())
				{
					return true;
				}
				else if (!A->IsStation() && B->IsStation())
				{
					return false;
				}

				// Ships
				else if (A->GetSize() > B->GetSize())
				{
					return true;
				}
				else if (A->GetSize() < B->GetSize())
				{
					return false;
				}
				else if (A->IsMilitary())
				{
					if (!B->IsMilitary())
					{
						return true;
					}
					else
					{
						return A->GetWeaponsSystem()->GetWeaponGroupCount() > B->GetWeaponsSystem()->GetWeaponGroupCount();
					}
				}
				else
				{
					return false;
				}
			}
			return false;
		}
	};

	ClearSelection();

	// Apply filters
	FilteredObjectList.Empty();
	for (auto Object : ObjectList)
	{
		// Ships have three filters
		if (Object->SpacecraftPtr)
		{
			bool IsStation = Object->SpacecraftPtr->IsStation();
			bool IsMilitary = Object->SpacecraftPtr->IsMilitary();

			if ((IsStation && ShowStationsButton->IsActive())
			 || (IsMilitary && ShowMilitaryButton->IsActive())
			 || (!IsStation && !IsMilitary && ShowFreightersButton->IsActive()))
			{
				FilteredObjectList.Add(Object);
			}
		}

		// Fleets have no filters
		else
		{
			FilteredObjectList.Add(Object);
		}
	}

	// Sort and update
	FilteredObjectList.Sort(FSortBySize());
	WidgetList->RequestListRefresh();
	SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale());
}

void SFlareList::ClearSelection()
{
	WidgetList->ClearSelection();

	// De-select previous widget
	if (PreviousWidget.IsValid())
	{
		if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
		{
			StaticCastSharedRef<SFlareSpacecraftInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
		}
		else if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
		{
			StaticCastSharedRef<SFlareFleetInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
		}

		PreviousWidget->SetSelected(false);
	}
}

void SFlareList::SetTitle(FText NewTitle)
{
	Title->SetText(NewTitle);
}

void SFlareList::SetUseCompactDisplay(bool Status)
{
	UseCompactDisplay = Status;
}

void SFlareList::Reset()
{
	HasShips = false;

	ObjectList.Empty();
	FilteredObjectList.Empty();

	WidgetList->ClearSelection();
	WidgetList->RequestListRefresh();

	SelectedObject.Reset();
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

EVisibility SFlareList::GetNoObjectsVisibility() const
{
	return (FilteredObjectList.Num() > 0 ? EVisibility::Collapsed : EVisibility::Visible);
}

EVisibility SFlareList::GetShipFiltersVisibility() const
{
	return (HasShips ? EVisibility::Visible : EVisibility::Hidden);
}

TSharedRef<ITableRow> SFlareList::GenerateTargetInfo(TSharedPtr<FInterfaceContainer> Item, const TSharedRef<STableViewBase>& OwnerTable)
{
	TSharedPtr<SFlareListItem> ListItem;
	int32 Width = 15;
	int32 Height = 1;

	// Ship
	if (Item->SpacecraftPtr)
	{
		TSharedPtr<SFlareSpacecraftInfo> Temp;

		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Width(Width)
		.Height(Height)
		.Content()
		[
			SAssignNew(Temp, SFlareSpacecraftInfo)
			.Player(MenuManager->GetPC())
			.OwnerWidget(this)
			.Minimized(true)
			.OnRemoved(this, &SFlareList::OnShipRemoved)
		];

		Temp->SetSpacecraft(Item->SpacecraftPtr);
		Temp->Show();
	}

	// Fleet
	else if (Item->FleetPtr)
	{
		TSharedPtr<SFlareFleetInfo> Temp;

		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Width(Width)
		.Height(Height)
		.Content()
		[
			SAssignNew(Temp, SFlareFleetInfo)
			.Player(MenuManager->GetPC())
			.OwnerWidget(this)
			.Minimized(true)
		];

		Temp->SetFleet(Item->FleetPtr);
		Temp->Show();
	}

	// Invalid item
	else
	{
		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Content()
		[
			SNew(STextBlock).Text(LOCTEXT("Invalid", "Invalid item"))
		];
	}

	return ListItem.ToSharedRef();
}

void SFlareList::OnTargetSelected(TSharedPtr<FInterfaceContainer> Item, ESelectInfo::Type SelectInfo)
{
	FLOG("SFlareList::OnTargetSelected");

	SelectedObject = Item;
	TSharedPtr<SFlareListItem> NewWidget = StaticCastSharedPtr<SFlareListItem>(WidgetList->WidgetFromItem(Item));
	bool UseExpandedDisplay = Item.IsValid() && (Item->SpacecraftPtr || Item->FleetPtr) && !UseCompactDisplay;

	// De-select previous item
	if (PreviousWidget.IsValid())
	{
		if (UseExpandedDisplay)
		{
			if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
			{
				StaticCastSharedRef<SFlareSpacecraftInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
			}
			else if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
			{
				StaticCastSharedRef<SFlareFleetInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
			}
		}

		PreviousWidget->SetSelected(false);
	}

	// Select new item
	if (NewWidget.IsValid())
	{
		if (OnItemSelected.IsBound())
		{
			OnItemSelected.Execute(Item);
		}

		if (UseExpandedDisplay)
		{
			if (NewWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
			{
				StaticCastSharedRef<SFlareSpacecraftInfo>(NewWidget->GetContainer()->GetContent())->SetMinimized(false);
			}
			else if (NewWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
			{
				StaticCastSharedRef<SFlareFleetInfo>(NewWidget->GetContainer()->GetContent())->SetMinimized(false);
			}
		}

		NewWidget->SetSelected(true);
		PreviousWidget = NewWidget;
	}
}

void SFlareList::OnToggleShowFlags()
{
	RefreshList();
}

void SFlareList::OnShipRemoved(UFlareSimulatedSpacecraft* Ship)
{
	for (auto Spacecraft : ObjectList)
	{
		if (Spacecraft->SpacecraftPtr == Ship)
		{
			ObjectList.Remove(Spacecraft);
			break;
		}
	}

	PreviousWidget.Reset();
	RefreshList();
}

#undef LOCTEXT_NAMESPACE

<commit_msg>#1068 Fix fleets not ordered in a sane way<commit_after>
#include "FlareList.h"
#include "../../Flare.h"

#include "../../Game/FlareGame.h"
#include "../../Game/FlareGameTools.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"

#include "../../Spacecrafts/Subsystems/FlareSimulatedSpacecraftWeaponsSystem.h"

#define LOCTEXT_NAMESPACE "FlareList"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareList::Construct(const FArguments& InArgs)
{
	// Data
	MenuManager = InArgs._MenuManager;
	UseCompactDisplay = InArgs._UseCompactDisplay;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	AFlarePlayerController* PC = MenuManager->GetPC();
	OnItemSelected = InArgs._OnItemSelected;
	HasShips = false;

	// Build structure
	ChildSlot
	.VAlign(VAlign_Fill)
	.HAlign(HAlign_Left)
	[
		SNew(SBox)
		.WidthOverride(Theme.ContentWidth)
		[
			SNew(SVerticalBox)

			// Filters
			+ SVerticalBox::Slot()
			.AutoHeight()
			.HAlign(HAlign_Fill)
			.Padding(Theme.TitlePadding)
			[
				SNew(SHorizontalBox)

				+ SHorizontalBox::Slot()
				.VAlign(VAlign_Center)
				[
					SAssignNew(Title, STextBlock)
					.Text(InArgs._Title)
					.TextStyle(&FFlareStyleSet::GetDefaultTheme().SubTitleFont)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowStationsButton, SFlareButton)
					.Text(LOCTEXT("ShowStations", "Stations"))
					.HelpText(LOCTEXT("ShowStationsInfo", "Show stations in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowMilitaryButton, SFlareButton)
					.Text(LOCTEXT("ShowMilitary", "Military"))
					.HelpText(LOCTEXT("ShowMilitaryInfo", "Show military ships in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]

				+ SHorizontalBox::Slot()
				.AutoWidth()
				[
					SAssignNew(ShowFreightersButton, SFlareButton)
					.Text(LOCTEXT("ShowFreighters", "Freighters"))
					.HelpText(LOCTEXT("ShowFreightersInfo", "Show freighters in the list"))
					.OnClicked(this, &SFlareList::OnToggleShowFlags)
					.Visibility(this, &SFlareList::GetShipFiltersVisibility)
					.Small(true)
					.Transparent(true)
					.Toggle(true)
					.Width(2)
				]
			]

			// Box
			+ SVerticalBox::Slot()
			.AutoHeight()
			.HAlign(HAlign_Fill)
			[
				SNew(SVerticalBox)

				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SNew(STextBlock)
					.Text(UFlareGameTools::AddLeadingSpace(LOCTEXT("NothingSpaced", "No objects.\n\n"), 3))
					.TextStyle(&FFlareStyleSet::GetDefaultTheme().TextFont)
					.Visibility(this, &SFlareList::GetNoObjectsVisibility)
				]

				+ SVerticalBox::Slot()
				.AutoHeight()
				[
					SAssignNew(WidgetList, SListView< TSharedPtr<FInterfaceContainer> >)
					.ListItemsSource(&FilteredObjectList)
					.SelectionMode(ESelectionMode::Single)
					.OnGenerateRow(this, &SFlareList::GenerateTargetInfo)
					.OnSelectionChanged(this, &SFlareList::OnTargetSelected)
				]
			]
		]
	];

	// Set filters
	ShowStationsButton->SetActive(true);
	ShowMilitaryButton->SetActive(true);
	ShowFreightersButton->SetActive(true);
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareList::AddFleet(UFlareFleet* Fleet)
{
	ObjectList.AddUnique(FInterfaceContainer::New(Fleet));
}

void SFlareList::AddShip(UFlareSimulatedSpacecraft* Ship)
{
	HasShips = true;
	ObjectList.AddUnique(FInterfaceContainer::New(Ship));
}

void SFlareList::RefreshList()
{
	struct FSortBySize
	{
		FORCEINLINE bool operator()(const TSharedPtr<FInterfaceContainer> PtrA, const TSharedPtr<FInterfaceContainer> PtrB) const
		{
			FCHECK(PtrA.IsValid());
			FCHECK(PtrB.IsValid());

			// Fleets
			if (PtrA->FleetPtr)
			{
				if (PtrB->FleetPtr)
				{
					UFlareFleet* PlayerFleet = PtrA->FleetPtr->GetGame()->GetPC()->GetPlayerFleet();

					if (PtrA->FleetPtr == PlayerFleet)
					{
						return true;
					}
					else if (PtrB->FleetPtr == PlayerFleet)
					{
						return false;
					}
					else
					{
						int32 ValueA = PtrA->FleetPtr->GetCombatPoints(true);
						int32 ValueB = PtrB->FleetPtr->GetCombatPoints(true);

						if (ValueA != ValueB)
						{
							return ValueA > ValueB;
						}
						else
						{
							return PtrA->FleetPtr->GetFleetName().ToString().Compare(PtrB->FleetPtr->GetFleetName().ToString()) < 0;
						}
					}
				}
				else
				{
					return true;
				}
			}
			else if (PtrB->FleetPtr)
			{
				return false;
			}

			// Stations
			else
			{
				UFlareSimulatedSpacecraft* A = PtrA->SpacecraftPtr;
				UFlareSimulatedSpacecraft* B = PtrB->SpacecraftPtr;

				if (A->IsPlayerShip() != B->IsPlayerShip())
				{
					return A->IsPlayerShip();
				}
				else if (A->IsStation() && B->IsStation())
				{
					if (A->GetDescription()->IsSubstation && !B->GetDescription()->IsSubstation)
					{
						return true;
					}
					else if (!A->GetDescription()->IsSubstation && B->GetDescription()->IsSubstation)
					{
						return false;
					}
					else if (A->GetDescription()->GetCapacity() != B->GetDescription()->GetCapacity())
					{
						return A->GetDescription()->GetCapacity() > B->GetDescription()->GetCapacity();
					}
					else
					{
						return A->GetDescription()->Mass > B->GetDescription()->Mass;
					}
				}
				else if (A->IsStation() && !B->IsStation())
				{
					return true;
				}
				else if (!A->IsStation() && B->IsStation())
				{
					return false;
				}

				// Ships
				else if (A->GetSize() > B->GetSize())
				{
					return true;
				}
				else if (A->GetSize() < B->GetSize())
				{
					return false;
				}
				else if (A->IsMilitary())
				{
					if (!B->IsMilitary())
					{
						return true;
					}
					else
					{
						return A->GetWeaponsSystem()->GetWeaponGroupCount() > B->GetWeaponsSystem()->GetWeaponGroupCount();
					}
				}
				else
				{
					return false;
				}
			}
			return false;
		}
	};

	ClearSelection();

	// Apply filters
	FilteredObjectList.Empty();
	for (auto Object : ObjectList)
	{
		// Ships have three filters
		if (Object->SpacecraftPtr)
		{
			bool IsStation = Object->SpacecraftPtr->IsStation();
			bool IsMilitary = Object->SpacecraftPtr->IsMilitary();

			if ((IsStation && ShowStationsButton->IsActive())
			 || (IsMilitary && ShowMilitaryButton->IsActive())
			 || (!IsStation && !IsMilitary && ShowFreightersButton->IsActive()))
			{
				FilteredObjectList.Add(Object);
			}
		}

		// Fleets have no filters
		else
		{
			FilteredObjectList.Add(Object);
		}
	}

	// Sort and update
	FilteredObjectList.Sort(FSortBySize());
	WidgetList->RequestListRefresh();
	SlatePrepass(FSlateApplicationBase::Get().GetApplicationScale());
}

void SFlareList::ClearSelection()
{
	WidgetList->ClearSelection();

	// De-select previous widget
	if (PreviousWidget.IsValid())
	{
		if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
		{
			StaticCastSharedRef<SFlareSpacecraftInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
		}
		else if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
		{
			StaticCastSharedRef<SFlareFleetInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
		}

		PreviousWidget->SetSelected(false);
	}
}

void SFlareList::SetTitle(FText NewTitle)
{
	Title->SetText(NewTitle);
}

void SFlareList::SetUseCompactDisplay(bool Status)
{
	UseCompactDisplay = Status;
}

void SFlareList::Reset()
{
	HasShips = false;

	ObjectList.Empty();
	FilteredObjectList.Empty();

	WidgetList->ClearSelection();
	WidgetList->RequestListRefresh();

	SelectedObject.Reset();
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

EVisibility SFlareList::GetNoObjectsVisibility() const
{
	return (FilteredObjectList.Num() > 0 ? EVisibility::Collapsed : EVisibility::Visible);
}

EVisibility SFlareList::GetShipFiltersVisibility() const
{
	return (HasShips ? EVisibility::Visible : EVisibility::Hidden);
}

TSharedRef<ITableRow> SFlareList::GenerateTargetInfo(TSharedPtr<FInterfaceContainer> Item, const TSharedRef<STableViewBase>& OwnerTable)
{
	TSharedPtr<SFlareListItem> ListItem;
	int32 Width = 15;
	int32 Height = 1;

	// Ship
	if (Item->SpacecraftPtr)
	{
		TSharedPtr<SFlareSpacecraftInfo> Temp;

		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Width(Width)
		.Height(Height)
		.Content()
		[
			SAssignNew(Temp, SFlareSpacecraftInfo)
			.Player(MenuManager->GetPC())
			.OwnerWidget(this)
			.Minimized(true)
			.OnRemoved(this, &SFlareList::OnShipRemoved)
		];

		Temp->SetSpacecraft(Item->SpacecraftPtr);
		Temp->Show();
	}

	// Fleet
	else if (Item->FleetPtr)
	{
		TSharedPtr<SFlareFleetInfo> Temp;

		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Width(Width)
		.Height(Height)
		.Content()
		[
			SAssignNew(Temp, SFlareFleetInfo)
			.Player(MenuManager->GetPC())
			.OwnerWidget(this)
			.Minimized(true)
		];

		Temp->SetFleet(Item->FleetPtr);
		Temp->Show();
	}

	// Invalid item
	else
	{
		SAssignNew(ListItem, SFlareListItem, OwnerTable)
		.Content()
		[
			SNew(STextBlock).Text(LOCTEXT("Invalid", "Invalid item"))
		];
	}

	return ListItem.ToSharedRef();
}

void SFlareList::OnTargetSelected(TSharedPtr<FInterfaceContainer> Item, ESelectInfo::Type SelectInfo)
{
	FLOG("SFlareList::OnTargetSelected");

	SelectedObject = Item;
	TSharedPtr<SFlareListItem> NewWidget = StaticCastSharedPtr<SFlareListItem>(WidgetList->WidgetFromItem(Item));
	bool UseExpandedDisplay = Item.IsValid() && (Item->SpacecraftPtr || Item->FleetPtr) && !UseCompactDisplay;

	// De-select previous item
	if (PreviousWidget.IsValid())
	{
		if (UseExpandedDisplay)
		{
			if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
			{
				StaticCastSharedRef<SFlareSpacecraftInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
			}
			else if (PreviousWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
			{
				StaticCastSharedRef<SFlareFleetInfo>(PreviousWidget->GetContainer()->GetContent())->SetMinimized(true);
			}
		}

		PreviousWidget->SetSelected(false);
	}

	// Select new item
	if (NewWidget.IsValid())
	{
		if (OnItemSelected.IsBound())
		{
			OnItemSelected.Execute(Item);
		}

		if (UseExpandedDisplay)
		{
			if (NewWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareSpacecraftInfo")
			{
				StaticCastSharedRef<SFlareSpacecraftInfo>(NewWidget->GetContainer()->GetContent())->SetMinimized(false);
			}
			else if (NewWidget->GetContainer()->GetContent()->GetTypeAsString() == "SFlareFleetInfo")
			{
				StaticCastSharedRef<SFlareFleetInfo>(NewWidget->GetContainer()->GetContent())->SetMinimized(false);
			}
		}

		NewWidget->SetSelected(true);
		PreviousWidget = NewWidget;
	}
}

void SFlareList::OnToggleShowFlags()
{
	RefreshList();
}

void SFlareList::OnShipRemoved(UFlareSimulatedSpacecraft* Ship)
{
	for (auto Spacecraft : ObjectList)
	{
		if (Spacecraft->SpacecraftPtr == Ship)
		{
			ObjectList.Remove(Spacecraft);
			break;
		}
	}

	PreviousWidget.Reset();
	RefreshList();
}

#undef LOCTEXT_NAMESPACE

<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <string>
#include <iostream>
#include <vector>
#include <atomic>

#include "cxxopts.hpp"

#include "Options.hpp"
#include "Utils.hpp"

using namespace eddic;

namespace {

void init_options(cxxopts::Options& options){
    options.add_options("General")
        ("h,help", "Generate this help message")
        ("S,assembly", "Generate only the assembly")
        ("k,keep", "Keep the assembly file")
        ("version", "Print the version of eddic")
        ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out"))
        ("g,debug", "Add debugging symbols")
        ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100"))
        ("32", "Force the compilation for 32 bits platform")
        ("64", "Force the compilation for 64 bits platform")
        ("warning-all", "Enable all the warning messages")
        ("warning-unused", "Warn about unused variables, parameters and functions")
        ("warning-cast", "Warn about useless casts")
        ("warning-effects", "Warn about statements without effect")
        ("warning-includes", "Warn about useless includes")
        ;

    options.add_options("Display")
        ("ast", "Print the Abstract Syntax Tree representation of the source")
        ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ")
        ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
        ("mtac", "Print the medium-level Three Address Code representation of the source")
        ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed")
        ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)")
        ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers")
        ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization")
        ("ltac", "Print the final low-level Three Address Code representation of the source")
        ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)")
        ;

    options.add_options("Optimization")
        ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2"))
        ("O0", "Disable all optimizations")
        ("O1", "Enable low-level optimizations")
        ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.")
        ("O3", "Enable all optimizations improving the speed but can increase the size of the program.")
        ("fglobal-optimization", "Enable optimizer engine")
        ("fparameter-allocation", "Enable parameter allocation in register")
        ("fpeephole-optimization", "Enable peephole optimizer")
        ("fomit-frame-pointer", "Omit frame pointer from functions")
        ("finline-functions", "Enable inlining")
        ("fno-inline-functions", "Disable inlining")
        ("funroll-loops", "Enable Loop Unrolling")
        ("fcomplete-peel-loops", "Enable Complete Loop Peeling")
        ;

    options.add_options("Backend")
        ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0"))
        ("q,quiet", "Do not print anything")
        ("v,verbose", "Make the compiler verbose")
        ("single-threaded", "Disable the multi-threaded optimization")
        ("time", "Activate the timing system")
        ("stats", "Activate the statistics system")
        ("input", "Input file", cxxopts::value<std::string>())
        ;
}

using triggers_t = std::unordered_map<std::string, std::vector<std::string>>;

void add_trigger(triggers_t& triggers, const std::string& option, const std::vector<std::string>& childs){
   triggers[option] = childs;
}

inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){
    for(auto& child : childs){
        configuration->values[child].defined = true;
        configuration->values[child].value = std::string("true");
    }
}

} //end of anonymous namespace

std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) {
    //Create a new configuration
    auto configuration = std::make_shared<Configuration>();

    triggers_t triggers;

    try {
        add_trigger(triggers, "warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"});

        //Special triggers for optimization levels
        add_trigger(triggers, "__1", {"fpeephole-optimization"});
        add_trigger(triggers, "__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"});
        add_trigger(triggers, "__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"});

        cxxopts::Options options("eddic", "  source.eddi");

        init_options(options);

        options.parse_positional("input");

        auto& v = const_cast<char**&>(argv);
        options.parse(argc, v);

        for(auto& group : options.groups()){
            for(auto& option : options.group_help(group).options){
                auto name = option.l.empty() ? option.s : option.l;

                ConfigValue value;

                if(options.count(name)){
                    value.defined = true;

                    if(option.has_arg){
                        value.value = options[name].as<std::string>();
                    } else {
                        value.value = "true";
                    }
                } else {
                    value.defined = false;
                    value.value = "false";
                }

                configuration->values[name] = value;
            }
        }

        if(options.count("O0") + options.count("O1") + options.count("O2") > 1){
            std::cout << "Invalid command line options : only one optimization level should be set" << std::endl;

            return nullptr;
        }

        if(options.count("64") && options.count("32")){
            std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;

            return nullptr;
        }

        //Update optimization level based on special switches
        if(options.count("O0")){
            configuration->values["Opt"].value = "0";
        } else if(options.count("O1")){
            configuration->values["Opt"].value = "1";
        } else if(options.count("O2")){
            configuration->values["Opt"].value = "2";
        } else if(options.count("O3")){
            configuration->values["Opt"].value = "3";
        }

        //Triggers dependent options
        for(auto& trigger : triggers){
            if(configuration->option_defined(trigger.first)){
                trigger_childs(configuration, trigger.second);
            }
        }

        if(configuration->option_int_value("Opt") >= 1){
            trigger_childs(configuration, triggers["__1"]);
        }

        if(configuration->option_int_value("Opt") >= 2){
            trigger_childs(configuration, triggers["__2"]);
        }

        if(configuration->option_int_value("Opt") >= 3){
            trigger_childs(configuration, triggers["__3"]);
        }
    } catch (const cxxopts::OptionException& e) {
        std::cout << "Invalid command line options: " << e.what() << std::endl;

        return nullptr;
    }

    return configuration;
}

bool Configuration::option_defined(const std::string& option_name){
    return values[option_name].defined;
}

std::string Configuration::option_value(const std::string& option_name){
    return values[option_name].value;
}

int Configuration::option_int_value(const std::string& option_name){
    return toNumber<int>(values[option_name].value);
}

void eddic::print_help(){
    cxxopts::Options options("eddic", "  source.eddi");

    init_options(options);

    std::cout << options.help({"General", "Display", "Optimization"}) << std::endl;
}

void eddic::print_version(){
    std::cout << "eddic version 1.2.3" << std::endl;
}
<commit_msg>No need for RTTI here<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2014.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <string>
#include <iostream>
#include <vector>
#include <atomic>

#define CXXOPTS_NO_RTTI
#include "cxxopts.hpp"

#include "Options.hpp"
#include "Utils.hpp"

using namespace eddic;

namespace {

void init_options(cxxopts::Options& options){
    options.add_options("General")
        ("h,help", "Generate this help message")
        ("S,assembly", "Generate only the assembly")
        ("k,keep", "Keep the assembly file")
        ("version", "Print the version of eddic")
        ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out"))
        ("g,debug", "Add debugging symbols")
        ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100"))
        ("32", "Force the compilation for 32 bits platform")
        ("64", "Force the compilation for 64 bits platform")
        ("warning-all", "Enable all the warning messages")
        ("warning-unused", "Warn about unused variables, parameters and functions")
        ("warning-cast", "Warn about useless casts")
        ("warning-effects", "Warn about statements without effect")
        ("warning-includes", "Warn about useless includes")
        ;

    options.add_options("Display")
        ("ast", "Print the Abstract Syntax Tree representation of the source")
        ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ")
        ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
        ("mtac", "Print the medium-level Three Address Code representation of the source")
        ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed")
        ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)")
        ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers")
        ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization")
        ("ltac", "Print the final low-level Three Address Code representation of the source")
        ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)")
        ;

    options.add_options("Optimization")
        ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2"))
        ("O0", "Disable all optimizations")
        ("O1", "Enable low-level optimizations")
        ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.")
        ("O3", "Enable all optimizations improving the speed but can increase the size of the program.")
        ("fglobal-optimization", "Enable optimizer engine")
        ("fparameter-allocation", "Enable parameter allocation in register")
        ("fpeephole-optimization", "Enable peephole optimizer")
        ("fomit-frame-pointer", "Omit frame pointer from functions")
        ("finline-functions", "Enable inlining")
        ("fno-inline-functions", "Disable inlining")
        ("funroll-loops", "Enable Loop Unrolling")
        ("fcomplete-peel-loops", "Enable Complete Loop Peeling")
        ;

    options.add_options("Backend")
        ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0"))
        ("q,quiet", "Do not print anything")
        ("v,verbose", "Make the compiler verbose")
        ("single-threaded", "Disable the multi-threaded optimization")
        ("time", "Activate the timing system")
        ("stats", "Activate the statistics system")
        ("input", "Input file", cxxopts::value<std::string>())
        ;
}

using triggers_t = std::unordered_map<std::string, std::vector<std::string>>;

void add_trigger(triggers_t& triggers, const std::string& option, const std::vector<std::string>& childs){
   triggers[option] = childs;
}

inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){
    for(auto& child : childs){
        configuration->values[child].defined = true;
        configuration->values[child].value = std::string("true");
    }
}

} //end of anonymous namespace

std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) {
    //Create a new configuration
    auto configuration = std::make_shared<Configuration>();

    triggers_t triggers;

    try {
        add_trigger(triggers, "warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"});

        //Special triggers for optimization levels
        add_trigger(triggers, "__1", {"fpeephole-optimization"});
        add_trigger(triggers, "__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"});
        add_trigger(triggers, "__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"});

        cxxopts::Options options("eddic", "  source.eddi");

        init_options(options);

        options.parse_positional("input");

        auto& v = const_cast<char**&>(argv);
        options.parse(argc, v);

        for(auto& group : options.groups()){
            for(auto& option : options.group_help(group).options){
                auto name = option.l.empty() ? option.s : option.l;

                ConfigValue value;

                if(options.count(name)){
                    value.defined = true;

                    if(option.has_arg){
                        value.value = options[name].as<std::string>();
                    } else {
                        value.value = "true";
                    }
                } else {
                    value.defined = false;
                    value.value = "false";
                }

                configuration->values[name] = value;
            }
        }

        if(options.count("O0") + options.count("O1") + options.count("O2") > 1){
            std::cout << "Invalid command line options : only one optimization level should be set" << std::endl;

            return nullptr;
        }

        if(options.count("64") && options.count("32")){
            std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;

            return nullptr;
        }

        //Update optimization level based on special switches
        if(options.count("O0")){
            configuration->values["Opt"].value = "0";
        } else if(options.count("O1")){
            configuration->values["Opt"].value = "1";
        } else if(options.count("O2")){
            configuration->values["Opt"].value = "2";
        } else if(options.count("O3")){
            configuration->values["Opt"].value = "3";
        }

        //Triggers dependent options
        for(auto& trigger : triggers){
            if(configuration->option_defined(trigger.first)){
                trigger_childs(configuration, trigger.second);
            }
        }

        if(configuration->option_int_value("Opt") >= 1){
            trigger_childs(configuration, triggers["__1"]);
        }

        if(configuration->option_int_value("Opt") >= 2){
            trigger_childs(configuration, triggers["__2"]);
        }

        if(configuration->option_int_value("Opt") >= 3){
            trigger_childs(configuration, triggers["__3"]);
        }
    } catch (const cxxopts::OptionException& e) {
        std::cout << "Invalid command line options: " << e.what() << std::endl;

        return nullptr;
    }

    return configuration;
}

bool Configuration::option_defined(const std::string& option_name){
    return values[option_name].defined;
}

std::string Configuration::option_value(const std::string& option_name){
    return values[option_name].value;
}

int Configuration::option_int_value(const std::string& option_name){
    return toNumber<int>(values[option_name].value);
}

void eddic::print_help(){
    cxxopts::Options options("eddic", "  source.eddi");

    init_options(options);

    std::cout << options.help({"General", "Display", "Optimization"}) << std::endl;
}

void eddic::print_version(){
    std::cout << "eddic version 1.2.3" << std::endl;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPropPicker.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPropPicker.h"
#include "vtkWorldPointPicker.h"
#include "vtkAssemblyNode.h"
#include "vtkObjectFactory.h"

vtkPropPicker* vtkPropPicker::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPropPicker");
  if(ret)
    {
    return (vtkPropPicker*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPropPicker;
}

vtkPropPicker::vtkPropPicker()
{
  this->PickFromProps = NULL;
  this->WorldPointPicker = vtkWorldPointPicker::New();
}

vtkPropPicker::~vtkPropPicker()
{
  this->WorldPointPicker->Delete();
}

// set up for a pick
void vtkPropPicker::Initialize()
{
  this->vtkAbstractPropPicker::Initialize();
}

// Pick from the given collection
int vtkPropPicker::Pick(float selectionX, float selectionY,
                        float vtkNotUsed(z), vtkRenderer *renderer)
{
  return this->PickProp(selectionX, selectionY, renderer);
}

// Pick from the given collection
int vtkPropPicker::PickProp(float selectionX, float selectionY,
			    vtkRenderer *renderer, vtkPropCollection* pickfrom)
{
  this->PickFromProps = pickfrom;
  int ret = this->PickProp(selectionX, selectionY, renderer);
  this->PickFromProps = NULL;
  return ret;
}

// Perform pick operation with selection point provided. The z location
// is recovered from the zBuffer. Always returns 0 since no actors are picked.
int vtkPropPicker::PickProp(float selectionX, float selectionY,
                            vtkRenderer *renderer)
{
  //  Initialize picking process
  this->Initialize();
  this->Renderer = renderer;
  this->SelectionPoint[0] = selectionX;
  this->SelectionPoint[1] = selectionY;
  this->SelectionPoint[2] = 0;

  // Invoke start pick method if defined
  if ( this->StartPickMethod )
    {
    (*this->StartPickMethod)(this->StartPickMethodArg);
    }

  // Have the renderer do the hardware pick
  this->SetPath(
    renderer->PickPropFrom(selectionX, selectionY, this->PickFromProps));

  // If there was a pick then find the world x,y,z for the pick, and invoke
  // its pick method.
  if ( this->Path )
    {
    this->WorldPointPicker->Pick(selectionX, selectionY, 0, renderer);
    this->Path->GetLastNode()->GetProp()->Pick();
    if ( this->PickMethod )
      {
      (*this->PickMethod)(this->PickMethodArg);
      }
    }

  if ( this->EndPickMethod )
    {
    (*this->EndPickMethod)(this->EndPickMethodArg);
    }

  // Call Pick on the Prop that was picked, and return 1 for success
  if ( this->Path )
    {
    return 1;
    }
  else
    {
    return 0;
    }
}

void vtkPropPicker::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkAbstractPropPicker::PrintSelf(os, indent);

  if (this->PickFromProps)
    {
    os << indent << "PickFrom List: " << this->PickFromProps << endl;
    }
  else
    {
    os << indent << "PickFrom List: (none)" << endl;
    }

}
<commit_msg>ENH:Not updating the PickPosition<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPropPicker.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPropPicker.h"
#include "vtkWorldPointPicker.h"
#include "vtkAssemblyNode.h"
#include "vtkObjectFactory.h"

vtkPropPicker* vtkPropPicker::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPropPicker");
  if(ret)
    {
    return (vtkPropPicker*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPropPicker;
}

vtkPropPicker::vtkPropPicker()
{
  this->PickFromProps = NULL;
  this->WorldPointPicker = vtkWorldPointPicker::New();
}

vtkPropPicker::~vtkPropPicker()
{
  this->WorldPointPicker->Delete();
}

// set up for a pick
void vtkPropPicker::Initialize()
{
  this->vtkAbstractPropPicker::Initialize();
}

// Pick from the given collection
int vtkPropPicker::Pick(float selectionX, float selectionY,
                        float vtkNotUsed(z), vtkRenderer *renderer)
{
  return this->PickProp(selectionX, selectionY, renderer);
}

// Pick from the given collection
int vtkPropPicker::PickProp(float selectionX, float selectionY,
			    vtkRenderer *renderer, vtkPropCollection* pickfrom)
{
  this->PickFromProps = pickfrom;
  int ret = this->PickProp(selectionX, selectionY, renderer);
  this->PickFromProps = NULL;
  return ret;
}

// Perform pick operation with selection point provided. The z location
// is recovered from the zBuffer. Always returns 0 since no actors are picked.
int vtkPropPicker::PickProp(float selectionX, float selectionY,
                            vtkRenderer *renderer)
{
  //  Initialize picking process
  this->Initialize();
  this->Renderer = renderer;
  this->SelectionPoint[0] = selectionX;
  this->SelectionPoint[1] = selectionY;
  this->SelectionPoint[2] = 0;

  // Invoke start pick method if defined
  if ( this->StartPickMethod )
    {
    (*this->StartPickMethod)(this->StartPickMethodArg);
    }

  // Have the renderer do the hardware pick
  this->SetPath(
    renderer->PickPropFrom(selectionX, selectionY, this->PickFromProps));

  // If there was a pick then find the world x,y,z for the pick, and invoke
  // its pick method.
  if ( this->Path )
    {
    this->WorldPointPicker->Pick(selectionX, selectionY, 0, renderer);
    this->WorldPointPicker->GetPickPosition(this->PickPosition);
    this->Path->GetLastNode()->GetProp()->Pick();
    if ( this->PickMethod )
      {
      (*this->PickMethod)(this->PickMethodArg);
      }
    }

  if ( this->EndPickMethod )
    {
    (*this->EndPickMethod)(this->EndPickMethodArg);
    }

  // Call Pick on the Prop that was picked, and return 1 for success
  if ( this->Path )
    {
    return 1;
    }
  else
    {
    return 0;
    }
}

void vtkPropPicker::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkAbstractPropPicker::PrintSelf(os, indent);

  if (this->PickFromProps)
    {
    os << indent << "PickFrom List: " << this->PickFromProps << endl;
    }
  else
    {
    os << indent << "PickFrom List: (none)" << endl;
    }

}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                            OpenSim:  testDataTable.cpp                     *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2015 Stanford University and the Authors                *
 * Authors:                                                                   *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

#include <OpenSim/Common/TimeSeriesTable.h>

int main() {
    using namespace SimTK;
    using namespace OpenSim;
    using OpenSim::Exception;

    // Default construct, add metadata to columns, append rows one at a time.

    ValueArray<std::string> labels{};
    for(unsigned i = 1; i <= 5; ++i)
        labels.upd().push_back(SimTK::Value<std::string>{std::to_string(i)});

    ValueArray<unsigned> col_index{};
    for(unsigned i = 1; i <= 5; ++i)
        col_index.upd().push_back(SimTK::Value<unsigned>{i});

    DataTable::DependentsMetaData dep_metadata{};
    dep_metadata.setValueArrayForKey("labels", labels);
    dep_metadata.setValueArrayForKey("column-index", col_index);

    DataTable::IndependentMetaData ind_metadata{};
    ind_metadata.setValueForKey("labels", std::string{"0"});
    ind_metadata.setValueForKey("column-index", unsigned{0});

    TimeSeriesTable table{};
    table.setDependentsMetaData(dep_metadata);
    table.setIndependentMetaData(ind_metadata);

    SimTK::RowVector_<double> row{5, double{0}};

    for(unsigned i = 0; i < 5; ++i)
        table.appendRow(0.00 + 0.25 * i, row + i);

    for(unsigned i = 0; i < 5; ++i)
        table.updRowAtIndex(i) += 1;

    for(unsigned i = 0; i < 5; ++i)
        table.updRow(0 + 0.25 * i) -= 1;

    try {
        table.appendRow(0.5, row);
    } catch (OpenSim::Exception&) {}

    table.updTableMetaData().setValueForKey("DataRate", 600);
    table.updTableMetaData().setValueForKey("Filename",
                                            std::string{"/path/to/file"});

    // Retrieve added metadata and rows to check.
    if(table.getNumRows() != unsigned{5})
        throw Exception{"Test Failed: table.getNumRows() != unsigned{5}"};

    if(table.getNumColumns() != unsigned{5})
        throw Exception{"Test Failed: table.getNumColumns() != unsigned{5}"};

    const auto& dep_metadata_ref = table.getDependentsMetaData();

    const auto& labels_ref = dep_metadata_ref.getValueArrayForKey("labels");
    for(unsigned i = 0; i < 5; ++i)
        if(labels_ref[i].getValue<std::string>() != std::to_string(i + 1))
            throw Exception{"Test failed: labels_ref[i].getValue<std::string>()"
                    " != std::to_string(i + 1)"};

    const auto& col_index_ref
        = dep_metadata_ref.getValueArrayForKey("column-index");
    for(unsigned i = 0; i < 5; ++i)
        if(col_index_ref[i].getValue<unsigned>() != i + 1)
            throw Exception{"Test failed: col_index_ref[i].getValue<unsigned>()"
                    " != i + 1"};

    const auto& ind_metadata_ref = table.getIndependentMetaData();

    if(ind_metadata_ref.getValueForKey("labels").getValue<std::string>()
       != std::string{"0"})
        throw Exception{"Test failed: ind_metadata_ref.getValueForKey"
                "(\"labels\").getValue<std::string>() != std::string{\"0\"}"};
    if(ind_metadata_ref.getValueForKey("column-index").getValue<unsigned>()
       != unsigned{0})
        throw Exception{"Test failed: ind_metadata_ref.getValueForKey"
                "(\"column-index\").getValue<unsigned>() != unsigned{0}"};

    for(unsigned i = 0; i < 5; ++i) {
        for(unsigned j = 0; j < 5; ++j) {
            const auto row_i_1 = table.getRowAtIndex(i);
            if(row_i_1[j] != (row + i)[j])
                throw Exception{"Test failed: row_i_1[j] != (row + i)[j]"};

            const auto row_i_2 = table.getRow(0 + 0.25 * i);
            if(row_i_2[j] != (row + i)[j])
                throw Exception{"Test failed: row_i_2[j] != (row + i)[j]"};

            if(table.getDependentColumnAtIndex(i)[j] != j)
                throw Exception{"Test failed: table.getDependentColumnAtIndex"
                        "(i)[j] != j"};
        }
    }

    const auto& tab_metadata_ref = table.getTableMetaData();
    if(tab_metadata_ref.getValueForKey("DataRate").getValue<int>()
       != 600)
        throw Exception{"Test failed: tab_metadata_ref.getValueForKey"
                "(\"DataRate\").getValue<int>() != 600"};
    if(tab_metadata_ref.getValueForKey("Filename").getValue<std::string>()
       != std::string{"/path/to/file"})
        throw Exception{"Test failed: tab_metadata_ref.getValueForKey"
                "(\"Filename\").getValue<std::string>() != std::string"
                "{\"/path/to/file\"}"};

    return 0;
}
<commit_msg>Fix test fail.<commit_after>/* -------------------------------------------------------------------------- *
 *                            OpenSim:  testDataTable.cpp                     *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2015 Stanford University and the Authors                *
 * Authors:                                                                   *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

#include <OpenSim/Common/TimeSeriesTable.h>

int main() {
    using namespace SimTK;
    using namespace OpenSim;
    using OpenSim::Exception;

    // Default construct, add metadata to columns, append rows one at a time.

    ValueArray<std::string> labels{};
    for(unsigned i = 1; i <= 5; ++i)
        labels.upd().push_back(SimTK::Value<std::string>{std::to_string(i)});

    ValueArray<unsigned> col_index{};
    for(unsigned i = 1; i <= 5; ++i)
        col_index.upd().push_back(SimTK::Value<unsigned>{i});

    DataTable::DependentsMetaData dep_metadata{};
    dep_metadata.setValueArrayForKey("labels", labels);
    dep_metadata.setValueArrayForKey("column-index", col_index);

    DataTable::IndependentMetaData ind_metadata{};
    ind_metadata.setValueForKey("labels", std::string{"0"});
    ind_metadata.setValueForKey("column-index", unsigned{0});

    TimeSeriesTable table{};
    table.setDependentsMetaData(dep_metadata);
    table.setIndependentMetaData(ind_metadata);

    SimTK::RowVector_<double> row{5, double{0}};

    for(unsigned i = 0; i < 5; ++i)
        table.appendRow(0.00 + 0.25 * i, row + i);

    for(unsigned i = 0; i < 5; ++i)
        table.updRowAtIndex(i) += 1;

    for(unsigned i = 0; i < 5; ++i)
        table.updRow(0 + 0.25 * i) -= 1;

    try {
        table.appendRow(0.5, row);
    } catch (OpenSim::Exception&) {}

    table.updTableMetaData().setValueForKey("DataRate", 600);
    table.updTableMetaData().setValueForKey("Filename",
                                            std::string{"/path/to/file"});

    // Retrieve added metadata and rows to check.
    if(table.getNumRows() != unsigned{5})
        throw Exception{"Test Failed: table.getNumRows() != unsigned{5}"};

    if(table.getNumColumns() != unsigned{5})
        throw Exception{"Test Failed: table.getNumColumns() != unsigned{5}"};

    const auto& dep_metadata_ref = table.getDependentsMetaData();

    const auto& labels_ref = dep_metadata_ref.getValueArrayForKey("labels");
    for(unsigned i = 0; i < 5; ++i)
        if(labels_ref[i].getValue<std::string>() != std::to_string(i + 1))
            throw Exception{"Test failed: labels_ref[i].getValue<std::string>()"
                    " != std::to_string(i + 1)"};

    const auto& col_index_ref
        = dep_metadata_ref.getValueArrayForKey("column-index");
    for(unsigned i = 0; i < 5; ++i)
        if(col_index_ref[i].getValue<unsigned>() != i + 1)
            throw Exception{"Test failed: col_index_ref[i].getValue<unsigned>()"
                    " != i + 1"};

    const auto& ind_metadata_ref = table.getIndependentMetaData();

    if(ind_metadata_ref.getValueForKey("labels").getValue<std::string>()
       != std::string{"0"})
        throw Exception{"Test failed: ind_metadata_ref.getValueForKey"
                "(\"labels\").getValue<std::string>() != std::string{\"0\"}"};
    if(ind_metadata_ref.getValueForKey("column-index").getValue<unsigned>()
       != unsigned{0})
        throw Exception{"Test failed: ind_metadata_ref.getValueForKey"
                "(\"column-index\").getValue<unsigned>() != unsigned{0}"};

    for(unsigned i = 0; i < 5; ++i) {
        for(unsigned j = 0; j < 5; ++j) {
            const auto row_i_1 = table.getRowAtIndex(i);
            if(row_i_1[j] != (row + i)[j])
                throw Exception{"Test failed: row_i_1[j] != (row + i)[j]"};

            const auto row_i_2 = table.getRow(0 + 0.25 * i);
            if(row_i_2[j] != (row + i)[j])
                throw Exception{"Test failed: row_i_2[j] != (row + i)[j]"};

            const auto col_i = table.getDependentColumnAtIndex(i);
            if(col_i[j] != j)
                throw Exception{"Test failed: table.getDependentColumnAtIndex"
                        "(i)[j] != j"};
        }
    }

    const auto& tab_metadata_ref = table.getTableMetaData();
    if(tab_metadata_ref.getValueForKey("DataRate").getValue<int>()
       != 600)
        throw Exception{"Test failed: tab_metadata_ref.getValueForKey"
                "(\"DataRate\").getValue<int>() != 600"};
    if(tab_metadata_ref.getValueForKey("Filename").getValue<std::string>()
       != std::string{"/path/to/file"})
        throw Exception{"Test failed: tab_metadata_ref.getValueForKey"
                "(\"Filename\").getValue<std::string>() != std::string"
                "{\"/path/to/file\"}"};

    return 0;
}
<|endoftext|>


<commit_before>/*
 * (C) 2015 Augustin Cavalier
 * All rights reserved. Distributed under the terms of the MIT license.
 */
#include <iostream>
#include <vector>

#include "Phoenix.h"
#include "generators/Generators.h"
#include "util/FSUtil.h"

using std::vector;
using std::string;
using std::cerr;

void printUsage(string program)
{
	cerr << "Phoenix, version " PHOENIX_VERSION << ". ";
	cerr << "(C) 2015 Augustin Cavalier." << std::endl << std::endl;
	cerr << "Usage: " << std::endl;
	cerr << "\t" << program << " [options] <path/to/source>" << std::endl;
	cerr << "\t" << program << " [options] <path/to/build/directory>" << std::endl;
}

int main(int argc, char* argv[])
{
	vector<string> arguments(argv, argv + argc);
	if (arguments.size() < 2) {
		printUsage(arguments[0]);
		cerr << std::endl;
		cerr << "Run '" << arguments[0] << " --help' for full usage information.";
		cerr << std::endl;
		return 1;
	}

	string directory = ".";
	for (int i = 1; i < argc; i++) {
		string arg = arguments[i];
		if (arg.find("--help") == 0) {
			printUsage(arguments[0]);
			cerr << "Options: " << std::endl;
			cerr << "\t-G<generator>\t\tBuild system generator to use (default: '" << Generators::defaultName() << "')." << std::endl;
			// cerr << "\t-X<target>\tCross-compile to <target>." << std::endl; // TODO
			cerr << "\t-C:<lang>:<compiler>\tCompiler for <lang> to use (default depends on target)." << std::endl;
			return 1;
		} else {
			std::cout << FSUtil::which(arg);
		}
	}

	return 0;
}
<commit_msg>Tweaks.<commit_after>/*
 * (C) 2015 Augustin Cavalier
 * All rights reserved. Distributed under the terms of the MIT license.
 */
#include <iostream>
#include <vector>

#include "Phoenix.h"
#include "generators/Generators.h"
#include "util/FSUtil.h"

using std::vector;
using std::string;
using std::cerr;

void printUsage(string program)
{
	cerr << "Phoenix, version " PHOENIX_VERSION << ". ";
	cerr << "(C) 2015 Augustin Cavalier." << std::endl << std::endl;
	cerr << "Usage: " << std::endl;
	cerr << "\t" << program << " [options] <path/to/source>" << std::endl;
	cerr << "\t" << program << " [options] <path/to/build/directory>" << std::endl;
}

int main(int argc, char* argv[])
{
	vector<string> arguments(argv, argv + argc);
	if (arguments.size() < 2) {
		printUsage(arguments[0]);
		cerr << std::endl;
		cerr << "Run '" << arguments[0] << " --help' for full usage information.";
		cerr << std::endl;
		return 1;
	}

	string directory = ".";
	for (int i = 1; i < argc; i++) {
		string arg = arguments[i];
		if (arg.find("--help") == 0) {
			printUsage(arguments[0]);
			cerr << "Options: " << std::endl;
			cerr << "\t-G<generator>\t\tBuild system generator to use (default: '" <<
				Generators::defaultName() << "')." << std::endl;
			// cerr << "\t-X<target>\tCross-compile to <target>." << std::endl; // TODO
			cerr << "\t-C:<lang>:<compiler>\tCompiler for <lang> to use (default depends on target)." <<
				std::endl;
			return 1;
		} else {
			std::cout << FSUtil::which(arg);
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
(c) Matthew Slocum 2015

This file contains code from the public domain found at https://web.archive.org/web/20050110121238/http://www.xs4all.nl/~cg/ciphersaber/comp/c++.txt
// ciphersabre-1 by graydon hoare
// placed in public domain, jun 2000

This file contain sudo code from https://github.com/PSU-CS-300-Fall2015/ciphersaber2
this sudo code is licenced under the MIT Licence
*/

#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <vector>
#include <fstream>
#include "secComponent.h"

using namespace std;

secComponent::secComponent() {

}

//"Produce an RC4 keystream of length" n "with" r "rounds of key scheduling given key" k "of length" l
//returns keystream
string secComponent::rc4(int n, int r, char* k, int l) {
  /*
  rc4(n, r, k):
    l <- length k
    -- Initialize the array.
    S <- "zero-based array of 256 bytes"
    for i in 0..255
        S[i] <- i
    -- Do key scheduling.
    j <- 0
    repeat r times
        for i in 0..255
            j <- (j + S[i] + k[i mod l]) mod 256
            S[i] <-> S[j]
    -- Finally, produce the stream.
    keystream <- "zero-based array of" n "bytes"
    j <- 0
    for i in 0..n-1
        i' <- (i + 1) mod 256
        j <- (j + S[i']) mod 256
        S[i'] <-> S[j]
        keystream[i] <- S[(S[i'] + S[j]) mod 256]
  return keystream
  */

  //init array
  unsigned char S [256] = { };
  for(int i=0; i<256; i++) {
      S[i]=i;
  }

  //do key scheduling
  int j=0;
  for(int ri=0; ri<r; ri++) {
      for(int i=0; i<256; i++) {
          j = (j + S[i] + k[i%l]) % 256;
          swap(S[i], S[j]);
      }
  }

  //produce the keystream
  string keystream;
  j=0;
  int ip;
  for(int i=0; i<n; i++) {
      ip = (i+1) % 256;
      j = (j+S[ip]) % 256;
      swap(S[ip], S[j]);
      keystream.append(to_string(S[(S[ip]+S[j]) % 256]));
  }
  //cout << "keystream: " << keystream << endl;
  return keystream;
}

//"Ciphersaber-2 encrypt message" m "with key" k "and" r "rounds of key scheduling" "outputting to" ciphertext
//return length of ciphertext
int secComponent::encrypt(string m, string k, int r, char * ciphertext) {
  /*
  encrypt(m, r, k):
     n <- length m
     iv <- "appropriately-chosen 10-byte IV"
     k' <- prepend k to iv
     keystream <- rc4(n, r, k')
     ciphertext <- "zero-based array of" n + 10 "bytes"
     for i in 0..9
         ciphertext[i] <- iv[i]
     for i in 0..n
         ciphertext[i + 10] <- m[i] xor keystream[i]
   return ciphertext
  */

    //get length of message
    int n = m.length();
    string iv = "1234567890"; //CHANGEME

    //create a holder(kp) for the key + iv
    char kp[10+k.length()];

    //load the key into kp
    for(int i=0; i<k.length(); i++) {
        kp[i] = k[i];
    }

    //load the iv into kp
    for(int i=k.length(); i<k.length()+10; i++) {
        kp[i] = iv[i-k.length()];
    }

    //get a keystream
    string keystream = rc4(n, r, kp, k.length()+10);

    //load the iv into the payload
    for(int i=0; i<10; i++) {
        ciphertext[i] = iv[i];
    }

    //encrypt the message with the keystream and save to output
    for(int i=0; i<n; i++) {
        ciphertext[i+10] = m[i] ^ keystream[i];  //replaced xor with ^
    }

    //return size of ciphertext
    return n+10;
}

//"Ciphersaber-2 decrypt ciphertext" m "with key" k "and" r "rounds of key scheduling" "ouputting to" plaintext
//returns length of plaintext
int secComponent::decrypt(char* m, int m_len, string k, int r, char* plaintext) {
  /*
  --
  decrypt(m, r, k):
     n <- length m
     iv <- m[0..9]
     "delete the first 10 characters of" m
     k' <- prepend k to iv
     keystream <- rc4(n - 10, r, k')
     plaintext <- "zero-based array of" n - 10 "bytes"
     for i in 0..n-10
         plaintext[i] <- m[i] xor keystream[i]
     return plaintext
  */
  int n = m_len;

  //load iv
  char iv [10];
  for(int i=0; i<10; i++) {
      iv[i] = m[i];
  }

  //get the message without the iv
  char msg_no_iv [m_len-10];
  for(int k=0; k<m_len-10; k++) {
      msg_no_iv[k]=m[k+10];
  }

          //debug code
          /*
          cout << "msg_no_iv: ";
          for(int k=0;k<m_len-10;k++) {
              cout << msg_no_iv[k];
          }
          cout << endl;
          */

  //prepend k to iv (store in kp)
  char kp[k.length()+10];
  //put the key in
  for(int i=0; i<k.length(); i++) {
      kp[i] = k[i];
  }
  //put the iv in
  for(int i=k.length(); i<k.length()+10; i++) {
      kp[i] = iv[i-k.length()];
  }

  //get a keystream
  string keystream = rc4(n-10, r, kp, k.length()+10);

  //decrypt the message with the keystream and save to output
  for(int i=0; i<n-10; i++) {
    plaintext[i] = msg_no_iv[i] ^ keystream[i];
  }

  //return the length of the plaintext
  return n-10;
}

<commit_msg>cleaned up existing code<commit_after>/*
(c) Matthew Slocum 2015

secComponent.cpp

secComponent is responsible for the encryption/decryption of messages.

This file contains code from the public domain found at https://web.archive.org/web/20050110121238/http://www.xs4all.nl/~cg/ciphersaber/comp/c++.txt
// ciphersabre-1 by graydon hoare
// placed in public domain, jun 2000

This file contain sudo code from https://github.com/PSU-CS-300-Fall2015/ciphersaber2
this sudo code is licenced under the MIT Licence
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <vector>
#include <fstream>
#include "secComponent.h"

using namespace std;

secComponent::secComponent() {

}

//"Produce an RC4 keystream of length" n "with" r "rounds of key scheduling given key" k "of length" l
//returns keystream
string secComponent::rc4(int n, int r, char* k, int l) {
  //init array
  unsigned char S [256] = { };
  for(int i=0; i<256; i++) {
      S[i]=i;
  }
  //do key scheduling
  int j=0;
  for(int ri=0; ri<r; ri++) {
      for(int i=0; i<256; i++) {
          j = (j + S[i] + k[i%l]) % 256;
          swap(S[i], S[j]);
      }
  }
  //produce the keystream
  string keystream;
  j=0;
  int ip;
  for(int i=0; i<n; i++) {
      ip = (i+1) % 256;
      j = (j+S[ip]) % 256;
      swap(S[ip], S[j]);
      keystream.append(to_string(S[(S[ip]+S[j]) % 256]));
  }
  return keystream;
}

//"Ciphersaber-2 encrypt message" m "with key" k "and" r "rounds of key scheduling" "outputting to" ciphertext
//return length of ciphertext
int secComponent::encrypt(string m, string k, int r, char * ciphertext) {
    //get length of message
    int n = m.length();
    string iv = "1234567890"; //CHANGEME
    //create a holder(kp) for the key + iv
    char kp[10+k.length()];
    //load the key into kp
    for(int i=0; i<k.length(); i++) {
        kp[i] = k[i];
    }
    //load the iv into kp
    for(int i=k.length(); i<k.length()+10; i++) {
        kp[i] = iv[i-k.length()];
    }
    //get a keystream
    string keystream = rc4(n, r, kp, k.length()+10);
    //load the iv into the payload
    for(int i=0; i<10; i++) {
        ciphertext[i] = iv[i];
    }
    //encrypt the message with the keystream and save to output
    for(int i=0; i<n; i++) {
        ciphertext[i+10] = m[i] ^ keystream[i];  //replaced xor with ^
    }
    //return size of ciphertext
    return n+10;
}

//"Ciphersaber-2 decrypt ciphertext" m "with key" k "and" r "rounds of key scheduling" "ouputting to" plaintext
//returns length of plaintext
int secComponent::decrypt(char* m, int m_len, string k, int r, char* plaintext) {
  //get length of m (unneccisary)
  int n = m_len;
  //load iv
  char iv [10];
  for(int i=0; i<10; i++) {
      iv[i] = m[i];
  }
  //get the message without the iv
  char msg_no_iv [m_len-10];
  for(int k=0; k<m_len-10; k++) {
      msg_no_iv[k]=m[k+10];
  }
  //prepend k to iv (store in kp)
  char kp[k.length()+10];
  //put the key in
  for(int i=0; i<k.length(); i++) {
      kp[i] = k[i];
  }
  //put the iv in
  for(int i=k.length(); i<k.length()+10; i++) {
      kp[i] = iv[i-k.length()];
  }
  //get a keystream
  string keystream = rc4(n-10, r, kp, k.length()+10);
  //decrypt the message with the keystream and save to output
  for(int i=0; i<n-10; i++) {
    plaintext[i] = msg_no_iv[i] ^ keystream[i];
  }
  //return the length of the plaintext
  return n-10;
}

<|endoftext|>