private static WorkerTask DefaultWorkerTask()
        {
            WorkerTask tempTask = new WorkerTask(new Workflow("CLI"));

            foreach (int o in listOutputTypes)
            {
                tempTask.WorkflowConfig.DestConfig.Outputs.Add((OutputEnum)o);
            }
            if (tempTask.WorkflowConfig.DestConfig.Outputs.Count == 0)
            {
                tempTask.WorkflowConfig.DestConfig.Outputs.Add(OutputEnum.Clipboard);
                tempTask.WorkflowConfig.DestConfig.Outputs.Add(OutputEnum.LocalDisk);
            }

            if (clipboardContent > 0)
            {
                tempTask.WorkflowConfig.DestConfig.TaskClipboardContent.Add((ClipboardContentEnum)clipboardContent);
            }
            else
            {
                tempTask.WorkflowConfig.DestConfig.TaskClipboardContent.Add(ClipboardContentEnum.Data);
            }

            foreach (int ut in listImageHosts)
            {
                if (bVerbose) Console.WriteLine(string.Format("Added {0}", ((ImageDestination)ut).GetDescription()));
                tempTask.WorkflowConfig.DestConfig.ImageUploaders.Add((ImageDestination)ut);
            }
            foreach (int ut in listFileHosts)
            {
                if (bVerbose) Console.WriteLine(string.Format("Added {0}", ((FileDestination)ut).GetDescription()));
                tempTask.WorkflowConfig.DestConfig.FileUploaders.Add((FileDestination)ut);
            }
            return tempTask;
        }
        protected virtual void Initialize(WorkerTask task, WorkflowWizardGUIOptions gui)
        {
            if (task != null)
            {
                this.Config = task.WorkflowConfig;
                this.Text = Application.ProductName + " - Workflow - " + task.Info.Job.GetDescription();
            }
            else
            {
                this.Text = Application.ProductName;
            }

            tcMain.TabPages.Clear();
            tcMain.TabPages.Add(tpOutputs);

            if (gui != null)
            {
                gbTasks.Visible = false;
                this.MinimumSize = new System.Drawing.Size(this.Width - gbTasks.Width, this.Height);
                this.Width = this.MinimumSize.Width;
                this.GUI = gui;
            }
            if (task != null)
            {
                this.Task = task;
            }
        }
 private void DoJob(object sender, WorkerTask.JobLevel2 e)
 {
     EventJob(sender, e);
     if (Engine.conf.CloseQuickActions)
     {
         this.Close();
     }
 }
        public override WorkerTask CreateTask(WorkerTask.JobLevel2 job, TaskInfo tiCreateTask = null)
        {
            if (tiCreateTask == null) tiCreateTask = new TaskInfo();

            tiCreateTask.Job = job;

            WorkerTask createTask = new WorkerTask(CreateWorker(), tiCreateTask);

            return createTask;
        }
 public static Workflow GetProfile(WorkerTask.JobLevel2 job)
 {
     foreach (Workflow profile in ConfigWorkflow.Workflows98)
     {
         if (profile.Job == job)
         {
             return profile;
         }
     }
     return null;
 }
 private static void CaptureRectRegion(WorkerTask.JobLevel2 job2)
 {
     WorkerTask csTask = DefaultWorkerTask();
     csTask.StartWork(job2);
     if (csTask.IsNotCanceled())
     {
         csTask.PublishData();
         Console.WriteLine(csTask.ToErrorString());
         PostPublishTask(csTask);
     }
 }
        public void AddHistoryItem(WorkerTask task)
        {
            if (Engine.ConfigOptions.HistorySave)
            {
                foreach (UploadResult ur in task.UploadResults)
                {
                    HistoryManager.AddHistoryItemAsync(Engine.HistoryPath, task.GenerateHistoryItem(ur));
                }
            }

            Adapter.AddRecentItem(task.Info.LocalFilePath);
        }
 public DestOptions(WorkerTask task)
 {
     InitializeComponent();
     this.Task = task;
     btnBrowse.Enabled = !task.States.Contains(WorkerTask.TaskState.ThreadMode);
     txtFilePath.Enabled = task.Job2 != WorkerTask.JobLevel2.UploadFromExplorer;
     DestSelectorHelper dsh = new DestSelectorHelper(ucDestOptions);
     dsh.AddEnumOutputsWithConfigSettings(Task.WorkflowConfig.DestConfig.Outputs);
     dsh.AddEnumClipboardContentWithRuntimeSettings(Task.WorkflowConfig.DestConfig.TaskClipboardContent);
     dsh.AddEnumLinkFormatWithRuntimeSettings(Task.WorkflowConfig.DestConfig.LinkFormat.Cast<int>().ToList());
     dsh.AddEnumDestImageToMenuWithRuntimeSettings(Task.WorkflowConfig.DestConfig.ImageUploaders.Cast<int>().ToList());
     dsh.AddEnumDestTextToMenuWithRuntimeSettings(Task.WorkflowConfig.DestConfig.TextUploaders.Cast<int>().ToList());
     dsh.AddEnumDestFileToMenuWithRuntimeSettings(Task.WorkflowConfig.DestConfig.FileUploaders.Cast<int>().ToList());
     dsh.AddEnumDestLinkToMenuWithRuntimeSettings(Task.WorkflowConfig.DestConfig.LinkUploaders.Cast<int>().ToList());
 }
 public void ClickBalloonTip(WorkerTask task)
 {
     string cbString;
     if (task != null)
     {
         switch (task.Job2)
         {
             case WorkerTask.JobLevel2.Translate:
                 cbString = task.TranslationInfo.Result;
                 if (!string.IsNullOrEmpty(cbString))
                 {
                     Clipboard.SetText(cbString); // ok
                 }
                 break;
             default:
                 if (task.UploadResults.Count > 0)
                 {
                     foreach (UploadResult ur in task.UploadResults)
                     {
                         if (!string.IsNullOrEmpty(ur.URL))
                         {
                             try
                             {
                                 ThreadPool.QueueUserWorkItem(x => Process.Start(ur.URL));
                                 break;
                             }
                             catch (Exception ex)
                             {
                                 DebugHelper.WriteException(ex);
                             }
                         }
                     }
                 }
                 else if (File.Exists(task.Info.LocalFilePath))
                 {
                     Process.Start(task.Info.LocalFilePath);
                 }
                 break;
         }
     }
 }
        public JBirdWorkflowWizard(WorkerTask task = null, Workflow workflow = null, WorkflowWizardGUIOptions gui = null)
        {
            base.InitializeComponent();
            InitializeComponent();
            base.Initialize(task, gui);

            HotkeyManager tempHotkeyMgr;
            this.Task = new WorkerTask(workflow);
            this.Config = workflow;
            Program.HotkeyMgrs.TryGetValue(this.Config.ID, out tempHotkeyMgr);
            if (tempHotkeyMgr != null)
            {
                hmcHotkeys.PrepareHotkeys(tempHotkeyMgr);
            }
            else
            {
                HotkeyManager hm = new HotkeyManager(Program.CoreUI, ZAppType.JBird);
                hm.AddHotkey(JBirdHotkey.Workflow, Config.Hotkey, Config.Start);
                hmcHotkeys.PrepareHotkeys(hm);
            }
        }
        public static void Test()
        {
            #region Image Uploaders

            foreach (ImageDestType uploader in Enum.GetValues(typeof(UploadersLib.ImageDestType)))
            {
                Console.WriteLine("Starting: " + uploader.GetDescription());
                WorkerTask task = new WorkerTask(WorkerTask.Jobs.UPLOAD_IMAGE);
                task.MyImageUploader = uploader;
                task.UpdateLocalFilePath(Tester.TestFile);
                if (uploader != ImageDestType.TWITSNAPS)
                {
                    new TaskManager(ref task).UploadImage();
                }
            }

            #endregion

            #region Text Uploaders
            /*
            foreach (TextDestType uploader in Enum.GetValues(typeof(UploadersLib.TextDestType)))
            {
                WorkerTask task = new WorkerTask(WorkerTask.Jobs.UploadFromClipboard);

                task.MyText = TextInfo.FromString(uploader);
                task.MakeTinyURL = false; // preventing Error: TinyURL redirects to a TinyURL.
                task.MyTextUploader = uploader;
                task.RunWorker();
            }
            */
            #endregion

            #region File Uploaders

            #endregion

            #region URL Shorteners

            #endregion
        }
 public virtual WorkerTask CreateTask(WorkerTask.JobLevel2 job, TaskInfo tiCreateTask = null)
 {
     return new WorkerTask(Engine.ConfigWorkflow);
 }
        public string ShowBalloonTip(WorkerTask task)
        {
            StringBuilder sbMsg = new StringBuilder();
            ToolTipIcon tti = ToolTipIcon.Info;

            if (task.Job2 == WorkerTask.JobLevel2.Translate)
            {
                sbMsg.AppendLine(task.TranslationInfo.SourceLanguage + " -> " + task.TranslationInfo.TargetLanguage);
                sbMsg.AppendLine("Text: " + task.TranslationInfo.Text);
                sbMsg.AppendLine("Result: " + task.TranslationInfo.Result);
            }
            else
            {
                sbMsg.AppendLine("Name: " + task.GetDescription());

                switch (task.Job1)
                {
                    case EDataType.Text:
                        string dest = string.Empty;
                        switch (task.Job3)
                        {
                            case WorkerTask.JobLevel3.ShortenURL:
                                dest = task.WorkflowConfig.DestConfig.ToStringLinkUploaders();
                                break;
                            default:
                                dest = task.WorkflowConfig.DestConfig.ToStringTextUploaders();
                                break;
                        }
                        sbMsg.AppendLine(string.Format("Destination: {0}", dest));
                        break;
                    default:
                        sbMsg.Append("Outputs: ");
                        sbMsg.AppendLine(task.WorkflowConfig.DestConfig.ToStringOutputs());
                        break;
                }

                foreach (UploadResult ur in task.UploadResults)
                {
                    if (!string.IsNullOrEmpty(ur.URL))
                    {
                        sbMsg.AppendLine(ur.URL);
                        break;
                    }
                }

                if (task.UploadResults.Count == 0 && task.IsError)
                {
                    tti = ToolTipIcon.Warning;
                    sbMsg.AppendLine("Warnings: ");
                    foreach (string err in task.Errors)
                    {
                        sbMsg.AppendLine(err);
                    }
                }

                if (Engine.ConfigOptions.ShowUploadDuration && task.UploadDuration > 0)
                {
                    sbMsg.AppendLine("Upload duration: " + task.UploadDuration + " ms");
                }
            }

            string message = sbMsg.ToString();

            if (!string.IsNullOrEmpty(message))
            {
                niTray.ShowBalloonTip(1000, Application.ProductName, message, tti);
            }

            return message;
        }
 private static void ChangeListViewItemStatus(WorkerTask wt)
 {
     if (ListViewControl != null)
     {
         ListViewItem lvi = ListViewControl.Items[wt.Id];
         lvi.SubItems[1].Text = wt.Status.GetDescription();
     }
 }
        /// <summary>
        /// Function to return the file path of a captured image. ImageFormat is based on length of the image.
        /// </summary>
        /// <param name="img">The actual image</param>
        /// <param name="filePath">The path to where the image will be saved</param>
        /// <returns>Returns the file path to a screenshot</returns>
        public static string SaveImage(ref WorkerTask task)
        {
            Image img = task.MyImage;
            string filePath = task.LocalFilePath;

            if (!string.IsNullOrEmpty(filePath))
            {
                img = ImageEffects.ApplySizeChanges(img);
                img = ImageEffects.ApplyScreenshotEffects(img);
                if (task.Job != WorkerTask.Jobs.UploadFromClipboard || !Engine.conf.WatermarkExcludeClipboardUpload)
                {
                    img = ImageEffects.ApplyWatermark(img);
                }

                long size = (long)Engine.conf.SwitchAfter * 1024;

                MemoryStream ms = null;

                GraphicsMgr.SaveImageToMemoryStreamOptions opt = new GraphicsMgr.SaveImageToMemoryStreamOptions(img, Engine.zImageFileFormat);
                opt.GIFQuality = Engine.conf.GIFQuality;
                opt.JpgQuality = Engine.conf.JpgQuality;
                opt.MakeJPGBackgroundWhite = Engine.conf.MakeJPGBackgroundWhite;

                try
                {
                    ms = GraphicsMgr.SaveImageToMemoryStream(opt);

                    if (ms.Length > size && size != 0)
                    {
                        opt.MyImageFileFormat = Engine.zImageFileFormatSwitch;
                        ms = GraphicsMgr.SaveImageToMemoryStream(opt);
                        filePath = Path.ChangeExtension(filePath, Engine.zImageFileFormatSwitch.Extension);
                    }

                    if (!Directory.Exists(Path.GetDirectoryName(filePath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    }

                    int retry = 3;
                    while (retry > 0 && !File.Exists(filePath))
                    {
                        using (FileStream fi = File.Create(filePath))
                        {
                            if (retry < 3) { System.Threading.Thread.Sleep(1000); }
                            FileSystem.AppendDebug(string.Format("Writing image {0}x{1} to {2}", img.Width, img.Height, filePath));
                            ms.WriteTo(fi);
                            retry--;
                        }
                    }
                }
                catch (Exception ex)
                {
                    FileSystem.AppendDebug("Error while saving image", ex);
                }
                finally
                {
                    if (ms != null) ms.Dispose();
                }
            }

            task.UpdateLocalFilePath(filePath);
            return filePath;
        }
        private static void CreateListViewItem(WorkerTask wt)
        {
            if (ListViewControl != null)
            {
                DebugHelper.WriteLine("Upload in queue. ID: {0}, Job: {1}, Type: {2}, Host: {3}",
                    wt.Id, wt.Job1, wt.Job2, wt.GetDestinationName());

                ListViewItem lvi = new ListViewItem();
                lvi.Text = wt.Info.FileName;
                lvi.SubItems.Add("In queue");
                lvi.SubItems.Add(string.Empty);
                lvi.SubItems.Add(string.Empty);
                lvi.SubItems.Add(string.Empty);
                lvi.SubItems.Add(string.Empty);
                lvi.SubItems.Add(wt.GetDescription());
                lvi.SubItems.Add(wt.GetDestinationName());
                lvi.SubItems.Add(string.Empty);
                lvi.BackColor = wt.Id % 2 == 0 ? Color.White : Color.WhiteSmoke;
                lvi.ImageIndex = 3;
                ListViewControl.Items.Add(lvi);
                lvi.EnsureVisible();
                ListViewControl.FillLastColumn();
            }
        }
 private static void StartUpload(WorkerTask task)
 {
     Tasks.Add(task);
     task.Id = Tasks.Count - 1;
     task.UploadPreparing += new WorkerTask.TaskEventHandler(task_UploadPreparing);
     task.UploadStarted += new WorkerTask.TaskEventHandler(task_UploadStarted);
     task.UploadProgressChanged2 += new WorkerTask.TaskEventHandler(task_UploadProgressChanged);
     task.UploadCompleted += new WorkerTask.TaskEventHandler(task_UploadCompleted);
     CreateListViewItem(task);
     // StartTasks();
 }
 private static void task_UploadProgressChanged(WorkerTask info)
 {
     if (ListViewControl != null)
     {
         ListViewItem lvi = ListViewControl.Items[info.Id];
         lvi.SubItems[2].Text = string.Format("{0:N0}%  {1:N0} KiB / {2:N0} KiB", info.Progress.Percentage,
             info.Progress.Position / 1024, info.Progress.Length / 1024);
         lvi.SubItems[3].Text = string.Format("{0:N0} kB/s", info.Progress.Speed);
         lvi.SubItems[4].Text = string.Format("{0:00}:{1:00}", info.Progress.Elapsed.Minutes, info.Progress.Elapsed.Seconds);
         lvi.SubItems[5].Text = string.Format("{0:00}:{1:00}", info.Progress.Remaining.Minutes, info.Progress.Remaining.Seconds);
     }
 }
 internal void EventJobs(object sender, WorkerTask.JobLevel2 job)
 {
     WorkerTask task = CreateTask(job);
     switch (job)
     {
         case WorkerTask.JobLevel2.CaptureEntireScreen:
             CaptureEntireScreen();
             break;
         case WorkerTask.JobLevel2.CaptureActiveWindow:
             CaptureActiveWindow();
             break;
         case WorkerTask.JobLevel2.CaptureSelectedWindow:
             CaptureSelectedWindow();
             break;
         case WorkerTask.JobLevel2.CaptureRectRegion:
             CaptureRectRegion();
             break;
         case WorkerTask.JobLevel2.CaptureLastCroppedWindow:
             CaptureRectRegionLast();
             break;
         case WorkerTask.JobLevel2.AutoCapture:
             ShowAutoCapture();
             break;
         case WorkerTask.JobLevel2.UploadFromClipboard:
             UploadUsingClipboardOrGoogleTranslate();
             break;
         case WorkerTask.JobLevel2.UploadFromExplorer:
             ShowDropWindow();
             break;
         case WorkerTask.JobLevel2.Translate:
             StartWorkerTranslator();
             break;
         case WorkerTask.JobLevel2.ScreenColorPicker:
             ShowScreenColorPicker();
             break;
     }
 }
        private static void task_UploadCompleted(WorkerTask task)
        {
            try
            {
                if (ListViewControl != null && task != null && task.Result != null)
                {
                    ListViewItem lvi = ListViewControl.Items[task.Id];
                    lvi.Tag = task.Result;

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

                        DebugHelper.WriteLine("Upload failed. ID: {0}, Filename: {1}, Errors:\r\n{2}", task.Id, task.Info.FileName, errors);

                        lvi.SubItems[1].Text = "Error";
                        lvi.SubItems[8].Text = string.Empty;
                        lvi.ImageIndex = 1;

                        if (Engine.ConfigOptions.CompleteSound)
                        {
                            SystemSounds.Asterisk.Play();
                        }
                    }
                    else
                    {
                        DebugHelper.WriteLine("Upload completed. ID: {0}, Filename: {1}, URL: {2}, Duration: {3}ms", task.Id, task.Info.FileName,
                            task.Result.URL, (int)task.UploadDuration);

                        lvi.SubItems[1].Text = task.Status.GetDescription();
                        lvi.ImageIndex = 2;

                        if (!string.IsNullOrEmpty(task.Result.URL))
                        {
                            string url = string.IsNullOrEmpty(task.Result.ShortenedURL) ? task.Result.URL : task.Result.ShortenedURL;

                            lvi.SubItems[8].Text = url;

                            if (Engine.ConfigWorkflow.ClipboardOverwrite)
                            {
                                ZAppHelper.CopyTextSafely(url);
                            }

                            if (Engine.ConfigOptions.HistorySave)
                            {
                                HistoryManager.AddHistoryItemAsync(Engine.HistoryPath, task.GenerateHistoryItem());
                            }
                        }

                        if (Engine.ConfigOptions.CompleteSound)
                        {
                            SystemSounds.Exclamation.Play();
                        }
                    }

                    lvi.EnsureVisible();
                }
            }
            finally
            {
                StartTasks();
                //  UpdateTrayIcon();
            }
        }
        /// <summary>
        /// Worker for Screenshots: Active Window, Crop, Entire Screen
        /// </summary>
        /// <param name="job">Job Type</param>
        public void RunWorkerAsync(WorkerTask screenshotTask)
        {
            if (screenshotTask == null) return;
            if (screenshotTask.States.Contains(WorkerTask.TaskState.CancellationPending))
            {
                PostWorkerTasks();
                return;
            }

            screenshotTask.WasToTakeScreenshot = true;
            // the last point before the task enters background
            if (screenshotTask.TempImage != null)
            {
                pbPreview.LoadImage(screenshotTask.TempImage);
                screenshotTask.RunWorker();
            }
            else
            {
                screenshotTask.States.Add(WorkerTask.TaskState.CancellationPending);
                PostWorkerTasks();
            }
        }
        /// <summary>
        /// Sets Clipboard text and returns the content
        /// </summary>
        /// <returns></returns>
        public static string SetClipboardText(WorkerTask task, bool showDialog)
        {
            string clipboardText = "";

            switch (task.JobCategory)
            {
                case JobCategoryType.PICTURES:
                case JobCategoryType.SCREENSHOTS:
                case JobCategoryType.BINARY:
                    ScreenshotsHistory = task.LinkManager;
                    if (GraphicsMgr.IsValidImage(task.LocalFilePath))
                    {
                        if (Engine.conf.ShowClipboardModeChooser || showDialog)
                        {
                            ClipboardOptions cmp = new ClipboardOptions(task);
                            cmp.Icon = Resources.zss_main;
                            if (showDialog) { cmp.ShowDialog(); } else { cmp.Show(); }
                        }

                        if (task.MyImageUploader == ImageDestType.FILE)
                        {
                            clipboardText = task.LocalFilePath;
                        }
                        else
                        {
                            clipboardText = ScreenshotsHistory.GetUrlByType(Engine.conf.ClipboardUriMode).ToString().Trim();
                            if (task.MakeTinyURL)
                            {
                                string tinyUrl = ScreenshotsHistory.GetUrlByType(ClipboardUriType.FULL_TINYURL);
                                if (!string.IsNullOrEmpty(tinyUrl))
                                {
                                    clipboardText = tinyUrl.Trim();
                                }
                            }
                        }
                    }
                    break;
                case JobCategoryType.TEXT:
                    switch (task.Job)
                    {
                        case WorkerTask.Jobs.LANGUAGE_TRANSLATOR:
                            if (null != task.TranslationInfo)
                            {
                                clipboardText = task.TranslationInfo.Result.TranslatedText;
                            }
                            break;
                        default:
                            if (!string.IsNullOrEmpty(task.RemoteFilePath))
                            {
                                clipboardText = task.RemoteFilePath;
                            }
                            else if (null != task.MyText)
                            {
                                clipboardText = task.MyText.LocalString;
                            }
                            else
                            {
                                clipboardText = task.LocalFilePath;
                            }
                            break;
                    }
                    break;
            }

            // after all this the clipboard text can be null

            if (!string.IsNullOrEmpty(clipboardText))
            {
                Engine.ClipboardUnhook();
                FileSystem.AppendDebug("Setting Clipboard with URL: " + clipboardText);
                Clipboard.SetText(clipboardText);

                // optional deletion link
                string linkdel = ScreenshotsHistory.GetDeletionLink();
                if (!string.IsNullOrEmpty(linkdel))
                {
                    FileSystem.AppendDebug("Deletion Link: " + linkdel);
                }

                Engine.zClipboardText = clipboardText;
                Engine.ClipboardHook();
            }
            return clipboardText;
        }
        public override WorkerTask CreateTask(WorkerTask.JobLevel2 job, TaskInfo tiCreateTask = null)
        {
            DebugHelper.WriteLine(string.Format("Creating job: {0}", job));
            if (tiCreateTask == null) tiCreateTask = new TaskInfo();

            tiCreateTask.Job = job;
            tiCreateTask.DestConfig = GetDestConfig(ucDestOptions);
            if (job == WorkerTask.JobLevel2.CaptureRectRegionClipboard)
            {
                tiCreateTask.DestConfig.TaskClipboardContent.Clear();
                tiCreateTask.DestConfig.ImageUploaders.Clear();
                tiCreateTask.DestConfig.TaskClipboardContent.Add(ClipboardContentEnum.Data);
            }
            tiCreateTask.TrayIcon = this.niTray;

            WorkerTask createTask = new WorkerTask(CreateWorker(), tiCreateTask);

            switch (job)
            {
                case WorkerTask.JobLevel2.Translate:
                    Loader.MyGTGUI.btnTranslate.Enabled = false;
                    createTask.SetTranslationInfo(new GoogleTranslateInfo()
                    {
                        Text = Loader.MyGTGUI.txtTranslateText.Text,
                        SourceLanguage = Engine.ConfigGT.GoogleSourceLanguage,
                        TargetLanguage = Engine.ConfigGT.GoogleTargetLanguage
                    });

                    break;
            }

            return createTask;
        }
        private static void task_UploadStarted(WorkerTask task)
        {
            string status = string.Format("Upload started. ID: {0}, Filename: {1}", task.Id, task.Info.FileName);
            if (!string.IsNullOrEmpty(task.Info.LocalFilePath)) status += ", Filepath: " + task.Info.LocalFilePath;
            DebugHelper.WriteLine(status);

            ListViewItem lvi = ListViewControl.Items[task.Id];
            lvi.Text = task.Info.FileName;
            lvi.SubItems[1].Text = task.Status.GetDescription();
            lvi.ImageIndex = 0;
        }
 public WorkerTask CreateTask(Workflow workflow)
 {
     Engine.ConfigWorkflow = workflow;
     WorkerTask tempTask = new WorkerTask(CreateWorker(), workflow);
     return tempTask;
 }
 public WorkflowWizard(WorkerTask info = null, WorkflowWizardGUIOptions gui = null)
     : this()
 {
     Initialize(info, gui);
 }
 public void RetryTask(WorkerTask task)
 {
     task.Errors.Clear();
     task.MyWorker = CreateWorker();
     task.PublishData();
 }
 private static void task_UploadPreparing(WorkerTask info)
 {
     Engine.EngineLogger.WriteLine("Upload preparing. ID: {0}", info.Id);
     ChangeListViewItemStatus(info);
 }
        public ClipboardOptions(WorkerTask task)
        {
            InitializeComponent();

            if (task != null && task.UploadResults.Count > 0)
            {
                this.urTask = task;
                this.Text = task.GetDescription();
                this.pbPreview.LoadingImage = Resources.Loading;
                foreach (UploadResult ur in task.UploadResults)
                {
                    string path = File.Exists(ur.LocalFilePath) ? ur.LocalFilePath : ur.URL;

                    if (ZAppHelper.IsImageFile(path) && (File.Exists(ur.LocalFilePath) || !string.IsNullOrEmpty(ur.URL)))
                    {
                        this.pbPreview.LoadImage(task.Info.LocalFilePath, ur.URL);
                        break;
                    }
                    else if (task.TempImage != null)
                    {
                        this.pbPreview.LoadImage(task.TempImage);
                    }
                }

                int count = 0;
                foreach (UploadResult ur in task.UploadResults)
                {
                    TreeNode tnUploadResult = new TreeNode(ur.Host);

                    foreach (LinkFormatEnum type in Enum.GetValues(typeof(LinkFormatEnum)))
                    {
                        string url = ur.GetUrlByType(type, ur.URL);
                        if (!string.IsNullOrEmpty(url))
                        {
                            if (type == LinkFormatEnum.FULL)
                            {
                                this.longUrl = url;
                            }
                            TreeNode tnLink = new TreeNode(type.GetDescription());
                            tnLink.Nodes.Add(url);
                            tnUploadResult.Nodes.Add(tnLink);
                            count++;
                        }
                    }

                    tvLinks.Nodes.Add(tnUploadResult);
                }

                if (!string.IsNullOrEmpty(task.OCRText) && tvLinks.Nodes.Count > 0)
                {
                    TreeNode tnOcr = new TreeNode(ClipboardContentEnum.OCR.GetDescription());
                    tnOcr.Nodes.Add(task.OCRText);
                    tvLinks.Nodes[0].Nodes.Add(tnOcr);
                }

                tvLinks.ExpandAll();
                if (tvLinks.Nodes.Count > 0 && tvLinks.Nodes[0].Nodes.Count > 0)
                {
                    tvLinks.SelectedNode = tvLinks.Nodes[0].Nodes[0].Nodes[0];
                }

                Button btnCopyLink = new Button();
                btnCopyLink.Text = "Copy &Text";
                btnCopyLink.AutoSize = true;
                btnCopyLink.Click += new EventHandler(btnCopyLink_Click);
                flpButtons.Controls.Add(btnCopyLink);

                Button btnCopyImage = new Button();
                btnCopyImage.Text = "Copy &Image";
                btnCopyImage.AutoSize = true;
                btnCopyImage.Click += new EventHandler(btnCopyImage_Click);
                flpButtons.Controls.Add(btnCopyImage);

                this.MinimumSize = new Size(this.Width, this.Height);

                if (File.Exists(task.Info.LocalFilePath))
                {
                    Button btnOpenLocal = new Button();
                    btnOpenLocal.Text = "Open &Local file";
                    btnOpenLocal.AutoSize = true;
                    btnOpenLocal.Click += new EventHandler(btnOpenLocal_Click);
                    flpButtons.Controls.Add(btnOpenLocal);

                    Button btnDeleteClose = new Button();
                    btnDeleteClose.Text = "&Delete Local file and Close";
                    btnDeleteClose.AutoSize = true;
                    btnDeleteClose.Click += new EventHandler(btnDeleteClose_Click);
                    flpButtons.Controls.Add(btnDeleteClose);
                }

                if (!string.IsNullOrEmpty(longUrl))
                {
                    Button btnOpenRemote = new Button();
                    btnOpenRemote.Text = "Open &Remote file";
                    btnOpenRemote.AutoSize = true;
                    btnOpenRemote.Click += new EventHandler(btnOpenRemote_Click);
                    flpButtons.Controls.Add(btnOpenRemote);
                }

                Button btnClose = new Button();
                btnClose.Text = "&Close";
                btnClose.AutoSize = true;
                btnClose.Click += new EventHandler(btnClose_Click);
                flpButtons.Controls.Add(btnClose);

                this.AddResetTimerToButtons();
            }
        }
        public WorkerTask RetryUpload(WorkerTask task)
        {
            if (task.UploadResults.Count > 0 && task.Job2 != WorkerTask.JobLevel2.Translate)
            {
                if (!task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Data) &&
                    !task.WorkflowConfig.DestConfig.TaskClipboardContent.Contains(ClipboardContentEnum.Local) &&
                    string.IsNullOrEmpty(task.UploadResults[0].URL) && Engine.ConfigUI.ImageUploadRetryOnFail &&
                    task.States.Contains(WorkerTask.TaskState.RetryPending) && File.Exists(task.Info.LocalFilePath))
                {
                    WorkerTask task2 = CreateTask(WorkerTask.JobLevel2.UploadImage);
                    task2.SetImage(task.Info.LocalFilePath);
                    task2.States.Add(WorkerTask.TaskState.Finished); // we do not retry again

                    if (task.Job1 == EDataType.Image)
                    {
                        if (Engine.ConfigUI.ImageUploadRandomRetryOnFail)
                        {
                            List<ImageDestination> randomDest = new List<ImageDestination>() { ImageDestination.ImageShack, ImageDestination.TinyPic, ImageDestination.Imgur };
                            int r = Adapter.RandomNumber(3, 3 + randomDest.Count - 1);
                            while (task.WorkflowConfig.DestConfig.ImageUploaders.Contains((ImageDestination)r))
                            {
                                r = Adapter.RandomNumber(3, 3 + randomDest.Count - 1);
                            }
                            if (!task.WorkflowConfig.DestConfig.ImageUploaders.Contains((ImageDestination)r))
                            {
                                task.WorkflowConfig.DestConfig.ImageUploaders.Add((ImageDestination)r);
                            }
                        }
                        else
                        {
                            if (!task.WorkflowConfig.DestConfig.ImageUploaders.Contains(ImageDestination.TinyPic))
                            {
                                task.WorkflowConfig.DestConfig.ImageUploaders.Add((ImageDestination.TinyPic));
                            }
                            else if (!task.WorkflowConfig.DestConfig.ImageUploaders.Contains(ImageDestination.ImageShack))
                            {
                                task.WorkflowConfig.DestConfig.ImageUploaders.Add((ImageDestination.ImageShack));
                            }
                        }
                    }

                    task2.MyWorker.RunWorkerAsync(task2);
                    return task2;
                }
            }
            task.States.Add(WorkerTask.TaskState.Finished);
            return task;
        }