ShareX/ShareX/TaskHelpers.cs

617 lines
23 KiB
C#
Raw Normal View History

2013-11-03 23:53:49 +13:00
#region License Information (GPL v3)
/*
ShareX - A program that allows you to take screenshots and share any file type
2014-05-13 21:06:40 +12:00
Copyright (C) 2007-2014 ShareX Developers
2013-11-03 23:53:49 +13:00
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/
#endregion License Information (GPL v3)
using HelpersLib;
using ImageEffectsLib;
using ScreenCaptureLib;
2013-11-03 23:53:49 +13:00
using System.Collections.Generic;
2014-05-03 05:56:51 +12:00
using System.Diagnostics;
2013-11-03 23:53:49 +13:00
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Media;
using System.Windows.Forms;
using UploadersLib;
using UploadersLib.HelperClasses;
2013-11-03 23:53:49 +13:00
namespace ShareX
{
public static class TaskHelpers
{
private const int PropertyTagSoftwareUsed = 0x0131;
public static ImageData PrepareImage(Image img, TaskSettings taskSettings)
{
ImageData imageData = new ImageData();
imageData.ImageFormat = taskSettings.ImageSettings.ImageFormat;
2013-11-03 23:53:49 +13:00
if (taskSettings.ImageSettings.ImageFormat == EImageFormat.JPEG)
2013-11-03 23:53:49 +13:00
{
img = ImageHelpers.FillBackground(img, Color.White);
2013-11-03 23:53:49 +13:00
}
imageData.ImageStream = SaveImage(img, taskSettings.ImageSettings.ImageFormat, taskSettings);
2013-11-03 23:53:49 +13:00
int sizeLimit = taskSettings.ImageSettings.ImageSizeLimit * 1000;
2013-11-03 23:53:49 +13:00
if (taskSettings.ImageSettings.ImageFormat != taskSettings.ImageSettings.ImageFormat2 && sizeLimit > 0 && imageData.ImageStream.Length > sizeLimit)
2013-11-03 23:53:49 +13:00
{
if (taskSettings.ImageSettings.ImageFormat2 == EImageFormat.JPEG)
2013-11-03 23:53:49 +13:00
{
img = ImageHelpers.FillBackground(img, Color.White);
2013-11-03 23:53:49 +13:00
}
imageData.ImageStream = SaveImage(img, taskSettings.ImageSettings.ImageFormat2, taskSettings);
imageData.ImageFormat = taskSettings.ImageSettings.ImageFormat2;
2013-11-03 23:53:49 +13:00
}
return imageData;
}
public static string CreateThumbnail(Image img, string folder, string filename, TaskSettings taskSettings)
{
if ((taskSettings.ImageSettings.ThumbnailWidth > 0 || taskSettings.ImageSettings.ThumbnailHeight > 0) && (!taskSettings.ImageSettings.ThumbnailCheckSize ||
(img.Width > taskSettings.ImageSettings.ThumbnailWidth && img.Height > taskSettings.ImageSettings.ThumbnailHeight)))
{
string thumbnailFileName = Path.GetFileNameWithoutExtension(filename) + taskSettings.ImageSettings.ThumbnailName + ".jpg";
string thumbnailFilePath = TaskHelpers.CheckFilePath(folder, thumbnailFileName, taskSettings);
if (!string.IsNullOrEmpty(thumbnailFilePath))
{
Image thumbImage = null;
try
{
thumbImage = (Image)img.Clone();
thumbImage = new Resize
{
Width = taskSettings.ImageSettings.ThumbnailWidth,
Height = taskSettings.ImageSettings.ThumbnailHeight
}.Apply(thumbImage);
thumbImage = ImageHelpers.FillBackground(thumbImage, Color.White);
thumbImage.SaveJPG(thumbnailFilePath, 90);
return thumbnailFilePath;
}
finally
{
if (thumbImage != null)
{
thumbImage.Dispose();
}
}
}
}
return null;
}
2013-11-03 23:53:49 +13:00
public static MemoryStream SaveImage(Image img, EImageFormat imageFormat, TaskSettings taskSettings)
{
MemoryStream stream = new MemoryStream();
switch (imageFormat)
{
case EImageFormat.PNG:
img.Save(stream, ImageFormat.Png);
break;
case EImageFormat.JPEG:
img.SaveJPG(stream, taskSettings.ImageSettings.ImageJPEGQuality);
2013-11-03 23:53:49 +13:00
break;
case EImageFormat.GIF:
img.SaveGIF(stream, taskSettings.ImageSettings.ImageGIFQuality);
2013-11-03 23:53:49 +13:00
break;
case EImageFormat.BMP:
img.Save(stream, ImageFormat.Bmp);
break;
case EImageFormat.TIFF:
img.Save(stream, ImageFormat.Tiff);
break;
}
return stream;
}
public static string GetFilename(TaskSettings taskSettings, string extension = "")
{
NameParser nameParser = new NameParser(NameParserType.FileName)
{
AutoIncrementNumber = Program.Settings.NameParserAutoIncrementNumber,
MaxNameLength = taskSettings.AdvancedSettings.NamePatternMaxLength,
MaxTitleLength = taskSettings.AdvancedSettings.NamePatternMaxTitleLength
2013-11-03 23:53:49 +13:00
};
string filename = nameParser.Parse(taskSettings.UploadSettings.NameFormatPattern);
2013-11-03 23:53:49 +13:00
if (!string.IsNullOrEmpty(extension))
{
filename += "." + extension.TrimStart('.');
}
Program.Settings.NameParserAutoIncrementNumber = nameParser.AutoIncrementNumber;
return filename;
}
public static string GetImageFilename(TaskSettings taskSettings, Image image)
{
string filename;
NameParser nameParser = new NameParser(NameParserType.FileName)
{
Picture = image,
AutoIncrementNumber = Program.Settings.NameParserAutoIncrementNumber,
MaxNameLength = taskSettings.AdvancedSettings.NamePatternMaxLength,
MaxTitleLength = taskSettings.AdvancedSettings.NamePatternMaxTitleLength
};
2013-11-03 23:53:49 +13:00
ImageTag imageTag = image.Tag as ImageTag;
if (imageTag != null)
{
nameParser.WindowText = imageTag.ActiveWindowTitle;
nameParser.ProcessName = imageTag.ActiveProcessName;
2013-11-03 23:53:49 +13:00
}
if (string.IsNullOrEmpty(nameParser.WindowText))
{
filename = nameParser.Parse(taskSettings.UploadSettings.NameFormatPattern) + ".bmp";
2013-11-03 23:53:49 +13:00
}
else
{
filename = nameParser.Parse(taskSettings.UploadSettings.NameFormatPatternActiveWindow) + ".bmp";
2013-11-03 23:53:49 +13:00
}
Program.Settings.NameParserAutoIncrementNumber = nameParser.AutoIncrementNumber;
return filename;
}
public static void ShowResultNotifications(string notificationText, TaskSettings taskSettings, string filePath)
2013-11-03 23:53:49 +13:00
{
if (!taskSettings.AdvancedSettings.DisableNotifications)
2013-11-03 23:53:49 +13:00
{
if (!string.IsNullOrEmpty(notificationText))
2013-11-03 23:53:49 +13:00
{
switch (taskSettings.GeneralSettings.PopUpNotification)
{
case PopUpNotificationType.BalloonTip:
if (Program.MainForm.niTray.Visible)
{
Program.MainForm.niTray.Tag = notificationText;
Program.MainForm.niTray.ShowBalloonTip(5000, "ShareX - Task completed", notificationText, ToolTipIcon.Info);
}
break;
case PopUpNotificationType.ToastNotification:
NotificationFormConfig toastConfig = new NotificationFormConfig()
{
Action = taskSettings.AdvancedSettings.ToastWindowClickAction,
FilePath = filePath,
Text = "ShareX - Task completed\r\n" + notificationText,
URL = notificationText
};
NotificationForm.Show((int)(taskSettings.AdvancedSettings.ToastWindowDuration * 1000), taskSettings.AdvancedSettings.ToastWindowPlacement,
taskSettings.AdvancedSettings.ToastWindowSize, toastConfig);
break;
}
2013-11-03 23:53:49 +13:00
}
if (taskSettings.GeneralSettings.PlaySoundAfterUpload)
{
SystemSounds.Exclamation.Play();
}
}
}
public static bool ShowAfterCaptureForm(TaskSettings taskSettings, Image img = null)
{
if (taskSettings.GeneralSettings.ShowAfterCaptureTasksForm)
{
using (AfterCaptureForm afterCaptureForm = new AfterCaptureForm(img, taskSettings))
{
afterCaptureForm.ShowDialog();
switch (afterCaptureForm.Result)
{
case AfterCaptureFormResult.Continue:
taskSettings.AfterCaptureJob = afterCaptureForm.AfterCaptureTasks;
break;
case AfterCaptureFormResult.Copy:
taskSettings.AfterCaptureJob = AfterCaptureTasks.CopyImageToClipboard;
break;
case AfterCaptureFormResult.Cancel:
if (img != null) img.Dispose();
return false;
}
}
}
return true;
}
public static void AnnotateImage(string filePath)
{
AnnotateImage(null, filePath);
}
public static Image AnnotateImage(Image img, string imgPath)
2013-11-03 23:53:49 +13:00
{
return ImageHelpers.AnnotateImage(img, imgPath, !Program.IsSandbox, Program.PersonalPath,
2013-11-03 23:53:49 +13:00
x => Program.MainForm.InvokeSafe(() => ClipboardHelpers.CopyImage(x)),
2014-05-04 10:03:45 +12:00
x => Program.MainForm.InvokeSafe(() => UploadManager.RunImageTask(x)),
(x, filePath) => Program.MainForm.InvokeSafe(() => ImageHelpers.SaveImage(x, filePath)),
(x, filePath) =>
{
string newFilePath = null;
Program.MainForm.InvokeSafe(() => newFilePath = ImageHelpers.SaveImageFileDialog(x, filePath));
return newFilePath;
});
2013-11-03 23:53:49 +13:00
}
public static Image AddImageEffects(Image img, TaskSettings taskSettings)
{
if (taskSettings.ImageSettings.ShowImageEffectsWindowAfterCapture)
2013-11-03 23:53:49 +13:00
{
using (ImageEffectsForm imageEffectsForm = new ImageEffectsForm(img, taskSettings.ImageSettings.ImageEffects))
2013-11-03 23:53:49 +13:00
{
if (imageEffectsForm.ShowDialog() == DialogResult.OK)
{
taskSettings.ImageSettings.ImageEffects = imageEffectsForm.Effects;
2013-11-03 23:53:49 +13:00
}
}
}
using (img)
{
return ImageEffectManager.ApplyEffects(img, taskSettings.ImageSettings.ImageEffects);
2013-11-03 23:53:49 +13:00
}
}
public static void AddDefaultExternalPrograms(TaskSettings taskSettings)
{
if (taskSettings.ExternalPrograms == null)
{
taskSettings.ExternalPrograms = new List<ExternalProgram>();
}
AddExternalProgramFromRegistry(taskSettings, "Paint", "mspaint.exe");
AddExternalProgramFromRegistry(taskSettings, "Paint.NET", "PaintDotNet.exe");
AddExternalProgramFromRegistry(taskSettings, "Adobe Photoshop", "Photoshop.exe");
AddExternalProgramFromRegistry(taskSettings, "IrfanView", "i_view32.exe");
AddExternalProgramFromRegistry(taskSettings, "XnView", "xnview.exe");
AddExternalProgramFromFile(taskSettings, "OptiPNG", "optipng.exe");
}
private static void AddExternalProgramFromFile(TaskSettings taskSettings, string name, string filename, string args = "")
{
if (!taskSettings.ExternalPrograms.Exists(x => x.Name == name))
2013-11-03 23:53:49 +13:00
{
if (File.Exists(filename))
{
DebugHelper.WriteLine("Found program: " + filename);
taskSettings.ExternalPrograms.Add(new ExternalProgram(name, filename, args));
2013-11-03 23:53:49 +13:00
}
}
}
private static void AddExternalProgramFromRegistry(TaskSettings taskSettings, string name, string filename)
{
if (!taskSettings.ExternalPrograms.Exists(x => x.Name == name))
2013-11-03 23:53:49 +13:00
{
ExternalProgram externalProgram = RegistryHelpers.FindProgram(name, filename);
if (externalProgram != null)
{
taskSettings.ExternalPrograms.Add(externalProgram);
2013-11-03 23:53:49 +13:00
}
}
}
public static bool SelectRegion(out Rectangle rect)
{
using (RectangleRegion surface = new RectangleRegion())
{
surface.AreaManager.WindowCaptureMode = true;
surface.AreaManager.IncludeControls = true;
2013-11-03 23:53:49 +13:00
surface.Prepare();
surface.ShowDialog();
if (surface.Result == SurfaceResult.Region)
{
if (surface.AreaManager.IsCurrentAreaValid)
{
rect = CaptureHelpers.ClientToScreen(surface.AreaManager.CurrentArea);
return true;
}
}
else if (surface.Result == SurfaceResult.Fullscreen)
{
rect = CaptureHelpers.GetScreenBounds();
return true;
}
}
rect = Rectangle.Empty;
return false;
}
public static PointInfo SelectPointColor(SurfaceOptions surfaceOptions = null)
{
using (Image fullscreen = Screenshot.CaptureFullscreen())
using (RectangleRegion surface = new RectangleRegion(fullscreen))
{
if (surfaceOptions != null)
{
surface.Config = new SurfaceOptions
{
MagnifierPixelCount = surfaceOptions.MagnifierPixelCount,
MagnifierPixelSize = surfaceOptions.MagnifierPixelSize
};
}
surface.OneClickMode = true;
surface.Prepare();
surface.ShowDialog();
if (surface.Result == SurfaceResult.Region)
{
PointInfo pointInfo = new PointInfo();
pointInfo.Position = CaptureHelpers.ClientToScreen(surface.OneClickPosition);
pointInfo.Color = ((Bitmap)fullscreen).GetPixel(surface.OneClickPosition.X, surface.OneClickPosition.Y);
return pointInfo;
}
}
return null;
}
public static Icon GetProgressIcon(int percentage)
{
using (Bitmap bmp = new Bitmap(16, 16))
using (Graphics g = Graphics.FromImage(bmp))
{
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.Black);
int width = (int)(16 * (percentage / 100f));
if (width > 0)
{
using (Brush brush = new LinearGradientBrush(new Rectangle(0, 0, width, 16), Color.DarkBlue, Color.DodgerBlue, LinearGradientMode.Vertical))
{
g.FillRectangle(brush, 0, 0, width, 16);
}
}
2014-07-20 07:10:25 +12:00
using (Font font = new Font("Arial", 7, FontStyle.Bold))
2013-11-03 23:53:49 +13:00
using (StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
{
2014-07-20 07:10:25 +12:00
g.DrawString(percentage.ToString(), font, Brushes.White, 8, 8, sf);
2013-11-03 23:53:49 +13:00
}
2013-11-11 19:28:23 +13:00
g.DrawRectangleProper(Pens.WhiteSmoke, 0, 0, 16, 16);
2013-11-03 23:53:49 +13:00
return Icon.FromHandle(bmp.GetHicon());
}
}
public static UpdateChecker CheckUpdate()
{
UpdateChecker updateChecker = new GitHubUpdateChecker("ShareX", "ShareX");
updateChecker.Proxy = ProxyInfo.Current.GetWebProxy();
updateChecker.CheckUpdate();
// Fallback if GitHub API fails
if (updateChecker.UpdateInfo == null || updateChecker.UpdateInfo.Status == UpdateStatus.UpdateCheckFailed)
{
updateChecker = new XMLUpdateChecker("http://getsharex.com/Update.xml", "ShareX");
updateChecker.Proxy = ProxyInfo.Current.GetWebProxy();
updateChecker.CheckUpdate();
}
return updateChecker;
}
2014-03-13 22:13:02 +13:00
public static string CheckFilePath(string folder, string filename, TaskSettings taskSettings)
2014-03-13 22:13:02 +13:00
{
string filepath = Path.Combine(folder, filename);
2014-03-13 22:13:02 +13:00
if (File.Exists(filepath))
{
switch (taskSettings.ImageSettings.FileExistAction)
2014-03-13 22:13:02 +13:00
{
case FileExistAction.Ask:
using (FileExistForm form = new FileExistForm(filepath))
{
form.ShowDialog();
filepath = form.Filepath;
}
break;
case FileExistAction.UniqueName:
filepath = Helpers.GetUniqueFilePath(filepath);
break;
case FileExistAction.Cancel:
filepath = string.Empty;
break;
2014-03-13 22:13:02 +13:00
}
}
return filepath;
}
2013-11-03 23:53:49 +13:00
2014-05-03 05:56:51 +12:00
public static void OpenDropWindow()
{
2014-07-06 06:28:30 +12:00
DropForm.GetInstance(Program.Settings.DropSize, Program.Settings.DropOffset, Program.Settings.DropAlignment, Program.Settings.DropOpacity, Program.Settings.DropHoverOpacity).ShowActivate();
2014-05-03 05:56:51 +12:00
}
public static void DoScreenRecorder(TaskSettings taskSettings = null)
{
if (taskSettings == null) taskSettings = TaskSettings.GetDefaultTaskSettings();
ScreenRecordForm form = ScreenRecordForm.Instance;
if (form.IsRecording)
{
form.StopRecording();
}
else
{
form.StartRecording(taskSettings);
}
}
public static void OpenAutoCapture()
{
AutoCaptureForm.Instance.ShowActivate();
}
public static void StartAutoCapture()
{
if (!AutoCaptureForm.IsRunning)
{
AutoCaptureForm form = AutoCaptureForm.Instance;
form.Show();
form.Execute();
}
}
public static void OpenScreenColorPicker(TaskSettings taskSettings = null)
{
if (taskSettings == null) taskSettings = TaskSettings.GetDefaultTaskSettings();
new ScreenColorPicker(taskSettings).Show();
}
public static void OpenRuler()
{
using (Image fullscreen = Screenshot.CaptureFullscreen())
using (RectangleRegion surface = new RectangleRegion(fullscreen))
{
surface.RulerMode = true;
surface.Config.QuickCrop = false;
surface.Config.ShowInfo = true;
2014-05-03 05:56:51 +12:00
surface.Prepare();
surface.ShowDialog();
}
}
public static void OpenHashCheck()
{
new HashCheckForm().Show();
}
public static void OpenIndexFolder()
{
UploadManager.IndexFolder();
}
2014-07-17 18:58:17 +12:00
public static void OpenImageEditor(string filePath = null)
{
2014-07-17 18:58:17 +12:00
if (string.IsNullOrEmpty(filePath))
{
2014-07-17 18:58:17 +12:00
filePath = ImageHelpers.OpenImageFileDialog();
}
if (!string.IsNullOrEmpty(filePath))
{
TaskHelpers.AnnotateImage(filePath);
}
}
2014-05-03 05:56:51 +12:00
public static void OpenImageEffects()
{
string filePath = ImageHelpers.OpenImageFileDialog();
if (!string.IsNullOrEmpty(filePath))
{
Image img = ImageHelpers.LoadImage(filePath);
ImageEffectsForm form = new ImageEffectsForm(img);
form.EditorMode();
form.Show();
}
}
public static void OpenMonitorTest()
{
using (MonitorTestForm monitorTestForm = new MonitorTestForm())
{
monitorTestForm.ShowDialog();
}
}
public static void OpenDNSChanger()
{
try
{
string path = Path.Combine(Application.StartupPath, "DNSChanger.exe");
ProcessStartInfo psi = new ProcessStartInfo(path);
psi.UseShellExecute = true;
psi.Verb = "runas";
Process.Start(psi);
}
catch { }
}
2014-05-21 10:46:06 +12:00
public static void OpenQRCode()
{
new QRCodeForm().Show();
}
public static void TweetMessage()
{
TaskEx.Run(() =>
{
OAuthInfo twitterOAuth = Program.UploadersConfig.TwitterOAuthInfoList.ReturnIfValidIndex(Program.UploadersConfig.TwitterSelectedAccount);
if (twitterOAuth != null)
{
using (TwitterTweetForm twitter = new TwitterTweetForm(twitterOAuth))
{
if (twitter.ShowDialog() == DialogResult.OK && twitter.IsTweetSent)
{
if (Program.MainForm.niTray.Visible)
{
Program.MainForm.niTray.Tag = null;
Program.MainForm.niTray.ShowBalloonTip(5000, "ShareX - Twitter", "Tweet successfully sent.", ToolTipIcon.Info);
}
}
}
}
});
}
2014-05-03 05:56:51 +12:00
public static void OpenFTPClient()
{
if (Program.UploadersConfig != null && Program.UploadersConfig.FTPAccountList.IsValidIndex(Program.UploadersConfig.FTPSelectedImage))
{
FTPAccount account = Program.UploadersConfig.FTPAccountList[Program.UploadersConfig.FTPSelectedImage];
2014-05-25 16:39:13 +12:00
new FTPClientForm(account).Show();
2014-05-03 05:56:51 +12:00
}
}
2013-11-03 23:53:49 +13:00
}
}