void Command_Diff_NextPrevious(bool next, bool shiftDown) { if (DiffTarget == null) { throw new Exception("Diff not in progress"); } if ((TabsParent.GetIndex(this) < DiffTarget.TabsParent.GetIndex(DiffTarget)) && (DiffTarget.Active)) { return; } var lines = Selections.AsParallel().AsOrdered().Select(range => GetDiffNextPrevious(range, next)).ToList(); for (var pass = 0; pass < 2; ++pass) { var target = pass == 0 ? this : DiffTarget; var sels = lines.Select(tuple => new Range(target.Data.GetOffset(tuple.Item2, 0, true), target.Data.GetOffset(tuple.Item1, 0, true))).ToList(); if (shiftDown) { sels.AddRange(target.Selections); } target.SetSelections(sels); } }
void Command_Network_AbsoluteURL(NetworkAbsoluteURLDialog.Result result) { var results = GetFixedExpressionResults <string>(result.Expression); var newStrs = Selections.Zip(results, (range, baseUrl) => new { range, baseUrl }).AsParallel().AsOrdered().Select(obj => new Uri(new Uri(obj.baseUrl), GetString(obj.range)).AbsoluteUri).ToList(); ReplaceSelections(newStrs); }
public GADefinition(decimal mutation, int population, Crossovers crossover, Selections selection) { Mutation = mutation; Population = population; Crossover = crossover; Selection = selection; }
/// <inheritdoc/> public ProcessStartInfo GetStartInfo(Selections selections, params string[] arguments) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (arguments == null) throw new ArgumentNullException(nameof(arguments)); #endregion if (string.IsNullOrEmpty(selections.Command)) throw new ExecutorException("The Selections document does not specify a start command."); if (selections.Implementations.Count == 0) throw new ExecutorException("The Selections document does not list any implementations."); Selections = selections; ProcessUtils.SanitizeEnvironmentVariables(); try { var startInfo = BuildStartInfoWithBindings(); var commandLine = GetCommandLine(GetMainImplementation(), Selections.Command, startInfo); PrependWrapper(commandLine); AppendUserArgs(arguments, commandLine); ProcessRunEnvBindings(startInfo); ApplyCommandLine(commandLine, startInfo); return startInfo; } #region Error handling catch (KeyNotFoundException ex) { // Wrap exception since only certain exception types are allowed throw new ExecutorException(ex.Message); } #endregion }
protected Selector <TModel, TSelector> Select(params Expression <Func <TSelector, object> >[] expressions) { foreach (var expression in expressions) { var member = (expression.Body as MemberExpression)?.Member; if (member == null) { var unary = (expression.Body as UnaryExpression)?.Operand; member = (unary as MemberExpression)?.Member; } if (member == null) { continue; } if (Selections.TryGetValue(member.Name, out var selection)) { selection.IsSelected = true; } if (!SelectedProperties.ContainsKey(member.Name)) { SelectedProperties.Add(member.Name, PropertyInfoMapping[member.Name]); } } return(this); }
void Command_Select_Invert() { var start = new[] { 0 }.Concat(Selections.Select(sel => sel.End)); var end = Selections.Select(sel => sel.Start).Concat(new[] { Data.NumChars }); SetSelections(Enumerable.Zip(start, end, (startPos, endPos) => new Range(endPos, startPos)).Where(range => (range.HasSelection) || ((range.Start != 0) && (range.Start != Data.NumChars))).ToList()); }
void Command_Diff_SelectedFiles() { if (!Selections.Any()) { return; } if (Selections.Count % 2 != 0) { throw new Exception("Must have even number of selections."); } var files = GetSelectionStrings(); if (files.Any(file => !File.Exists(file))) { throw new Exception("Selections must be files."); } var tabs = new Tabs(); var batches = files.Batch(2).ToList(); foreach (var batch in batches) { tabs.AddDiff(fileName1: batch[0], fileName2: batch[1]); } }
private bool Equals(CompletionEvent other) { return(base.Equals(other) && Equals(Context2, other.Context2) && Equals(ProposalCollection, other.ProposalCollection) && Selections.SequenceEqual(other.Selections) && TerminatedBy == other.TerminatedBy && TerminatedState == other.TerminatedState); }
private void Succ(DudeMoveState dude) { if (dude.CubeStorage > dude.MaximumStorage || dude.SuccCooldown * dude.SuccSpeed < 1) { return; } dude.SuccCooldown = 0; RaycastHit hit; if (Physics.SphereCast(dude.transform.position + Vector3.up, 1.5f, (dude.Cursor.position - dude.transform.position).normalized, out hit, (dude.Cursor.position - dude.transform.position).magnitude, ~((1 << 10) & (1 << 11)))) { var selection = Selections.SphereSelection(World.Instance, hit.point.ToVector3Int(), dude.SuccArea); var tiles = selection.SolidTiles.ToList(); var cubes = tiles.Count; for (int i = 0; i < cubes; i++) { _pool.SpawnFromPool("SuccCube", tiles[i].Position + Vector3.one / 2, Quaternion.identity); } dude.CubeStorage += cubes; selection.DeleteAll(); } }
void SelectRegEx(string pattern) { var regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.IgnoreCase); var results = Selections.AsParallel().AsOrdered().Select(region => Data.RegexMatches(regex, region.Start, region.Length, false, false, false)).SelectMany().Select(tuple => Range.FromIndex(tuple.Item1, tuple.Item2)).ToList(); SetSelections(results); }
private void DownloadUncachedImplementations(IEnumerable <ImplementationSelection> selectedImplementations) { var selections = new Selections(selectedImplementations); var uncachedImplementations = SelectionsManager.GetUncachedSelections(selections).ToList(); // Do not waste time on Fetcher subsystem if nothing is missing from cache if (uncachedImplementations.Count == 0) { return; } // Only show implementations in the UI that need to be downloaded Handler.ShowSelections(new Selections(uncachedImplementations), FeedManager); try { var toDownload = SelectionsManager.GetImplementations(uncachedImplementations); Fetcher.Fetch(toDownload); } #region Error handling catch { // Suppress any left-over errors if the user canceled anyway Handler.CancellationToken.ThrowIfCancellationRequested(); throw; } #endregion }
private ProcessStartInfo GetStartInfo() { if (_solverSelections == null) { _solverSelections = _backingSolver.Solve(_solverRequirements); } var missing = _selectionsManager.GetUncachedImplementations(_solverSelections); _fetcher.Fetch(missing); var arguments = new[] { "--console", "slave", ApiVersion }; for (int i = 0; i < (int)_handler.Verbosity; i++) { arguments = arguments.Append("--verbose"); } var startInfo = _executor.GetStartInfo(_solverSelections, arguments); startInfo.CreateNoWindow = true; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; if (Locations.IsPortable) { startInfo.EnvironmentVariables["ZEROINSTALL_PORTABLE_BASE"] = Locations.PortableBase; } return(startInfo); }
protected override bool TryFulfill(IEnumerable <SolverDemand> demands) { var(essential, recommended) = Bucketize(demands); // Quickly reject impossible sets of demands if (essential.Any(demand => !demand.Candidates.Any(candidate => candidate.IsSuitable))) { return(false); } var selectionsSnapshot = Selections.Clone(); // Create snapshot foreach (var permutation in essential.Permutate()) { if (permutation.All(TryFulfill)) { recommended.ForEach(x => TryFulfill(x)); return(true); } else { Selections = selectionsSnapshot.Clone(); // Revert to snapshot } } return(false); }
// GET: Users/Options/5 public async Task <IActionResult> Selections(int?id) { if (id == null) { return(NotFound()); } User user = await _context.User.Where(x => x.UserId == id).FirstOrDefaultAsync(); List <UserSelection> userSelections = await _context.UserSelection.Where(x => x.UserId == id).OrderBy(y => y.Type).ToListAsync(); Selections selections = new Selections { UserId = user.UserId, ProductId = user.ProductId, EmailAddress = user.EmailAddress }; foreach (var item in userSelections) { item.Name = user.EmailAddress; item.Options = await _context.ProductOption.Where(x => x.ProductId == user.ProductId && x.Type == item.Type).ToListAsync(); foreach (var option in item.Options) { if (option.ProductOptionId == item.ProductOptionId) { option.Default = true; switch (option.Type) { case "Fabric": selections.Fabric = option.ProductOptionId; break; case "Mesh": selections.Mesh = option.ProductOptionId; break; case "Frame": selections.Frame = option.ProductOptionId; break; case "Arms": selections.Arms = option.ProductOptionId; break; case "Castors": selections.Castors = option.ProductOptionId; break; } } else { option.Default = false; } } } selections.UserSelections = userSelections; return(View(selections)); }
/// <summary> /// Runs <see cref="ISolver.Solve"/> (unless <see cref="SelectionsDocument"/> is <see langword="true"/>) and stores the result in <see cref="Selections"/>. /// </summary> /// <returns>The same result as stored in <see cref="Selections"/>.</returns> /// <exception cref="OperationCanceledException">The user canceled the process.</exception> /// <exception cref="WebException">A file could not be downloaded from the internet.</exception> /// <exception cref="IOException">An external application or file required by the solver could not be accessed.</exception> /// <exception cref="SolverException">The <see cref="ISolver"/> was unable to provide a set of <see cref="Selections"/> that fulfill the <see cref="Requirements"/>.</exception> protected virtual void Solve() { // TODO: Handle named apps // Don't run the solver if the user provided an external selections document if (SelectionsDocument) { return; } try { Selections = Solver.Solve(Requirements); } #region Error handling catch { // Suppress any left-over errors if the user canceled anyway Handler.CancellationToken.ThrowIfCancellationRequested(); throw; } #endregion Handler.CancellationToken.ThrowIfCancellationRequested(); }
public async Task <IActionResult> Selections(Selections selections) { List <UserSelection> userSelections = await _context.UserSelection.Where(x => x.UserId == selections.UserId).ToListAsync(); foreach (var item in userSelections) { switch (item.Type) { case "Fabric": item.ProductOptionId = selections.Fabric; break; case "Mesh": item.ProductOptionId = selections.Mesh; break; case "Frame": item.ProductOptionId = selections.Frame; break; } _context.Entry(item).State = EntityState.Modified; } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
protected override Selection GetSelection(Point coords, bool inMotion = false, bool skipSelected = false) { Selection sel = null; Selection selected = null; /* Regular GetSelection */ if (!ViewModel.ShowLinks) { return(base.GetSelection(coords, inMotion, skipSelected)); } /* With ShowLinks, only links and anchor can be selected */ if (Selections.Count > 0) { selected = Selections.LastOrDefault(); } foreach (ICanvasSelectableObject co in Objects) { sel = co.GetSelection(coords, Accuracy, inMotion); if (sel == null || sel.Drawable is DashboardButtonView) { continue; } if (skipSelected && selected != null && sel.Drawable == selected.Drawable) { continue; } break; } return(sel); }
internal void AddCaretMoveToSelections(Selection selection) { var caretPosition = view.Caret.Position.BufferPosition; var newSelection = new Selection { Start = null, End = null, Caret = Snapshot.CreateTrackingPoint(caretPosition), ColumnPosition = selection.ColumnPosition, VirtualSpaces = view.Caret.Position.VirtualSpaces }; var newPosition = newSelection.GetCaretColumnPosition( caretPosition, Snapshot, view.FormattedLineSource.TabSize); newSelection.Caret = Snapshot.CreateTrackingPoint(newPosition); if (Selections.Any(s => s.Caret.GetPoint(Snapshot) == newPosition)) { return; } Selections.Add(newSelection); }
private Color SelectColor(Selections selected) { if (currentSelection == selected) return Color.White; else return Color.DarkGray; }
public PauseMenu(IGameState prevGameState, Game1 game) { this.game = game; this.prevGameState = prevGameState; currentSelection = Selections.Resume; font = MenuSpriteFactory.CreateHUDFont(); }
protected virtual Selection GetSelection(Point coords, bool inMotion = false, bool skipSelected = false) { Selection sel = null; Selection selected = null; if (Selections.Count > 0) { selected = Selections.LastOrDefault(); /* Try with the selected item first */ if (!skipSelected) { sel = selected.Drawable.GetSelection(coords, Accuracy, inMotion); } } /* Iterate over all the objects now */ if (sel == null) { foreach (ICanvasSelectableObject co in Objects) { sel = co.GetSelection(coords, Accuracy, inMotion); if (sel == null) { continue; } if (skipSelected && selected != null && sel.Drawable == selected.Drawable) { continue; } break; } } return(sel); }
/// <summary> /// Handle drag and drop of text parts in the editor. /// </summary> /// <param name="s"></param> /// <param name="e"></param> private void HandleDragOver(object s, DragEventArgs e) { // convert cursor position to text position var point = PointToClient(new Point(e.X, e.Y)); int pos = CharPositionFromPoint(point.X, point.Y); // refresh text control Refresh(); // if the mouse is over a selected area, dropping will not be possible if (Selections.IndexOf(x => x.Start <= pos && pos < x.End) >= 0) { e.Effect = DragDropEffects.None; return; } // draw line at cursor position in text var g = CreateGraphics(); var pen = new Pen(Color.Black, 2); var height = TextRenderer.MeasureText("0", Font).Height; point.X = PointXFromPosition(pos); point.Y = PointYFromPosition(pos); g.DrawLine(pen, point.X, point.Y, point.X, point.Y + height); // show "MOVE" cursor e.Effect = DragDropEffects.Move; }
void Command_Database_ExecuteQuery() { ValidateConnection(); var selections = Selections.ToList(); if ((Selections.Count == 1) && (!Selections[0].HasSelection)) { selections = new List <Range> { FullRange } } ; var strs = GetSelectionStrings(); // Not in parallel because prior selections may affect later ones var results = selections.Select((range, index) => RunDBSelect(strs[index])).ToList(); for (var ctr = 0; ctr < strs.Count; ++ctr) { var exception = results[ctr].Select(result => result.Exception).NonNull().FirstOrDefault(); strs[ctr] += $": {(exception == null ? "Success" : $"{exception.Message}")}"; foreach (var table in results[ctr].Where(table => table.Table != null)) { OpenTable(table.Table, table.TableName); } } ReplaceSelections(strs); }
void Command_Numeric_Round(NumericFloorRoundCeilingDialog.Result result) { var baseValue = new NEExpression(result.BaseValue).EvaluateList <double>(GetVariables(), Selections.Count()); var interval = new NEExpression(result.Interval).EvaluateList <double>(GetVariables(), Selections.Count()); ReplaceSelections(Selections.AsParallel().AsOrdered().Select((range, index) => (Math.Round((double.Parse(GetString(range), NumberStyles.Float) - baseValue[index]) / interval[index], MidpointRounding.AwayFromZero) * interval[index] + baseValue[index]).ToString()).ToList()); }
/// <inheritdoc/> public IEnumerable <ImplementationSelection> GetUncachedSelections(Selections selections) { #region Sanity checks if (selections == null) { throw new ArgumentNullException(nameof(selections)); } #endregion foreach (ImplementationSelection implementation in selections.Implementations) { // Local paths are considered to be always cached if (!string.IsNullOrEmpty(implementation.LocalPath)) { continue; } if (implementation.ID.StartsWith(ExternalImplementation.PackagePrefix)) { if (!File.Exists(implementation.QuickTestFile) && !_packageManager.Lookup(implementation).IsInstalled) { yield return(implementation); } } else { if (!_store.Contains(implementation.ManifestDigest)) { yield return(implementation); } } } }
internal void CombineOverlappingSelections() { var overlappingSelections = new List <int>(); var selections = Selections .Where(s => s.IsSelection()) .Select((selection, index) => new { index, selection }) .OrderBy(s => s.selection.Caret.GetPoint(Snapshot)) .ToList(); for (var index = 0; index < selections.Count - 1; index++) { var selection = selections[index].selection; var nextSelection = selections[index + 1].selection; if (selection.End.GetPoint(Snapshot) > nextSelection.Start.GetPoint(Snapshot)) { nextSelection.Start = Snapshot.CreateTrackingPoint(selection.Start.GetPosition(Snapshot)); if (selection.IsReversed(Snapshot)) { nextSelection.Caret = selection.Caret; } overlappingSelections.Add(selections[index].index); } } foreach (var index in overlappingSelections.OrderByDescending(n => n)) { Selections.RemoveAt(index); } }
private static void VerifyEnvironment(ProcessStartInfo startInfo, Selections selections) { startInfo.EnvironmentVariables["TEST1_PATH_SELF"].Should().Be("default" + Path.PathSeparator + Test1Path, because: "Should append implementation path"); startInfo.EnvironmentVariables["TEST1_VALUE"].Should().Be("test1", because: "Should directly set value"); startInfo.EnvironmentVariables["TEST1_EMPTY"].Should().Be("", because: "Should set empty environment variables"); startInfo.EnvironmentVariables["TEST2_PATH_SELF"].Should().Be(Test2Path + Path.PathSeparator + "default", because: "Should prepend implementation path"); startInfo.EnvironmentVariables["TEST2_VALUE"].Should().Be("test2", because: "Should directly set value"); startInfo.EnvironmentVariables["TEST2_PATH_SUB_DEP"].Should().Be("default" + Path.PathSeparator + Path.Combine(Test2Path, "sub"), because: "Should append implementation sub-path"); startInfo.EnvironmentVariables["TEST1_PATH_COMMAND"].Should().Be(Test1Path, because: "Should set implementation path"); startInfo.EnvironmentVariables["TEST1_PATH_COMMAND_DEP"].Should().Be(Test1Path + Path.PathSeparator + Test1Path, because: "Should set implementation path for command dependency for each reference"); startInfo.WorkingDirectory.Should().Be(Path.Combine(Test1Path, "bin"), because: "Should set implementation path"); string execFile = Path.Combine(Test2Path, FileUtils.UnifySlashes(selections.Implementations[2].Commands[0].Path)); var execArgs = new[] { selections.Implementations[2].Commands[0].Arguments[0].ToString(), selections.Implementations[1].Commands[1].Runner.Arguments[0].ToString(), Path.Combine(Test1Path, FileUtils.UnifySlashes(selections.Implementations[1].Commands[1].Path)), selections.Implementations[1].Commands[1].Arguments[0].ToString() }; if (WindowsUtils.IsWindows) { startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_FILE_exec-in-var"].Should().Be(execFile); startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_ARGS_exec-in-var"].Should().Be(execArgs.JoinEscapeArguments()); startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_FILE_exec-in-path"].Should().Be(execFile); startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_ARGS_exec-in-path"].Should().Be(execArgs.JoinEscapeArguments()); } else { startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_exec-in-var"].Should().Be(execArgs.Prepend(execFile).JoinEscapeArguments()); startInfo.EnvironmentVariables["ZEROINSTALL_RUNENV_exec-in-path"].Should().Be(execArgs.Prepend(execFile).JoinEscapeArguments()); } startInfo.EnvironmentVariables["PATH"].Should().Be(Locations.GetCacheDirPath("0install.net", false, "injector", "executables", "exec-in-path") + Path.PathSeparator + new ProcessStartInfo().EnvironmentVariables["PATH"]); }
public void Reset() { currentSelection = Selections.Start; titleBG.Position = new Vector2(330, 170); twoPlayersPosition = new Vector2(628, 300); instructPosition = new Vector2(628, 350); startPosition = new Vector2(670, 170); endurancePosition = new Vector2(640, 250); scorePosition = new Vector2(645, 400); optionsPosition = new Vector2(660, 450); buyPosition = new Vector2(650, 500); startColour = Color.Yellow; enduranceColour = Color.White; twoPlayersColour = Color.White; instructColour = Color.White; scoresColour = Color.White; optionsColour = Color.White; }
void Command_Region_Select_Regions_Region(bool shiftDown, int?useRegion = null) { var sels = shiftDown ? Selections.ToList() : new List <Range>(); sels.AddRange(Regions.Where(pair => pair.Key == (useRegion ?? pair.Key)).SelectMany(pair => pair.Value)); SetSelections(sels); }
private void ProcessFoundOccurrence(SnapshotSpan occurrence) { if (!Selections.Any(s => s.OverlapsWith(occurrence, Snapshot))) { var start = Snapshot.CreateTrackingPoint(occurrence.Start); var end = Snapshot.CreateTrackingPoint(occurrence.End); var caret = Selections.Last().IsReversed(Snapshot) ? start : end; Selections.Add( new Selection { Start = start, End = end, Caret = caret, ColumnPosition = Snapshot.GetLineColumnFromPosition(caret.GetPoint(Snapshot)) } ); outliningManager.ExpandAll(occurrence, r => r.IsCollapsed); view.Caret.MoveTo(caret == start ? occurrence.Start : occurrence.End); view.ViewScroller.EnsureSpanVisible( new SnapshotSpan(view.Caret.Position.BufferPosition, 0) ); } }
public TitleState(Game game) : base(game) { titleSprite = new Sprite(GameCore.PublicTitleTexture); titleBG = new Sprite(GameCore.PublicTitleBG); titleBG.Position = new Vector2(330, 170); twoPlayersSprite = GameCore.PublicTwoPlayersButtonTexture; twoPlayersPosition = new Vector2(628, 300); instructSprite = GameCore.PublicInstructionsButtonTexture; instructPosition = new Vector2(628, 350); startSprite = GameCore.PublicStoryButtonTexture; startPosition = new Vector2(670, 180); enduranceSprite = GameCore.PublicEnduranceButtonTexture; endurancePosition = new Vector2(640, 250); scoreSprite = GameCore.PublicHighScoresButtonTexture; scorePosition = new Vector2(645, 400); optionsSprite = GameCore.PublicOptionsButtonTexture; optionsPosition = new Vector2(660, 450); buySprite = GameCore.PublicBuyButtonTexture; buyPosition = new Vector2(628, 500); currentSelection = Selections.Start; startColour = Color.Yellow; enduranceColour = Color.White; twoPlayersColour = Color.White; instructColour = Color.White; scoresColour = Color.White; optionsColour = Color.White; buyColour = Color.White; }
void Command_Select_Lines(bool includeEndings) { var lineSets = Selections.AsParallel().Select(range => new { start = Data.GetOffsetLine(range.Start), end = Data.GetOffsetLine(Math.Max(range.Start, range.End - 1)) }).ToList(); var hasLine = new bool[Data.NumLines]; foreach (var set in lineSets) { for (var ctr = set.start; ctr <= set.end; ++ctr) { hasLine[ctr] = true; } } var lines = new List <int>(); for (var line = 0; line < hasLine.Length; ++line) { if ((hasLine[line]) && (!Data.IsDiffGapLine(line))) { lines.Add(line); } } SetSelections(lines.AsParallel().AsOrdered().Select(line => Range.FromIndex(Data.GetOffset(line, 0), Data.GetLineLength(line) + (includeEndings ? Data.GetEndingLength(line) : 0))).ToList()); }
internal void ConvertSelectionToMultipleCursors() { var beginLineNumber = view.Selection.Start.Position.GetContainingLine().LineNumber; var endLineNumber = view.Selection.End.Position.GetContainingLine().LineNumber; if (beginLineNumber != endLineNumber) { for (var lineNumber = beginLineNumber; lineNumber < endLineNumber; lineNumber++) { var line = Snapshot.GetLineFromLineNumber(lineNumber); Selections.Add( new Selection { Caret = Snapshot.CreateTrackingPoint(line.End.Position), ColumnPosition = Snapshot.GetLineColumnFromPosition(line.End.Position) } ); } Selections.Add( new Selection { Caret = Snapshot.CreateTrackingPoint(view.Selection.End.Position), ColumnPosition = Snapshot.GetLineColumnFromPosition(view.Selection.End.Position) } ); view.Selection.Clear(); } else { AddCurrentSelectionToSelections(); } }
/// <inheritdoc/> public Process Start(Selections selections, params string[] arguments) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (arguments == null) throw new ArgumentNullException(nameof(arguments)); #endregion return GetStartInfo(selections, arguments).Start(); }
/// <inheritdoc/> public void ShowSelections(Selections selections, IFeedManager feedManager) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (feedManager == null) throw new ArgumentNullException(nameof(feedManager)); #endregion // TODO: Implement }
/// <summary> /// Shows the user the <see cref="Selections"/> made by the <see cref="ISolver"/>. /// Returns immediately. /// </summary> /// <param name="selections">The <see cref="Selections"/> as provided by the <see cref="ISolver"/>.</param> /// <param name="feedManager">The feed manager used to retrieve feeds for additional information about implementations.</param> /// <exception cref="InvalidOperationException">The value is set from a thread other than the UI thread.</exception> /// <remarks>This method must not be called from a background thread.</remarks> public void ShowSelections(Selections selections, IFeedManager feedManager) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (feedManager == null) throw new ArgumentNullException(nameof(feedManager)); if (InvokeRequired) throw new InvalidOperationException("Method called from a non UI thread."); #endregion taskControl.Visible = false; _selectionsShown = selectionsControl.Visible = true; selectionsControl.SetSelections(selections, feedManager); }
/// <summary> /// Creates a new exporter. /// </summary> /// <param name="selections">A list of <see cref="ImplementationSelection"/>s to check for referenced feeds.</param> /// <param name="architecture">The target architecture to use for bootstrap binaries.</param> /// <param name="destination">The path of the directory to export to.</param> public Exporter([NotNull] Selections selections, Architecture architecture, [NotNull] string destination) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (string.IsNullOrEmpty(destination)) throw new ArgumentNullException(nameof(destination)); #endregion _selections = selections; _architecture = architecture; _destination = destination; Directory.CreateDirectory(_destination); }
//--------------------// #region Selections /// <summary> /// Shows the user the <see cref="Selections"/> made by the <see cref="ISolver"/>. /// </summary> /// <param name="selections">The <see cref="Selections"/> as provided by the <see cref="ISolver"/>.</param> /// <param name="feedManager">The feed manager used to retrieve feeds for additional information about implementations.</param> /// <remarks> /// <para>This method must not be called from a background thread.</para> /// <para>This method must not be called before <see cref="Control.Handle"/> has been created.</para> /// </remarks> public void SetSelections([NotNull] Selections selections, [NotNull] IFeedManager feedManager) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); if (InvokeRequired) throw new InvalidOperationException("Method called from a non UI thread."); #endregion _selections = selections; _feedManager = feedManager; BuildTable(); if (_solveCallback != null) CreateLinkLabels(); }
/// <summary> /// Hooks into the creation of new processes on the current thread to inject API hooks. /// </summary> /// <param name="selections">The implementations chosen for launch.</param> /// <param name="executor">The executor used to launch the new process.</param> /// <param name="feedManager">Provides access to remote and local <see cref="Feed"/>s. Handles downloading, signature verification and caching.</param> /// <param name="handler">A callback object used when the the user needs to be asked questions or informed about download and IO tasks.</param> /// <exception cref="ImplementationNotFoundException">The main implementation is not cached (possibly because it is installed natively).</exception> public RunHook(Selections selections, IExecutor executor, IFeedManager feedManager, ITaskHandler handler) { var feed = feedManager[selections.InterfaceUri]; _target = new FeedTarget(selections.InterfaceUri, feed); var mainImplementation = selections.MainImplementation; _implementationDir = executor.GetImplementationPath(mainImplementation); _mainImplementation = feed[mainImplementation.ID]; _handler = handler; _registryFilter = GetRegistryFilter(); _relaunchControl = GetRelaunchControl(); Log.Info("Activating API hooking"); _hookW = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateProcessW"), new UnsafeNativeMethods.DCreateProcessW(CreateProcessWCallback), null); _hookW.ThreadACL.SetInclusiveACL(new[] {Thread.CurrentThread.ManagedThreadId}); _hookA = LocalHook.Create(LocalHook.GetProcAddress("kernel32.dll", "CreateProcessA"), new UnsafeNativeMethods.DCreateProcessA(CreateProcessACallback), null); _hookA.ThreadACL.SetInclusiveACL(new[] {Thread.CurrentThread.ManagedThreadId}); }
/// <summary> /// Helper method for <see cref="GetHumanReadable"/> that recursivley writes information about <see cref="ImplementationSelection"/>s to a <see cref="StringBuilder"/>. /// </summary> /// <param name="selections">The selections to be displayed.</param> /// <param name="builder">The string builder to write the output to.</param> /// <param name="handled">A list of interface URIs that have already been handled; used to prevent infinite recursion.</param> /// <param name="store">A store to search for implementation storage locations.</param> /// <param name="indent">An indention prefix for the current recursion level (to create a visual hierachy).</param> /// <param name="interfaceUri">The <see cref="ImplementationSelection.InterfaceUri"/> to look for.</param> private static void PrintNode(Selections selections, StringBuilder builder, HashSet<FeedUri> handled, IStore store, string indent, FeedUri interfaceUri) { // Prevent infinite recursion if (handled.Contains(interfaceUri)) return; handled.Add(interfaceUri); builder.AppendLine(indent + "- URI: " + interfaceUri); try { var implementation = selections[interfaceUri]; builder.AppendLine(indent + " Version: " + implementation.Version); builder.AppendLine(indent + " Path: " + (implementation.LocalPath ?? implementation.GetPath(store) ?? Resources.NotCached)); builder.AppendLine(); indent += " "; // Recurse into regular dependencies foreach (var dependency in implementation.Dependencies) PrintNode(selections, builder, handled, store, indent, dependency.InterfaceUri); if (implementation.Commands.Count != 0) { var command = implementation.Commands[0]; // Recurse into command dependencies foreach (var dependency in command.Dependencies) PrintNode(selections, builder, handled, store, indent, dependency.InterfaceUri); // Recurse into runner dependency if (command.Runner != null) PrintNode(selections, builder, handled, store, indent, command.Runner.InterfaceUri); } } catch (KeyNotFoundException) { builder.AppendLine(indent + " " + Resources.NoSelectedVersion); } }
/// <inheritdoc/> public IEnumerable<ImplementationSelection> GetUncachedSelections(Selections selections) { #region Sanity checks if (selections == null) throw new ArgumentNullException(nameof(selections)); #endregion foreach (ImplementationSelection implementation in selections.Implementations) { // Local paths are considered to be always cached if (!string.IsNullOrEmpty(implementation.LocalPath)) continue; if (implementation.ID.StartsWith(ExternalImplementation.PackagePrefix)) { if (!File.Exists(implementation.QuickTestFile) && !_packageManager.Lookup(implementation).IsInstalled) yield return implementation; } else { if (!_store.Contains(implementation.ManifestDigest)) yield return implementation; } } }
public Dictionary<string, Fields> CollectFields(ExecutionContext context, GraphType type, Selections selections, Dictionary<string, Fields> fields) { if (fields == null) { fields = new Dictionary<string, Fields>(); } selections.Apply(selection => { if (selection.Field != null) { if (!ShouldIncludeNode(context, selection.Field.Directives)) { return; } var name = selection.Field.Alias ?? selection.Field.Name; if (!fields.ContainsKey(name)) { fields[name] = new Fields(); } fields[name].Add(selection.Field); } else if (selection.Fragment != null) { if (selection.Fragment is FragmentSpread) { var spread = selection.Fragment as FragmentSpread; if (!ShouldIncludeNode(context, spread.Directives)) { return; } var fragment = context.Fragments.FindDefinition(spread.Name); if (!ShouldIncludeNode(context, fragment.Directives) || !DoesFragmentConditionMatch(context, fragment, type)) { return; } CollectFields(context, type, fragment.Selections, fields); } else if (selection.Fragment is InlineFragment) { var inline = selection.Fragment as InlineFragment; if (!ShouldIncludeNode(context, inline.Directives) || !DoesFragmentConditionMatch(context, inline, type)) { return; } CollectFields(context, type, inline.Selections, fields); } } }); return fields; }
private static void ApplyVersionRestrictions(Requirements requirements, Selections selections) { if (requirements.ExtraRestrictions.Count == 0) return; // TODO Log.Warn(string.Format("You have applied a version restriction to this app. Zero Install will continue to apply this restriction to any future updates. You will need to run '0install select --customize {0}' to undo this.", requirements.InterfaceUri)); foreach (var restriction in requirements.ExtraRestrictions) { var selection = selections.GetImplementation(restriction.Key); if (selection != null) { var pref = FeedPreferences.LoadForSafe(restriction.Key); pref.Implementations.Clear(); pref[selection.ID].UserStability = Stability.Preferred; pref.SaveFor(restriction.Key); } } }
/// <inheritdoc/> public void ShowSelections(Selections selections, IFeedManager feedManager) { // Stub to be overriden }
public override void Update(GameTime gameTime) { if (controlLag > 0) controlLag = controlLag - 1; switch (currentMode) { case mapModes.menuMode: if (controlLag == 0) { if (Master.controls.Up && selection != 0) { selection = (Selections)((int)selection - 1); controlLag = 20; } else if (Master.controls.Down && (int)selection != 2) { selection = (Selections)((int)selection + 1); controlLag = 20; } else if (Master.controls.Start || Master.controls.A || Master.controls.B) { switch (selection) { case Selections.Continue: currentMode = mapModes.runMode; controlLag = 20; break; case Selections.Save: game.saveGame(); controlLag = 20; saved = true; break; case Selections.Quit: game.master.UpdateScreen(new TitleScreen(game.master)); break; } } } break; default: // Update player.Update(); // Get keyboard input //KeyboardState state = Keyboard.GetState(); if (controlLag == 0) { if (Master.controls.Up) { player.faceDir = Master.Directions.Up; player.moving = true; } else if (Master.controls.Down) { player.faceDir = Master.Directions.Down; player.moving = true; } else if (Master.controls.Left) { player.faceDir = Master.Directions.Left; player.moving = true; } else if (Master.controls.Right) { player.faceDir = Master.Directions.Right; player.moving = true; } else { player.moving = false; } if (Master.controls.Start) { currentMode = mapModes.menuMode; saved = false; controlLag = 20; PlaySound.Play(PlaySound.SoundEffectName.Pause); } } break; } }
/// <inheritdoc/> public ProcessStartInfo GetStartInfo(Selections selections, params string[] arguments) { #region Sanity checks if (selections == null) throw new ArgumentNullException("selections"); if (arguments == null) throw new ArgumentNullException("arguments"); #endregion if (selections.Implementations.Count == 0) throw new ArgumentException(Resources.NoImplementationsPassed, "selections"); Selections = selections; var startInfo = BuildStartInfoWithBindings(); var commandLine = GetCommandLine(GetMainImplementation(), Selections.Command, startInfo); PrependWrapper(commandLine); AppendUserArgs(arguments, commandLine); ProcessRunEnvBindings(startInfo); ApplyCommandLine(commandLine, startInfo); return startInfo; }
/// <inheritdoc/> public void ShowSelections(Selections selections, IFeedCache feedCache) { #region Sanity checks if (selections == null) throw new ArgumentNullException("selections"); if (feedCache == null) throw new ArgumentNullException("feedCache"); #endregion // TODO: Implement }
private void DownloadUncachedImplementations(IEnumerable<ImplementationSelection> selectedImplementations) { var selections = new Selections(selectedImplementations); var uncachedImplementations = SelectionsManager.GetUncachedSelections(selections).ToList(); // Do not waste time on Fetcher subsystem if nothing is missing from cache if (uncachedImplementations.Count == 0) return; // Only show implementations in the UI that need to be downloaded Handler.ShowSelections(new Selections(uncachedImplementations), FeedCache); try { var toDownload = SelectionsManager.GetImplementations(uncachedImplementations); Fetcher.Fetch(toDownload); } #region Error handling catch { // Suppress any left-over errors if the user canceled anyway Handler.CancellationToken.ThrowIfCancellationRequested(); throw; } #endregion }
/// <summary> /// Shows the user the <see cref="Selections"/> made by the <see cref="ISolver"/>. /// Returns immediately. /// </summary> /// <param name="selections">The <see cref="Selections"/> as provided by the <see cref="ISolver"/>.</param> /// <param name="feedCache">The feed cache used to retrieve feeds for additional information about implementations.</param> /// <exception cref="InvalidOperationException">The value is set from a thread other than the UI thread.</exception> /// <remarks>This method must not be called from a background thread.</remarks> public void ShowSelections(Selections selections, IFeedCache feedCache) { #region Sanity checks if (selections == null) throw new ArgumentNullException("selections"); if (InvokeRequired) throw new InvalidOperationException("Method called from a non UI thread."); #endregion trackingControl.Visible = false; _selectionsShown = selectionsControl.Visible = true; selectionsControl.SetSelections(selections, feedCache); }
private static IStore GetMockStore(Selections selections) { var storeMock = new Mock<IStore>(MockBehavior.Loose); storeMock.Setup(x => x.GetPath(selections.Implementations[1].ManifestDigest)).Returns(Test1Path); storeMock.Setup(x => x.GetPath(selections.Implementations[2].ManifestDigest)).Returns(Test2Path); return storeMock.Object; }
/// <summary> /// Runs <see cref="ISolver.Solve"/> (unless <see cref="SelectionsDocument"/> is <see langword="true"/>) and stores the result in <see cref="Selections"/>. /// </summary> /// <returns>The same result as stored in <see cref="Selections"/>.</returns> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="WebException">A file could not be downloaded from the internet.</exception> /// <exception cref="IOException">An external application or file required by the solver could not be accessed.</exception> /// <exception cref="SolverException">The <see cref="ISolver"/> was unable to provide a set of <see cref="Selections"/> that fulfill the <see cref="Requirements"/>.</exception> protected virtual void Solve() { // TODO: Handle named apps // Don't run the solver if the user provided an external selections document if (SelectionsDocument) return; try { Selections = Solver.Solve(Requirements); } #region Error handling catch { // Suppress any left-over errors if the user canceled anyway Handler.CancellationToken.ThrowIfCancellationRequested(); throw; } #endregion Handler.CancellationToken.ThrowIfCancellationRequested(); }
private static void ExpectCommandException(Selections selections) { var storeMock = new Mock<IStore>(MockBehavior.Loose); storeMock.Setup(x => x.GetPath(It.IsAny<ManifestDigest>())).Returns("test path"); var executor = new Executor(storeMock.Object); executor.Invoking(x => x.GetStartInfo(selections)) .ShouldThrow<ExecutorException>(because: "Invalid Selections should be rejected"); }
/// <inheritdoc/> public void ShowSelections(Selections selections, IFeedCache feedCache) { // Stub to be overriden }
/// <summary> /// Runs <see cref="ISolver.Solve"/> (unless <see cref="SelectionsDocument"/> is <c>true</c>) and stores the result in <see cref="Selections"/>. /// </summary> /// <returns>The same result as stored in <see cref="Selections"/>.</returns> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="WebException">A file could not be downloaded from the internet.</exception> /// <exception cref="IOException">An external application or file required by the solver could not be accessed.</exception> /// <exception cref="SolverException">The <see cref="ISolver"/> was unable to provide a set of <see cref="Selections"/> that fulfill the <see cref="Requirements"/>.</exception> protected virtual void Solve() { // TODO: Handle named apps // Don't run the solver if the user provided an external selections document if (SelectionsDocument) return; try { Selections = Solver.Solve(Requirements); } #region Error handling catch { // Suppress any left-over errors if the user canceled anyway Handler.CancellationToken.ThrowIfCancellationRequested(); throw; } #endregion try { Selections.Name = FeedCache.GetFeed(Selections.InterfaceUri).Name; } #region Error handling catch (KeyNotFoundException) { // Fall back to using feed file name Selections.Name = Selections.InterfaceUri.ToString().GetRightPartAtLastOccurrence('/'); } #endregion Handler.CancellationToken.ThrowIfCancellationRequested(); }
/// <summary> /// Runs the Solver to select a version of Zero Install. /// </summary> private void Solve() { _selections = Solver.Solve(_requirements); }
public void NextChoice() { currentSelection++; if (((int)currentSelection) == Enum.GetNames(typeof(Selections)).Length) currentSelection = 0; }
/// <summary> /// Run solver with refresh forced off to get the old values /// </summary> private void OldSolve() { FeedManager.Refresh = false; _oldSelections = Solver.Solve(Requirements); }
/// <summary> /// Trys to parse <see cref="Store.Model.Requirements.InterfaceUri"/> as a pre-computed <see cref="Store.Model.Selection.Selections"/> document. /// </summary> /// <seealso cref="SelectionsDocument"/> private void TryParseSelectionsDocument() { try { // Try to parse as selections document Selections = XmlStorage.LoadXml<Selections>(Requirements.InterfaceUri.LocalPath); Requirements.InterfaceUri = Selections.InterfaceUri; SelectionsDocument = true; } catch (InvalidDataException) { // If that fails assume it is an interface } }
public void PreviousChoice() { currentSelection--; if (((int)currentSelection) < 0) currentSelection = 0; }