Ejemplo n.º 1
0
        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);
            }
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
 public GADefinition(decimal mutation, int population, Crossovers crossover, Selections selection)
 {
     Mutation   = mutation;
     Population = population;
     Crossover  = crossover;
     Selection  = selection;
 }
Ejemplo n.º 4
0
        /// <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
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
        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());
        }
Ejemplo n.º 7
0
        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]);
            }
        }
Ejemplo n.º 8
0
 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);
 }
Ejemplo n.º 9
0
    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();
        }
    }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
            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));
        }
Ejemplo n.º 15
0
        /// <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)));
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        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);
        }
Ejemplo n.º 19
0
 private Color SelectColor(Selections selected)
 {
     if (currentSelection == selected)
         return Color.White;
     else
         return Color.DarkGray;
 }
Ejemplo n.º 20
0
 public PauseMenu(IGameState prevGameState, Game1 game)
 {
     this.game = game;
     this.prevGameState = prevGameState;
     currentSelection = Selections.Resume;
     font = MenuSpriteFactory.CreateHUDFont();
 }
Ejemplo n.º 21
0
        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);
        }
Ejemplo n.º 22
0
        /// <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);
        }
Ejemplo n.º 24
0
        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());
        }
Ejemplo n.º 25
0
        /// <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);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        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);
            }
        }
Ejemplo n.º 27
0
        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"]);
        }
Ejemplo n.º 28
0
        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;
        }
Ejemplo n.º 29
0
        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);
        }
Ejemplo n.º 30
0
        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)
                    );
            }
        }
Ejemplo n.º 31
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;
        }
Ejemplo n.º 32
0
        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());
        }
Ejemplo n.º 33
0
        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();
            }
        }
Ejemplo n.º 34
0
        /// <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();
        }
Ejemplo n.º 35
0
        /// <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
        }
Ejemplo n.º 36
0
        /// <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);
        }
Ejemplo n.º 37
0
        /// <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);
        }
Ejemplo n.º 38
0
        //--------------------//

        #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();
        }
Ejemplo n.º 39
0
        /// <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});
        }
Ejemplo n.º 40
0
        /// <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);
            }
        }
Ejemplo n.º 41
0
        /// <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;
                }
            }
        }
Ejemplo n.º 42
0
        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;
        }
Ejemplo n.º 43
0
        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);
                }
            }
        }
Ejemplo n.º 44
0
 /// <inheritdoc/>
 public void ShowSelections(Selections selections, IFeedManager feedManager)
 {
     // Stub to be overriden
 }
Ejemplo n.º 45
0
        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;
            }
        }
Ejemplo n.º 46
0
        /// <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;
        }
Ejemplo n.º 47
0
        /// <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
        }
Ejemplo n.º 48
0
        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
        }
Ejemplo n.º 49
0
        /// <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);
        }
Ejemplo n.º 50
0
 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;
 }
Ejemplo n.º 51
0
        /// <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();
        }
Ejemplo n.º 52
0
        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"]);
        }
Ejemplo n.º 53
0
 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");
 }
Ejemplo n.º 54
0
 /// <inheritdoc/>
 public void ShowSelections(Selections selections, IFeedCache feedCache)
 {
     // Stub to be overriden
 }
Ejemplo n.º 55
0
        /// <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();
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Runs the Solver to select a version of Zero Install.
 /// </summary>
 private void Solve()
 {
     _selections = Solver.Solve(_requirements);
 }
Ejemplo n.º 57
0
 public void NextChoice()
 {
     currentSelection++;
     if (((int)currentSelection) == Enum.GetNames(typeof(Selections)).Length)
         currentSelection = 0;
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Run solver with refresh forced off to get the old values
 /// </summary>
 private void OldSolve()
 {
     FeedManager.Refresh = false;
     _oldSelections = Solver.Solve(Requirements);
 }
Ejemplo n.º 59
0
 /// <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
     }
 }
Ejemplo n.º 60
0
 public void PreviousChoice()
 {
     currentSelection--;
     if (((int)currentSelection) < 0)
         currentSelection = 0;
 }