コード例 #1
0
ファイル: SVNTools.cs プロジェクト: wlgys8/UnitySVN
 static SVNTools()
 {
     _shell = new ShellHelper();
     #if UNITY_EDITOR_OSX
     _shell.AddEnvironmentVars(SVNSetting.Instance.osxSVNPath);
     #elif UNITY_EDITOR_WIN
     _shell.AddEnvironmentVars(SVNSetting.Instance.winSVNPath);
     #endif
 }
コード例 #2
0
        public SamplesTestServer() : base($"/service/{XenkoVersion.CurrentAsText}/SiliconStudio.Xenko.SamplesTestServer.exe")
        {
            //start logging the iOS device if we have the proper tools avail
            if (IosTracker.CanProxy())
            {
                var loggerProcess = Process.Start(new ProcessStartInfo($"{ Environment.GetEnvironmentVariable("SiliconStudioXenkoDir") }\\Bin\\Windows-Direct3D11\\idevicesyslog.exe", "-d")
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                });

                if (loggerProcess != null)
                {
                    loggerProcess.OutputDataReceived += (sender, args) =>
                    {
                        try
                        {
                            lock (loggerLock)
                            {
                                currentTester?.Send(new LogRequest {
                                    Message = $"STDIO: {args.Data}"
                                }).Wait();
                            }
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.ErrorDataReceived += (sender, args) =>
                    {
                        try
                        {
                            lock (loggerLock)
                            {
                                currentTester?.Send(new LogRequest {
                                    Message = $"STDERR: {args.Data}"
                                }).Wait();
                            }
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.BeginOutputReadLine();
                    loggerProcess.BeginErrorReadLine();

                    new AttachedChildProcessJob(loggerProcess);
                }
            }

            //Start also adb in case of android device
            {
                //clear the log first
                ShellHelper.RunProcessAndGetOutput("cmd.exe", "/C adb logcat -c");

                //start logger
                var loggerProcess = Process.Start(new ProcessStartInfo("cmd.exe", "/C adb logcat")
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                });

                if (loggerProcess != null)
                {
                    loggerProcess.OutputDataReceived += (sender, args) =>
                    {
                        try
                        {
                            currentTester?.Send(new LogRequest {
                                Message = $"STDIO: {args.Data}"
                            }).Wait();
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.ErrorDataReceived += (sender, args) =>
                    {
                        try
                        {
                            currentTester?.Send(new LogRequest {
                                Message = $"STDERR: {args.Data}"
                            }).Wait();
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.BeginOutputReadLine();
                    loggerProcess.BeginErrorReadLine();

                    new AttachedChildProcessJob(loggerProcess);
                }
            }
        }
コード例 #3
0
 private void linkLblAboutCalibration_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.OpenUrl("http://www.hristopavlov.net/Tangra/Calibration");
 }
コード例 #4
0
        /// @endcond


        /// @cond EXCLUDE_FROM_DOXYGEN
        /// <summary>
        /// Rebuilds the database asset, if needed.
        /// </summary>
        /// <param name="error">An error string that will be set if the build was
        /// unsuccessful.</param>
        public void BuildIfNeeded(out string error)
        {
            error = "";
            if (!m_IsRawDataDirty)
            {
                return;
            }

            string cliBinaryPath;

            if (!FindCliBinaryPath(out cliBinaryPath))
            {
                return;
            }

            var tempDirectoryPath = FileUtil.GetUniqueTempPathInProject();

            Directory.CreateDirectory(tempDirectoryPath);
            var inputImagesFile = Path.Combine(tempDirectoryPath, "inputImages");

            string[] fileLines = new string[m_Images.Count];
            for (int i = 0; i < m_Images.Count; i++)
            {
                var           imagePath = AssetDatabase.GetAssetPath(m_Images[i].Texture);
                StringBuilder sb        = new StringBuilder();
                sb.Append(m_Images[i].Name).Append('|').Append(imagePath);
                if (m_Images[i].Width > 0)
                {
                    sb.Append('|').Append(m_Images[i].Width);
                }

                fileLines[i] = sb.ToString();
            }

            File.WriteAllLines(inputImagesFile, fileLines);
            var    rawDatabasePath = Path.Combine(tempDirectoryPath, "out_database");
            string output;

#if !UNITY_EDITOR_WIN
            ShellHelper.RunCommand("chmod", "+x \"" + cliBinaryPath + "\"", out output, out error);
            if (!string.IsNullOrEmpty(error))
            {
                Debug.LogWarning(error);
                return;
            }
#endif
            ShellHelper.RunCommand(cliBinaryPath,
                                   string.Format(
                                       "build-db --input_image_list_path {0} --output_db_path {1}",
                                       inputImagesFile, rawDatabasePath), out output, out error);
            if (!string.IsNullOrEmpty(error))
            {
                return;
            }

            m_RawData        = File.ReadAllBytes(rawDatabasePath + ".imgdb");
            m_IsRawDataDirty = false;
            EditorUtility.SetDirty(this);

            // Force a save to make certain build process will get updated asset.
            AssetDatabase.SaveAssets();

            const int BYTES_IN_KBYTE = 1024;
            Debug.LogFormat(
                "Built AugmentedImageDatabase '{0}' ({1} Images, {2} KBytes)", name, Count,
                m_RawData.Length / BYTES_IN_KBYTE);

            // TODO:: Remove this log when all errors/warnings are moved to stderr for CLI tool.
            Debug.Log(output);
        }
コード例 #5
0
            /// <inheritdoc />
            protected override async Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
            {
                VideoAsset videoAsset = Parameters.Video;

                try
                {
                    // Get path to ffmpeg
                    var ffmpeg = ToolLocator.LocateTool("ffmpeg.exe")?.ToWindowsPath() ?? throw new AssetException("Failed to compile a video asset, ffmpeg was not found.");

                    // Get absolute path of asset source on disk
                    var assetDirectory = videoAsset.Source.GetParent();
                    var assetSource    = UPath.Combine(assetDirectory, videoAsset.Source);

                    //=====================================================================================
                    //Get the info from the video codec

                    //Check if we need to reencode the video
                    var mustReEncodeVideo    = false;
                    var sidedataStripCommand = "";

                    // check that the video file format is supported
                    if (Parameters.Platform == PlatformType.Windows && videoAsset.Source.GetFileExtension() != ".mp4")
                    {
                        mustReEncodeVideo = true;
                    }

                    //Use FFmpegMedia object (need to check more details first before I can use it)
                    VideoStream videoStream = null;
                    AudioStream audioStream = null;
                    FFmpegUtils.PreloadLibraries();
                    FFmpegUtils.Initialize();
                    using (var media = new FFmpegMedia())
                    {
                        media.Open(assetSource.ToWindowsPath());

                        // Get the first video stream
                        videoStream = media.Streams.OfType <VideoStream>().FirstOrDefault();
                        if (videoStream == null)
                        {
                            throw new AssetException("Failed to compile a video asset. Did not find the VideoStream from the media.");
                        }

                        // On windows MediaEngineEx player only decode the first video if the video is detected as a stereoscopic video,
                        // so we remove the tags inside the video in order to ensure the same behavior as on other platforms (side by side decoded texture)
                        // Unfortunately it does seem possible to disable this behavior from the MediaEngineEx API.
                        if (Parameters.Platform == PlatformType.Windows && media.IsStereoscopicVideo(videoStream))
                        {
                            mustReEncodeVideo    = true;
                            sidedataStripCommand = "-vf sidedata=delete";
                        }

                        // Get the first audio stream
                        audioStream = media.Streams.OfType <AudioStream>().FirstOrDefault();
                    }
                    Size2 videoSize = new Size2(videoStream.Width, videoStream.Height);

                    //check the format
                    if (ListSupportedCodecNames != null)
                    {
                        if (Array.IndexOf(ListSupportedCodecNames, videoStream.Codec) < 0)
                        {
                            mustReEncodeVideo = true;
                        }
                    }

                    // check if video need to be trimmed
                    var videoDuration = videoAsset.VideoDuration;
                    if (videoDuration.Enabled && (videoDuration.StartTime != TimeSpan.Zero ||
                                                  videoDuration.EndTime.TotalSeconds < videoStream.Duration.TotalSeconds - MathUtil.ZeroToleranceDouble))
                    {
                        mustReEncodeVideo = true;
                    }

                    //check the video target and source resolution
                    Size2 targetSize;
                    if (videoAsset.IsSizeInPercentage)
                    {
                        targetSize = new Size2((int)(videoSize.Width * videoAsset.Width / 100.0f), (int)(videoSize.Height * videoAsset.Height / 100.0f));
                    }
                    else
                    {
                        targetSize = new Size2((int)(videoAsset.Width), (int)(videoAsset.Height));
                    }

                    // ensure that the size is a multiple of 2 (ffmpeg cannot output video not multiple of 2, at least with this codec)
                    if (targetSize.Width % 2 == 1)
                    {
                        targetSize.Width += 1;
                    }
                    if (targetSize.Height % 2 == 1)
                    {
                        targetSize.Height += 1;
                    }

                    if (targetSize.Width != videoSize.Width || targetSize.Height != videoSize.Height)
                    {
                        mustReEncodeVideo = true;
                    }

                    //check the audio settings
                    int  audioChannelsTarget       = audioStream == null? 0: audioStream.ChannelCount;
                    bool mustReEncodeAudioChannels = false;
                    if (videoAsset.IsAudioChannelMono)
                    {
                        audioChannelsTarget = 1;
                        if (audioStream != null && audioStream.ChannelCount != audioChannelsTarget)
                        {
                            mustReEncodeAudioChannels = true;
                            mustReEncodeVideo         = true;
                        }
                    }

                    // Execute ffmpeg to convert source to H.264
                    string tempFile = null;
                    try
                    {
                        if (mustReEncodeVideo)
                        {
                            string targetCodecFormat = "h264";  //hardcodec for now
                            commandContext.Logger.Info(string.Format("Video Asset Compiler: \"{0}\". Re-encode the Video. Format:{1}, Size:{2}x{3}. Audio Channels:{4}",
                                                                     videoAsset.Source.GetFileName(), targetCodecFormat, targetSize.Width, targetSize.Height, audioChannelsTarget));

                            tempFile = Path.GetTempFileName();
                            string channelFlag = "";
                            if (mustReEncodeAudioChannels)
                            {
                                channelFlag = string.Format(" -ac {0}", audioChannelsTarget);
                            }

                            var startTime       = videoDuration.StartTime;
                            var duration        = videoDuration.EndTime - videoDuration.StartTime;
                            var trimmingOptions = videoDuration.Enabled ?
                                                  $" -ss {startTime.Hours:D2}:{startTime.Minutes:D2}:{startTime.Seconds:D2}.{startTime.Milliseconds:D3}" +
                                                  $" -t {duration.Hours:D2}:{duration.Minutes:D2}:{duration.Seconds:D2}.{duration.Milliseconds:D3}":
                                                  "";

                            var commandLine = "  -hide_banner -loglevel error" +                       // hide most log output
                                              "  -nostdin" +                                           // no interaction (background process)
                                              $" -i \"{assetSource.ToWindowsPath()}\"" +               // input file
                                              $"{trimmingOptions}" +
                                              "  -f mp4 -vcodec " + targetCodecFormat +                // codec
                                              channelFlag +                                            // audio channels
                                              $"  -vf scale={targetSize.Width}:{targetSize.Height} " + // adjust the resolution
                                              sidedataStripCommand +                                   // strip of stereoscopic sidedata tag
                                                                                                       //" -an" + // no audio
                                                                                                       //" -pix_fmt yuv422p" + // pixel format (planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples))
                                              $" -y \"{tempFile}\"";                                   // output file (always overwrite)
                            var ret = await ShellHelper.RunProcessAndGetOutputAsync(ffmpeg, commandLine, commandContext.Logger);

                            if (ret != 0 || commandContext.Logger.HasErrors)
                            {
                                throw new AssetException($"Failed to compile a video asset. ffmpeg failed to convert {assetSource}.");
                            }
                        }
                        else
                        {
                            commandContext.Logger.Info(string.Format("Video Asset Compiler: \"{0}\". No Re-encoding necessary",
                                                                     videoAsset.Source.GetFileName()));

                            // Use temporary file
                            tempFile = assetSource.ToWindowsPath();
                        }

                        var dataUrl = Url + "_Data";
                        var video   = new Video.Video
                        {
                            CompressedDataUrl = dataUrl,
                        };

                        // Make sure we don't compress h264 data
                        commandContext.AddTag(new ObjectUrl(UrlType.Content, dataUrl), Builder.DoNotCompressTag);

                        // Write the data
                        using (var reader = new BinaryReader(new FileStream(tempFile, FileMode.Open, FileAccess.Read)))
                            using (var outputStream = MicrothreadLocalDatabases.DatabaseFileProvider.OpenStream(dataUrl, VirtualFileMode.Create, VirtualFileAccess.Write, VirtualFileShare.Read, StreamFlags.Seekable))
                            {
                                // For now write everything at once, 1MB at a time
                                var length = reader.BaseStream.Length;
                                for (var position = 0L; position < length; position += 2 << 20)
                                {
                                    var buffer = reader.ReadBytes(2 << 20);
                                    outputStream.Write(buffer, 0, buffer.Length);
                                }
                            }

                        var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService);
                        assetManager.Save(Url, video);

                        return(ResultStatus.Successful);
                    }
                    finally
                    {
                        if (mustReEncodeVideo)
                        {
                            if (tempFile != null)
                            {
                                File.Delete(tempFile);
                            }
                        }
                    }
                }
                catch (AssetException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw new AssetException("Failed to compile a video asset. Unexpected exception.", ex);
                }
            }
コード例 #6
0
 private void linkLabelMoreAboutLiveClipboard_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.LaunchUrl(GLink.Instance.MoreAboutLiveClipboard);
 }
コード例 #7
0
        public int DragOver(ShellAPI.MK grfKeyState, ShellAPI.POINT pt, ref DragDropEffects pdwEffect)
        {
            bool reset = false;

            #region Get DropItem

            Point point = br.FileView.PointToClient(new Point(pt.x, pt.y));
            ListViewHitTestInfo hitTest = br.FileView.HitTest(point);
            if (hitTest.Item != null &&
                (br.FileView.View != View.Details || hitTest.SubItem == null || hitTest.Item.Name == hitTest.SubItem.Name) &&
                (hitTest.Location == ListViewHitTestLocations.Image ||
                 hitTest.Location == ListViewHitTestLocations.Label ||
                 hitTest.Location == ListViewHitTestLocations.StateImage))
            {
                if (!hitTest.Item.Equals(dropListItem))
                {
                    if (dropTarget != null)
                    {
                        dropTarget.DragLeave();
                    }

                    ReleaseCom();

                    if (dropListItem != null)
                    {
                        dropListItem.Selected = wasSelected;
                    }

                    dropListItem          = hitTest.Item;
                    wasSelected           = dropListItem.Selected;
                    dropListItem.Selected = true;

                    ShellItem item = (ShellItem)dropListItem.Tag;
                    parentDropItem = item;

                    ShellHelper.GetIDropTarget(item, out dropTargetPtr, out dropTarget);
                    reset = true;
                }
            }
            else
            {
                if (dropListItem != null)
                {
                    if (dropTarget != null)
                    {
                        dropTarget.DragLeave();
                    }

                    ReleaseCom();

                    dropListItem.Selected = wasSelected;

                    dropListItem   = null;
                    parentDropItem = br.SelectedItem;

                    ShellHelper.GetIDropTarget(br.SelectedItem, out dropTargetPtr, out dropTarget);
                    reset = true;
                }
            }

            #endregion

            if (dropTarget != null)
            {
                if (reset)
                {
                    dropTarget.DragEnter(dropDataObject, grfKeyState, pt, ref pdwEffect);
                }
                else
                {
                    dropTarget.DragOver(grfKeyState, pt, ref pdwEffect);
                }
            }
            else
            {
                pdwEffect = DragDropEffects.None;
            }

            if (dropHelper != null)
            {
                dropHelper.DragOver(ref pt, pdwEffect);
            }

            return(ShellAPI.S_OK);
        }
コード例 #8
0
 private void privacyPolicyLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.LaunchUrl("http://www.dotnetfoundation.org/privacy-policy");
 }
コード例 #9
0
ファイル: Taskbar.xaml.cs プロジェクト: josuave/RetroBar
 private void TaskManagerMenuItem_OnClick(object sender, RoutedEventArgs e)
 {
     ShellHelper.StartTaskManager();
 }
コード例 #10
0
        public void EnsureLoggedIn(string username, string password, string service, bool showUi, string uri)
        {
            try
            {
                if (IsValid(username, password, service))
                {
                    return;
                }

                string captchaToken = null;
                string captchaValue = null;

                string source = string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", ApplicationEnvironment.CompanyName, ApplicationEnvironment.ProductName, ApplicationEnvironment.ProductVersion);

                while (true)
                {
                    GoogleLoginRequestFactory glrf = new GoogleLoginRequestFactory(username,
                                                                                   password,
                                                                                   service,
                                                                                   source,
                                                                                   captchaToken,
                                                                                   captchaValue);
                    if (captchaToken != null && captchaValue != null)
                    {
                        captchaToken = null;
                        captchaValue = null;
                    }

                    HttpWebResponse response;
                    try
                    {
                        response = RedirectHelper.GetResponse(uri, new RedirectHelper.RequestFactory(glrf.Create));
                    }
                    catch (WebException we)
                    {
                        response = (HttpWebResponse)we.Response;
                        if (response == null)
                        {
                            Trace.Fail(we.ToString());
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.WeblogConnectionError, we.Message);
                            }
                            throw;
                        }
                    }

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Hashtable ht = ParseAuthResponse(response.GetResponseStream());
                        if (ht.ContainsKey("Auth"))
                        {
                            _auths[new AuthKey(username, password, service)] = new AuthValue((string)ht["Auth"], ht["YouTubeUser"] as string);
                            return;
                        }
                        else
                        {
                            if (showUi)
                            {
                                showUi = false;
                                ShowError(MessageId.GoogleAuthTokenNotFound);
                            }
                            throw new BlogClientInvalidServerResponseException(uri, "No Auth token was present in the response.", string.Empty);
                        }
                    }
                    else if (response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        // login failed

                        Hashtable ht    = ParseAuthResponse(response.GetResponseStream());
                        string    error = ht["Error"] as string;
                        if (error != null && error == "CaptchaRequired")
                        {
                            captchaToken = (string)ht["CaptchaToken"];
                            string captchaUrl = (string)ht["CaptchaUrl"];

                            GDataCaptchaHelper helper = new GDataCaptchaHelper(
                                new Win32WindowImpl(BlogClientUIContext.ContextForCurrentThread.Handle),
                                captchaUrl);

                            BlogClientUIContext.ContextForCurrentThread.Invoke(new ThreadStart(helper.ShowCaptcha), null);

                            if (helper.DialogResult == DialogResult.OK)
                            {
                                captchaValue = helper.Reply;
                                continue;
                            }
                            else
                            {
                                throw new BlogClientOperationCancelledException();
                            }
                        }

                        if (showUi)
                        {
                            if (error == "NoLinkedYouTubeAccount")
                            {
                                if (DisplayMessage.Show(MessageId.YouTubeSignup, username) == DialogResult.Yes)
                                {
                                    ShellHelper.LaunchUrl(GLink.Instance.YouTubeRegister);
                                }
                                return;
                            }

                            showUi = false;

                            if (error == "BadAuthentication")
                            {
                                ShowError(MessageId.LoginFailed, ApplicationEnvironment.ProductNameQualified);
                            }
                            else
                            {
                                ShowError(MessageId.BloggerError, TranslateError(error));
                            }
                        }
                        throw new BlogClientAuthenticationException(error, TranslateError(error));
                    }
                    else
                    {
                        if (showUi)
                        {
                            showUi = false;
                            ShowError(MessageId.BloggerError, response.StatusCode + ": " + response.StatusDescription);
                        }
                        throw new BlogClientAuthenticationException(response.StatusCode + "", response.StatusDescription);
                    }
                }
            }
            catch (BlogClientOperationCancelledException)
            {
                throw;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e.ToString());
                if (showUi)
                {
                    ShowError(MessageId.UnexpectedErrorLogin, e.Message);
                }
                throw;
            }
        }
 void linkLabelLearnMore_Click(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.LaunchUrl(GLink.Instance.LearnMore);
 }
コード例 #12
0
ファイル: AndroidTracker.cs プロジェクト: rohitshe/Code
        public static void TrackDevices(Router router)
        {
            var currentAndroidDevices = new Dictionary <string, ConnectedDevice>();

            // Start new devices
            int startLocalPort = 51153; // Use ports in the dynamic port range

            // Check if ADB is on the path
            var adbPath = AndroidDeviceEnumerator.GetAdbPath();

            if (adbPath == null)
            {
                return;
            }

            // Wait and process android device changes events
            while (true)
            {
                // Fill list of android devices
                var newAndroidDevices = new Dictionary <string, string>();
                foreach (var device in AndroidDeviceEnumerator.ListAndroidDevices())
                {
                    newAndroidDevices.Add(device.Serial, string.Format("{0} ({1})", device.Name, device.Serial));
                }

                DeviceHelper.UpdateDevices(Log, newAndroidDevices, currentAndroidDevices, (connectedDevice) =>
                {
                    // First, try adb reverse port mapping (supported on newest adb+device)
                    // This is the best solution, as nothing specific needs to be done.
                    // NOTE: disabled for now, as it's difficult to know what to try first from the device itself.
                    //var output = ShellHelper.RunProcessAndGetOutput(AndroidDeviceEnumerator.GetAdbPath(), string.Format(@"-s {0} reverse tcp:{1} tcp:{2}", newAndroidDevice, LocalPort, LocalPort));
                    //if (output.ExitCode == 0)
                    //    continue;

                    // Setup adb port forward (tries up to 5 times for open ports)
                    int localPort            = 0;
                    int firstTestedLocalPort = startLocalPort;
                    for (int i = 0; i < 4; ++i)
                    {
                        int testedLocalPort = startLocalPort++;
                        if (startLocalPort >= 65536) // Make sure we stay in the range of dynamic ports: 49152-65535
                        {
                            startLocalPort = 49152;
                        }

                        var output = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} forward tcp:{1} tcp:{2}", connectedDevice.Key, testedLocalPort, RouterClient.DefaultListenPort));

                        if (output.ExitCode == 0)
                        {
                            localPort = testedLocalPort;
                            Log.Info("Device connected: {0}; successfully mapped port {1}:{2}", connectedDevice.Name, testedLocalPort, RouterClient.DefaultListenPort);
                            break;
                        }
                    }

                    if (localPort == 0)
                    {
                        int lastTestedLocalPort = startLocalPort;
                        Log.Info("Device connected: {0}; error when mapping port [{1}-{2}]:{3}", connectedDevice.Name, firstTestedLocalPort, lastTestedLocalPort - 1, RouterClient.DefaultListenPort);
                        return;
                    }

                    // Launch a client thread that will automatically tries to connect to this port
                    Task.Run(() => DeviceHelper.LaunchPersistentClient(connectedDevice, router, "localhost", localPort));
                });

                Thread.Sleep(1000); // Detect new devices every 1000 msec
            }
        }
コード例 #13
0
ファイル: SamplesTestServer.cs プロジェクト: xen2/stride
        public SamplesTestServer() : base($"/service/{XenkoVersion.NuGetVersion}/Xenko.SamplesTestServer.exe")
        {
            GameTestingSystem.Initialized = true;

            //start logging the iOS device if we have the proper tools avail
            if (IosTracker.CanProxy())
            {
                var loggerProcess = Process.Start(new ProcessStartInfo($"{ Environment.GetEnvironmentVariable("XenkoDir") }\\Bin\\Windows\\idevicesyslog.exe", "-d")
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                });

                if (loggerProcess != null)
                {
                    loggerProcess.OutputDataReceived += (sender, args) =>
                    {
                        try
                        {
                            lock (loggerLock)
                            {
                                currentTester?.Send(new LogRequest {
                                    Message = $"STDIO: {args.Data}"
                                }).Wait();
                            }
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.ErrorDataReceived += (sender, args) =>
                    {
                        try
                        {
                            lock (loggerLock)
                            {
                                currentTester?.Send(new LogRequest {
                                    Message = $"STDERR: {args.Data}"
                                }).Wait();
                            }
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.BeginOutputReadLine();
                    loggerProcess.BeginErrorReadLine();

                    new AttachedChildProcessJob(loggerProcess);
                }
            }

            //Start also adb in case of android device
            var adbPath = AndroidDeviceEnumerator.GetAdbPath();

            if (!string.IsNullOrEmpty(adbPath) && AndroidDeviceEnumerator.ListAndroidDevices().Length > 0)
            {
                //clear the log first
                ShellHelper.RunProcessAndGetOutput("cmd.exe", $"/C {adbPath} logcat -c");

                //start logger
                var loggerProcess = Process.Start(new ProcessStartInfo("cmd.exe", $"/C {adbPath} logcat")
                {
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                    RedirectStandardError  = true,
                    RedirectStandardOutput = true,
                });

                if (loggerProcess != null)
                {
                    loggerProcess.OutputDataReceived += (sender, args) =>
                    {
                        try
                        {
                            currentTester?.Send(new LogRequest {
                                Message = $"STDIO: {args.Data}"
                            }).Wait();
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.ErrorDataReceived += (sender, args) =>
                    {
                        try
                        {
                            currentTester?.Send(new LogRequest {
                                Message = $"STDERR: {args.Data}"
                            }).Wait();
                        }
                        catch
                        {
                        }
                    };

                    loggerProcess.BeginOutputReadLine();
                    loggerProcess.BeginErrorReadLine();

                    new AttachedChildProcessJob(loggerProcess);
                }
            }
        }
コード例 #14
0
 private void linkExamples_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.OpenUrl("http://www.hristopavlov.net/Tangra/AstrometryExamples");
 }
コード例 #15
0
 static bool ExecuteScriptFile()
 {
     return(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
         ? ShellHelper.ExecuteFile("win.bat", "C:\\", true)
         : ShellHelper.ExecuteFile("linux-mac.sh", "-lh", true));
 }
コード例 #16
0
ファイル: ShaderCompiler.cs プロジェクト: xa8et67/xenko
        /// <summary>
        /// Converts the hlsl code into glsl and stores the result as plain text
        /// </summary>
        /// <param name="shaderSource">the hlsl shader</param>
        /// <param name="entryPoint">the entrypoint function name</param>
        /// <param name="stage">the shader pipeline stage</param>
        /// <param name="effectParameters"></param>
        /// <param name="reflection">the reflection gathered from the hlsl analysis</param>
        /// <param name="sourceFilename">the name of the source file</param>
        /// <returns></returns>
        public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, ShaderStage stage, EffectCompilerParameters effectParameters, EffectReflection reflection, string sourceFilename = null)
        {
            var shaderBytecodeResult = new ShaderBytecodeResult();

            byte[] rawData;

            var inputAttributeNames = new Dictionary <int, string>();
            var resourceBindings    = new Dictionary <string, int>();

            GlslShaderPlatform shaderPlatform;
            int shaderVersion;

            switch (effectParameters.Platform)
            {
            case GraphicsPlatform.OpenGL:
                shaderPlatform = GlslShaderPlatform.OpenGL;
                shaderVersion  = 410;
                break;

            case GraphicsPlatform.OpenGLES:
                shaderPlatform = GlslShaderPlatform.OpenGLES;
                shaderVersion  = effectParameters.Profile >= GraphicsProfile.Level_10_0 ? 300 : 100;
                break;

            case GraphicsPlatform.Vulkan:
                shaderPlatform = GlslShaderPlatform.Vulkan;
                shaderVersion  = 450;
                break;

            default:
                throw new ArgumentOutOfRangeException("effectParameters.Platform");
            }

            var shader = Compile(shaderSource, entryPoint, stage, shaderPlatform, shaderVersion, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);

            if (shader == null)
            {
                return(shaderBytecodeResult);
            }

            if (effectParameters.Platform == GraphicsPlatform.OpenGLES)      // TODO: Add check to run on android only. The current version breaks OpenGL ES on windows.
            {
                //TODO: Remove this ugly hack!
                if (shaderSource.Contains($"Texture2D XenkoInternal_TextureExt0") && shader.Contains("uniform sampler2D"))
                {
                    if (shaderPlatform != GlslShaderPlatform.OpenGLES || shaderVersion != 300)
                    {
                        throw new Exception("Invalid GLES platform or version: require OpenGLES 300");
                    }

                    shader = shader.Replace("uniform sampler2D", "uniform samplerExternalOES");
                    shader = shader.Replace("#version 300 es", "#version 300 es\n#extension GL_OES_EGL_image_external_essl3 : require");
                }
            }

            if (effectParameters.Platform == GraphicsPlatform.OpenGLES)
            {
                // store both ES 2 and ES 3 on OpenGL ES platforms
                var shaderBytecodes = new ShaderLevelBytecode();
                if (effectParameters.Profile >= GraphicsProfile.Level_10_0)
                {
                    shaderBytecodes.DataES3 = shader;
                    shaderBytecodes.DataES2 = null;
                }
                else
                {
                    shaderBytecodes.DataES2 = shader;
                    shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, GlslShaderPlatform.OpenGLES, 300, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);
                }
                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
                    rawData = stream.GetBuffer();
                }
            }
            else if (effectParameters.Platform == GraphicsPlatform.Vulkan)
            {
                string inputFileExtension;
                switch (stage)
                {
                case ShaderStage.Vertex: inputFileExtension = ".vert"; break;

                case ShaderStage.Pixel: inputFileExtension = ".frag"; break;

                case ShaderStage.Geometry: inputFileExtension = ".geom"; break;

                case ShaderStage.Domain: inputFileExtension = ".tese"; break;

                case ShaderStage.Hull: inputFileExtension = ".tesc"; break;

                case ShaderStage.Compute: inputFileExtension = ".comp"; break;

                default:
                    shaderBytecodeResult.Error("Unknown shader profile");
                    return(shaderBytecodeResult);
                }

                var inputFileName  = Path.ChangeExtension(Path.GetTempFileName(), inputFileExtension);
                var outputFileName = Path.ChangeExtension(inputFileName, ".spv");

                // Write shader source to disk
                File.WriteAllBytes(inputFileName, Encoding.ASCII.GetBytes(shader));

                // Run shader compiler
                var filename = Platform.Type == PlatformType.Windows ? "glslangValidator.exe" : "glslangValidator";
                ShellHelper.RunProcessAndRedirectToLogger(filename, $"-V -o {outputFileName} {inputFileName}", null, shaderBytecodeResult);

                if (!File.Exists(outputFileName))
                {
                    shaderBytecodeResult.Error("Failed to generate SPIR-V from GLSL");
                    return(shaderBytecodeResult);
                }

                // Read compiled shader
                var shaderBytecodes = new ShaderInputBytecode
                {
                    InputAttributeNames = inputAttributeNames,
                    ResourceBindings    = resourceBindings,
                    Data = File.ReadAllBytes(outputFileName),
                };

                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
                    rawData = stream.ToArray();
                }

                // Cleanup temp files
                File.Delete(inputFileName);
                File.Delete(outputFileName);
            }
            else
            {
                // store string on OpenGL platforms
                rawData = Encoding.UTF8.GetBytes(shader);
            }

            var bytecodeId = ObjectId.FromBytes(rawData);
            var bytecode   = new ShaderBytecode(bytecodeId, rawData);

            bytecode.Stage = stage;

            shaderBytecodeResult.Bytecode = bytecode;

            return(shaderBytecodeResult);
        }
コード例 #17
0
 /// <summary>
 /// Run an imageMagick shell command.
 /// </summary>
 /// <param name="commandName">The name of the command.</param>
 /// <param name="commandParameters">The arguments of the command.</param>
 /// <returns>The output of the command.</returns>
 private static ProcessOutputs RunImageMagickCommand(string commandName, string commandParameters)
 {
     return(ShellHelper.RunProcessAndGetOutput(Path.Combine(imageMagickDir, commandName), commandParameters));
 }
コード例 #18
0
        public int DragOver(ShellAPI.MK grfKeyState, ShellAPI.POINT pt, ref DragDropEffects pdwEffect)
        {
            bool reset = false;

            #region Get DropItem

            Point point = br.FolderView.PointToClient(new Point(pt.x, pt.y));
            TreeViewHitTestInfo hitTest = br.FolderView.HitTest(point);
            if (!TreeNode.Equals(dropNode, hitTest.Node))
            {
                if (dropTarget != null)
                {
                    dropTarget.DragLeave();
                }

                ReleaseCom();

                dropNode = hitTest.Node;
                br.FolderView.SelectedNode = dropNode;

                if (dropNode == null)
                {
                    pdwEffect = DragDropEffects.None;

                    if (dropHelper != null)
                    {
                        dropHelper.DragOver(ref pt, pdwEffect);
                    }

                    return(ShellAPI.S_OK);
                }
                else
                {
                    ShellItem item = (ShellItem)dropNode.Tag;
                    parentDropItem = item;

                    ShellHelper.GetIDropTarget(item, out dropTargetPtr, out dropTarget);
                    reset = true;
                }
            }
            else if (dropNode == null)
            {
                if (dropTarget != null)
                {
                    dropTarget.DragLeave();
                }

                ReleaseCom();

                dropNode        = null;
                br.SelectedNode = null;

                pdwEffect = DragDropEffects.None;

                if (dropHelper != null)
                {
                    dropHelper.DragOver(ref pt, pdwEffect);
                }

                return(ShellAPI.S_OK);
            }

            #endregion

            if (dropTarget != null)
            {
                if (reset)
                {
                    dropTarget.DragEnter(dropDataObject, grfKeyState, pt, ref pdwEffect);
                }
                else
                {
                    dropTarget.DragOver(grfKeyState, pt, ref pdwEffect);
                }
            }
            else
            {
                pdwEffect = DragDropEffects.None;
            }

            if (dropHelper != null)
            {
                dropHelper.DragOver(ref pt, pdwEffect);
            }

            return(ShellAPI.S_OK);
        }
コード例 #19
0
        public async Task DockerBuildAsync()
        {
            var result = ShellHelper.Execute("docker build", _ciSettings.Value.SolutionPath);

            _logger.LogInformation("docker build result: " + result);
        }
コード例 #20
0
 public void OpenFile()
 {
     ShellHelper.Start(Path.Combine(_drive.DriveRoot, Magnet.FileName));
 }
コード例 #21
0
        public async Task DockerPushAsync()
        {
            var result = ShellHelper.Execute("docker push", _ciSettings.Value.SolutionPath);

            _logger.LogInformation("docker run result: " + result);
        }
コード例 #22
0
        /// <summary>
        /// Converts the hlsl code into glsl and stores the result as plain text
        /// </summary>
        /// <param name="shaderSource">the hlsl shader</param>
        /// <param name="entryPoint">the entrypoint function name</param>
        /// <param name="stage">the shader pipeline stage</param>
        /// <param name="effectParameters"></param>
        /// <param name="reflection">the reflection gathered from the hlsl analysis</param>
        /// <param name="sourceFilename">the name of the source file</param>
        /// <returns></returns>
        public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, ShaderStage stage, EffectCompilerParameters effectParameters, EffectReflection reflection, string sourceFilename = null)
        {
            var shaderBytecodeResult = new ShaderBytecodeResult();

            byte[] rawData;

            var inputAttributeNames = new Dictionary <int, string>();
            var resourceBindings    = new Dictionary <string, int>();

            GlslShaderPlatform shaderPlatform;
            int shaderVersion;

            switch (effectParameters.Platform)
            {
            case GraphicsPlatform.OpenGL:
                shaderPlatform = GlslShaderPlatform.OpenGL;
                shaderVersion  = 410;
                break;

            case GraphicsPlatform.OpenGLES:
                shaderPlatform = GlslShaderPlatform.OpenGLES;
                shaderVersion  = effectParameters.Profile >= GraphicsProfile.Level_10_0 ? 300 : 100;
                break;

            case GraphicsPlatform.Vulkan:
                shaderPlatform = GlslShaderPlatform.Vulkan;
                shaderVersion  = 450;
                break;

            default:
                throw new ArgumentOutOfRangeException("effectParameters.Platform");
            }

            var shader = Compile(shaderSource, entryPoint, stage, shaderPlatform, shaderVersion, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);

            if (shader == null)
            {
                return(shaderBytecodeResult);
            }

            if (effectParameters.Platform == GraphicsPlatform.OpenGLES)
            {
                // store both ES 2 and ES 3 on OpenGL ES platforms
                var shaderBytecodes = new ShaderLevelBytecode();
                if (effectParameters.Profile >= GraphicsProfile.Level_10_0)
                {
                    shaderBytecodes.DataES3 = shader;
                    shaderBytecodes.DataES2 = null;
                }
                else
                {
                    shaderBytecodes.DataES2 = shader;
                    shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, GlslShaderPlatform.OpenGLES, 300, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename);
                }
                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
#if !SILICONSTUDIO_RUNTIME_CORECLR && !SILICONSTUDIO_PLATFORM_UWP
                    rawData = stream.GetBuffer();
#else
// FIXME: Manu: The call to "ToArray()" might be slower than "GetBuffer()"
                    rawData = stream.ToArray();
#endif
                }
            }
#if !SILICONSTUDIO_RUNTIME_CORECLR && !SILICONSTUDIO_PLATFORM_UWP
            else if (effectParameters.Platform == GraphicsPlatform.Vulkan)
            {
                string inputFileExtension;
                switch (stage)
                {
                case ShaderStage.Vertex: inputFileExtension = ".vert"; break;

                case ShaderStage.Pixel: inputFileExtension = ".frag"; break;

                case ShaderStage.Geometry: inputFileExtension = ".geom"; break;

                case ShaderStage.Domain: inputFileExtension = ".tese"; break;

                case ShaderStage.Hull: inputFileExtension = ".tesc"; break;

                case ShaderStage.Compute: inputFileExtension = ".comp"; break;

                default:
                    shaderBytecodeResult.Error("Unknown shader profile");
                    return(shaderBytecodeResult);
                }

                var inputFileName  = Path.ChangeExtension(Path.GetTempFileName(), inputFileExtension);
                var outputFileName = Path.ChangeExtension(inputFileName, ".spv");

                // Write shader source to disk
                File.WriteAllBytes(inputFileName, Encoding.ASCII.GetBytes(shader));

                // Run shader compiler
                var filename = Platform.Type == PlatformType.Windows ? "glslangValidator.exe" : "glslangValidator";
                ShellHelper.RunProcessAndRedirectToLogger(filename, $"-V -o {outputFileName} {inputFileName}", null, shaderBytecodeResult);

                if (!File.Exists(outputFileName))
                {
                    shaderBytecodeResult.Error("Failed to generate SPIR-V from GLSL");
                    return(shaderBytecodeResult);
                }

                // Read compiled shader
                var shaderBytecodes = new ShaderInputBytecode
                {
                    InputAttributeNames = inputAttributeNames,
                    ResourceBindings    = resourceBindings,
                    Data = File.ReadAllBytes(outputFileName),
                };

                using (var stream = new MemoryStream())
                {
                    BinarySerialization.Write(stream, shaderBytecodes);
                    rawData = stream.ToArray();
                }

                // Cleanup temp files
                File.Delete(inputFileName);
                File.Delete(outputFileName);
            }
#endif
            else
            {
                // store string on OpenGL platforms
                rawData = Encoding.UTF8.GetBytes(shader);
            }

            var bytecodeId = ObjectId.FromBytes(rawData);
            var bytecode   = new ShaderBytecode(bytecodeId, rawData);
            bytecode.Stage = stage;

            shaderBytecodeResult.Bytecode = bytecode;

            return(shaderBytecodeResult);
        }
コード例 #23
0
        public static void MakeScript(string port)
        {
            string path  = Properties.Resources.runscript;
            string path2 = Properties.Resources.killscript;

            try
            {
                // Delete the file if it exists.
                if (File.Exists(path))
                {
                    // Note that no lock is put on the
                    // file and the possibility exists
                    // that another process could do
                    // something with it between
                    // the calls to Exists and Delete.
                    File.Delete(path);
                }

                // Delete the file if it exists.
                if (File.Exists(path2))
                {
                    // Note that no lock is put on the
                    // file and the possibility exists
                    // that another process could do
                    // something with it between
                    // the calls to Exists and Delete.
                    File.Delete(path2);
                }

                string script = "#Kill all processes that hold up ports user for the system\n" +
                                "fuser -k -n tcp " + port + "\n";

                foreach (Servers server in Servers)
                {
                    script += "fuser -k -n tcp " + server.api_port + "\n";
                }

                // Create the file for killing the processes
                using (FileStream fs = File.Create(path2))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes(script);
                    // Add some information to the file.
                    fs.Write(info, 0, info.Length);

                    ShellHelper.Bash("sudo chmod -R a+r+w+x " + path2);
                }


                script += "\n#Build and publish\n" +
                          "dotnet restore ~/Distributed/UniprotDistributed\n" +
                          "dotnet build ~/Distributed/UniprotDistributed\n" +
                          "dotnet publish ~/Distributed/UniprotDistributed\n" +
                          "\n#Remove and make directories and copy the stuff to each slave and make log and wd folders\n" +
                          "rm -r ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves; mkdir ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/\n";

                foreach (Servers server in Servers)
                {
                    script +=
                        "\nmkdir ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "\n" +
                        "cp -r ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/publish ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "\n" +
                        "mkdir ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "/publish/logs\n" +
                        "mkdir ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "/publish/wd\n";
                }

                script += "\n#Run the thing\n" +
                          "dotnet ~/Distributed/UniprotDistributed/UniprotDistributedServer/bin/Debug/netcoreapp2.0/publish/UniprotDistributedServer.dll &\n";

                foreach (Servers server in Servers)
                {
                    script += "dotnet ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "/publish/UniprotDistributedSlave.dll --urls " + server.api_call + " >> ~/Distributed/UniprotDistributed/UniprotDistributedSlave/bin/Debug/netcoreapp2.0/slaves/Slave" + server.slave_id + "/publish/logs/log.txt &\n";
                }

                // Create the file.
                using (FileStream fs = File.Create(path))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes(script);
                    // Add some information to the file.
                    fs.Write(info, 0, info.Length);

                    ShellHelper.Bash("sudo chmod -R a+r+w+x " + path);
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Could not create the script. Original error: " + ex.ToString());
            }
        }
コード例 #24
0
ファイル: ucAAV8bit.cs プロジェクト: alexcherney/tangra3
 private void linkLabelAAV_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     ShellHelper.OpenUrl("http://www.hristopavlov.net/OccuRec");
 }
コード例 #25
0
        private void ListView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(ApplicationInfo)))
            {
                ShellLogger.Debug(e.Data.GetData(typeof(ApplicationInfo)).ToString());
                ApplicationInfo dropData   = e.Data.GetData(typeof(ApplicationInfo)) as ApplicationInfo;
                ListView        dropTarget = sender as ListView;

                if (dropTarget.ItemsSource is Category)
                {
                    Category target = dropTarget.ItemsSource as Category;

                    if (target.Type == AppCategoryType.QuickLaunch)
                    {
                        e.Effects = DragDropEffects.Copy;

                        // Do not duplicate entries
                        if (!target.Contains(dropData))
                        {
                            ApplicationInfo dropClone = dropData.Clone();

                            if (e.OriginalSource != null && e.OriginalSource is FrameworkElement && (e.OriginalSource as FrameworkElement).DataContext != null && (e.OriginalSource as FrameworkElement).DataContext is ApplicationInfo)
                            {
                                target.Insert(target.IndexOf((e.OriginalSource as FrameworkElement).DataContext as ApplicationInfo), dropClone);
                            }
                            else
                            {
                                target.Add(dropClone);
                            }

                            dropClone.Icon = null; // icon may differ depending on category
                        }
                        else
                        {
                            // reorder existing
                            if (e.OriginalSource != null && e.OriginalSource is FrameworkElement && (e.OriginalSource as FrameworkElement).DataContext != null && (e.OriginalSource as FrameworkElement).DataContext is ApplicationInfo)
                            {
                                target.Move(target.IndexOf(dropData), target.IndexOf((e.OriginalSource as FrameworkElement).DataContext as ApplicationInfo));
                            }
                        }
                    }
                    else if (sourceView != null && sourceView != sender)
                    {
                        e.Effects = DragDropEffects.Move;

                        Category source = sourceView.ItemsSource as Category;

                        source.Remove(dropData);

                        if (source.Type != AppCategoryType.QuickLaunch)
                        {
                            target.Add(dropData); // if coming from quick launch, simply remove from quick launch

                            if (dropTarget.Items.Contains(dropData))
                            {
                                dropTarget.ScrollIntoView(dropTarget.Items[dropTarget.Items.IndexOf(dropData)]);
                            }
                        }
                    }
                }
                else
                {
                    e.Effects = DragDropEffects.Move;

                    (sourceView.ItemsSource as IList <ApplicationInfo>).Remove(dropData);
                    (dropTarget.ItemsSource as IList <ApplicationInfo>).Add(dropData);

                    if (dropTarget.Items.Contains(dropData))
                    {
                        dropTarget.ScrollIntoView(dropTarget.Items[dropTarget.Items.IndexOf(dropData)]);
                    }
                }
            }
            else if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
                if (fileNames != null)
                {
                    ListView dropTarget = sender as ListView;

                    if (!(dropTarget.ItemsSource is Category))
                    {
                        foreach (String fileName in fileNames)
                        {
                            ShellLogger.Debug(fileName);

                            if (ShellHelper.Exists(fileName))
                            {
                                ApplicationInfo customApp = AppGrabberService.PathToApp(fileName, false, false);
                                if (!object.ReferenceEquals(customApp, null))
                                {
                                    (dropTarget.ItemsSource as IList <ApplicationInfo>).Add(customApp);

                                    if (dropTarget.Items.Contains(customApp))
                                    {
                                        dropTarget.ScrollIntoView(dropTarget.Items[dropTarget.Items.IndexOf(customApp)]);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sourceView = null;
            isDragging = false;
        }
コード例 #26
0
        public int RunAndroidTest(ConnectedDevice device, bool reinstall, string packageName, string packageFile, string resultFile)
        {
            try
            {
                server = StartServer();
                ProcessOutputs adbOutputs;

                var adbPath = AndroidDeviceEnumerator.GetAdbPath();
                if (adbPath == null)
                {
                    throw new InvalidOperationException("Can't find adb");
                }

                var logStack = new List <string>();
                if (reinstall)
                {
                    // force stop - only works for Android 3.0 and above.
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} shell am force-stop {1}", device.Serial, packageName));

                    // uninstall
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} uninstall {1}", device.Serial, packageName));

                    // install
                    adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} install {1}", device.Serial, packageFile));
                    Console.WriteLine("adb install: exitcode {0}\nOutput: {1}\nErrors: {2}", adbOutputs.ExitCode, adbOutputs.OutputAsString, adbOutputs.ErrorsAsString);
                    if (adbOutputs.ExitCode != 0)
                    {
                        throw new InvalidOperationException("Invalid error code from adb install.\n Shell log: {0}");
                    }
                }

                // run
                var parameters = new StringBuilder();
                parameters.Append("-s "); parameters.Append(device.Serial);
                parameters.Append(@" shell am start -a android.intent.action.MAIN -n " + packageName + "/nunitlite.tests.MainActivity");
                AddAndroidParameter(parameters, TestRunner.XenkoServerIp, serverAddresses);
                AddAndroidParameter(parameters, TestRunner.XenkoServerPort, ((IPEndPoint)server.Server.LocalEndPoint).Port.ToString());
                AddAndroidParameter(parameters, TestRunner.XenkoBuildNumber, buildNumber.ToString());
                if (!String.IsNullOrEmpty(branchName))
                {
                    AddAndroidParameter(parameters, TestRunner.XenkoBranchName, branchName);
                }
                Console.WriteLine(parameters.ToString());

                adbOutputs = ShellHelper.RunProcessAndGetOutput(adbPath, parameters.ToString());
                Console.WriteLine("adb shell am start: exitcode {0}\nOutput: {1}\nErrors: {2}", adbOutputs.ExitCode, adbOutputs.OutputAsString, adbOutputs.ErrorsAsString);
                if (adbOutputs.ExitCode != 0)
                {
                    throw new InvalidOperationException("Invalid error code from adb shell am start.");
                }

                // Wait for client to connect
                const int WaitingTime = 30;
                for (int i = 0; i < WaitingTime; i++)
                {
                    if (server.Pending())
                    {
                        break;
                    }

                    Thread.Sleep(1000);
                }
                if (!server.Pending())
                {
                    throw new InvalidOperationException("The client (the remote test application) failed to establish the connection.");
                }

                var client = server.AcceptTcpClient();

                Console.WriteLine("Device connected, wait for results...");

                var clientStream = client.GetStream();
                var binaryReader = new BinaryReader(clientStream);

                // Read output
                var output = binaryReader.ReadString();
                Console.WriteLine(output);

                // Read XML result
                var result = binaryReader.ReadString();
                Console.WriteLine(result);

                // Write XML result to disk
                File.WriteAllText(resultFile, result);

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(@"An error was thrown when running the test on Android: {0}", e);
                return(-1);
            }
        }
コード例 #27
0
        public TorrentStartItem(TorrentProvider torrentProvider, Magnet magnet, Torrent torrent = null)
        {
            Progress         = float.PositiveInfinity;
            _torrentProvider = torrentProvider;
            Magnet           = magnet;
            var ml = new MagnetLink(magnet.ToString());

            // find or create torrent
            _manager = _torrentProvider.Torrents.FirstOrDefault(t => t.InfoHash == ml.InfoHash);
            if (_manager == null)
            {
                if (torrent != null)
                {
                    var cacheFolder = torrentProvider.Client.ReserveCacheSpace(magnet.Size);

                    if (cacheFolder == null)
                    {
                        MessageBox.Show("Недостаточно свободного места на диске.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        Closed = true;
                        return;
                    }

                    _manager = new TorrentManager(torrent, cacheFolder, _torrentProvider.TorrentDefaults);

                    foreach (var torrentFile in _manager.Torrent.Files)
                    {
                        torrentFile.Priority = Priority.DoNotDownload;
                    }
                }
                else
                {
                    _manager = new TorrentManager(ml, StorageHelper.GetBestSaveDirectory(), _torrentProvider.TorrentDefaults, _torrentProvider.TorrentsFolder);
                }

                _torrentProvider.RegisterTorrent(_manager);
                _manager.Start();
            }
            else
            {
                if (!string.IsNullOrEmpty(magnet.FileName))
                {
                    _file = _manager.Torrent.Files.FirstOrDefault(f => f.Path == magnet.FileName);

                    // check if the file is downloaded completely
                    if (_file != null && _file.BitField.TrueCount == _file.BitField.Length)
                    {
                        Closed = true;
                        ShellHelper.Start(_file.FullPath);
                        return;
                    }
                }

                if (_manager.State == TorrentState.Stopped)
                {
                    _manager.Start();
                }
            }

            var switcher = _manager.PieceManager.GetPicker <EndGameSwitcher>();

            switcher.Reset();

#if DEBUG
            if (_torrentProvider.FrmDebug != null)
            {
                _torrentProvider.FrmDebug.SegementsControl.Manager = _manager;
            }
#endif

            new ThreadStart(FormThread).BeginInvoke(null, null);
        }
コード例 #28
0
        private Brush GetCairoBackgroundBrush_Image(string wallpaper, CairoWallpaperStyle wallpaperStyle)
        {
            ImageBrush backgroundImageBrush = null;

            if (!string.IsNullOrWhiteSpace(wallpaper) && ShellHelper.Exists(wallpaper))
            {
                try
                {
                    Uri         backgroundImageUri    = new Uri(wallpaper, UriKind.Absolute);
                    BitmapImage backgroundBitmapImage = new BitmapImage(backgroundImageUri);
                    backgroundBitmapImage.Freeze();
                    backgroundImageBrush = new ImageBrush(backgroundBitmapImage);

                    switch (wallpaperStyle)
                    {
                    case CairoWallpaperStyle.Tile:
                        backgroundImageBrush.AlignmentX = AlignmentX.Left;
                        backgroundImageBrush.AlignmentY = AlignmentY.Top;
                        backgroundImageBrush.TileMode   = TileMode.Tile;
                        backgroundImageBrush.Stretch    =
                            Stretch
                            .Fill;         // stretch to fill viewport, which is pixel size of image, as WPF is DPI-aware
                        backgroundImageBrush.Viewport = new Rect(0, 0,
                                                                 (backgroundImageBrush.ImageSource as BitmapSource).PixelWidth,
                                                                 (backgroundImageBrush.ImageSource as BitmapSource).PixelHeight);
                        backgroundImageBrush.ViewportUnits = BrushMappingMode.Absolute;
                        break;

                    case CairoWallpaperStyle.Center:
                        // need to find a way to ignore image DPI for this case
                        backgroundImageBrush.AlignmentX = AlignmentX.Center;
                        backgroundImageBrush.AlignmentY = AlignmentY.Center;
                        backgroundImageBrush.TileMode   = TileMode.None;
                        backgroundImageBrush.Stretch    = Stretch.None;
                        break;

                    case CairoWallpaperStyle.Fit:
                        backgroundImageBrush.AlignmentX = AlignmentX.Center;
                        backgroundImageBrush.AlignmentY = AlignmentY.Center;
                        backgroundImageBrush.TileMode   = TileMode.None;
                        backgroundImageBrush.Stretch    = Stretch.Uniform;
                        break;

                    case CairoWallpaperStyle.Fill:
                    case CairoWallpaperStyle.Span:     // TODO: Impliment multiple monitor backgrounds
                        backgroundImageBrush.AlignmentX = AlignmentX.Center;
                        backgroundImageBrush.AlignmentY = AlignmentY.Center;
                        backgroundImageBrush.TileMode   = TileMode.None;
                        backgroundImageBrush.Stretch    = Stretch.UniformToFill;
                        break;

                    case CairoWallpaperStyle.Stretch:
                    default:
                        backgroundImageBrush.AlignmentX = AlignmentX.Center;
                        backgroundImageBrush.AlignmentY = AlignmentY.Center;
                        backgroundImageBrush.TileMode   = TileMode.None;
                        backgroundImageBrush.Stretch    = Stretch.Fill;
                        break;
                    }

                    backgroundImageBrush.Freeze();
                }
                catch
                {
                    backgroundImageBrush = null;
                }
            }
            return(backgroundImageBrush);
        }
コード例 #29
0
 private void OpenLocationSettingsButton_OnClick(object sender, RoutedEventArgs e)
 {
     ShellHelper.ExecuteProcess("ms-settings:privacy-location");
 }
コード例 #30
0
 public static ShellRequest ProcessCMD(string cmd, string workDir)
 {
     return(ShellHelper.ProcessCommand(cmd, workDir, _enviroumentVars));
 }
コード例 #31
0
 static void ExecuteCommand()
 {
     ShellHelper.ExecuteCommand("dotnet", "--info");
 }