コード例 #1
0
ファイル: UploadTask.cs プロジェクト: DaveCS1/ShareX
        private void DoAfterCaptureJobs()
        {
            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddImageEffects))
            {
                tempImage = TaskHelpers.AddImageEffects(tempImage, Info.TaskSettings);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddWatermark) && Info.TaskSettings.ImageSettings.WatermarkConfig != null)
            {
                Info.TaskSettings.ImageSettings.WatermarkConfig.Apply(tempImage);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AnnotateImage))
            {
                tempImage = TaskHelpers.AnnotateImage(tempImage, Info.FileName);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyImageToClipboard))
            {
                ClipboardHelpers.CopyImage(tempImage);
                DebugHelper.WriteLine("CopyImageToClipboard");
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SendImageToPrinter))
            {
                if (Program.Settings.DontShowPrintSettingsDialog)
                {
                    using (PrintHelper printHelper = new PrintHelper(tempImage))
                    {
                        printHelper.Settings = Program.Settings.PrintSettings;
                        printHelper.Print();
                    }
                }
                else
                {
                    using (PrintForm printForm = new PrintForm(tempImage, Program.Settings.PrintSettings))
                    {
                        printForm.ShowDialog();
                    }
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlagAny(AfterCaptureTasks.SaveImageToFile, AfterCaptureTasks.SaveImageToFileWithDialog, AfterCaptureTasks.UploadImageToHost))
            {
                using (tempImage)
                {
                    ImageData imageData = TaskHelpers.PrepareImage(tempImage, Info.TaskSettings);
                    Data          = imageData.ImageStream;
                    Info.FileName = Path.ChangeExtension(Info.FileName, imageData.ImageFormat.GetDescription());

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFile))
                    {
                        string filePath = TaskHelpers.CheckFilePath(Info.TaskSettings.CaptureFolder, Info.FileName, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(filePath))
                        {
                            Info.FilePath = filePath;
                            imageData.Write(Info.FilePath);
                            DebugHelper.WriteLine("SaveImageToFile: " + Info.FilePath);
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFileWithDialog))
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            if (string.IsNullOrEmpty(lastSaveAsFolder) || !Directory.Exists(lastSaveAsFolder))
                            {
                                lastSaveAsFolder = Info.TaskSettings.CaptureFolder;
                            }

                            sfd.InitialDirectory = lastSaveAsFolder;
                            sfd.FileName         = Info.FileName;
                            sfd.DefaultExt       = Path.GetExtension(Info.FileName).Substring(1);
                            sfd.Filter           = string.Format("*{0}|*{0}|All files (*.*)|*.*", Path.GetExtension(Info.FileName));
                            sfd.Title            = "Choose a folder to save " + Path.GetFileName(Info.FileName);

                            if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                            {
                                Info.FilePath    = sfd.FileName;
                                lastSaveAsFolder = Path.GetDirectoryName(Info.FilePath);
                                imageData.Write(Info.FilePath);
                                DebugHelper.WriteLine("SaveImageToFileWithDialog: " + Info.FilePath);
                            }
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveThumbnailImageToFile))
                    {
                        string thumbnailFilename, thumbnailFolder;

                        if (!string.IsNullOrEmpty(Info.FilePath))
                        {
                            thumbnailFilename = Path.GetFileName(Info.FilePath);
                            thumbnailFolder   = Path.GetDirectoryName(Info.FilePath);
                        }
                        else
                        {
                            thumbnailFilename = Info.FileName;
                            thumbnailFolder   = Info.TaskSettings.CaptureFolder;
                        }

                        Info.ThumbnailFilePath = TaskHelpers.CreateThumbnail(tempImage, thumbnailFolder, thumbnailFilename, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(Info.ThumbnailFilePath))
                        {
                            DebugHelper.WriteLine("SaveThumbnailImageToFile: " + Info.ThumbnailFilePath);
                        }
                    }
                }
            }
        }
コード例 #2
0
        public void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, bool skipRegionSelection = false)
        {
            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!File.Exists(taskSettings.CaptureSettings.FFmpegOptions.CLIPath))
                {
                    string ffmpegText = string.IsNullOrEmpty(taskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : taskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                    if (MessageBox.Show(string.Format(Resources.ScreenRecordForm_StartRecording_does_not_exist, ffmpegText),
                                        "ShareX - " + Resources.ScreenRecordForm_StartRecording_Missing + " ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        if (FFmpegDownloader.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                        {
                            Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = taskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                                taskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                        }
                    }
                    else
                    {
                        return;
                    }
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle;

            if (skipRegionSelection)
            {
                captureRectangle = Program.Settings.ScreenRecordRegion;
            }
            else
            {
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;
            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ShowCursor;

            string trayText = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Waiting___;

            TrayIcon.Text    = trayText.Truncate(63);
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, duration);
            regionForm.RecordResetEvent = new ManualResetEvent(false);

            TaskEx.Run(() =>
            {
                try
                {
                    if (taskSettings.CaptureSettings.ScreenRecordAutoDisableAero)
                    {
                        dwmManager = new DWMManager();
                        dwmManager.AutoDisable();
                    }

                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(outputType, options, captureRectangle);

                    if (regionForm != null && regionForm.RecordResetEvent != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_start_recording_;
                        TrayIcon.Text = trayText.Truncate(63);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                regionForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            regionForm.RecordResetEvent.WaitOne();
                        }

                        if (regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }

                    if (!abortRequested)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_stop_recording_;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.control_record.ToIcon();

                        if (regionForm != null)
                        {
                            this.InvokeSafe(() => regionForm.StartTimer());
                        }

                        screenRecorder.StartRecording();

                        if (regionForm != null && regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }
                finally
                {
                    if (dwmManager != null)
                    {
                        dwmManager.Dispose();
                        dwmManager = null;
                    }

                    if (regionForm != null)
                    {
                        if (regionForm.RecordResetEvent != null)
                        {
                            regionForm.RecordResetEvent.Dispose();
                        }

                        this.InvokeSafe(() => regionForm.Close());
                        regionForm = null;
                    }
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Encoding___;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        string sourceFilePath = path;

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            if (taskSettings.CaptureSettings.RunScreencastCLI)
                            {
                                sourceFilePath = Path.ChangeExtension(Program.ScreenRecorderCacheFilePath, "gif");
                            }
                            else
                            {
                                sourceFilePath = path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            }

                            Helpers.CreateDirectoryIfNotExist(sourceFilePath);
                            screenRecorder.SaveAsGIF(sourceFilePath, taskSettings.ImageSettings.ImageGIFQuality);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if (taskSettings.CaptureSettings.RunScreencastCLI && !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
コード例 #3
0
ファイル: WorkerTask.cs プロジェクト: rymorg/ShareX
        private bool DoAfterCaptureJobs()
        {
            if (Image == null)
            {
                return(true);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddImageEffects))
            {
                Image = TaskHelpers.AddImageEffects(Image, Info.TaskSettings.ImageSettingsReference);

                if (Image == null)
                {
                    DebugHelper.WriteLine("Error: Applying image effects resulted empty image.");
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AnnotateImage))
            {
                Image = TaskHelpers.AnnotateImage(Image, null, Info.TaskSettings, true);

                if (Image == null)
                {
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyImageToClipboard))
            {
                ClipboardHelpers.CopyImage(Image);
                DebugHelper.WriteLine("Image copied to clipboard.");
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SendImageToPrinter))
            {
                TaskHelpers.PrintImage(Image);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlagAny(AfterCaptureTasks.SaveImageToFile, AfterCaptureTasks.SaveImageToFileWithDialog, AfterCaptureTasks.UploadImageToHost))
            {
                ImageData imageData = TaskHelpers.PrepareImage(Image, Info.TaskSettings);
                Data          = imageData.ImageStream;
                Info.FileName = Path.ChangeExtension(Info.FileName, imageData.ImageFormat.GetDescription());

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFile))
                {
                    string filePath = TaskHelpers.HandleExistsFile(Info.TaskSettings.CaptureFolder, Info.FileName, Info.TaskSettings);

                    if (!string.IsNullOrEmpty(filePath))
                    {
                        Info.FilePath = filePath;
                        imageData.Write(Info.FilePath);
                        DebugHelper.WriteLine("Image saved to file: " + Info.FilePath);
                    }
                }

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFileWithDialog))
                {
                    using (SaveFileDialog sfd = new SaveFileDialog())
                    {
                        string initialDirectory = null;

                        if (!string.IsNullOrEmpty(HelpersOptions.LastSaveDirectory) && Directory.Exists(HelpersOptions.LastSaveDirectory))
                        {
                            initialDirectory = HelpersOptions.LastSaveDirectory;
                        }
                        else
                        {
                            initialDirectory = Info.TaskSettings.CaptureFolder;
                        }

                        bool imageSaved;

                        do
                        {
                            sfd.InitialDirectory = initialDirectory;
                            sfd.FileName         = Info.FileName;
                            sfd.DefaultExt       = Path.GetExtension(Info.FileName).Substring(1);
                            sfd.Filter           = string.Format("*{0}|*{0}|All files (*.*)|*.*", Path.GetExtension(Info.FileName));
                            sfd.Title            = Resources.UploadTask_DoAfterCaptureJobs_Choose_a_folder_to_save + " " + Path.GetFileName(Info.FileName);

                            if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                            {
                                Info.FilePath = sfd.FileName;
                                HelpersOptions.LastSaveDirectory = Path.GetDirectoryName(Info.FilePath);
                                imageSaved = imageData.Write(Info.FilePath);

                                if (imageSaved)
                                {
                                    DebugHelper.WriteLine("Image saved to file with dialog: " + Info.FilePath);
                                }
                            }
                            else
                            {
                                break;
                            }
                        } while (!imageSaved);
                    }
                }

                if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveThumbnailImageToFile))
                {
                    string thumbnailFilename, thumbnailFolder;

                    if (!string.IsNullOrEmpty(Info.FilePath))
                    {
                        thumbnailFilename = Path.GetFileName(Info.FilePath);
                        thumbnailFolder   = Path.GetDirectoryName(Info.FilePath);
                    }
                    else
                    {
                        thumbnailFilename = Info.FileName;
                        thumbnailFolder   = Info.TaskSettings.CaptureFolder;
                    }

                    Info.ThumbnailFilePath = TaskHelpers.CreateThumbnail(Image, thumbnailFolder, thumbnailFilename, Info.TaskSettings);

                    if (!string.IsNullOrEmpty(Info.ThumbnailFilePath))
                    {
                        DebugHelper.WriteLine("Thumbnail saved to file: " + Info.ThumbnailFilePath);
                    }
                }
            }

            return(true);
        }
コード例 #4
0
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            if (outputType == ScreenRecordOutput.GIF)
            {
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec = FFmpegVideoCodec.gif;
            }

            if (taskSettings.CaptureSettings.FFmpegOptions.IsAnimatedImage)
            {
                taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding = true;
            }

            int fps;

            if (taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
            {
                fps = taskSettings.CaptureSettings.GIFFPS;
            }
            else
            {
                fps = taskSettings.CaptureSettings.ScreenRecordFPS;
            }

            DebugHelper.WriteLine("Starting screen recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                  taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(), fps);

            if (!TaskHelpers.CheckFFmpeg(taskSettings))
            {
                return;
            }

            if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
            {
                MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                if (taskSettings.CaptureSettings.ScreenRecordTransparentRegion)
                {
                    RegionCaptureTasks.GetRectangleRegionTransparent(out captureRectangle);
                }
                else
                {
                    RegionCaptureTasks.GetRectangleRegion(out captureRectangle, taskSettings.CaptureSettings.SurfaceOptions);
                }
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.CustomRegion:
                captureRectangle = taskSettings.CaptureSettings.CaptureCustomRegion;
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            Rectangle screenRectangle = CaptureHelpers.GetScreenBounds();

            captureRectangle = Rectangle.Intersect(captureRectangle, screenRectangle);

            if (taskSettings.CaptureSettings.FFmpegOptions.IsEvenSizeRequired)
            {
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, taskSettings, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            Task.Run(() =>
            {
                try
                {
                    string extension;
                    if (taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding)
                    {
                        extension = "mp4";
                    }
                    else
                    {
                        extension = taskSettings.CaptureSettings.FFmpegOptions.Extension;
                    }
                    string filename = TaskHelpers.GetFilename(taskSettings, extension);
                    path            = TaskHelpers.HandleExistsFile(taskSettings.CaptureFolder, filename, taskSettings);

                    if (string.IsNullOrEmpty(path))
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        recordForm.ChangeState(ScreenRecordState.BeforeStart);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                                recordForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            recordForm.RecordResetEvent.WaitOne();
                        }

                        if (recordForm.IsAbortRequested)
                        {
                            abortRequested = true;
                        }

                        if (!abortRequested)
                        {
                            ScreencastOptions options = new ScreencastOptions()
                            {
                                IsRecording = true,
                                IsLossless  = taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding,
                                FFmpeg      = taskSettings.CaptureSettings.FFmpegOptions,
                                FPS         = fps,
                                Duration    = duration,
                                OutputPath  = path,
                                CaptureArea = captureRectangle,
                                DrawCursor  = taskSettings.CaptureSettings.ScreenRecordShowCursor
                            };

                            Screenshot screenshot    = TaskHelpers.GetScreenshot(taskSettings);
                            screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

                            screenRecorder = new ScreenRecorder(ScreenRecordOutput.FFmpeg, options, screenshot, captureRectangle);
                            screenRecorder.RecordingStarted        += ScreenRecorder_RecordingStarted;
                            screenRecorder.EncodingProgressChanged += ScreenRecorder_EncodingProgressChanged;
                            recordForm.ChangeState(ScreenRecordState.AfterStart);
                            screenRecorder.StartRecording();

                            if (recordForm.IsAbortRequested)
                            {
                                abortRequested = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                if (taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding && !abortRequested && screenRecorder != null && File.Exists(path))
                {
                    recordForm.ChangeState(ScreenRecordState.Encoding);

                    path = ProcessTwoPassEncoding(path, taskSettings);
                }

                if (recordForm != null)
                {
                    recordForm.InvokeSafe(() =>
                    {
                        recordForm.Close();
                        recordForm.Dispose();
                        recordForm = null;
                    });
                }

                if (screenRecorder != null)
                {
                    screenRecorder.Dispose();
                    screenRecorder = null;

                    if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            }).ContinueInCurrentContext(() =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName, null, path))
                {
                    if (!string.IsNullOrEmpty(customFileName))
                    {
                        string currentFilename = Path.GetFileNameWithoutExtension(path);
                        string ext             = Path.GetExtension(path);

                        if (!currentFilename.Equals(customFileName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            path = Helpers.RenameFile(path, customFileName + ext);
                        }
                    }

                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
コード例 #5
0
ファイル: TaskManager.cs プロジェクト: sp1r00000/ShareX
        private static void task_UploadCompleted(UploadTask task)
        {
            try
            {
                if (ListViewControl != null && task != null)
                {
                    if (task.RequestSettingUpdate)
                    {
                        Program.MainForm.UpdateMainFormSettings();
                    }

                    TaskInfo info = task.Info;

                    if (info != null && info.Result != null)
                    {
                        ListViewItem lvi = FindListViewItem(task);

                        if (info.Result.IsError)
                        {
                            string errors = string.Join("\r\n\r\n", info.Result.Errors.ToArray());

                            DebugHelper.WriteLine("Task failed. Filename: {0}, Errors:\r\n{1}", info.FileName, errors);

                            if (lvi != null)
                            {
                                lvi.SubItems[1].Text = Resources.TaskManager_task_UploadCompleted_Error;
                                lvi.SubItems[6].Text = string.Empty;
                                lvi.ImageIndex       = 1;
                            }

                            if (!info.TaskSettings.AdvancedSettings.DisableNotifications)
                            {
                                if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                {
                                    TaskHelpers.PlayErrorSound(info.TaskSettings);
                                }

                                if (info.TaskSettings.GeneralSettings.PopUpNotification != PopUpNotificationType.None && Program.MainForm.niTray.Visible && !string.IsNullOrEmpty(errors))
                                {
                                    Program.MainForm.niTray.Tag = null;
                                    Program.MainForm.niTray.ShowBalloonTip(5000, "ShareX - " + Resources.TaskManager_task_UploadCompleted_Error, errors, ToolTipIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            DebugHelper.WriteLine("Task completed. Filename: {0}, URL: {1}, Duration: {2} ms", info.FileName, info.Result.ToString(), (int)info.UploadDuration.TotalMilliseconds);

                            string result = info.Result.ToString();

                            if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(info.FilePath))
                            {
                                result = info.FilePath;
                            }

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;

                                if (!string.IsNullOrEmpty(result))
                                {
                                    lvi.SubItems[6].Text = result;
                                }
                            }

                            if (!task.StopRequested && !string.IsNullOrEmpty(result))
                            {
                                if (info.TaskSettings.GeneralSettings.SaveHistory && (!info.TaskSettings.AdvancedSettings.HistorySaveOnlyURL ||
                                                                                      (!string.IsNullOrEmpty(info.Result.URL) || !string.IsNullOrEmpty(info.Result.ShortenedURL))))
                                {
                                    HistoryManager.AddHistoryItemAsync(Program.HistoryFilePath, info.GetHistoryItem());
                                }

                                RecentManager.Add(result);

                                if (Program.Settings.RecentLinksRemember)
                                {
                                    Program.Settings.RecentLinks = RecentManager.Items.ToArray();
                                }
                                else
                                {
                                    Program.Settings.RecentLinks = null;
                                }

                                if (!info.TaskSettings.AdvancedSettings.DisableNotifications && info.Job != TaskJob.ShareURL)
                                {
                                    if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                    {
                                        TaskHelpers.PlayTaskCompleteSound(info.TaskSettings);
                                    }

                                    if (!string.IsNullOrEmpty(info.TaskSettings.AdvancedSettings.BalloonTipContentFormat))
                                    {
                                        result = new UploadInfoParser().Parse(info, info.TaskSettings.AdvancedSettings.BalloonTipContentFormat);
                                    }

                                    if (!string.IsNullOrEmpty(result))
                                    {
                                        switch (info.TaskSettings.GeneralSettings.PopUpNotification)
                                        {
                                        case PopUpNotificationType.BalloonTip:
                                            if (Program.MainForm.niTray.Visible)
                                            {
                                                Program.MainForm.niTray.Tag = result;
                                                Program.MainForm.niTray.ShowBalloonTip(5000, "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed,
                                                                                       result, ToolTipIcon.Info);
                                            }
                                            break;

                                        case PopUpNotificationType.ToastNotification:
                                            NotificationFormConfig toastConfig = new NotificationFormConfig()
                                            {
                                                Action   = info.TaskSettings.AdvancedSettings.ToastWindowClickAction,
                                                FilePath = info.FilePath,
                                                Text     = "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed + "\r\n" + result,
                                                URL      = result
                                            };
                                            NotificationForm.Show((int)(info.TaskSettings.AdvancedSettings.ToastWindowDuration * 1000),
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowPlacement,
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowSize, toastConfig);
                                            break;
                                        }
                                    }

                                    if (info.TaskSettings.GeneralSettings.ShowAfterUploadForm)
                                    {
                                        AfterUploadForm dlg = new AfterUploadForm(info);
                                        NativeMethods.ShowWindow(dlg.Handle, (int)WindowShowStyle.ShowNoActivate);
                                    }
                                }
                            }
                        }

                        if (lvi != null)
                        {
                            lvi.EnsureVisible();
                        }
                    }
                }
            }
            finally
            {
                if (!IsBusy && Program.CLI.IsCommandExist("AutoClose"))
                {
                    Application.Exit();
                }
                else
                {
                    StartTasks();
                    UpdateProgressUI();
                }
            }
        }
コード例 #6
0
        public async void StartRecording(TaskSettings TaskSettings)
        {
            SelectRegion();
            Screenshot.CaptureCursor = TaskSettings.CaptureSettings.ShowCursor;

            if (IsRecording || CaptureRectangle.IsEmpty || screenRecorder != null)
            {
                return;
            }

            IsRecording = true;

            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            try
            {
                using (ScreenRegionManager screenRegionManager = new ScreenRegionManager())
                {
                    screenRegionManager.Start(CaptureRectangle);

                    await TaskEx.Run(() =>
                    {
                        if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                        {
                            path = Path.Combine(Program.ScreenshotsPath, TaskHelpers.GetFilename(TaskSettings, "avi"));
                        }
                        else
                        {
                            path = Program.ScreenRecorderCacheFilePath;
                        }

                        float duration = TaskSettings.CaptureSettings.ScreenRecordFixedDuration ? TaskSettings.CaptureSettings.ScreenRecordDuration : 0;

                        screenRecorder = new ScreenRecorder(TaskSettings.CaptureSettings.ScreenRecordFPS, duration, CaptureRectangle, path,
                                                            TaskSettings.CaptureSettings.ScreenRecordOutput);

                        int delay = (int)(TaskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                        if (delay > 0)
                        {
                            Thread.Sleep(delay);
                        }

                        screenRegionManager.ChangeColor();

                        this.InvokeSafe(() => TrayIcon.Icon = Resources.control_record.ToIcon());

                        screenRecorder.StartRecording();
                    });
                }

                if (screenRecorder != null && TaskSettings.CaptureSettings.ScreenRecordOutput != ScreenRecordOutput.AVI)
                {
                    TrayIcon.Icon = Resources.camcorder__pencil.ToIcon();

                    await TaskEx.Run(() =>
                    {
                        switch (TaskSettings.CaptureSettings.ScreenRecordOutput)
                        {
                        case ScreenRecordOutput.GIF:
                            path = Path.Combine(Program.ScreenshotsPath, TaskHelpers.GetFilename(TaskSettings, "gif"));
                            screenRecorder.SaveAsGIF(path, TaskSettings.ImageSettings.ImageGIFQuality);
                            break;

                        case ScreenRecordOutput.AVICommandLine:
                            path = Path.Combine(Program.ScreenshotsPath, TaskHelpers.GetFilename(TaskSettings,
                                                                                                 TaskSettings.CaptureSettings.ScreenRecordCommandLineOutputExtension));
                            screenRecorder.EncodeUsingCommandLine(path, TaskSettings.CaptureSettings.ScreenRecordCommandLinePath,
                                                                  TaskSettings.CaptureSettings.ScreenRecordCommandLineArgs);
                            break;
                        }
                    });
                }
            }
            finally
            {
                if (screenRecorder != null)
                {
                    if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVICommandLine &&
                        !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                    {
                        File.Delete(screenRecorder.CachePath);
                    }

                    screenRecorder.Dispose();
                    screenRecorder = null;
                }

                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }
            }

            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.UploadImageToHost))
                {
                    UploadManager.UploadFile(path, TaskSettings);
                }
                else
                {
                    if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFilePathToClipboard))
                    {
                        ClipboardHelpers.CopyText(path);
                    }

                    TaskHelpers.ShowResultNotifications(path, TaskSettings);
                }
            }

            IsRecording = false;
        }
コード例 #7
0
        private static void task_UploadCompleted(UploadTask task)
        {
            try
            {
                if (ListViewControl != null && task != null)
                {
                    if (task.RequestSettingUpdate)
                    {
                        Program.MainForm.UpdateMainFormSettings();
                    }

                    TaskInfo info = task.Info;

                    if (info != null && info.Result != null)
                    {
                        ListViewItem lvi = FindListViewItem(task);

                        if (info.Result.IsError)
                        {
                            string errors = string.Join("\r\n\r\n", info.Result.Errors.ToArray());

                            DebugHelper.WriteLine("Task failed. Filename: {0}, Errors:\r\n{1}", info.FileName, errors);

                            if (lvi != null)
                            {
                                lvi.SubItems[1].Text = "Error";
                                lvi.SubItems[6].Text = string.Empty;
                                lvi.ImageIndex       = 1;
                            }

                            if (task.Info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                            {
                                SystemSounds.Asterisk.Play();
                            }
                        }
                        else
                        {
                            DebugHelper.WriteLine("Task completed. Filename: {0}, URL: {1}, Duration: {2} ms", info.FileName, info.Result.ToString(), (int)info.UploadDuration.TotalMilliseconds);

                            string result = info.Result.ToString();

                            if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(info.FilePath))
                            {
                                result = info.FilePath;
                            }

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;

                                if (!string.IsNullOrEmpty(result))
                                {
                                    lvi.SubItems[6].Text = result;
                                }
                            }

                            if (!task.StopRequested && !string.IsNullOrEmpty(result))
                            {
                                if (task.Info.TaskSettings.GeneralSettings.SaveHistory)
                                {
                                    HistoryManager.AddHistoryItemAsync(Program.HistoryFilePath, info.GetHistoryItem());
                                }

                                if (!info.TaskSettings.AdvancedSettings.DisableNotifications && info.Job != TaskJob.ShareURL)
                                {
                                    if (task.Info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                    {
                                        SystemSounds.Exclamation.Play();
                                    }

                                    if (!string.IsNullOrEmpty(info.TaskSettings.AdvancedSettings.BalloonTipContentFormat))
                                    {
                                        result = new UploadInfoParser().Parse(info, info.TaskSettings.AdvancedSettings.BalloonTipContentFormat);
                                    }

                                    TaskHelpers.ShowResultNotifications(result, info.TaskSettings, info.FilePath);

                                    if (info.TaskSettings.GeneralSettings.ShowAfterUploadForm)
                                    {
                                        AfterUploadForm dlg = new AfterUploadForm(info);
                                        NativeMethods.ShowWindow(dlg.Handle, (int)WindowShowStyle.ShowNoActivate);
                                    }
                                }
                            }
                        }

                        if (lvi != null)
                        {
                            lvi.EnsureVisible();
                        }
                    }
                }
            }
            finally
            {
                StartTasks();
                UpdateProgressUI();
            }
        }
コード例 #8
0
ファイル: UploadInfoManager.cs プロジェクト: wathiq-iq/ShareX
 public void OCRImage()
 {
     if (IsItemSelected && SelectedItem.IsImageFile) TaskHelpers.OCRImage(SelectedItem.Info.FilePath);
 }
コード例 #9
0
        protected ImageInfo ExecuteRegionCapture(TaskSettings taskSettings)
        {
            ImageInfo imageInfo = new ImageInfo();

            RegionCaptureMode mode;

            if (taskSettings.AdvancedSettings.RegionCaptureDisableAnnotation)
            {
                mode = RegionCaptureMode.Default;
            }
            else
            {
                mode = RegionCaptureMode.Annotation;
            }

            RegionCaptureForm form = new RegionCaptureForm(mode);

            try
            {
                form.Config = taskSettings.CaptureSettingsReference.SurfaceOptions;
                Screenshot screenshot = TaskHelpers.GetScreenshot(taskSettings);
                screenshot.CaptureCursor = false;
                Image img = screenshot.CaptureFullscreen();

                CursorData cursorData = null;

                try
                {
                    if (taskSettings.CaptureSettings.ShowCursor)
                    {
                        cursorData = new CursorData();
                    }

                    form.Prepare(img);

                    if (cursorData != null)
                    {
                        form.AddCursor(cursorData.Handle, cursorData.Position);
                    }
                }
                finally
                {
                    if (cursorData != null)
                    {
                        cursorData.Dispose();
                    }
                }

                form.ShowDialog();

                imageInfo.Image = form.GetResultImage();

                if (imageInfo.Image != null)
                {
                    if (form.IsAnnotated)
                    {
                        AllowAnnotation = false;
                    }

                    if (form.Result == RegionResult.Region && taskSettings.UploadSettings.RegionCaptureUseWindowPattern)
                    {
                        WindowInfo windowInfo = form.GetWindowInfo();
                        imageInfo.UpdateInfo(windowInfo);
                    }

                    lastRegionCaptureType = RegionCaptureType.Default;
                }
            }
            finally
            {
                if (form != null)
                {
                    form.Dispose();
                }
            }

            return(imageInfo);
        }
コード例 #10
0
ファイル: UploadInfoManager.cs プロジェクト: wathiq-iq/ShareX
 public void EditImage()
 {
     if (IsItemSelected && SelectedItem.IsImageFile) TaskHelpers.AnnotateImage(SelectedItem.Info.FilePath);
 }
コード例 #11
0
ファイル: UploadInfoManager.cs プロジェクト: wathiq-iq/ShareX
 public void SearchImage()
 {
     if (IsItemSelected && SelectedItem.IsURLExist) TaskHelpers.SearchImage(SelectedItem.Info.Result.URL);
 }
コード例 #12
0
        public void StartRecording(TaskSettings TaskSettings)
        {
            if (TaskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(TaskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show("There is no valid CLI video encoder selected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else if (!Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show("CLI video encoder file does not exist: " + Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg && !File.Exists(TaskSettings.CaptureSettings.FFmpegOptions.CLIPath))
            {
                string ffmpegText = string.IsNullOrEmpty(TaskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : TaskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                if (MessageBox.Show(ffmpegText + " does not exist." + Environment.NewLine + Environment.NewLine + "Would you like to automatically download it?",
                                    Application.ProductName + " - Missing ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (FFmpegHelper.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                    {
                        Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = TaskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                            TaskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                    }
                }
                else
                {
                    return;
                }
            }

            if (TaskSettings.AdvancedSettings.ScreenRecorderUseActiveWindow)
            {
                ActiveWindowRegion(TaskSettings);
            }
            else
            {
                SelectRegion();
            }

            if (IsRecording || captureRectangle.IsEmpty || screenRecorder != null)
            {
                return;
            }

            IsRecording = true;
            Screenshot.CaptureCursor = TaskSettings.CaptureSettings.ShowCursor;

            TrayIcon.Text    = "ShareX - Waiting...";
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = TaskSettings.CaptureSettings.ScreenRecordFixedDuration ? TaskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, duration);

            TaskEx.Run(() =>
            {
                try
                {
                    if (TaskSettings.CaptureSettings.ScreenRecordAutoDisableAero)
                    {
                        dwmManager = new DWMManager();
                        dwmManager.AutoDisable();
                    }

                    if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                    {
                        path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "avi"));
                    }
                    else if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, TaskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = TaskSettings.CaptureSettings.FFmpegOptions,
                        AVI             = TaskSettings.CaptureSettings.AVIOptions,
                        ScreenRecordFPS = TaskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = TaskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = TaskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(options, captureRectangle, TaskSettings.CaptureSettings.ScreenRecordOutput);

                    int delay = (int)(TaskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                    if (delay > 0)
                    {
                        Thread.Sleep(delay);
                    }

                    TrayIcon.Text = "ShareX - Click tray icon to stop recording.";
                    TrayIcon.Icon = Resources.control_record.ToIcon();

                    if (regionForm != null)
                    {
                        this.InvokeSafe(() => regionForm.StartTimer());
                    }

                    screenRecorder.StartRecording();
                }
                finally
                {
                    if (dwmManager != null)
                    {
                        dwmManager.Dispose();
                        dwmManager = null;
                    }

                    if (regionForm != null)
                    {
                        this.InvokeSafe(() => regionForm.Close());
                    }
                }

                try
                {
                    if (screenRecorder != null)
                    {
                        TrayIcon.Text = "ShareX - Encoding...";
                        TrayIcon.Icon = Resources.camcorder__pencil.ToIcon();

                        string sourceFilePath = path;

                        if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.GIF)
                        {
                            if (TaskSettings.CaptureSettings.RunScreencastCLI)
                            {
                                sourceFilePath = Path.ChangeExtension(Program.ScreenRecorderCacheFilePath, "gif");
                            }
                            else
                            {
                                sourceFilePath = path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "gif"));
                            }

                            screenRecorder.SaveAsGIF(sourceFilePath, TaskSettings.ImageSettings.ImageGIFQuality);
                        }

                        if (TaskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if (TaskSettings.CaptureSettings.RunScreencastCLI && !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                IsRecording = false;

                if (!string.IsNullOrEmpty(path) && File.Exists(path))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, TaskSettings);
                    TaskManager.Start(task);
                }
            });
        }
コード例 #13
0
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
            {
                outputType = ScreenRecordOutput.GIF;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                DebugHelper.WriteLine("Starting screen recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                      taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                      taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                DebugHelper.WriteLine("Starting screen recording. FPS: {0}", taskSettings.CaptureSettings.GIFFPS);
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec = FFmpegVideoCodec.gif;
            }

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (!TaskHelpers.CheckFFmpeg(taskSettings))
            {
                return;
            }

            if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
            {
                MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                RegionCaptureTasks.GetRectangleRegion(out captureRectangle, taskSettings.CaptureSettings.SurfaceOptions);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.CustomRegion:
                captureRectangle = taskSettings.CaptureSettings.CaptureCustomRegion;
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            Rectangle screenRectangle = CaptureHelpers.GetScreenBounds();

            captureRectangle = Rectangle.Intersect(captureRectangle, screenRectangle);

            if (outputType != ScreenRecordOutput.GIF)
            {
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, taskSettings, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            Task.Run(() =>
            {
                try
                {
                    string filename = TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension);
                    path            = TaskHelpers.HandleExistsFile(taskSettings.CaptureFolder, filename, taskSettings);

                    if (string.IsNullOrEmpty(path))
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        recordForm.ChangeState(ScreenRecordState.BeforeStart);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                                recordForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            recordForm.RecordResetEvent.WaitOne();
                        }

                        if (recordForm.IsAbortRequested)
                        {
                            abortRequested = true;
                        }

                        if (!abortRequested)
                        {
                            ScreencastOptions options = new ScreencastOptions()
                            {
                                IsRecording = true,
                                IsLossless  = outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding,
                                FFmpeg      = taskSettings.CaptureSettings.FFmpegOptions,
                                FPS         = outputType == ScreenRecordOutput.GIF ? taskSettings.CaptureSettings.GIFFPS : taskSettings.CaptureSettings.ScreenRecordFPS,
                                Duration    = duration,
                                OutputPath  = path,
                                CaptureArea = captureRectangle,
                                DrawCursor  = taskSettings.CaptureSettings.ScreenRecordShowCursor
                            };

                            Screenshot screenshot    = TaskHelpers.GetScreenshot(taskSettings);
                            screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

                            screenRecorder = new ScreenRecorder(ScreenRecordOutput.FFmpeg, options, screenshot, captureRectangle);
                            screenRecorder.RecordingStarted += () => recordForm.ChangeState(ScreenRecordState.AfterRecordingStart);
                            recordForm.ChangeState(ScreenRecordState.AfterStart);
                            screenRecorder.StartRecording();

                            if (recordForm.IsAbortRequested)
                            {
                                abortRequested = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                try
                {
                    if (!abortRequested && screenRecorder != null && File.Exists(path))
                    {
                        recordForm.ChangeState(ScreenRecordState.AfterStop);

                        string input = path;

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(input, path, Program.ToolsFolder);
                        }
                        else if (taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                            screenRecorder.FFmpegEncodeVideo(input, path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI && !taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, input, path);
                        }
                    }
                }
                finally
                {
                    if (recordForm != null)
                    {
                        recordForm.InvokeSafe(() =>
                        {
                            recordForm.Close();
                            recordForm.Dispose();
                            recordForm = null;
                        });
                    }

                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI || taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            }).ContinueInCurrentContext(() =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName, null, path))
                {
                    if (!string.IsNullOrEmpty(customFileName))
                    {
                        string currentFilename = Path.GetFileNameWithoutExtension(path);
                        string ext             = Path.GetExtension(path);

                        if (!currentFilename.Equals(customFileName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            path = Helpers.RenameFile(path, customFileName + ext);
                        }
                    }

                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
コード例 #14
0
        public static void CaptureRectangleLight(TaskSettings taskSettings = null, bool autoHideForm = true)
        {
            if (taskSettings == null)
            {
                taskSettings = TaskSettings.GetDefaultTaskSettings();
            }

            DoCapture(() =>
            {
                Image img = null;

                using (RegionCaptureLightForm rectangleLight = new RegionCaptureLightForm(TaskHelpers.GetScreenshot(taskSettings)))
                {
                    if (rectangleLight.ShowDialog() == DialogResult.OK)
                    {
                        img = rectangleLight.GetAreaImage();

                        if (img != null)
                        {
                            lastRegionCaptureType = LastRegionCaptureType.Light;
                        }
                    }
                }

                return(img);
            }, CaptureType.Region, taskSettings, autoHideForm);
        }
コード例 #15
0
        private static void Task_TaskCompleted(WorkerTask task)
        {
            try
            {
                if (task != null)
                {
                    task.KeepImage = false;

                    if (task.RequestSettingUpdate)
                    {
                        Program.MainForm.UpdateCheckStates();
                    }

                    TaskInfo info = task.Info;

                    if (info != null && info.Result != null)
                    {
                        TaskThumbnailPanel panel = TaskThumbnailView.FindPanel(task);

                        if (panel != null)
                        {
                            panel.UpdateStatus();
                            panel.ProgressVisible = false;
                        }

                        ListViewItem lvi = TaskListView.FindItem(task);

                        if (task.Status == TaskStatus.Stopped)
                        {
                            DebugHelper.WriteLine($"Task stopped. Filename: {info.FileName}");

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;
                            }
                        }
                        else if (task.Status == TaskStatus.Failed)
                        {
                            string errors = string.Join("\r\n\r\n", info.Result.Errors.ToArray());

                            DebugHelper.WriteLine($"Task failed. Filename: {info.FileName}, Errors:\r\n{errors}");

                            if (lvi != null)
                            {
                                lvi.SubItems[1].Text = info.Status;
                                lvi.SubItems[6].Text = "";
                                lvi.ImageIndex       = 1;
                            }

                            if (!info.TaskSettings.AdvancedSettings.DisableNotifications)
                            {
                                if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                {
                                    TaskHelpers.PlayErrorSound(info.TaskSettings);
                                }

                                if (info.TaskSettings.GeneralSettings.PopUpNotification != PopUpNotificationType.None && !string.IsNullOrEmpty(errors) &&
                                    (!info.TaskSettings.AdvancedSettings.DisableNotificationsOnFullscreen || !CaptureHelpers.IsActiveWindowFullscreen()))
                                {
                                    TaskHelpers.ShowBalloonTip(errors, ToolTipIcon.Error, 5000, "ShareX - " + Resources.TaskManager_task_UploadCompleted_Error);
                                }
                            }
                        }
                        else
                        {
                            DebugHelper.WriteLine($"Task completed. Filename: {info.FileName}, Duration: {(long)info.TaskDuration.TotalMilliseconds} ms");

                            string result = info.ToString();

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;

                                if (!string.IsNullOrEmpty(result))
                                {
                                    lvi.SubItems[6].Text = result;
                                }
                            }

                            if (!task.StopRequested && !string.IsNullOrEmpty(result))
                            {
                                if (Program.Settings.HistorySaveTasks && (!Program.Settings.HistoryCheckURL ||
                                                                          (!string.IsNullOrEmpty(info.Result.URL) || !string.IsNullOrEmpty(info.Result.ShortenedURL))))
                                {
                                    HistoryItem historyItem = info.GetHistoryItem();
                                    AppendHistoryItemAsync(historyItem);
                                }

                                RecentManager.Add(task);

                                if (!info.TaskSettings.AdvancedSettings.DisableNotifications && info.Job != TaskJob.ShareURL)
                                {
                                    if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                    {
                                        TaskHelpers.PlayTaskCompleteSound(info.TaskSettings);
                                    }

                                    if (!string.IsNullOrEmpty(info.TaskSettings.AdvancedSettings.BalloonTipContentFormat))
                                    {
                                        result = new UploadInfoParser().Parse(info, info.TaskSettings.AdvancedSettings.BalloonTipContentFormat);
                                    }

                                    if (!string.IsNullOrEmpty(result) &&
                                        (!info.TaskSettings.AdvancedSettings.DisableNotificationsOnFullscreen || !CaptureHelpers.IsActiveWindowFullscreen()))
                                    {
                                        switch (info.TaskSettings.GeneralSettings.PopUpNotification)
                                        {
                                        case PopUpNotificationType.BalloonTip:
                                            BalloonTipAction action = new BalloonTipAction()
                                            {
                                                ClickAction = BalloonTipClickAction.OpenURL,
                                                Text        = result
                                            };

                                            TaskHelpers.ShowBalloonTip(result, ToolTipIcon.Info, 5000,
                                                                       "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed, action);
                                            break;

                                        case PopUpNotificationType.ToastNotification:
                                            task.KeepImage = true;

                                            NotificationFormConfig toastConfig = new NotificationFormConfig()
                                            {
                                                LeftClickAction   = info.TaskSettings.AdvancedSettings.ToastWindowClickAction,
                                                RightClickAction  = info.TaskSettings.AdvancedSettings.ToastWindowRightClickAction,
                                                MiddleClickAction = info.TaskSettings.AdvancedSettings.ToastWindowMiddleClickAction,
                                                FilePath          = info.FilePath,
                                                Image             = task.Image,
                                                Text = "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed + "\r\n" + result,
                                                URL  = result
                                            };
                                            NotificationForm.Show((int)(info.TaskSettings.AdvancedSettings.ToastWindowDuration * 1000),
                                                                  (int)(info.TaskSettings.AdvancedSettings.ToastWindowFadeDuration * 1000),
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowPlacement,
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowSize, toastConfig);
                                            break;
                                        }

                                        if (info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShowAfterUploadWindow) && info.IsUploadJob)
                                        {
                                            AfterUploadForm dlg = new AfterUploadForm(info);
                                            NativeMethods.ShowWindow(dlg.Handle, (int)WindowShowStyle.ShowNoActivate);
                                        }
                                    }
                                }
                            }
                        }

                        if (lvi != null)
                        {
                            lvi.EnsureVisible();

                            if (Program.Settings.AutoSelectLastCompletedTask)
                            {
                                TaskListView.ListViewControl.SelectSingle(lvi);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (!IsBusy && Program.CLI.IsCommandExist("AutoClose"))
                {
                    Application.Exit();
                }
                else
                {
                    StartTasks();
                    UpdateProgressUI();

                    if (Program.Settings.SaveSettingsAfterTaskCompleted && !IsBusy)
                    {
                        SettingManager.SaveAllSettingsAsync();
                    }
                }
            }
        }
コード例 #16
0
        private void DoAfterCaptureJobs()
        {
            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddImageEffects))
            {
                tempImage = TaskHelpers.AddImageEffects(tempImage, Info.TaskSettings);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddWatermark) && Info.TaskSettings.ImageSettings.WatermarkConfig != null)
            {
                WatermarkManager watermarkManager = new WatermarkManager(Info.TaskSettings.ImageSettings.WatermarkConfig);
                watermarkManager.ApplyWatermark(tempImage);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AnnotateImage))
            {
                tempImage = TaskHelpers.AnnotateImage(tempImage);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyImageToClipboard))
            {
                ClipboardHelpers.CopyImage(tempImage);
                DebugHelper.WriteLine("CopyImageToClipboard");
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SendImageToPrinter))
            {
                if (Program.Settings.DontShowPrintSettingsDialog)
                {
                    using (PrintHelper printHelper = new PrintHelper(tempImage))
                    {
                        printHelper.Settings = Program.Settings.PrintSettings;
                        printHelper.Print();
                    }
                }
                else
                {
                    using (PrintForm printForm = new PrintForm(tempImage, Program.Settings.PrintSettings))
                    {
                        printForm.ShowDialog();
                    }
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlagAny(AfterCaptureTasks.SaveImageToFile, AfterCaptureTasks.SaveImageToFileWithDialog,
                                                             AfterCaptureTasks.UploadImageToHost))
            {
                using (tempImage)
                {
                    ImageData imageData = TaskHelpers.PrepareImage(tempImage, Info.TaskSettings);
                    Data          = imageData.ImageStream;
                    Info.FileName = Path.ChangeExtension(Info.FileName, imageData.ImageFormat.GetDescription());

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFile))
                    {
                        Info.FilePath = Path.Combine(Program.ScreenshotsPath, Info.FileName);
                        imageData.Write(Info.FilePath);
                        DebugHelper.WriteLine("SaveImageToFile: " + Info.FilePath);
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFileWithDialog))
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.InitialDirectory = Program.ScreenshotsPath;
                            sfd.FileName         = Info.FileName;
                            sfd.DefaultExt       = Path.GetExtension(Info.FileName).Substring(1);
                            sfd.Filter           = string.Format("*{0}|*{0}|All files (*.*)|*.*", Path.GetExtension(Info.FileName));
                            sfd.Title            = "Choose a folder to save " + Path.GetFileName(Info.FileName);

                            if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                            {
                                Info.FilePath = sfd.FileName;
                                imageData.Write(Info.FilePath);
                                DebugHelper.WriteLine("SaveImageToFileWithDialog: " + Info.FilePath);
                            }
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFileToClipboard) && !string.IsNullOrEmpty(Info.FilePath) &&
                        File.Exists(Info.FilePath))
                    {
                        ClipboardHelpers.CopyFile(Info.FilePath);
                    }
                    else if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFilePathToClipboard) && !string.IsNullOrEmpty(Info.FilePath))
                    {
                        ClipboardHelpers.CopyText(Info.FilePath);
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.PerformActions) && Info.TaskSettings.ExternalPrograms != null &&
                        !string.IsNullOrEmpty(Info.FilePath) && File.Exists(Info.FilePath))
                    {
                        var actions = Info.TaskSettings.ExternalPrograms.Where(x => x.IsActive);

                        if (actions.Count() > 0)
                        {
                            if (Data != null)
                            {
                                Data.Dispose();
                            }

                            foreach (ExternalProgram fileAction in actions)
                            {
                                fileAction.Run(Info.FilePath);
                            }

                            Data = new FileStream(Info.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                        }
                    }
                }
            }
        }
コード例 #17
0
        private void HandleTask(TaskSettings taskSettings)
        {
            TaskSettings safeTaskSettings = TaskSettings.GetSafeTaskSettings(taskSettings);

            switch (safeTaskSettings.Job)
            {
            case HotkeyType.StopUploads:
                TaskManager.StopAllTasks();
                break;

            case HotkeyType.ClipboardUpload:
                UploadManager.ClipboardUpload(safeTaskSettings);
                break;

            case HotkeyType.ClipboardUploadWithContentViewer:
                UploadManager.ClipboardUploadWithContentViewer(safeTaskSettings);
                break;

            case HotkeyType.FileUpload:
                UploadManager.UploadFile(safeTaskSettings);
                break;

            case HotkeyType.DragDropUpload:
                TaskHelpers.OpenDropWindow();
                break;

            case HotkeyType.PrintScreen:
                CaptureScreenshot(CaptureType.Screen, safeTaskSettings, false);
                break;

            case HotkeyType.ActiveWindow:
                CaptureScreenshot(CaptureType.ActiveWindow, safeTaskSettings, false);
                break;

            case HotkeyType.ActiveMonitor:
                CaptureScreenshot(CaptureType.ActiveMonitor, safeTaskSettings, false);
                break;

            case HotkeyType.RectangleRegion:
                CaptureScreenshot(CaptureType.Rectangle, safeTaskSettings, false);
                break;

            case HotkeyType.WindowRectangle:
                CaptureScreenshot(CaptureType.RectangleWindow, safeTaskSettings, false);
                break;

            case HotkeyType.RoundedRectangleRegion:
                CaptureScreenshot(CaptureType.RoundedRectangle, safeTaskSettings, false);
                break;

            case HotkeyType.EllipseRegion:
                CaptureScreenshot(CaptureType.Ellipse, safeTaskSettings, false);
                break;

            case HotkeyType.TriangleRegion:
                CaptureScreenshot(CaptureType.Triangle, safeTaskSettings, false);
                break;

            case HotkeyType.DiamondRegion:
                CaptureScreenshot(CaptureType.Diamond, safeTaskSettings, false);
                break;

            case HotkeyType.PolygonRegion:
                CaptureScreenshot(CaptureType.Polygon, safeTaskSettings, false);
                break;

            case HotkeyType.FreeHandRegion:
                CaptureScreenshot(CaptureType.Freehand, safeTaskSettings, false);
                break;

            case HotkeyType.LastRegion:
                CaptureScreenshot(CaptureType.LastRegion, safeTaskSettings, false);
                break;

            case HotkeyType.ScreenRecorder:
                TaskHelpers.DoScreenRecorder(safeTaskSettings);
                break;

            case HotkeyType.AutoCapture:
                TaskHelpers.OpenAutoCapture();
                break;

            case HotkeyType.ScreenColorPicker:
                TaskHelpers.OpenScreenColorPicker(safeTaskSettings);
                break;

            case HotkeyType.Ruler:
                TaskHelpers.OpenRuler();
                break;

            case HotkeyType.FTPClient:
                TaskHelpers.OpenFTPClient();
                break;

            case HotkeyType.HashCheck:
                TaskHelpers.OpenHashCheck();
                break;

            case HotkeyType.IndexFolder:
                TaskHelpers.OpenIndexFolder();
                break;

            case HotkeyType.ImageEffects:
                TaskHelpers.OpenImageEffects();
                break;

            case HotkeyType.QRCode:
                TaskHelpers.OpenQRCode();
                break;
            }
        }
コード例 #18
0
ファイル: ScreenRecordForm.cs プロジェクト: Shipeci/ShareX
        public async void StartRecording(TaskSettings TaskSettings)
        {
            if (TaskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(TaskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show("There is no valid CLI video encoder selected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else if (!Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show("CLI video encoder file does not exist: " + Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg && !File.Exists(TaskSettings.CaptureSettings.FFmpegOptions.CLIPath))
            {
                string ffmpegText = string.IsNullOrEmpty(TaskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : TaskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                if (MessageBox.Show(ffmpegText + " does not exist." + Environment.NewLine + Environment.NewLine + "Would you like to automatically download it?",
                                    Application.ProductName + " - Missing ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (FFmpegHelper.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                    {
                        Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = TaskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                            TaskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                    }
                }
                else
                {
                    return;
                }
            }

            SelectRegion();

            if (IsRecording || captureRectangle.IsEmpty || screenRecorder != null)
            {
                return;
            }

            IsRecording = true;
            Screenshot.CaptureCursor = TaskSettings.CaptureSettings.ShowCursor;

            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            try
            {
                using (ScreenRegionManager screenRegionManager = new ScreenRegionManager())
                {
                    screenRegionManager.Start(captureRectangle);

                    await TaskEx.Run(() =>
                    {
                        if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                        {
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "avi"));
                        }
                        else if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg)
                        {
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, TaskSettings.CaptureSettings.FFmpegOptions.Extension));
                        }
                        else
                        {
                            path = Program.ScreenRecorderCacheFilePath;
                        }

                        ScreencastOptions options = new ScreencastOptions()
                        {
                            CaptureArea     = captureRectangle,
                            GIFFPS          = TaskSettings.CaptureSettings.GIFFPS,
                            ScreenRecordFPS = TaskSettings.CaptureSettings.ScreenRecordFPS,
                            OutputPath      = path,
                            Duration        = TaskSettings.CaptureSettings.ScreenRecordFixedDuration ? TaskSettings.CaptureSettings.ScreenRecordDuration : 0,
                            AVI             = TaskSettings.CaptureSettings.AVIOptions,
                            FFmpeg          = TaskSettings.CaptureSettings.FFmpegOptions,
                            DrawCursor      = TaskSettings.CaptureSettings.ShowCursor
                        };

                        screenRecorder = new ScreenRecorder(options, captureRectangle, TaskSettings.CaptureSettings.ScreenRecordOutput);

                        int delay = (int)(TaskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                        if (delay > 0)
                        {
                            Thread.Sleep(delay);
                        }

                        screenRegionManager.ChangeColor();

                        this.InvokeSafe(() => TrayIcon.Icon = Resources.control_record.ToIcon());

                        screenRecorder.StartRecording();
                    });
                }

                if (screenRecorder != null)
                {
                    TrayIcon.Icon = Resources.camcorder__pencil.ToIcon();

                    await TaskEx.Run(() =>
                    {
                        string sourceFilePath = path;

                        if (TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.GIF)
                        {
                            if (TaskSettings.CaptureSettings.RunScreencastCLI)
                            {
                                sourceFilePath = Path.ChangeExtension(Program.ScreenRecorderCacheFilePath, "gif");
                            }
                            else
                            {
                                sourceFilePath = path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, "gif"));
                            }
                            screenRecorder.SaveAsGIF(sourceFilePath, TaskSettings.ImageSettings.ImageGIFQuality);
                        }

                        if (TaskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[TaskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(TaskSettings.CaptureFolder, TaskHelpers.GetFilename(TaskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    });
                }
            }
            finally
            {
                if (screenRecorder != null)
                {
                    if (TaskSettings.CaptureSettings.RunScreencastCLI &&
                        !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                    {
                        File.Delete(screenRecorder.CachePath);
                    }

                    screenRecorder.Dispose();
                    screenRecorder = null;
                }

                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }
            }

            if (!string.IsNullOrEmpty(path) && File.Exists(path))
            {
                if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.UploadImageToHost))
                {
                    UploadManager.UploadFile(path, TaskSettings);
                }
                else
                {
                    if (TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyFilePathToClipboard))
                    {
                        ClipboardHelpers.CopyText(path);
                    }

                    TaskHelpers.ShowResultNotifications(path, TaskSettings, path);
                }
            }

            IsRecording = false;
        }
コード例 #19
0
ファイル: TaskManager.cs プロジェクト: yangyichen/ShareX
 private static void Task_UploadersConfigWindowRequested(IUploaderService uploaderService)
 {
     TaskHelpers.OpenUploadersConfigWindow(uploaderService);
 }
コード例 #20
0
ファイル: CaptureRegion.cs プロジェクト: hobosoft/ShareX
        protected TaskMetadata ExecuteRegionCapture(TaskSettings taskSettings)
        {
            RegionCaptureMode mode;

            if (taskSettings.AdvancedSettings.RegionCaptureDisableAnnotation)
            {
                mode = RegionCaptureMode.Default;
            }
            else
            {
                mode = RegionCaptureMode.Annotation;
            }

            Bitmap     canvas;
            Screenshot screenshot = TaskHelpers.GetScreenshot(taskSettings);

            screenshot.CaptureCursor = false;

            if (taskSettings.CaptureSettings.SurfaceOptions.ActiveMonitorMode)
            {
                canvas = screenshot.CaptureActiveMonitor();
            }
            else
            {
                canvas = screenshot.CaptureFullscreen();
            }

            CursorData cursorData = null;

            if (taskSettings.CaptureSettings.ShowCursor)
            {
                cursorData = new CursorData();
            }

            using (RegionCaptureForm form = new RegionCaptureForm(mode, taskSettings.CaptureSettingsReference.SurfaceOptions, canvas))
            {
                if (cursorData != null && cursorData.IsVisible)
                {
                    form.AddCursor(cursorData.Handle, form.PointToClient(cursorData.Position));
                }

                form.ShowDialog();

                Bitmap result = form.GetResultImage();

                if (result != null)
                {
                    TaskMetadata metadata = new TaskMetadata(result);

                    if (form.IsImageModified)
                    {
                        AllowAnnotation = false;
                    }

                    if (form.Result == RegionResult.Region)
                    {
                        WindowInfo windowInfo = form.GetWindowInfo();
                        metadata.UpdateInfo(windowInfo);
                    }

                    lastRegionCaptureType = RegionCaptureType.Default;

                    return(metadata);
                }
            }

            return(null);
        }
コード例 #21
0
        public TaskSettingsForm(TaskSettings hotkeySetting, bool isDefault = false)
        {
            InitializeComponent();
            Icon         = ShareXResources.Icon;
            TaskSettings = hotkeySetting;
            IsDefault    = isDefault;

            if (IsDefault)
            {
                Text = Application.ProductName + " - Task settings";
                tcHotkeySettings.TabPages.Remove(tpTask);
                chkUseDefaultGeneralSettings.Visible    = chkUseDefaultImageSettings.Visible = chkUseDefaultCaptureSettings.Visible = chkUseDefaultActions.Visible =
                    chkUseDefaultUploadSettings.Visible = chkUseDefaultIndexerSettings.Visible = chkUseDefaultAdvancedSettings.Visible = false;
                panelGeneral.BorderStyle = BorderStyle.None;
            }
            else
            {
                Text = Application.ProductName + " - Task settings for " + TaskSettings;
                tbDescription.Text = TaskSettings.Description;
                cbUseDefaultAfterCaptureSettings.Checked = TaskSettings.UseDefaultAfterCaptureJob;
                cbUseDefaultAfterUploadSettings.Checked  = TaskSettings.UseDefaultAfterUploadJob;
                cbUseDefaultDestinationSettings.Checked  = TaskSettings.UseDefaultDestinations;
                chkUseDefaultGeneralSettings.Checked     = TaskSettings.UseDefaultGeneralSettings;
                chkUseDefaultImageSettings.Checked       = TaskSettings.UseDefaultImageSettings;
                chkUseDefaultCaptureSettings.Checked     = TaskSettings.UseDefaultCaptureSettings;
                chkUseDefaultActions.Checked             = TaskSettings.UseDefaultActions;
                chkUseDefaultUploadSettings.Checked      = TaskSettings.UseDefaultUploadSettings;
                chkUseDefaultIndexerSettings.Checked     = TaskSettings.UseDefaultIndexerSettings;
                chkUseDefaultAdvancedSettings.Checked    = TaskSettings.UseDefaultAdvancedSettings;
            }

            AddEnumItems <HotkeyType>(x => TaskSettings.Job = x, cmsTask);
            AddMultiEnumItems <AfterCaptureTasks>(x => TaskSettings.AfterCaptureJob   = TaskSettings.AfterCaptureJob.Swap(x), cmsAfterCapture);
            AddMultiEnumItems <AfterUploadTasks>(x => TaskSettings.AfterUploadJob     = TaskSettings.AfterUploadJob.Swap(x), cmsAfterUpload);
            AddEnumItems <ImageDestination>(x => TaskSettings.ImageDestination        = x, cmsImageUploaders);
            AddEnumItems <TextDestination>(x => TaskSettings.TextDestination          = x, cmsTextUploaders);
            AddEnumItems <FileDestination>(x => TaskSettings.FileDestination          = x, cmsFileUploaders);
            AddEnumItems <UrlShortenerType>(x => TaskSettings.URLShortenerDestination = x, cmsURLShorteners);
            AddEnumItems <SocialNetworkingService>(x => TaskSettings.SocialNetworkingServiceDestination = x, cmsSocialNetworkingServices);

            SetEnumChecked(TaskSettings.Job, cmsTask);
            SetMultiEnumChecked(TaskSettings.AfterCaptureJob, cmsAfterCapture);
            SetMultiEnumChecked(TaskSettings.AfterUploadJob, cmsAfterUpload);
            SetEnumChecked(TaskSettings.ImageDestination, cmsImageUploaders);
            SetEnumChecked(TaskSettings.TextDestination, cmsTextUploaders);
            SetEnumChecked(TaskSettings.FileDestination, cmsFileUploaders);
            SetEnumChecked(TaskSettings.URLShortenerDestination, cmsURLShorteners);
            SetEnumChecked(TaskSettings.SocialNetworkingServiceDestination, cmsSocialNetworkingServices);

            // FTP
            if (Program.UploadersConfig != null && Program.UploadersConfig.FTPAccountList.Count > 1)
            {
                chkOverrideFTP.Checked = TaskSettings.OverrideFTP;
                cboFTPaccounts.Items.Clear();
                cboFTPaccounts.Items.AddRange(Program.UploadersConfig.FTPAccountList.ToArray());
                cboFTPaccounts.SelectedIndex = TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1);
            }

            UpdateDestinationStates();
            UpdateUploaderMenuNames();

            // General
            cbPlaySoundAfterCapture.Checked     = TaskSettings.GeneralSettings.PlaySoundAfterCapture;
            cbShowAfterCaptureTasksForm.Checked = TaskSettings.GeneralSettings.ShowAfterCaptureTasksForm;
            cbPlaySoundAfterUpload.Checked      = TaskSettings.GeneralSettings.PlaySoundAfterUpload;
            chkShowAfterUploadForm.Checked      = TaskSettings.GeneralSettings.ShowAfterUploadForm;
            cbTrayBalloonTipAfterUpload.Checked = TaskSettings.GeneralSettings.TrayBalloonTipAfterUpload;
            cbShowToastWindowAfterTask.Checked  = TaskSettings.GeneralSettings.ShowToastWindowAfterTask;
            cbHistorySave.Checked = TaskSettings.GeneralSettings.SaveHistory;

            // Image - Quality
            cbImageFormat.SelectedIndex     = (int)TaskSettings.ImageSettings.ImageFormat;
            nudImageJPEGQuality.Value       = TaskSettings.ImageSettings.ImageJPEGQuality;
            cbImageGIFQuality.SelectedIndex = (int)TaskSettings.ImageSettings.ImageGIFQuality;
            nudUseImageFormat2After.Value   = TaskSettings.ImageSettings.ImageSizeLimit;
            cbImageFormat2.SelectedIndex    = (int)TaskSettings.ImageSettings.ImageFormat2;

            // Image - Effects
            chkShowImageEffectsWindowAfterCapture.Checked = TaskSettings.ImageSettings.ShowImageEffectsWindowAfterCapture;
            cbImageEffectOnlyRegionCapture.Checked        = TaskSettings.ImageSettings.ImageEffectOnlyRegionCapture;

            // Capture
            cbShowCursor.Checked             = TaskSettings.CaptureSettings.ShowCursor;
            cbCaptureTransparent.Checked     = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Enabled          = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Checked          = TaskSettings.CaptureSettings.CaptureShadow;
            nudCaptureShadowOffset.Value     = TaskSettings.CaptureSettings.CaptureShadowOffset;
            cbCaptureClientArea.Checked      = TaskSettings.CaptureSettings.CaptureClientArea;
            cbScreenshotDelay.Checked        = TaskSettings.CaptureSettings.IsDelayScreenshot;
            nudScreenshotDelay.Value         = TaskSettings.CaptureSettings.DelayScreenshot;
            cbCaptureAutoHideTaskbar.Checked = TaskSettings.CaptureSettings.CaptureAutoHideTaskbar;

            if (TaskSettings.CaptureSettings.SurfaceOptions == null)
            {
                TaskSettings.CaptureSettings.SurfaceOptions = new SurfaceOptions();
            }
            pgShapesCapture.SelectedObject = TaskSettings.CaptureSettings.SurfaceOptions;

            // Capture / Screen recorder
            cbScreenRecorderOutput.Items.AddRange(Helpers.GetEnumDescriptions <ScreenRecordOutput>());
            cbScreenRecorderOutput.SelectedIndex  = (int)TaskSettings.CaptureSettings.ScreenRecordOutput;
            nudScreenRecorderFPS.Value            = TaskSettings.CaptureSettings.ScreenRecordFPS;
            cbScreenRecorderFixedDuration.Checked = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Enabled     = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Value       = (decimal)TaskSettings.CaptureSettings.ScreenRecordDuration;
            nudScreenRecorderStartDelay.Value     = (decimal)TaskSettings.CaptureSettings.ScreenRecordStartDelay;

            gbCommandLineEncoderSettings.Enabled             = TaskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVICommandLine;
            txtScreenRecorderCommandLinePath.Text            = TaskSettings.CaptureSettings.ScreenRecordCommandLinePath;
            txtScreenRecorderCommandLineArgs.Text            = TaskSettings.CaptureSettings.ScreenRecordCommandLineArgs;
            txtScreenRecorderCommandLineOutputExtension.Text = TaskSettings.CaptureSettings.ScreenRecordCommandLineOutputExtension;

            // Actions
            TaskHelpers.AddDefaultExternalPrograms(TaskSettings);

            foreach (ExternalProgram fileAction in TaskSettings.ExternalPrograms)
            {
                AddFileAction(fileAction);
            }

            // Watch folders
            cbWatchFolderEnabled.Checked = TaskSettings.WatchFolderEnabled;

            if (TaskSettings.WatchFolderList == null)
            {
                TaskSettings.WatchFolderList = new List <WatchFolderSettings>();
            }
            else
            {
                foreach (WatchFolderSettings watchFolder in TaskSettings.WatchFolderList)
                {
                    AddWatchFolder(watchFolder);
                }
            }

            // Upload / Name pattern
            txtNameFormatPattern.Text             = TaskSettings.UploadSettings.NameFormatPattern;
            txtNameFormatPatternActiveWindow.Text = TaskSettings.UploadSettings.NameFormatPatternActiveWindow;
            cmsNameFormatPattern               = NameParser.CreateCodesMenu(txtNameFormatPattern, ReplacementVariables.n);
            cmsNameFormatPatternActiveWindow   = NameParser.CreateCodesMenu(txtNameFormatPatternActiveWindow, ReplacementVariables.n);
            cbFileUploadUseNamePattern.Checked = TaskSettings.UploadSettings.FileUploadUseNamePattern;

            // Upload / Clipboard upload
            cbClipboardUploadAutoDetectURL.Checked = TaskSettings.UploadSettings.ClipboardUploadAutoDetectURL;

            // Indexer
            pgIndexerConfig.SelectedObject = TaskSettings.IndexerSettings;

            // Advanced
            pgTaskSettings.SelectedObject = TaskSettings.AdvancedSettings;

            UpdateDefaultSettingVisibility();
            loaded = true;
        }
コード例 #22
0
        private void ExecuteAction(ToastClickAction action)
        {
            switch (action)
            {
            case ToastClickAction.AnnotateImage:
                if (!string.IsNullOrEmpty(Config.FilePath) && Helpers.IsImageFile(Config.FilePath))
                {
                    TaskHelpers.AnnotateImageFromFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyImageToClipboard:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyImageFromFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyFile:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyFile(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyFilePath:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    ClipboardHelpers.CopyText(Config.FilePath);
                }
                break;

            case ToastClickAction.CopyUrl:
                if (!string.IsNullOrEmpty(Config.URL))
                {
                    ClipboardHelpers.CopyText(Config.URL);
                }
                break;

            case ToastClickAction.OpenFile:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    Helpers.OpenFile(Config.FilePath);
                }
                break;

            case ToastClickAction.OpenFolder:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    Helpers.OpenFolderWithFile(Config.FilePath);
                }
                break;

            case ToastClickAction.OpenUrl:
                if (!string.IsNullOrEmpty(Config.URL))
                {
                    URLHelpers.OpenURL(Config.URL);
                }
                break;

            case ToastClickAction.Upload:
                if (!string.IsNullOrEmpty(Config.FilePath))
                {
                    UploadManager.UploadFile(Config.FilePath);
                }
                break;
            }
        }
コード例 #23
0
        private void UpdateToolbar(List <HotkeyType> actions)
        {
            tsMain.SuspendLayout();

            tsMain.Items.Clear();

            ToolStripLabel tslTitle = new ToolStripLabel()
            {
                Margin      = new Padding(4, 0, 3, 0),
                Text        = "ShareX",
                ToolTipText = Resources.ActionsToolbar_Tip
            };

            tslTitle.MouseDown  += tslTitle_MouseDown;
            tslTitle.MouseEnter += tslTitle_MouseEnter;
            tslTitle.MouseLeave += tslTitle_MouseLeave;
            tslTitle.MouseUp    += tslTitle_MouseUp;

            tsMain.Items.Add(tslTitle);

            foreach (HotkeyType action in Program.Settings.ActionsToolbarList)
            {
                if (action == HotkeyType.None)
                {
                    ToolStripSeparator tss = new ToolStripSeparator()
                    {
                        Margin = new Padding(0)
                    };

                    tsMain.Items.Add(tss);
                }
                else
                {
                    ToolStripButton tsb = new ToolStripButton()
                    {
                        Text         = action.GetLocalizedDescription(),
                        DisplayStyle = ToolStripItemDisplayStyle.Image,
                        Image        = TaskHelpers.GetHotkeyTypeIcon(action)
                    };

                    tsb.Click += (sender, e) =>
                    {
                        if (Program.Settings.ActionsToolbarStayTopMost)
                        {
                            TopMost = false;
                        }

                        TaskHelpers.ExecuteJob(action);

                        if (Program.Settings.ActionsToolbarStayTopMost)
                        {
                            TopMost = true;
                        }
                    };

                    tsMain.Items.Add(tsb);
                }
            }

            foreach (ToolStripItem tsi in tsMain.Items)
            {
                tsi.MouseEnter += (sender, e) =>
                {
                    string text;

                    if (!string.IsNullOrEmpty(tsi.ToolTipText))
                    {
                        text = tsi.ToolTipText;
                    }
                    else
                    {
                        text = tsi.Text;
                    }

                    ttMain.SetToolTip(tsMain, text);
                };

                tsi.MouseLeave += tsMain_MouseLeave;
            }

            tsMain.ResumeLayout(false);
            tsMain.PerformLayout();
        }
コード例 #24
0
ファイル: NotificationForm.cs プロジェクト: roceys/ShareX
        private void NotificationForm_MouseClick(object sender, MouseEventArgs e)
        {
            tDuration.Stop();

            Close();

            if (e.Button == MouseButtons.Left)
            {
                switch (ToastConfig.Action)
                {
                case ToastClickAction.AnnotateImage:
                    if (!string.IsNullOrEmpty(ToastConfig.FilePath) && Helpers.IsImageFile(ToastConfig.FilePath))
                    {
                        TaskHelpers.AnnotateImage(ToastConfig.FilePath);
                    }
                    break;

                case ToastClickAction.CopyImageToClipboard:
                    if (!string.IsNullOrEmpty(ToastConfig.FilePath))
                    {
                        ClipboardHelpers.CopyImageFromFile(ToastConfig.FilePath);
                    }
                    break;

                case ToastClickAction.CopyUrl:
                    if (!string.IsNullOrEmpty(ToastConfig.URL))
                    {
                        ClipboardHelpers.CopyText(ToastConfig.URL);
                    }
                    break;

                case ToastClickAction.OpenFile:
                    if (!string.IsNullOrEmpty(ToastConfig.FilePath))
                    {
                        URLHelpers.OpenURL(ToastConfig.FilePath);
                    }
                    break;

                case ToastClickAction.OpenFolder:
                    if (!string.IsNullOrEmpty(ToastConfig.FilePath))
                    {
                        Helpers.OpenFolderWithFile(ToastConfig.FilePath);
                    }
                    break;

                case ToastClickAction.OpenUrl:
                    if (!string.IsNullOrEmpty(ToastConfig.URL))
                    {
                        URLHelpers.OpenURL(ToastConfig.URL);
                    }
                    break;

                case ToastClickAction.Upload:
                    if (!string.IsNullOrEmpty(ToastConfig.FilePath))
                    {
                        UploadManager.UploadFile(ToastConfig.FilePath);
                    }
                    break;
                }
            }
        }
コード例 #25
0
        public TaskSettingsForm(TaskSettings hotkeySetting, bool isDefault = false)
        {
            InitializeComponent();
            Icon         = ShareXResources.Icon;
            TaskSettings = hotkeySetting;
            IsDefault    = isDefault;

            if (IsDefault)
            {
                tcTaskSettings.TabPages.Remove(tpTask);
                chkUseDefaultGeneralSettings.Visible    = chkUseDefaultImageSettings.Visible = chkUseDefaultCaptureSettings.Visible = chkUseDefaultActions.Visible =
                    chkUseDefaultUploadSettings.Visible = chkUseDefaultIndexerSettings.Visible = chkUseDefaultAdvancedSettings.Visible = false;
            }
            else
            {
                tbDescription.Text = TaskSettings.Description;
                cbUseDefaultAfterCaptureSettings.Checked = TaskSettings.UseDefaultAfterCaptureJob;
                cbUseDefaultAfterUploadSettings.Checked  = TaskSettings.UseDefaultAfterUploadJob;
                cbUseDefaultDestinationSettings.Checked  = TaskSettings.UseDefaultDestinations;
                chkUseDefaultGeneralSettings.Checked     = TaskSettings.UseDefaultGeneralSettings;
                chkUseDefaultImageSettings.Checked       = TaskSettings.UseDefaultImageSettings;
                chkUseDefaultCaptureSettings.Checked     = TaskSettings.UseDefaultCaptureSettings;
                chkUseDefaultActions.Checked             = TaskSettings.UseDefaultActions;
                chkUseDefaultUploadSettings.Checked      = TaskSettings.UseDefaultUploadSettings;
                chkUseDefaultIndexerSettings.Checked     = TaskSettings.UseDefaultIndexerSettings;
                chkUseDefaultAdvancedSettings.Checked    = TaskSettings.UseDefaultAdvancedSettings;
            }

            UpdateWindowTitle();

            AddEnumItemsContextMenu <HotkeyType>(x =>
            {
                TaskSettings.Job   = x;
                tbDescription.Text = TaskSettings.Job.GetLocalizedDescription();
            }, cmsTask);
            AddMultiEnumItemsContextMenu <AfterCaptureTasks>(x => TaskSettings.AfterCaptureJob = TaskSettings.AfterCaptureJob.Swap(x), cmsAfterCapture);
            AddMultiEnumItemsContextMenu <AfterUploadTasks>(x => TaskSettings.AfterUploadJob   = TaskSettings.AfterUploadJob.Swap(x), cmsAfterUpload);
            // Destinations -> Image uploader
            AddEnumItems <ImageDestination>(x =>
            {
                TaskSettings.ImageDestination = x;
                // if click on "folder" with file destinations then set ImageFileDestination and check it
                if (x == ImageDestination.FileUploader)
                {
                    SetEnumChecked(TaskSettings.ImageFileDestination, tsmiImageFileUploaders);
                }
                else // if click not on "folder" with destinations then uncheck file destinations
                {
                    MainForm.Uncheck(tsmiImageFileUploaders);
                }
            }, tsmiImageUploaders);
            tsmiImageFileUploaders = (ToolStripDropDownItem)tsmiImageUploaders.DropDownItems[tsmiImageUploaders.DropDownItems.Count - 1];
            AddEnumItems <FileDestination>(x =>
            {
                TaskSettings.ImageFileDestination = x;
                tsmiImageFileUploaders.PerformClick();
            }, tsmiImageFileUploaders);
            // Destinations -> Text uploader
            AddEnumItems <TextDestination>(x =>
            {
                TaskSettings.TextDestination = x;
                // if click on "folder" with file destinations then set TextFileDestination and check it
                if (x == TextDestination.FileUploader)
                {
                    SetEnumChecked(TaskSettings.TextFileDestination, tsmiTextFileUploaders);
                }
                else // if click not on "folder" with destinations then uncheck file destinations
                {
                    MainForm.Uncheck(tsmiTextFileUploaders);
                }
            }, tsmiTextUploaders);
            tsmiTextFileUploaders = (ToolStripDropDownItem)tsmiTextUploaders.DropDownItems[tsmiTextUploaders.DropDownItems.Count - 1];
            AddEnumItems <FileDestination>(x =>
            {
                TaskSettings.TextFileDestination = x;
                tsmiTextFileUploaders.PerformClick();
            }, tsmiTextFileUploaders);
            // Destinations -> File uploader
            AddEnumItems <FileDestination>(x => TaskSettings.FileDestination                 = x, tsmiFileUploaders);
            AddEnumItems <UrlShortenerType>(x => TaskSettings.URLShortenerDestination        = x, tsmiURLShorteners);
            AddEnumItems <URLSharingServices>(x => TaskSettings.URLSharingServiceDestination = x, tsmiURLSharingServices);

            SetEnumCheckedContextMenu(TaskSettings.Job, cmsTask);
            SetMultiEnumCheckedContextMenu(TaskSettings.AfterCaptureJob, cmsAfterCapture);
            SetMultiEnumCheckedContextMenu(TaskSettings.AfterUploadJob, cmsAfterUpload);
            SetEnumChecked(TaskSettings.ImageDestination, tsmiImageUploaders);
            MainForm.SetImageFileDestinationChecked(TaskSettings.ImageDestination, TaskSettings.ImageFileDestination, tsmiImageFileUploaders);
            SetEnumChecked(TaskSettings.TextDestination, tsmiTextUploaders);
            MainForm.SetTextFileDestinationChecked(TaskSettings.TextDestination, TaskSettings.TextFileDestination, tsmiTextFileUploaders);
            SetEnumChecked(TaskSettings.FileDestination, tsmiFileUploaders);
            SetEnumChecked(TaskSettings.URLShortenerDestination, tsmiURLShorteners);
            SetEnumChecked(TaskSettings.URLSharingServiceDestination, tsmiURLSharingServices);

            if (Program.UploadersConfig != null)
            {
                // FTP
                if (Program.UploadersConfig.FTPAccountList.Count > 0)
                {
                    chkOverrideFTP.Checked = TaskSettings.OverrideFTP;
                    cboFTPaccounts.Items.Clear();
                    cboFTPaccounts.Items.AddRange(Program.UploadersConfig.FTPAccountList.ToArray());
                    cboFTPaccounts.SelectedIndex = TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1);
                }

                // Custom uploader
                if (Program.UploadersConfig.CustomUploadersList.Count > 0)
                {
                    chkOverrideCustomUploader.Checked = TaskSettings.OverrideCustomUploader;
                    cbOverrideCustomUploader.Items.Clear();
                    cbOverrideCustomUploader.Items.AddRange(Program.UploadersConfig.CustomUploadersList.ToArray());
                    cbOverrideCustomUploader.SelectedIndex = TaskSettings.CustomUploaderIndex.BetweenOrDefault(0, Program.UploadersConfig.CustomUploadersList.Count - 1);
                }
            }

            UpdateDestinationStates();
            UpdateUploaderMenuNames();

            // General
            cbPlaySoundAfterCapture.Checked     = TaskSettings.GeneralSettings.PlaySoundAfterCapture;
            cbShowAfterCaptureTasksForm.Checked = TaskSettings.GeneralSettings.ShowAfterCaptureTasksForm;
            chkShowBeforeUploadForm.Checked     = TaskSettings.GeneralSettings.ShowBeforeUploadForm;
            cbPlaySoundAfterUpload.Checked      = TaskSettings.GeneralSettings.PlaySoundAfterUpload;
            chkShowAfterUploadForm.Checked      = TaskSettings.GeneralSettings.ShowAfterUploadForm;
            cboPopUpNotification.Items.Clear();
            cboPopUpNotification.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <PopUpNotificationType>());
            cboPopUpNotification.SelectedIndex = (int)TaskSettings.GeneralSettings.PopUpNotification;
            cbHistorySave.Checked = TaskSettings.GeneralSettings.SaveHistory;

            // Image - General
            cbImageFormat.Items.AddRange(Enum.GetNames(typeof(EImageFormat)));
            cbImageFormat.SelectedIndex = (int)TaskSettings.ImageSettings.ImageFormat;
            nudImageJPEGQuality.Value   = TaskSettings.ImageSettings.ImageJPEGQuality;
            cbImageGIFQuality.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <GIFQuality>());
            cbImageGIFQuality.SelectedIndex = (int)TaskSettings.ImageSettings.ImageGIFQuality;
            nudUseImageFormat2After.Value   = TaskSettings.ImageSettings.ImageSizeLimit;
            cbImageFormat2.Items.AddRange(Enum.GetNames(typeof(EImageFormat)));
            cbImageFormat2.SelectedIndex = (int)TaskSettings.ImageSettings.ImageFormat2;
            cbImageFileExist.Items.Clear();
            cbImageFileExist.Items.AddRange(Helpers.GetLocalizedEnumDescriptions <FileExistAction>());
            cbImageFileExist.SelectedIndex = (int)TaskSettings.ImageSettings.FileExistAction;

            // Image - Effects
            chkShowImageEffectsWindowAfterCapture.Checked = TaskSettings.ImageSettings.ShowImageEffectsWindowAfterCapture;
            cbImageEffectOnlyRegionCapture.Checked        = TaskSettings.ImageSettings.ImageEffectOnlyRegionCapture;

            // Image - Thumbnail
            nudThumbnailWidth.Value      = TaskSettings.ImageSettings.ThumbnailWidth;
            nudThumbnailHeight.Value     = TaskSettings.ImageSettings.ThumbnailHeight;
            txtThumbnailName.Text        = TaskSettings.ImageSettings.ThumbnailName;
            lblThumbnailNamePreview.Text = "ImageName" + TaskSettings.ImageSettings.ThumbnailName + ".jpg";
            cbThumbnailIfSmaller.Checked = TaskSettings.ImageSettings.ThumbnailCheckSize;

            // Capture
            cbShowCursor.Checked             = TaskSettings.CaptureSettings.ShowCursor;
            cbCaptureTransparent.Checked     = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Enabled          = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Checked          = TaskSettings.CaptureSettings.CaptureShadow;
            nudCaptureShadowOffset.Value     = TaskSettings.CaptureSettings.CaptureShadowOffset;
            cbCaptureClientArea.Checked      = TaskSettings.CaptureSettings.CaptureClientArea;
            cbScreenshotDelay.Checked        = TaskSettings.CaptureSettings.IsDelayScreenshot;
            nudScreenshotDelay.Value         = TaskSettings.CaptureSettings.DelayScreenshot;
            cbCaptureAutoHideTaskbar.Checked = TaskSettings.CaptureSettings.CaptureAutoHideTaskbar;

            // Capture / Region capture
            if (TaskSettings.CaptureSettings.SurfaceOptions == null)
            {
                TaskSettings.CaptureSettings.SurfaceOptions = new SurfaceOptions();
            }
            pgRegionCapture.SelectedObject = TaskSettings.CaptureSettings.SurfaceOptions;

            // Capture / Rectangle annotate
            if (TaskSettings.CaptureSettings.RectangleAnnotateOptions == null)
            {
                TaskSettings.CaptureSettings.RectangleAnnotateOptions = new RectangleAnnotateOptions();
            }
            pgRectangleAnnotate.SelectedObject = TaskSettings.CaptureSettings.RectangleAnnotateOptions;

            // Capture / Screen recorder
            cbScreenRecorderOutput.Items.AddRange(Helpers.GetEnumDescriptions <ScreenRecordOutput>());
            cbScreenRecorderOutput.SelectedIndex = (int)TaskSettings.CaptureSettings.ScreenRecordOutput;
            chkRunScreencastCLI.Checked          = TaskSettings.CaptureSettings.RunScreencastCLI;
            UpdateVideoEncoders();

            nudScreenRecordFPS.Value = TaskSettings.CaptureSettings.ScreenRecordFPS.Between((int)nudScreenRecordFPS.Minimum, (int)nudScreenRecordFPS.Maximum);
            nudGIFFPS.Value          = TaskSettings.CaptureSettings.GIFFPS.Between((int)nudGIFFPS.Minimum, (int)nudGIFFPS.Maximum);
            cbScreenRecorderFixedDuration.Checked = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Enabled     = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Value       = (decimal)TaskSettings.CaptureSettings.ScreenRecordDuration;
            chkScreenRecordAutoStart.Checked      = TaskSettings.CaptureSettings.ScreenRecordAutoStart;
            nudScreenRecorderStartDelay.Enabled   = chkScreenRecordAutoStart.Checked;
            nudScreenRecorderStartDelay.Value     = (decimal)TaskSettings.CaptureSettings.ScreenRecordStartDelay;
            cbScreenRecordAutoDisableAero.Checked = TaskSettings.CaptureSettings.ScreenRecordAutoDisableAero;

            // Actions
            TaskHelpers.AddDefaultExternalPrograms(TaskSettings);
            TaskSettings.ExternalPrograms.ForEach(x => AddFileAction(x));

            // Watch folders
            cbWatchFolderEnabled.Checked = TaskSettings.WatchFolderEnabled;

            if (TaskSettings.WatchFolderList == null)
            {
                TaskSettings.WatchFolderList = new List <WatchFolderSettings>();
            }
            else
            {
                foreach (WatchFolderSettings watchFolder in TaskSettings.WatchFolderList)
                {
                    AddWatchFolder(watchFolder);
                }
            }

            // Upload / Name pattern
            txtNameFormatPattern.Text             = TaskSettings.UploadSettings.NameFormatPattern;
            txtNameFormatPatternActiveWindow.Text = TaskSettings.UploadSettings.NameFormatPatternActiveWindow;
            CodeMenu.Create <ReplCodeMenuEntry>(txtNameFormatPattern, ReplCodeMenuEntry.n, ReplCodeMenuEntry.t, ReplCodeMenuEntry.pn);
            CodeMenu.Create <ReplCodeMenuEntry>(txtNameFormatPatternActiveWindow, ReplCodeMenuEntry.n);
            cbFileUploadUseNamePattern.Checked = TaskSettings.UploadSettings.FileUploadUseNamePattern;

            // Upload / Clipboard upload
            chkClipboardUploadURLContents.Checked    = TaskSettings.UploadSettings.ClipboardUploadURLContents;
            cbClipboardUploadShortenURL.Checked      = TaskSettings.UploadSettings.ClipboardUploadShortenURL;
            cbClipboardUploadShareURL.Checked        = TaskSettings.UploadSettings.ClipboardUploadShareURL;
            cbClipboardUploadAutoIndexFolder.Checked = TaskSettings.UploadSettings.ClipboardUploadAutoIndexFolder;

            // Indexer
            pgIndexerConfig.SelectedObject = TaskSettings.IndexerSettings;

            // Advanced
            pgTaskSettings.SelectedObject = TaskSettings.AdvancedSettings;

            tttvMain.MainTabControl = tcTaskSettings;

            UpdateDefaultSettingVisibility();

            loaded = true;
        }
コード例 #26
0
 private void btnHotkeysDisabled_Click(object sender, EventArgs e)
 {
     TaskHelpers.ToggleHotkeys(false);
     btnHotkeysDisabled.Visible = false;
 }
コード例 #27
0
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            string debugText;

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                debugText = string.Format("Starting FFmpeg recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                          taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                          taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                debugText = string.Format("Starting Animated GIF recording. GIF encoding: \"{0}\", FPS: {1}",
                                          taskSettings.CaptureSettings.GIFEncoding.GetDescription(), taskSettings.CaptureSettings.GIFFPS);
            }

            DebugHelper.WriteLine(debugText);

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF && taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.FFmpeg)
            {
                outputType = ScreenRecordOutput.FFmpeg;
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec        = FFmpegVideoCodec.gif;
                taskSettings.CaptureSettings.FFmpegOptions.UseCustomCommands = false;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!TaskHelpers.CheckFFmpeg(taskSettings))
                {
                    return;
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                RegionCaptureHelpers.GetRectangleRegion(out captureRectangle, taskSettings.CaptureSettings.SurfaceOptions);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.CustomRegion:
                captureRectangle = taskSettings.CaptureSettings.CaptureCustomRegion;
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            TaskEx.Run(() =>
            {
                try
                {
                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    recordForm.ChangeState(ScreenRecordState.BeforeStart);

                    if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                    {
                        int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                        if (delay > 0)
                        {
                            recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                            recordForm.RecordResetEvent.WaitOne(delay);
                        }
                    }
                    else
                    {
                        recordForm.RecordResetEvent.WaitOne();
                    }

                    if (recordForm.AbortRequested)
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        ScreencastOptions options = new ScreencastOptions()
                        {
                            FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                            ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                            GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                            Duration        = duration,
                            OutputPath      = path,
                            CaptureArea     = captureRectangle,
                            DrawCursor      = taskSettings.CaptureSettings.ScreenRecordShowCursor
                        };

                        Screenshot screenshot    = TaskHelpers.GetScreenshot(taskSettings);
                        screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

                        screenRecorder = new ScreenRecorder(outputType, options, screenshot, captureRectangle);
                        screenRecorder.RecordingStarted += () => recordForm.ChangeState(ScreenRecordState.AfterRecordingStart);
                        recordForm.ChangeState(ScreenRecordState.AfterStart);
                        screenRecorder.StartRecording();

                        if (recordForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        recordForm.ChangeState(ScreenRecordState.AfterStop);

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.EncodingProgressChanged += progress => recordForm.ChangeStateProgress(progress);
                            GIFQuality gifQuality = taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.OctreeQuantizer ? GIFQuality.Bit8 : GIFQuality.Default;
                            screenRecorder.SaveAsGIF(path, gifQuality);
                        }
                        else if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder  = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            string sourceFilePath = path;
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (recordForm != null)
                    {
                        recordForm.InvokeSafe(() =>
                        {
                            recordForm.Close();
                            recordForm.Dispose();
                            recordForm = null;
                        });
                    }

                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI ||
                             (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName))
                {
                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
コード例 #28
0
ファイル: CaptureRegion.cs プロジェクト: AlexxNica/ShareX
        protected ImageInfo ExecuteRegionCaptureLight(TaskSettings taskSettings)
        {
            Image img = null;

            using (RegionCaptureLightForm rectangleLight = new RegionCaptureLightForm(TaskHelpers.GetScreenshot(taskSettings)))
            {
                if (rectangleLight.ShowDialog() == DialogResult.OK)
                {
                    img = rectangleLight.GetAreaImage();

                    if (img != null)
                    {
                        lastRegionCaptureType = RegionCaptureType.Light;
                    }
                }
            }

            return(new ImageInfo(img));
        }
コード例 #29
0
        private void ExecuteClickAction(ThumbnailViewClickAction clickAction, TaskInfo info)
        {
            if (info != null)
            {
                string filePath = info.FilePath;

                switch (clickAction)
                {
                case ThumbnailViewClickAction.Default:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                    {
                        if (FileHelpers.IsImageFile(filePath))
                        {
                            pbThumbnail.Enabled = false;

                            try
                            {
                                OnImagePreviewRequested();
                            }
                            finally
                            {
                                pbThumbnail.Enabled = true;
                            }
                        }
                        else if (FileHelpers.IsTextFile(filePath) || FileHelpers.IsVideoFile(filePath) ||
                                 MessageBox.Show("Would you like to open this file?" + "\r\n\r\n" + filePath,
                                                 Resources.ShareXConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            FileHelpers.OpenFile(filePath);
                        }
                    }
                    break;

                case ThumbnailViewClickAction.OpenImageViewer:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && FileHelpers.IsImageFile(filePath))
                    {
                        pbThumbnail.Enabled = false;

                        try
                        {
                            OnImagePreviewRequested();
                        }
                        finally
                        {
                            pbThumbnail.Enabled = true;
                        }
                    }
                    break;

                case ThumbnailViewClickAction.OpenFile:
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        FileHelpers.OpenFile(filePath);
                    }
                    break;

                case ThumbnailViewClickAction.OpenFolder:
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        FileHelpers.OpenFolderWithFile(filePath);
                    }
                    break;

                case ThumbnailViewClickAction.OpenURL:
                    if (info.Result != null)
                    {
                        URLHelpers.OpenURL(info.Result.ToString());
                    }
                    break;

                case ThumbnailViewClickAction.EditImage:
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath) && FileHelpers.IsImageFile(filePath))
                    {
                        TaskHelpers.AnnotateImageFromFile(filePath);
                    }
                    break;
                }
            }
        }
コード例 #30
0
ファイル: TaskSettingsForm.cs プロジェクト: rushil33d/ShareX
        public TaskSettingsForm(TaskSettings hotkeySetting, bool isDefault = false)
        {
            InitializeComponent();
            Icon         = ShareXResources.Icon;
            TaskSettings = hotkeySetting;
            IsDefault    = isDefault;

            if (IsDefault)
            {
                Text = Application.ProductName + " - Task settings";
                tcHotkeySettings.TabPages.Remove(tpTask);
                chkUseDefaultGeneralSettings.Visible    = chkUseDefaultImageSettings.Visible = chkUseDefaultCaptureSettings.Visible = chkUseDefaultActions.Visible =
                    chkUseDefaultUploadSettings.Visible = chkUseDefaultIndexerSettings.Visible = chkUseDefaultAdvancedSettings.Visible = false;
                panelGeneral.BorderStyle = BorderStyle.None;
            }
            else
            {
                Text = Application.ProductName + " - Task settings for " + TaskSettings;
                tbDescription.Text = TaskSettings.Description;
                cbUseDefaultAfterCaptureSettings.Checked = TaskSettings.UseDefaultAfterCaptureJob;
                cbUseDefaultAfterUploadSettings.Checked  = TaskSettings.UseDefaultAfterUploadJob;
                cbUseDefaultDestinationSettings.Checked  = TaskSettings.UseDefaultDestinations;
                chkUseDefaultGeneralSettings.Checked     = TaskSettings.UseDefaultGeneralSettings;
                chkUseDefaultImageSettings.Checked       = TaskSettings.UseDefaultImageSettings;
                chkUseDefaultCaptureSettings.Checked     = TaskSettings.UseDefaultCaptureSettings;
                chkUseDefaultActions.Checked             = TaskSettings.UseDefaultActions;
                chkUseDefaultUploadSettings.Checked      = TaskSettings.UseDefaultUploadSettings;
                chkUseDefaultIndexerSettings.Checked     = TaskSettings.UseDefaultIndexerSettings;
                chkUseDefaultAdvancedSettings.Checked    = TaskSettings.UseDefaultAdvancedSettings;
            }

            AddEnumItemsContextMenu <HotkeyType>(x => TaskSettings.Job = x, cmsTask);
            AddMultiEnumItemsContextMenu <AfterCaptureTasks>(x => TaskSettings.AfterCaptureJob = TaskSettings.AfterCaptureJob.Swap(x), cmsAfterCapture);
            AddMultiEnumItemsContextMenu <AfterUploadTasks>(x => TaskSettings.AfterUploadJob   = TaskSettings.AfterUploadJob.Swap(x), cmsAfterUpload);
            AddEnumItems <ImageDestination>(x => TaskSettings.ImageDestination = x, tsmiImageUploaders);
            tsmiImageFileUploaders = (ToolStripDropDownItem)tsmiImageUploaders.DropDownItems[tsmiImageUploaders.DropDownItems.Count - 1];
            AddEnumItems <FileDestination>(x => TaskSettings.ImageFileDestination = x, tsmiImageFileUploaders);
            AddEnumItems <TextDestination>(x => TaskSettings.TextDestination      = x, tsmiTextUploaders);
            tsmiTextFileUploaders = (ToolStripDropDownItem)tsmiTextUploaders.DropDownItems[tsmiTextUploaders.DropDownItems.Count - 1];
            AddEnumItems <FileDestination>(x => TaskSettings.TextFileDestination      = x, tsmiTextFileUploaders);
            AddEnumItems <FileDestination>(x => TaskSettings.FileDestination          = x, tsmiFileUploaders);
            AddEnumItems <UrlShortenerType>(x => TaskSettings.URLShortenerDestination = x, tsmiURLShorteners);
            AddEnumItems <SocialNetworkingService>(x => TaskSettings.SocialNetworkingServiceDestination = x, tsmiSocialServices);

            SetEnumCheckedContextMenu(TaskSettings.Job, cmsTask);
            SetMultiEnumCheckedContextMenu(TaskSettings.AfterCaptureJob, cmsAfterCapture);
            SetMultiEnumCheckedContextMenu(TaskSettings.AfterUploadJob, cmsAfterUpload);
            SetEnumChecked(TaskSettings.ImageDestination, tsmiImageUploaders);
            SetEnumChecked(TaskSettings.ImageFileDestination, tsmiImageFileUploaders);
            SetEnumChecked(TaskSettings.TextDestination, tsmiTextUploaders);
            SetEnumChecked(TaskSettings.TextFileDestination, tsmiTextFileUploaders);
            SetEnumChecked(TaskSettings.FileDestination, tsmiFileUploaders);
            SetEnumChecked(TaskSettings.URLShortenerDestination, tsmiURLShorteners);
            SetEnumChecked(TaskSettings.SocialNetworkingServiceDestination, tsmiSocialServices);

            // FTP
            if (Program.UploadersConfig != null && Program.UploadersConfig.FTPAccountList.Count > 1)
            {
                chkOverrideFTP.Checked = TaskSettings.OverrideFTP;
                cboFTPaccounts.Items.Clear();
                cboFTPaccounts.Items.AddRange(Program.UploadersConfig.FTPAccountList.ToArray());
                cboFTPaccounts.SelectedIndex = TaskSettings.FTPIndex.BetweenOrDefault(0, Program.UploadersConfig.FTPAccountList.Count - 1);
            }

            UpdateDestinationStates();
            UpdateUploaderMenuNames();

            // General
            cbPlaySoundAfterCapture.Checked     = TaskSettings.GeneralSettings.PlaySoundAfterCapture;
            cbShowAfterCaptureTasksForm.Checked = TaskSettings.GeneralSettings.ShowAfterCaptureTasksForm;
            chkShowBeforeUploadForm.Checked     = TaskSettings.GeneralSettings.ShowBeforeUploadForm;
            cbPlaySoundAfterUpload.Checked      = TaskSettings.GeneralSettings.PlaySoundAfterUpload;
            chkShowAfterUploadForm.Checked      = TaskSettings.GeneralSettings.ShowAfterUploadForm;
            cboPopUpNotification.Items.Clear();
            cboPopUpNotification.Items.AddRange(Helpers.GetEnumDescriptions <PopUpNotificationType>());
            cboPopUpNotification.SelectedIndex = (int)TaskSettings.GeneralSettings.PopUpNotification;
            cbHistorySave.Checked = TaskSettings.GeneralSettings.SaveHistory;

            // Image - General
            cbImageFormat.SelectedIndex     = (int)TaskSettings.ImageSettings.ImageFormat;
            nudImageJPEGQuality.Value       = TaskSettings.ImageSettings.ImageJPEGQuality;
            cbImageGIFQuality.SelectedIndex = (int)TaskSettings.ImageSettings.ImageGIFQuality;
            nudUseImageFormat2After.Value   = TaskSettings.ImageSettings.ImageSizeLimit;
            cbImageFormat2.SelectedIndex    = (int)TaskSettings.ImageSettings.ImageFormat2;
            cbImageFileExist.Items.Clear();
            cbImageFileExist.Items.AddRange(Helpers.GetEnumDescriptions <FileExistAction>());
            cbImageFileExist.SelectedIndex = (int)TaskSettings.ImageSettings.FileExistAction;

            // Image - Effects
            chkShowImageEffectsWindowAfterCapture.Checked = TaskSettings.ImageSettings.ShowImageEffectsWindowAfterCapture;
            cbImageEffectOnlyRegionCapture.Checked        = TaskSettings.ImageSettings.ImageEffectOnlyRegionCapture;

            // Image - Thumbnail
            nudThumbnailWidth.Value      = TaskSettings.ImageSettings.ThumbnailWidth;
            nudThumbnailHeight.Value     = TaskSettings.ImageSettings.ThumbnailHeight;
            txtThumbnailName.Text        = TaskSettings.ImageSettings.ThumbnailName;
            lblThumbnailNamePreview.Text = "ImageName" + TaskSettings.ImageSettings.ThumbnailName + ".jpg";
            cbThumbnailIfSmaller.Checked = TaskSettings.ImageSettings.ThumbnailCheckSize;

            // Capture
            cbShowCursor.Checked             = TaskSettings.CaptureSettings.ShowCursor;
            cbCaptureTransparent.Checked     = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Enabled          = TaskSettings.CaptureSettings.CaptureTransparent;
            cbCaptureShadow.Checked          = TaskSettings.CaptureSettings.CaptureShadow;
            nudCaptureShadowOffset.Value     = TaskSettings.CaptureSettings.CaptureShadowOffset;
            cbCaptureClientArea.Checked      = TaskSettings.CaptureSettings.CaptureClientArea;
            cbScreenshotDelay.Checked        = TaskSettings.CaptureSettings.IsDelayScreenshot;
            nudScreenshotDelay.Value         = TaskSettings.CaptureSettings.DelayScreenshot;
            cbCaptureAutoHideTaskbar.Checked = TaskSettings.CaptureSettings.CaptureAutoHideTaskbar;

            if (TaskSettings.CaptureSettings.SurfaceOptions == null)
            {
                TaskSettings.CaptureSettings.SurfaceOptions = new SurfaceOptions();
            }
            pgShapesCapture.SelectedObject = TaskSettings.CaptureSettings.SurfaceOptions;

            // Capture / Screen recorder
            cbScreenRecorderOutput.Items.AddRange(Helpers.GetEnumDescriptions <ScreenRecordOutput>());
            cbScreenRecorderOutput.SelectedIndex = (int)TaskSettings.CaptureSettings.ScreenRecordOutput;
            chkRunScreencastCLI.Checked          = TaskSettings.CaptureSettings.RunScreencastCLI;
            UpdateVideoEncoders();

            nudGIFFPS.Value          = TaskSettings.CaptureSettings.GIFFPS;
            nudScreenRecordFPS.Value = TaskSettings.CaptureSettings.ScreenRecordFPS;
            cbScreenRecorderFixedDuration.Checked = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Enabled     = TaskSettings.CaptureSettings.ScreenRecordFixedDuration;
            nudScreenRecorderDuration.Value       = (decimal)TaskSettings.CaptureSettings.ScreenRecordDuration;
            nudScreenRecorderStartDelay.Value     = (decimal)TaskSettings.CaptureSettings.ScreenRecordStartDelay;

            // Actions
            TaskHelpers.AddDefaultExternalPrograms(TaskSettings);
            TaskSettings.ExternalPrograms.ForEach(x => AddFileAction(x));

            // Watch folders
            cbWatchFolderEnabled.Checked = TaskSettings.WatchFolderEnabled;

            if (TaskSettings.WatchFolderList == null)
            {
                TaskSettings.WatchFolderList = new List <WatchFolderSettings>();
            }
            else
            {
                foreach (WatchFolderSettings watchFolder in TaskSettings.WatchFolderList)
                {
                    AddWatchFolder(watchFolder);
                }
            }

            // Upload / Name pattern
            txtNameFormatPattern.Text             = TaskSettings.UploadSettings.NameFormatPattern;
            txtNameFormatPatternActiveWindow.Text = TaskSettings.UploadSettings.NameFormatPatternActiveWindow;
            NameParser.CreateCodesMenu(txtNameFormatPattern, ReplacementVariables.n);
            NameParser.CreateCodesMenu(txtNameFormatPatternActiveWindow, ReplacementVariables.n);
            cbFileUploadUseNamePattern.Checked = TaskSettings.UploadSettings.FileUploadUseNamePattern;

            // Upload / Clipboard upload
            chkClipboardUploadContents.Checked       = TaskSettings.UploadSettings.ClipboardUploadURLContents;
            cbClipboardUploadAutoDetectURL.Checked   = TaskSettings.UploadSettings.ClipboardUploadShortenURL;
            cbClipboardUploadAutoIndexFolder.Checked = TaskSettings.UploadSettings.ClipboardUploadAutoIndexFolder;

            // Indexer
            pgIndexerConfig.SelectedObject = TaskSettings.IndexerSettings;

            // Advanced
            pgTaskSettings.SelectedObject = TaskSettings.AdvancedSettings;

            UpdateDefaultSettingVisibility();
            loaded = true;
        }