Merge branch 'release/1.3' into feature/imgur_via_greenshotweb

# Conflicts:
#	GreenshotGooglePhotosPlugin/LanguageKeys.cs
#	GreenshotPlugin/Core/EnvironmentInfo.cs
#	GreenshotPlugin/Core/NetworkHelper.cs
#	GreenshotPlugin/Core/OAuthHelper.cs
This commit is contained in:
Robin Krom 2021-03-26 23:32:25 +01:00
commit d1d095bc78
No known key found for this signature in database
GPG key ID: BCC01364F1371490
177 changed files with 3172 additions and 10096 deletions

78
.editorconfig Normal file
View file

@ -0,0 +1,78 @@
# EditorConfig is awesome:http://EditorConfig.org
# top-most EditorConfig file
root = true
# Don't use tabs for indentation.
[*]
indent_style = space
# (Please don't specify an indent_size here; that has too many unintended consequences.)
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# Dotnet code style settings:
[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion
# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
# Suggest more modern language features when available
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
# CSharp code style settings:
[*.cs]
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
# Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = false:none
csharp_style_expression_bodied_constructors = false:none
csharp_style_expression_bodied_operators = false:none
# Prefer property-like constructs to have an expression-body
csharp_style_expression_bodied_properties = true:none
csharp_style_expression_bodied_indexers = true:none
csharp_style_expression_bodied_accessors = true:none
# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = true

46
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at getgreenshot@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

18
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,18 @@
The general rule we follow is "use Visual Studio defaults".
1. We use [Allman style](http://en.wikipedia.org/wiki/Indent_style#Allman_style) braces, where each brace begins on a new line. A single line statement block can go without braces but the block must be properly indented on its own line and it must not be nested in other statement blocks that use braces (See issue [381](https://github.com/dotnet/corefx/issues/381) for examples).
2. We use four spaces of indentation (no tabs).
3. We use `_camelCase` for internal and private fields and use `readonly` where possible. Prefix instance fields with `_`, static fields with `s_` and thread static fields with `t_`. When used on static fields, `readonly` should come after `static` (e.g. `static readonly` not `readonly static`).
4. We avoid `this.` unless absolutely necessary.
5. We always specify the visibility, even if it's the default (e.g. `private string _foo` not `string _foo`). Visibility should be the first modifier (e.g. `public abstract` not `abstract public`).
6. Namespace imports should be specified at the top of the file, *outside* of `namespace` declarations and should be sorted alphabetically.
7. Avoid more than one empty line at any time. For example, do not have two blank lines between members of a type.
8. Avoid spurious free spaces. For example avoid `if (someVar == 0)...`, where the dots mark the spurious free spaces. Consider enabling "View White Space (Ctrl+E, S)" if using Visual Studio, to aid detection.
9. If a file happens to differ in style from these guidelines (e.g. private members are named `m_member` rather than `_member`), the existing style in that file takes precedence.
10. We only use `var` when it's obvious what the variable type is (e.g. `var stream = new FileStream(...)` not `var stream = OpenStandardInput()`).
11. We use language keywords instead of BCL types (e.g. `int, string, float` instead of `Int32, String, Single`, etc) for both type references as well as method calls (e.g. `int.Parse` instead of `Int32.Parse`). See issue [391](https://github.com/dotnet/corefx/issues/391) for examples.
12. We use PascalCasing to name all our constant local variables and fields. The only exception is for interop code where the constant value should exactly match the name and value of the code you are calling via interop.
13. We use ```nameof(...)``` instead of ```"..."``` whenever possible and relevant.
14. Fields should be specified at the top within type declarations.
15. When including non-ASCII characters in the source code use Unicode escape sequences (\uXXXX) instead of literal characters. Literal non-ASCII characters occasionally get garbled by a tool or editor.
16. Do not use labels (e.g. for goto).

View file

@ -14,10 +14,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Greenshot", "Greenshot\Gree
{697CF066-9077-4F22-99D9-D989CCE7282B} = {697CF066-9077-4F22-99D9-D989CCE7282B}
{47F23C86-604E-4CC3-8767-B3D4088F30BB} = {47F23C86-604E-4CC3-8767-B3D4088F30BB}
{80D8DEB9-94E3-4876-8CCA-2DF1ED5F2C50} = {80D8DEB9-94E3-4876-8CCA-2DF1ED5F2C50}
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02} = {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}
{AD7CFFE2-40E7-46CF-A172-D48CF7AE9A12} = {AD7CFFE2-40E7-46CF-A172-D48CF7AE9A12}
{1893A2E4-A78A-4713-A8E7-E70058DABEE0} = {1893A2E4-A78A-4713-A8E7-E70058DABEE0}
{C6988EE8-2FEE-4349-9F09-F9628A0D8965} = {C6988EE8-2FEE-4349-9F09-F9628A0D8965}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotPlugin", "GreenshotPlugin\GreenshotPlugin.csproj", "{5B924697-4DCD-4F98-85F1-105CB84B7341}"
@ -30,13 +28,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotImgurPlugin", "Gre
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotJiraPlugin", "GreenshotJiraPlugin\GreenshotJiraPlugin.csproj", "{19FEEF09-313F-43C7-819D-F1BCA782B08B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotOCRPlugin", "GreenshotOCRPlugin\GreenshotOCRPlugin.csproj", "{C6988EE8-2FEE-4349-9F09-F9628A0D8965}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotOCRCommand", "GreenshotOCRCommand\GreenshotOCRCommand.csproj", "{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}"
ProjectSection(ProjectDependencies) = postProject
{C6988EE8-2FEE-4349-9F09-F9628A0D8965} = {C6988EE8-2FEE-4349-9F09-F9628A0D8965}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotBoxPlugin", "GreenshotBoxPlugin\GreenshotBoxPlugin.csproj", "{697CF066-9077-4F22-99D9-D989CCE7282B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotDropboxPlugin", "GreenshotDropboxPlugin\GreenshotDropboxPlugin.csproj", "{AD7CFFE2-40E7-46CF-A172-D48CF7AE9A12}"
@ -51,6 +42,12 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotPhotobucketPlugin"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GreenshotWin10Plugin", "GreenshotWin10Plugin\GreenshotWin10Plugin.csproj", "{9801F62C-540F-4BFE-9211-6405DEDE563B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{82987F1E-D7E6-4C44-B934-981D366E4672}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
azure-pipelines.yml = azure-pipelines.yml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -107,22 +104,6 @@ Global
{19FEEF09-313F-43C7-819D-F1BCA782B08B}.Release|Any CPU.Build.0 = Release|Any CPU
{19FEEF09-313F-43C7-819D-F1BCA782B08B}.Release|x86.ActiveCfg = Release|Any CPU
{19FEEF09-313F-43C7-819D-F1BCA782B08B}.Release|x86.Build.0 = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Debug|x86.ActiveCfg = Debug|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Debug|x86.Build.0 = Debug|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|Any CPU.Build.0 = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.ActiveCfg = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.Build.0 = Release|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Release|Any CPU.Build.0 = Release|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Release|x86.ActiveCfg = Release|Any CPU
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Release|x86.Build.0 = Release|Any CPU
{697CF066-9077-4F22-99D9-D989CCE7282B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{697CF066-9077-4F22-99D9-D989CCE7282B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{697CF066-9077-4F22-99D9-D989CCE7282B}.Debug|x86.ActiveCfg = Debug|Any CPU

View file

@ -25,219 +25,56 @@ namespace Greenshot.Configuration {
[SuppressMessage("ReSharper", "InconsistentNaming")]
public enum LangKey {
none,
about_bugs,
about_donations,
about_host,
about_icons,
about_license,
about_title,
about_translation,
application_title,
bugreport_cancel,
bugreport_info,
bugreport_title,
clipboard_error,
clipboard_inuse,
colorpicker_alpha,
colorpicker_apply,
colorpicker_blue,
colorpicker_green,
colorpicker_htmlcolor,
colorpicker_recentcolors,
colorpicker_red,
colorpicker_title,
colorpicker_transparent,
config_unauthorizedaccess_write,
contextmenu_about,
contextmenu_capturearea,
contextmenu_captureclipboard,
contextmenu_capturefullscreen,
contextmenu_capturefullscreen_all,
contextmenu_capturefullscreen_all,
contextmenu_capturefullscreen_left,
contextmenu_capturefullscreen_top,
contextmenu_capturefullscreen_right,
contextmenu_capturefullscreen_bottom,
contextmenu_capturelastregion,
contextmenu_capturewindow,
contextmenu_donate,
contextmenu_exit,
contextmenu_help,
contextmenu_openfile,
contextmenu_quicksettings,
contextmenu_settings,
contextmenu_captureie,
contextmenu_openrecentcapture,
editor_align_bottom,
editor_align_center,
editor_align_horizontal,
editor_align_middle,
editor_align_left,
editor_align_right,
editor_align_top,
editor_align_vertical,
editor_arrange,
editor_arrowheads,
editor_arrowheads_both,
editor_arrowheads_end,
editor_arrowheads_none,
editor_arrowheads_start,
editor_backcolor,
editor_blur_radius,
editor_bold,
editor_brightness,
editor_cancel,
editor_clipboardfailed,
editor_close,
contextmenu_captureie,
editor_clipboardfailed,
editor_close_on_save,
editor_close_on_save_title,
editor_confirm,
editor_copyimagetoclipboard,
editor_copypathtoclipboard,
editor_copytoclipboard,
editor_crop,
editor_cursortool,
editor_cuttoclipboard,
editor_deleteelement,
editor_downonelevel,
editor_downtobottom,
editor_drawarrow,
editor_drawellipse,
editor_drawhighlighter,
editor_drawline,
editor_drawfreehand,
editor_drawrectangle,
editor_drawtextbox,
editor_duplicate,
editor_edit,
editor_email,
editor_file,
editor_fontsize,
editor_forecolor,
editor_highlight_area,
editor_highlight_grayscale,
editor_highlight_mode,
editor_highlight_text,
editor_highlight_magnify,
editor_pixel_size,
editor_imagesaved,
editor_italic,
editor_load_objects,
editor_magnification_factor,
editor_match_capture_size,
editor_obfuscate,
editor_obfuscate_blur,
editor_obfuscate_mode,
editor_obfuscate_pixelize,
editor_object,
editor_opendirinexplorer,
editor_pastefromclipboard,
editor_preview_quality,
editor_print,
editor_save,
editor_save_objects,
editor_saveas,
editor_selectall,
editor_senttoprinter,
editor_shadow,
editor_torn_edge,
editor_border,
editor_grayscale,
editor_effects,
editor_storedtoclipboard,
editor_thickness,
editor_title,
editor_uponelevel,
editor_uptotop,
editor_autocrop,
editor_undo,
editor_redo,
editor_insertwindow,
editor_resetsize,
error,
error_multipleinstances,
error_nowriteaccess,
error_openfile,
error_openlink,
error_save,
error_save_invalid_chars,
help_title,
jpegqualitydialog_choosejpegquality,
qualitydialog_dontaskagain,
qualitydialog_title,
settings_reducecolors,
print_error,
printoptions_allowcenter,
printoptions_allowenlarge,
printoptions_allowrotate,
printoptions_allowshrink,
printoptions_colors,
printoptions_dontaskagain,
printoptions_pagelayout,
printoptions_printcolor,
printoptions_printgrayscale,
printoptions_printmonochrome,
printoptions_timestamp,
printoptions_inverted,
printoptions_title,
quicksettings_destination_file,
settings_alwaysshowqualitydialog,
settings_alwaysshowprintoptionsdialog,
settings_applicationsettings,
settings_autostartshortcut,
settings_capture,
settings_capture_mousepointer,
settings_capture_windows_interactive,
settings_copypathtoclipboard,
settings_destination,
settings_destination_clipboard,
settings_destination_editor,
settings_destination_email,
settings_destination_file,
settings_destination_fileas,
settings_destination_printer,
settings_destination_picker,
settings_editor,
settings_filenamepattern,
settings_general,
settings_iecapture,
settings_jpegquality,
settings_qualitysettings,
settings_language,
settings_message_filenamepattern,
settings_output,
settings_playsound,
settings_plugins,
settings_plugins_name,
settings_plugins_version,
settings_plugins_createdby,
settings_plugins_dllpath,
settings_preferredfilesettings,
settings_primaryimageformat,
settings_printer,
settings_printoptions,
settings_registerhotkeys,
settings_showflashlight,
settings_storagelocation,
settings_title,
settings_tooltip_filenamepattern,
settings_tooltip_language,
settings_tooltip_primaryimageformat,
settings_tooltip_registerhotkeys,
settings_tooltip_storagelocation,
settings_visualization,
settings_shownotify,
settings_waittime,
settings_windowscapture,
settings_window_capture_mode,
settings_network,
settings_checkperiod,
settings_usedefaultproxy,
tooltip_firststart,
warning,
warning_hotkeys,
hotkeys,
wait_ie_capture,
update_found,
exported_to
update_found
}
}

View file

@ -28,8 +28,6 @@ namespace Greenshot.Controls {
/// See: http://blogs.msdn.com/b/rickbrew/archive/2006/01/09/511003.aspx
/// </summary>
public class MenuStripEx : MenuStrip {
private const int WM_MOUSEACTIVATE = 0x21;
private enum NativeConstants : uint {
MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2,

View file

@ -40,10 +40,12 @@ namespace Greenshot.Destinations {
private readonly IImageEditor editor;
private static readonly Image greenshotIcon = GreenshotResources.GetGreenshotIcon().ToBitmap();
public EditorDestination() {
}
public EditorDestination(IImageEditor editor) {
public EditorDestination()
{
// Do not remove, is needed for the framework
}
public EditorDestination(IImageEditor editor) {
this.editor = editor;
}

View file

@ -30,17 +30,13 @@ namespace Greenshot.Drawing {
/// <summary>
/// empty container for filter-only elements
/// </summary>
[Serializable()]
[Serializable]
public abstract class FilterContainer : DrawableContainer {
public enum PreparedFilterMode {OBFUSCATE, HIGHLIGHT};
public enum PreparedFilter {BLUR, PIXELIZE, TEXT_HIGHTLIGHT, AREA_HIGHLIGHT, GRAYSCALE, MAGNIFICATION};
public PreparedFilter Filter {
get { return (PreparedFilter)GetFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); }
}
public FilterContainer(Surface parent) : base(parent) {
public FilterContainer(Surface parent) : base(parent) {
Init();
}

View file

@ -34,9 +34,7 @@ namespace Greenshot.Drawing {
/// </summary>
[Serializable()]
public class LineContainer : DrawableContainer {
public static readonly int MAX_CLICK_DISTANCE_TOLERANCE = 10;
public LineContainer(Surface parent) : base(parent) {
public LineContainer(Surface parent) : base(parent) {
Init();
}

View file

@ -1,135 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Greenshot.Drawing {
/// <summary>
/// TODO: currently this is only used in the capture form, we might move this code directly to there!
/// </summary>
public abstract class RoundedRectangle {
[Flags]
public enum RectangleCorners {
None = 0, TopLeft = 1, TopRight = 2,
BottomLeft = 4, BottomRight = 8,
All = TopLeft | TopRight | BottomLeft | BottomRight
}
public static GraphicsPath Create2(int x, int y, int width, int height, int radius) {
GraphicsPath gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - radius * 2, y); // Line
gp.AddArc(x + width - radius * 2, y, radius * 2, radius * 2, 270, 90); // Corner
gp.AddLine(x + width, y + radius, x + width, y + height - radius * 2); // Line
gp.AddArc(x + width - radius * 2, y + height - radius * 2, radius * 2, radius * 2, 0, 90); // Corner
gp.AddLine(x + width - radius * 2, y + height, x + radius, y + height); // Line
gp.AddArc(x, y + height - radius * 2, radius * 2, radius * 2, 90, 90); // Corner
gp.AddLine(x, y + height - radius * 2, x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure();
return gp;
}
public static GraphicsPath Create(int x, int y, int width, int height, int radius, RectangleCorners corners) {
int xw = x + width;
int yh = y + height;
int xwr = xw - radius;
int yhr = yh - radius;
int xr = x + radius;
int yr = y + radius;
int r2 = radius * 2;
int xwr2 = xw - r2;
int yhr2 = yh - r2;
GraphicsPath p = new GraphicsPath();
p.StartFigure();
//Top Left Corner
if ((RectangleCorners.TopLeft & corners) == RectangleCorners.TopLeft) {
p.AddArc(x, y, r2, r2, 180, 90);
} else {
p.AddLine(x, yr, x, y);
p.AddLine(x, y, xr, y);
}
//Top Edge
p.AddLine(xr, y, xwr, y);
//Top Right Corner
if ((RectangleCorners.TopRight & corners) == RectangleCorners.TopRight) {
p.AddArc(xwr2, y, r2, r2, 270, 90);
} else {
p.AddLine(xwr, y, xw, y);
p.AddLine(xw, y, xw, yr);
}
//Right Edge
p.AddLine(xw, yr, xw, yhr);
//Bottom Right Corner
if ((RectangleCorners.BottomRight & corners) == RectangleCorners.BottomRight) {
p.AddArc(xwr2, yhr2, r2, r2, 0, 90);
} else {
p.AddLine(xw, yhr, xw, yh);
p.AddLine(xw, yh, xwr, yh);
}
//Bottom Edge
p.AddLine(xwr, yh, xr, yh);
//Bottom Left Corner
if ((RectangleCorners.BottomLeft & corners) == RectangleCorners.BottomLeft) {
p.AddArc(x, yhr2, r2, r2, 90, 90);
} else {
p.AddLine(xr, yh, x, yh);
p.AddLine(x, yh, x, yhr);
}
//Left Edge
p.AddLine(x, yhr, x, yr);
p.CloseFigure();
return p;
}
public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners corners) {
return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, corners);
}
public static GraphicsPath Create(int x, int y, int width, int height, int radius) {
return Create(x, y, width, height, radius, RectangleCorners.All);
}
public static GraphicsPath Create(Rectangle rect, int radius) {
return Create(rect.X, rect.Y, rect.Width, rect.Height, radius);
}
public static GraphicsPath Create(int x, int y, int width, int height) {
return Create(x, y, width, height, 5);
}
public static GraphicsPath Create(Rectangle rect) {
return Create(rect.X, rect.Y, rect.Width, rect.Height);
}
}
}

View file

@ -598,9 +598,15 @@ namespace Greenshot.Drawing
DrawText(graphics, rect, lineThickness, lineColor, drawShadow, _stringFormat, text, _font);
}
/// <summary>
/// Convert the StringFormat information into a TextFormatFlags
/// This is important for the rending to work, have it aligned to the correct place
/// </summary>
/// <param name="stringFormat">StringFormat</param>
/// <returns>TextFormatFlags</returns>
private static TextFormatFlags ConvertStringFormat(StringFormat stringFormat)
{
TextFormatFlags flags = TextFormatFlags.Default;
var flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak;
if (stringFormat == null)
{
return flags;
@ -683,14 +689,7 @@ namespace Greenshot.Drawing
drawingRectange.Inflate(-textOffset, -textOffset);
}
if (stringFormat != null)
{
TextRenderer.DrawText(graphics, text, font, drawingRectange, fontColor, ConvertStringFormat(stringFormat));
}
else
{
TextRenderer.DrawText(graphics, text, font, drawingRectange, fontColor);
}
TextRenderer.DrawText(graphics, text, font, drawingRectange, fontColor, ConvertStringFormat(stringFormat));
}
public override bool ClickableAt(int x, int y)

View file

@ -98,7 +98,7 @@ namespace Greenshot.Forms {
this.linkLblLicense.Size = new System.Drawing.Size(369, 23);
this.linkLblLicense.TabIndex = 5;
this.linkLblLicense.TabStop = true;
this.linkLblLicense.Text = "http://www.gnu.org/licenses/gpl.html";
this.linkLblLicense.Text = "https://www.gnu.org/licenses/gpl.html";
this.linkLblLicense.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
//
// linkLblHost
@ -118,7 +118,7 @@ namespace Greenshot.Forms {
this.linkLblBugs.Size = new System.Drawing.Size(465, 23);
this.linkLblBugs.TabIndex = 8;
this.linkLblBugs.TabStop = true;
this.linkLblBugs.Text = "http://getgreenshot.org/tickets/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLblBugs.Text = "https://getgreenshot.org/tickets/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLblBugs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
//
// lblBugs
@ -136,7 +136,7 @@ namespace Greenshot.Forms {
this.linkLblDonations.Size = new System.Drawing.Size(465, 23);
this.linkLblDonations.TabIndex = 10;
this.linkLblDonations.TabStop = true;
this.linkLblDonations.Text = "http://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLblDonations.Text = "https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLblDonations.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
//
// lblDonations
@ -154,7 +154,7 @@ namespace Greenshot.Forms {
this.linkLblIcons.Size = new System.Drawing.Size(279, 23);
this.linkLblIcons.TabIndex = 12;
this.linkLblIcons.TabStop = true;
this.linkLblIcons.Text = "http://p.yusukekamiyamane.com";
this.linkLblIcons.Text = "https://p.yusukekamiyamane.com";
this.linkLblIcons.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
//
// lblIcons
@ -172,7 +172,7 @@ namespace Greenshot.Forms {
this.linkLabel1.Size = new System.Drawing.Size(130, 23);
this.linkLabel1.TabIndex = 13;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "http://getgreenshot.org/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLabel1.Text = "https://getgreenshot.org/?version=" + EnvironmentInfo.GetGreenshotVersion(true);
this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabelClicked);
//

View file

@ -905,7 +905,7 @@ namespace Greenshot.Forms {
// horizontal ruler
if (fixedRect.Width > hSpace + 3)
{
using GraphicsPath p = RoundedRectangle.Create2(
using GraphicsPath p = CreateRoundedRectangle(
fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3,
fixedRect.Y - dist - 7,
measureWidth.Width - 3,
@ -923,7 +923,7 @@ namespace Greenshot.Forms {
// vertical ruler
if (fixedRect.Height > vSpace + 3)
{
using GraphicsPath p = RoundedRectangle.Create2(
using GraphicsPath p = CreateRoundedRectangle(
fixedRect.X - measureHeight.Width + 1,
fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2,
measureHeight.Width - 3,
@ -990,7 +990,7 @@ namespace Greenshot.Forms {
string xy = _cursorPos.X + " x " + _cursorPos.Y;
using Font f = new Font(FontFamily.GenericSansSerif, 8);
Size xySize = TextRenderer.MeasureText(xy, f);
using GraphicsPath gp = RoundedRectangle.Create2(_cursorPos.X + 5, _cursorPos.Y + 5, xySize.Width - 3, xySize.Height, 3);
using GraphicsPath gp = CreateRoundedRectangle(_cursorPos.X + 5, _cursorPos.Y + 5, xySize.Width - 3, xySize.Height, 3);
using (Brush bgBrush = new SolidBrush(Color.FromArgb(200, 217, 240, 227))) {
graphics.FillPath(bgBrush, gp);
}
@ -1014,5 +1014,21 @@ namespace Greenshot.Forms {
DrawZoom(graphics, sourceRectangle, destinationRectangle);
}
}
private static GraphicsPath CreateRoundedRectangle(int x, int y, int width, int height, int radius)
{
var gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - radius * 2, y); // Line
gp.AddArc(x + width - radius * 2, y, radius * 2, radius * 2, 270, 90); // Corner
gp.AddLine(x + width, y + radius, x + width, y + height - radius * 2); // Line
gp.AddArc(x + width - radius * 2, y + height - radius * 2, radius * 2, radius * 2, 0, 90); // Corner
gp.AddLine(x + width - radius * 2, y + height, x + radius, y + height); // Line
gp.AddArc(x, y + height - radius * 2, radius * 2, radius * 2, 90, 90); // Corner
gp.AddLine(x, y + height - radius * 2, x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure();
return gp;
}
}
}

View file

@ -59,8 +59,6 @@ namespace Greenshot.Forms {
set { PreviewColor(value, this); }
}
public IList<Color> RecentColors => EditorConfig.RecentColors;
private void CreateColorPalette(int x, int y, int w, int h) {
CreateColorButtonColumn(255, 0, 0, x, y, w, h, 11);
x += w;

View file

@ -73,12 +73,7 @@ namespace Greenshot.Forms {
/// </summary>
private readonly Fraction[] ZOOM_VALUES = new Fraction[] { (1, 4), (1, 2), (2, 3), (3, 4), (1 ,1), (2, 1), (3, 1), (4, 1), (6, 1) };
/// <summary>
/// An Implementation for the IImageEditor, this way Plugins have access to the HWND handles wich can be used with Win32 API calls.
/// </summary>
public IWin32Window WindowHandle => this;
public static List<IImageEditor> Editors {
public static List<IImageEditor> Editors {
get {
try {
EditorList.Sort((e1, e2) => string.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal));
@ -517,14 +512,6 @@ namespace Greenshot.Forms {
public ICaptureDetails CaptureDetails => _surface.CaptureDetails;
public ToolStripMenuItem GetPluginMenuItem() {
return pluginToolStripMenuItem;
}
public ToolStripMenuItem GetFileMenuItem() {
return fileStripMenuItem;
}
private void BtnSaveClick(object sender, EventArgs e) {
string destinationDesignation = FileDestination.DESIGNATION;
if (_surface.LastSaveFullPath == null) {

View file

@ -486,12 +486,7 @@ namespace Greenshot.Forms {
}
}
/// <summary>
/// Main context menu
/// </summary>
public ContextMenuStrip MainMenu => contextMenu;
protected override void WndProc(ref Message m) {
protected override void WndProc(ref Message m) {
if (HotkeyControl.HandleMessages(ref m)) {
return;
}
@ -923,7 +918,7 @@ namespace Greenshot.Forms {
private void ShowThumbnailOnEnter(object sender, EventArgs e) {
if (sender is not ToolStripMenuItem captureWindowItem) return;
WindowDetails window = captureWindowItem.Tag as WindowDetails;
var window = captureWindowItem.Tag as WindowDetails;
if (_thumbnailForm == null) {
_thumbnailForm = new ThumbnailForm();
}
@ -944,29 +939,39 @@ namespace Greenshot.Forms {
_thumbnailForm = null;
}
/// <summary>
/// Create the "capture window from list" list
/// </summary>
/// <param name="menuItem">ToolStripMenuItem</param>
/// <param name="eventHandler">EventHandler</param>
public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) {
menuItem.DropDownItems.Clear();
// check if thumbnailPreview is enabled and DWM is enabled
bool thumbnailPreview = _conf.ThumnailPreview && DWM.IsDwmEnabled;
foreach(WindowDetails window in WindowDetails.GetTopLevelWindows()) {
foreach(var window in WindowDetails.GetTopLevelWindows()) {
if (LOG.IsDebugEnabled)
{
LOG.Debug(window.ToString());
}
string title = window.Text;
if (title != null) {
if (title.Length > _conf.MaxMenuItemLength) {
title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength));
}
ToolStripItem captureWindowItem = menuItem.DropDownItems.Add(title);
captureWindowItem.Tag = window;
captureWindowItem.Image = window.DisplayIcon;
captureWindowItem.Click += eventHandler;
// Only show preview when enabled
if (thumbnailPreview) {
captureWindowItem.MouseEnter += ShowThumbnailOnEnter;
captureWindowItem.MouseLeave += HideThumbnailOnLeave;
}
}
}
if (string.IsNullOrEmpty(title))
{
continue;
}
if (title.Length > _conf.MaxMenuItemLength) {
title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength));
}
ToolStripItem captureWindowItem = menuItem.DropDownItems.Add(title);
captureWindowItem.Tag = window;
captureWindowItem.Image = window.DisplayIcon;
captureWindowItem.Click += eventHandler;
// Only show preview when enabled
if (thumbnailPreview) {
captureWindowItem.MouseEnter += ShowThumbnailOnEnter;
captureWindowItem.MouseLeave += HideThumbnailOnLeave;
}
}
}
private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) {

View file

@ -22,7 +22,6 @@
using GreenshotPlugin.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using GreenshotPlugin.IniFile;
@ -57,77 +56,8 @@ namespace Greenshot.Forms {
Image = _defaultImage;
}
public ToolStripMenuSelectList() : this(null,false) {}
public ToolStripMenuSelectList(object identifier) : this(identifier,false) {}
/// <summary>
/// gets or sets the currently checked item
/// </summary>
public ToolStripMenuSelectListItem CheckedItem {
get {
IEnumerator items = DropDownItems.GetEnumerator();
while (items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (tsmi != null && tsmi.Checked) {
return tsmi;
}
}
return null;
}
set {
IEnumerator items = DropDownItems.GetEnumerator();
while (items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (tsmi != null && !_multiCheckAllowed && !tsmi.Equals(value)) {
tsmi.Checked = false;
} else if (tsmi != null && tsmi.Equals(value)) {
tsmi.Checked = true;
}
}
}
}
/// <summary>
/// gets or sets the currently checked items
/// </summary>
public ToolStripMenuSelectListItem[] CheckedItems {
get {
List<ToolStripMenuSelectListItem> sel = new List<ToolStripMenuSelectListItem>();
IEnumerator items = DropDownItems.GetEnumerator();
while(items.MoveNext()) {
ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current;
if (tsmi != null && tsmi.Checked) {
sel.Add(tsmi);
}
}
return sel.ToArray();
}
set {
if (!_multiCheckAllowed) {
throw new ArgumentException("Writing to checkedItems is only allowed in multi-check mode. Either set allowMultiCheck to true or use set SelectedItem instead of SelectedItems.");
}
IEnumerator items = DropDownItems.GetEnumerator();
IEnumerator sel = value.GetEnumerator();
while (items.MoveNext()) {
var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current;
if (toolStripMenuSelectListItem == null)
{
continue;
}
while (sel.MoveNext())
{
toolStripMenuSelectListItem.Checked = toolStripMenuSelectListItem.Equals(sel.Current);
if (!_multiCheckAllowed && !toolStripMenuSelectListItem.Equals(sel.Current)) {
toolStripMenuSelectListItem.Checked = false;
} else if (toolStripMenuSelectListItem.Equals(value)) {
toolStripMenuSelectListItem.Checked = true;
}
}
}
}
}
private void ItemCheckStateChanged(object sender, EventArgs e) {
private void ItemCheckStateChanged(object sender, EventArgs e) {
if (_updateInProgress) {
return;
}
@ -172,44 +102,8 @@ namespace Greenshot.Forms {
DropDownItems.Add(toolStripMenuSelectListItem);
}
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
/// <param name="image">the icon to be displayed</param>
public void AddItem(string label, Image image) {
AddItem(label, image, null, false);
}
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
/// <param name="data">the data to be returned when an item is queried</param>
public void AddItem(string label, object data) {
AddItem(label, null, data, false);
}
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
public void AddItem(string label) {
AddItem(label, null, null, false);
}
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
/// <param name="image">the icon to be displayed</param>
/// <param name="isChecked">whether the item is initially checked</param>
public void AddItem(string label, Image image, bool isChecked) {
AddItem(label, image, null, isChecked);
}
/// <summary>
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
@ -219,16 +113,7 @@ namespace Greenshot.Forms {
AddItem(label, null, data, isChecked);
}
/// <summary>
/// adds an item to the select list
/// </summary>
/// <param name="label">the label to be displayed</param>
/// <param name="isChecked">whether the item is initially checked</param>
public void AddItem(string label, bool isChecked) {
AddItem(label, null, null, isChecked);
}
/// <summary>
/// <summary>
/// unchecks all items of the list
/// </summary>
public void UncheckAll() {

View file

@ -970,7 +970,7 @@ namespace Greenshot.Helpers {
// The following, to be precise the HideApp, causes the app to close as described in BUG-1620
// Added check for metro (Modern UI) apps, which might be maximized and cover the screen.
//foreach(WindowDetails app in WindowDetails.GetMetroApps()) {
//foreach(WindowDetails app in WindowDetails.GetAppWindows()) {
// if (app.Maximised) {
// app.HideApp();
// }

View file

@ -28,7 +28,7 @@ namespace Greenshot.Helpers {
public static class GuiRectangle {
public static Rectangle GetGuiRectangle(int x, int y, int w, int h) {
Rectangle rect = new Rectangle(x, y, w, h);
var rect = new Rectangle(x, y, w, h);
MakeGuiRectangle(ref rect);
return rect;
}
@ -43,22 +43,5 @@ namespace Greenshot.Helpers {
rect.Height = -rect.Height;
}
}
public static RectangleF GetGuiRectangleF(float x, float y, float w, float h) {
RectangleF rect = new RectangleF(x, y, w, h);
MakeGuiRectangleF(ref rect);
return rect;
}
public static void MakeGuiRectangleF(ref RectangleF rect) {
if (rect.Width < 0) {
rect.X += rect.Width;
rect.Width = -rect.Width;
}
if (rect.Height < 0) {
rect.Y += rect.Height;
rect.Height = -rect.Height;
}
}
}
}
}

View file

@ -60,27 +60,7 @@ namespace Greenshot.Helpers {
ieAccessible.ActivateIETab(tabIndex);
}
/// <summary>
/// Return true if the supplied window has a sub-window which covers more than the supplied percentage
/// </summary>
/// <param name="someWindow">WindowDetails to check</param>
/// <param name="minimumPercentage">min percentage</param>
/// <returns></returns>
public static bool IsMostlyIeWindow(WindowDetails someWindow, int minimumPercentage) {
WindowDetails ieWindow = someWindow.GetChild("Internet Explorer_Server");
if (ieWindow == null) return false;
Rectangle wholeClient = someWindow.ClientRectangle;
Rectangle partClient = ieWindow.ClientRectangle;
int percentage = (int)(100*(float)(partClient.Width * partClient.Height) / (wholeClient.Width * wholeClient.Height));
Log.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage);
if (percentage > minimumPercentage) {
return true;
}
return false;
}
/// <summary>
/// <summary>
/// Does the supplied window have a IE part?
/// </summary>
/// <param name="someWindow"></param>
@ -321,15 +301,7 @@ namespace Greenshot.Helpers {
return returnDocumentContainer;
}
/// <summary>
/// Here the logic for capturing the IE Content is located
/// </summary>
/// <param name="capture">ICapture where the capture needs to be stored</param>
/// <returns>ICapture with the content (if any)</returns>
public static ICapture CaptureIe(ICapture capture) {
return CaptureIe(capture, WindowDetails.GetActiveWindow());
}
/// <summary>
/// <summary>
/// Here the logic for capturing the IE Content is located
/// </summary>
/// <param name="capture">ICapture where the capture needs to be stored</param>

View file

@ -126,14 +126,7 @@ namespace Greenshot.Helpers {
_manualResetEvent = new ManualResetEvent(false);
}
/// <summary>
/// Creates a new mail message with the specified subject.
/// </summary>
public MapiMailMessage(string subject) : this() {
Subject = subject;
}
/// <summary>
/// <summary>
/// Creates a new mail message with the specified subject and body.
/// </summary>
public MapiMailMessage(string subject, string body) : this() {
@ -437,21 +430,6 @@ namespace Greenshot.Helpers {
public MapiMailMessage.RecipientType RecipientType = MapiMailMessage.RecipientType.To;
/// <summary>
/// Creates a new recipient with the specified address.
/// </summary>
public Recipient(string address) {
Address = address;
}
/// <summary>
/// Creates a new recipient with the specified address and display name.
/// </summary>
public Recipient(string address, string displayName) {
Address = address;
DisplayName = displayName;
}
/// <summary>
/// Creates a new recipient with the specified address and recipient type.
/// </summary>
public Recipient(string address, MapiMailMessage.RecipientType recipientType) {
@ -459,15 +437,6 @@ namespace Greenshot.Helpers {
RecipientType = recipientType;
}
/// <summary>
/// Creates a new recipient with the specified address, display name and recipient type.
/// </summary>
public Recipient(string address, string displayName, MapiMailMessage.RecipientType recipientType) {
Address = address;
DisplayName = displayName;
RecipientType = recipientType;
}
/// <summary>
/// Returns an interop representation of a recepient.
/// </summary>
@ -499,40 +468,7 @@ namespace Greenshot.Helpers {
List.Add(value);
}
/// <summary>
/// Adds a new recipient with the specified address to this collection.
/// </summary>
public void Add(string address) {
Add(new Recipient(address));
}
/// <summary>
/// Adds a new recipient with the specified address and display name to this collection.
/// </summary>
public void Add(string address, string displayName) {
Add(new Recipient(address, displayName));
}
/// <summary>
/// Adds a new recipient with the specified address and recipient type to this collection.
/// </summary>
public void Add(string address, MapiMailMessage.RecipientType recipientType) {
Add(new Recipient(address, recipientType));
}
/// <summary>
/// Adds a new recipient with the specified address, display name and recipient type to this collection.
/// </summary>
public void Add(string address, string displayName, MapiMailMessage.RecipientType recipientType) {
Add(new Recipient(address, displayName, recipientType));
}
/// <summary>
/// Returns the recipient stored in this collection at the specified index.
/// </summary>
public Recipient this[int index] => (Recipient)List[index];
internal InteropRecipientCollection GetInteropRepresentation() {
internal InteropRecipientCollection GetInteropRepresentation() {
return new InteropRecipientCollection(this);
}

View file

@ -101,34 +101,8 @@ namespace Greenshot.Helpers {
}
return newRect;
}
/// <summary>
/// calculates the Rectangle an element must be resized an positioned to, in ordder to fit another element, keeping aspect ratio
/// </summary>
/// <param name="currentRect">the rectangle of the element to be resized/repositioned</param>
/// <param name="targetRect">the target size/position of the element</param>
/// <param name="crop">in case the aspect ratio of currentSize and targetSize differs: shall the scaled size fit into targetSize (i.e. that one of its dimensions is smaller - false) or vice versa (true)</param>
/// <param name="alignment">the System.Drawing.ContentAlignment value indicating how the element is to be aligned should the width or height differ from targetSize</param>
/// <returns>a new RectangleF object indicating the width and height the element should be scaled to and the position that should be applied to it for proper alignment</returns>
public static RectangleF GetScaledRectangle(RectangleF currentRect, RectangleF targetRect, bool crop, ContentAlignment alignment) {
SizeF newSize = GetScaledSize(currentRect.Size, targetRect.Size, crop);
RectangleF newRect = new RectangleF(new Point(0,0), newSize);
return GetAlignedRectangle(newRect, targetRect, alignment);
}
public static void RationalScale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, ScaleOptions.Rational);
}
public static void CenteredScale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, ScaleOptions.Centered);
}
public static void Scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, null);
}
/// <summary>
/// <summary>
/// Calculates target size of a given rectangle scaled by dragging one of its handles (corners)
/// </summary>
/// <param name="originalRectangle">bounds of the current rectangle, scaled values will be written to this reference</param>
@ -139,7 +113,7 @@ namespace Greenshot.Helpers {
options ??= GetScaleOptions();
if ((options & ScaleOptions.Rational) == ScaleOptions.Rational) {
adjustCoordsForRationalScale(originalRectangle, resizeHandlePosition, ref resizeHandleCoords);
AdjustCoordsForRationalScale(originalRectangle, resizeHandlePosition, ref resizeHandleCoords);
}
if ((options & ScaleOptions.Centered) == ScaleOptions.Centered) {
@ -147,15 +121,15 @@ namespace Greenshot.Helpers {
float rectCenterX = originalRectangle.Left + originalRectangle.Width / 2;
float rectCenterY = originalRectangle.Top + originalRectangle.Height / 2;
// scale rectangle using handle coordinates
scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
// mirror handle coordinates via rectangle center coordinates
resizeHandleCoords.X -= 2 * (resizeHandleCoords.X - rectCenterX);
resizeHandleCoords.Y -= 2 * (resizeHandleCoords.Y - rectCenterY);
// scale again with opposing handle and mirrored coordinates
resizeHandlePosition = (Positions)((((int)resizeHandlePosition) + 4) % 8);
scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
} else {
scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
}
}
@ -166,7 +140,7 @@ namespace Greenshot.Helpers {
/// <param name="originalRectangle">bounds of the current rectangle, scaled values will be written to this reference</param>
/// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param>
/// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param>
private static void scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
private static void Scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
switch(resizeHandlePosition) {
case Positions.TopLeft:
@ -223,7 +197,7 @@ namespace Greenshot.Helpers {
/// <param name="originalRectangle">bounds of the current rectangle</param>
/// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see Position</param>
/// <param name="resizeHandleCoords">coordinates of the used handle/gripper, adjusted coordinates will be written to this reference</param>
private static void adjustCoordsForRationalScale(RectangleF originalRectangle, Positions resizeHandlePosition, ref PointF resizeHandleCoords) {
private static void AdjustCoordsForRationalScale(RectangleF originalRectangle, Positions resizeHandlePosition, ref PointF resizeHandleCoords) {
float originalRatio = originalRectangle.Width / originalRectangle.Height;
float newWidth, newHeight, newRatio;
switch(resizeHandlePosition) {
@ -273,12 +247,8 @@ namespace Greenshot.Helpers {
break;
}
}
public static void Scale(Rectangle boundsBeforeResize, int cursorX, int cursorY, ref RectangleF boundsAfterResize) {
Scale(boundsBeforeResize, cursorX, cursorY, ref boundsAfterResize, null);
}
public static void Scale(Rectangle boundsBeforeResize, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) {
public static void Scale(Rectangle boundsBeforeResize, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) {
Scale(boundsBeforeResize, Positions.TopLeft, cursorX, cursorY, ref boundsAfterResize, angleRoundBehavior);
}
@ -343,15 +313,6 @@ namespace Greenshot.Helpers {
return Math.Round(angle/15)*15;
}
}
public class FixedAngleRoundBehavior : IDoubleProcessor {
private readonly double fixedAngle;
public FixedAngleRoundBehavior(double fixedAngle) {
this.fixedAngle = fixedAngle;
}
public double Process(double angle) {
return fixedAngle;
}
}
}
}
}

View file

@ -54,16 +54,8 @@ namespace Greenshot.Helpers {
public static void Enable(ToolStripItem tsi) {
Endisable(tsi, true, PropagationMode.CHILDREN | PropagationMode.ANCESTORS);
}
/// <summary>
/// Disables the ToolStripItem, including children (ToolStripDropDownItem),
/// but NOT the ancestor (OwnerItem)
/// </summary>
public static void Disable(ToolStripItem tsi) {
Endisable(tsi, false, PropagationMode.CHILDREN);
}
private static void Endisable(ToolStrip ts, bool enable, PropagationMode mode)
private static void Endisable(ToolStrip ts, bool enable, PropagationMode mode)
{
if ((mode & PropagationMode.CHILDREN) != PropagationMode.CHILDREN) return;

View file

@ -93,17 +93,6 @@ namespace Greenshot.Helpers
_ = BackgroundTask(() => TimeSpan.FromDays(CoreConfig.UpdateCheckInterval), UpdateCheck, _cancellationTokenSource.Token);
}
/// <summary>
/// Stop the update checks
/// </summary>
public void Shutdown()
{
if (!_cancellationTokenSource.IsCancellationRequested)
{
_cancellationTokenSource.Cancel();
}
}
/// <summary>
/// This runs a periodic task in the background
/// </summary>

View file

@ -25,6 +25,7 @@ Source: {#ReleaseDir}\Dapplo.Http*.dll; DestDir: {app}; Components: greenshot; F
Source: {#ReleaseDir}\Dapplo.Log.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
Source: {#ReleaseDir}\Svg.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
Source: {#ReleaseDir}\Fizzler.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
Source: {#ReleaseDir}\HtmlAgilityPack.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
Source: {#ReleaseDir}\Newtonsoft.Json.dll; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
Source: ..\..\log4net.xml; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion
Source: {#ReleaseDir}\checksum.SHA256; DestDir: {app}; Components: greenshot; Flags: overwritereadonly ignoreversion replacesameversion
@ -78,11 +79,6 @@ Source: ..\..\Languages\*zh-TW*; Excludes: "*installer*,*website*"; DestDir: {ap
;Office Plugin
Source: {#BaseDir}\GreenshotOfficePlugin\{#BinDir}\GreenshotOfficePlugin.dll; DestDir: {app}\Plugins\GreenshotOfficePlugin; Components: plugins\office; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
;OCR Plugin
Source: {#BaseDir}\GreenshotOCRPlugin\{#BinDir}\GreenshotOCRPlugin.dll; DestDir: {app}\Plugins\GreenshotOCRPlugin; Components: plugins\ocr; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
Source: {#BaseDir}\GreenshotOCRPlugin\Languages\language_ocr*.xml; DestDir: {app}\Languages\Plugins\GreenshotOCRPlugin; Components: plugins\ocr; Flags: overwritereadonly ignoreversion replacesameversion;
Source: {#BaseDir}\GreenshotOCRCommand\{#BinDir}\GreenshotOCRCommand.exe; DestDir: {app}\Plugins\GreenshotOCRPlugin; Components: plugins\ocr; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
Source: {#BaseDir}\GreenshotOCRCommand\{#BinDir}\GreenshotOCRCommand.exe.config; DestDir: {app}\Plugins\GreenshotOCRPlugin; Components: plugins\ocr; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
;JIRA Plugin
Source: {#BaseDir}\GreenshotJiraPlugin\{#BinDir}\GreenshotJiraPlugin.dll; DestDir: {app}\Plugins\GreenshotJiraPlugin; Components: plugins\jira; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
Source: {#BaseDir}\GreenshotJiraPlugin\{#BinDir}\Dapplo.Jira*.dll; DestDir: {app}\Plugins\GreenshotJiraPlugin; Components: plugins\jira; Flags: overwritereadonly recursesubdirs ignoreversion replacesameversion;
@ -260,7 +256,6 @@ en.flickr=Flickr plug-in
en.imgur=Imgur plug-in (See: http://imgur.com)
en.jira=Jira plug-in
en.language=Additional languages
en.ocr=OCR plug-in (needs Microsoft Office Document Imaging (MODI))
en.office=Microsoft Office plug-in
en.optimize=Optimizing performance, this may take a while.
en.photobucket=Photobucket plug-in
@ -278,7 +273,6 @@ de.externalcommand=Externes Kommando Plug-in
de.imgur=Imgur Plug-in (Siehe: http://imgur.com)
de.jira=Jira Plug-in
de.language=Zusätzliche Sprachen
de.ocr=OCR Plug-in (benötigt Microsoft Office Document Imaging (MODI))
de.office=Microsoft Office Plug-in
de.optimize=Optimierung der Leistung, kann etwas dauern.
de.startgreenshot={#ExeName} starten
@ -291,7 +285,6 @@ es.externalcommand=Extensión para abrir con programas externos
es.imgur=Extensión para Imgur (Ver http://imgur.com)
es.jira=Extensión para Jira
es.language=Idiomas adicionales
es.ocr=Extensión para OCR (necesita Microsoft Office Document Imaging (MODI))
es.optimize=Optimizando rendimiento; por favor, espera.
es.startgreenshot=Lanzar {#ExeName}
es.startup=Lanzar {#ExeName} al iniciarse Windows
@ -303,7 +296,6 @@ fi.externalcommand=Avaa Ulkoinen komento-liitännäisellä
fi.imgur=Imgur-liitännäinen (Katso: http://imgur.com)
fi.jira=Jira-liitännäinen
fi.language=Lisäkielet
fi.ocr=OCR-liitännäinen (Tarvitaan: Microsoft Office Document Imaging (MODI))
fi.office=Microsoft-Office-liitännäinen
fi.optimize=Optimoidaan suorituskykyä, tämä voi kestää hetken.
fi.startgreenshot=Käynnistä {#ExeName}
@ -316,7 +308,6 @@ fr.externalcommand=Ouvrir avec le greffon de commande externe
fr.imgur=Greffon Imgur (Voir: http://imgur.com)
fr.jira=Greffon Jira
fr.language=Langues additionnelles
fr.ocr=Greffon OCR (nécessite Document Imaging de Microsoft Office [MODI])
fr.office=Greffon Microsoft Office
fr.optimize=Optimisation des performances, Ceci peut prendre un certain temps.
fr.startgreenshot=Démarrer {#ExeName}
@ -332,7 +323,6 @@ it.flickr=Plugin Flickr
it.imgur=Plugin Imgur (vedi: http://imgur.com)
it.jira=Plugin Jira
it.language=Lingue aggiuntive
it.ocr=Plugin OCR (richiede Microsoft Office Document Imaging (MODI))
it.office=Plugin Microsoft Office
it.optimize=Ottimizzazione prestazioni (può richiedere tempo).
it.photobucket=Plugin Photobucket
@ -386,7 +376,6 @@ lt.externalcommand=Pielāgotu darbību spraudnis
lt.imgur=Imgur spraudnis (Vairāk šeit: http://imgur.com)
lt.jira=Jira spraudnis
lt.language=Papildus valodas
lt.ocr=OCR spraudnis (nepieciešams Microsoft Office Document Imaging (MODI))
lt.office=Microsoft Office spraudnis
lt.optimize=Uzlaboju veikstpēju, tas prasīs kādu laiciņu.
lt.startgreenshot=Palaist {#ExeName}
@ -399,7 +388,6 @@ lt.externalcommand=Pielāgotu darbību spraudnis
lt.imgur=Imgur spraudnis (Vairāk šeit: http://imgur.com)
lt.jira=Jira spraudnis
lt.language=Papildus valodas
lt.ocr=OCR spraudnis (nepieciešams Microsoft Office Document Imaging (MODI))
lt.office=Microsoft Office spraudnis
lt.optimize=Uzlaboju veikstpēju, tas prasīs kādu laiciņu.
lt.startgreenshot=Palaist {#ExeName}
@ -412,7 +400,6 @@ nl.externalcommand=Openen met extern commando plug-in
nl.imgur=Imgur plug-in (zie: http://imgur.com)
nl.jira=Jira plug-in
nl.language=Extra talen
nl.ocr=OCR plug-in (vereist Microsoft Office Document Imaging (MODI))
nl.office=Microsoft Office plug-in
nl.optimize=Prestaties verbeteren, even geduld.
nl.startgreenshot={#ExeName} starten
@ -425,7 +412,6 @@ nn.externalcommand=Tillegg for å opne med ekstern kommando
nn.imgur=Imgur-tillegg (sjå http://imgur.com)
nn.jira=Jira-tillegg
nn.language=Andre språk
nn.ocr=OCR-tillegg (krev Microsoft Office Document Imaging (MODI))
nn.office=Microsoft Office Tillegg
nn.optimize=Optimaliserar ytelse, dette kan ta litt tid...
nn.startgreenshot=Start {#ExeName}
@ -438,7 +424,6 @@ ru.externalcommand=Открыть с плагином с помощью внеш
ru.imgur=Плагин Imgur (смотрите https://imgur.com/)
ru.jira=Плагин Jira
ru.language=Дополнительные языки
ru.ocr=Плагин OCR (требуется Microsoft Office Document Imaging (MODI))
ru.office=Плагин Microsoft Office
ru.optimize=Идет оптимизация производительности, это может занять некоторое время.
ru.startgreenshot=Запустить {#ExeName}
@ -451,7 +436,6 @@ sr.externalcommand=Отвори са прикључком за спољне на
sr.imgur=Прикључак за Имиџер (http://imgur.com)
sr.jira=Прикључак за Џиру
sr.language=Додатни језици
sr.ocr=OCR прикључак (захтева Microsoft Office Document Imaging (MODI))
sr.optimize=Оптимизујем перформансе…
sr.startgreenshot=Покрени Гриншот
sr.startup=Покрени програм са системом
@ -462,7 +446,6 @@ sv.externalcommand=Öppna med externt kommando-insticksprogram
sv.imgur=Imgur-insticksprogram (Se: http://imgur.com)
sv.jira=Jira-insticksprogram
sv.language=Ytterligare språk
sv.ocr=OCR-insticksprogram (kräver Microsoft Office Document Imaging (MODI))
sv.optimize=Optimerar prestanda, detta kan ta en stund.
sv.startgreenshot=Starta {#ExeName}
sv.startup=Starta {#ExeName} med Windows
@ -474,7 +457,6 @@ uk.externalcommand=Плагін запуску зовнішньої команд
uk.imgur=Плагін Imgur (див.: http://imgur.com)
uk.jira=Плагін Jira
uk.language=Додаткові мови
uk.ocr=Плагін OCR (потребує Microsoft Office Document Imaging (MODI))
uk.optimize=Оптимізація продуктивності, це може забрати час.
uk.startgreenshot=Запустити {#ExeName}
uk.startup=Запускати {#ExeName} під час запуску Windows
@ -486,7 +468,6 @@ cn.externalcommand=使用外部命令打开插件
cn.imgur=Imgur插件( (请访问: http://imgur.com))
cn.jira=Jira插件
cn.language=其它语言
cn.ocr=OCR插件(需要Microsoft Office Document Imaging (MODI)的支持)
cn.optimize=正在优化性能,这可能需要一点时间。
cn.startgreenshot=启动{#ExeName}
cn.startup=让{#ExeName}随Windows一起启动
@ -508,7 +489,6 @@ Name: "plugins\externalcommand"; Description: {cm:externalcommand}; Types: defau
Name: "plugins\flickr"; Description: {cm:flickr}; Types: full custom; Flags: disablenouninstallwarning
Name: "plugins\imgur"; Description: {cm:imgur}; Types: default full custom; Flags: disablenouninstallwarning
Name: "plugins\jira"; Description: {cm:jira}; Types: full custom; Flags: disablenouninstallwarning
Name: "plugins\ocr"; Description: {cm:ocr}; Types: default full custom; Flags: disablenouninstallwarning
Name: "plugins\office"; Description: {cm:office}; Types: default full custom; Flags: disablenouninstallwarning
Name: "plugins\photobucket"; Description: {cm:photobucket}; Types: full custom; Flags: disablenouninstallwarning
;Name: "plugins\picasa"; Description: {cm:picasa}; Types: full custom; Flags: disablenouninstallwarning

View file

@ -21,7 +21,6 @@
using GreenshotPlugin.Core;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
@ -30,10 +29,10 @@ using GreenshotPlugin.IniFile;
namespace GreenshotBoxPlugin {
/// <summary>
/// Description of ImgurUtils.
/// </summary>
public static class BoxUtils {
/// <summary>
/// Description of BoxUtils.
/// </summary>
public static class BoxUtils {
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(BoxUtils));
private static readonly BoxConfiguration Config = IniConfig.GetIniSection<BoxConfiguration>();
private const string UploadFileUri = "https://upload.box.com/api/2.0/files/content";
@ -121,19 +120,7 @@ namespace GreenshotBoxPlugin {
/// A simple helper class for the DataContractJsonSerializer
/// </summary>
internal static class JsonSerializer {
/// <summary>
/// Helper method to serialize object to JSON
/// </summary>
/// <param name="jsonObject">JSON object</param>
/// <returns>string</returns>
public static string Serialize(object jsonObject) {
var serializer = new DataContractJsonSerializer(jsonObject.GetType());
using MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, jsonObject);
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>
/// <summary>
/// Helper method to parse JSON to object
/// </summary>
/// <typeparam name="T"></typeparam>
@ -141,7 +128,7 @@ namespace GreenshotBoxPlugin {
/// <returns></returns>
public static T Deserialize<T>(string jsonString) {
var deserializer = new DataContractJsonSerializer(typeof(T));
using MemoryStream stream = new MemoryStream();
using var stream = new MemoryStream();
byte[] content = Encoding.UTF8.GetBytes(jsonString);
stream.Write(content, 0, content.Length);
stream.Seek(0, SeekOrigin.Begin);

View file

@ -21,13 +21,8 @@
namespace GreenshotBoxPlugin {
public enum LangKey {
upload_menu_item,
settings_title,
label_upload_format,
upload_success,
upload_failure,
communication_wait,
Configure,
label_AfterUpload,
label_AfterUploadLinkToClipBoard
Configure
}
}

View file

@ -33,15 +33,8 @@ namespace GreenshotConfluencePlugin {
private Type _type;
private IDictionary _displayValues;
private IDictionary _reverseValues;
public EnumDisplayer() {
}
public EnumDisplayer(Type type) {
Type = type;
}
public Type Type {
public Type Type {
get { return _type; }
set {
if (!value.IsEnum) {

View file

@ -1,113 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Collections;
using System.Windows.Forms;
namespace GreenshotConfluencePlugin.Forms
{
/// <summary>
/// This class is an implementation of the 'IComparer' interface.
/// </summary>
public class ListViewColumnSorter : IComparer {
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int _columnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder _orderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
private readonly CaseInsensitiveComparer _objectCompare;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public ListViewColumnSorter() {
// Initialize the column to '0'
_columnToSort = 0;
// Initialize the sort order to 'none'
_orderOfSort = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
_objectCompare = new CaseInsensitiveComparer();
}
/// <summary>
/// This method is inherited from the IComparer interface. It compares the two objects passed using a case insensitive comparison.
/// </summary>
/// <param name="x">First object to be compared</param>
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
public int Compare(object x, object y) {
int compareResult;
ListViewItem listviewX, listviewY;
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
// Compare the two items
compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text);
// Calculate correct return value based on object comparison
if (_orderOfSort == SortOrder.Ascending) {
// Ascending sort is selected, return normal result of compare operation
return compareResult;
} else if (_orderOfSort == SortOrder.Descending) {
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
} else {
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn {
set {
_columnToSort = value;
}
get {
return _columnToSort;
}
}
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order {
set {
_orderOfSort = value;
}
get {
return _orderOfSort;
}
}
}
}

View file

@ -22,14 +22,7 @@
namespace GreenshotConfluencePlugin {
public enum LangKey {
login_error,
login_title,
label_url,
label_upload_format,
OK,
CANCEL,
upload_menu_item,
upload_success,
upload_failure,
communication_wait
}
}

View file

@ -29,12 +29,7 @@ namespace GreenshotConfluencePlugin.Support {
public ITranslationProvider TranslationProvider { get; set; }
private void OnLanguageChanged()
{
LanguageChanged?.Invoke(this, EventArgs.Empty);
}
public object Translate(string key) {
public object Translate(string key) {
object translatedValue = TranslationProvider?.Translate(key);
if( translatedValue != null) {
return translatedValue;

View file

@ -21,13 +21,8 @@
namespace GreenshotDropboxPlugin {
public enum LangKey {
upload_menu_item,
settings_title,
label_upload_format,
upload_success,
upload_failure,
communication_wait,
Configure,
label_AfterUpload,
label_AfterUploadLinkToClipBoard
}
Configure
}
}

View file

@ -29,134 +29,158 @@ using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
namespace GreenshotExternalCommandPlugin {
/// <summary>
/// An Plugin to run commands after an image was written
/// </summary>
namespace GreenshotExternalCommandPlugin
{
/// <summary>
/// An Plugin to run commands after an image was written
/// </summary>
[Plugin("ExternalCommand", true)]
public class ExternalCommandPlugin : IGreenshotPlugin {
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ExternalCommandPlugin));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection<ExternalCommandConfiguration>();
private ToolStripMenuItem _itemPlugInRoot;
public class ExternalCommandPlugin : IGreenshotPlugin
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ExternalCommandPlugin));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection<ExternalCommandConfiguration>();
private ToolStripMenuItem _itemPlugInRoot;
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (_itemPlugInRoot == null) return;
_itemPlugInRoot.Dispose();
_itemPlugInRoot = null;
}
private IEnumerable<IDestination> Destinations() {
foreach(string command in ExternalCommandConfig.Commands) {
yield return new ExternalCommandDestination(command);
}
}
private IEnumerable<IDestination> Destinations()
{
foreach (string command in ExternalCommandConfig.Commands)
{
yield return new ExternalCommandDestination(command);
}
}
/// <summary>
/// Check and eventually fix the command settings
/// </summary>
/// <param name="command"></param>
/// <returns>false if the command is not correctly configured</returns>
private bool IsCommandValid(string command) {
if (!ExternalCommandConfig.RunInbackground.ContainsKey(command)) {
Log.WarnFormat("Found missing runInbackground for {0}", command);
// Fix it
ExternalCommandConfig.RunInbackground.Add(command, true);
}
if (!ExternalCommandConfig.Argument.ContainsKey(command)) {
Log.WarnFormat("Found missing argument for {0}", command);
// Fix it
ExternalCommandConfig.Argument.Add(command, "{0}");
}
if (!ExternalCommandConfig.Commandline.ContainsKey(command)) {
Log.WarnFormat("Found missing commandline for {0}", command);
return false;
}
string commandline = FilenameHelper.FillVariables(ExternalCommandConfig.Commandline[command], true);
commandline = FilenameHelper.FillCmdVariables(commandline, true);
/// <summary>
/// Check and eventually fix the command settings
/// </summary>
/// <param name="command"></param>
/// <returns>false if the command is not correctly configured</returns>
private bool IsCommandValid(string command)
{
if (!ExternalCommandConfig.RunInbackground.ContainsKey(command))
{
Log.WarnFormat("Found missing runInbackground for {0}", command);
// Fix it
ExternalCommandConfig.RunInbackground.Add(command, true);
}
if (!ExternalCommandConfig.Argument.ContainsKey(command))
{
Log.WarnFormat("Found missing argument for {0}", command);
// Fix it
ExternalCommandConfig.Argument.Add(command, "{0}");
}
if (!ExternalCommandConfig.Commandline.ContainsKey(command))
{
Log.WarnFormat("Found missing commandline for {0}", command);
return false;
}
string commandline = FilenameHelper.FillVariables(ExternalCommandConfig.Commandline[command], true);
commandline = FilenameHelper.FillCmdVariables(commandline, true);
if (!File.Exists(commandline)) {
Log.WarnFormat("Found 'invalid' commandline {0} for command {1}", ExternalCommandConfig.Commandline[command], command);
return false;
}
if (!File.Exists(commandline))
{
Log.WarnFormat("Found 'invalid' commandline {0} for command {1}", ExternalCommandConfig.Commandline[command], command);
return false;
}
return true;
}
/// <summary>
/// Implementation of the IGreenshotPlugin.Initialize
/// </summary>
public virtual bool Initialize()
{
Log.DebugFormat("Initialize called");
var commandsToDelete = new List<string>();
// Check configuration
foreach (string command in ExternalCommandConfig.Commands)
{
if (!IsCommandValid(command))
{
commandsToDelete.Add(command);
}
}
// cleanup
foreach (string command in commandsToDelete)
{
ExternalCommandConfig.Delete(command);
}
SimpleServiceProvider.Current.AddService(Destinations());
return true;
}
/// <summary>
/// Implementation of the IGreenshotPlugin.Initialize
/// </summary>
public virtual bool Initialize() {
Log.DebugFormat("Initialize called");
List<string> commandsToDelete = new List<string>();
// Check configuration
foreach(string command in ExternalCommandConfig.Commands) {
if (!IsCommandValid(command)) {
commandsToDelete.Add(command);
}
}
// cleanup
foreach (string command in commandsToDelete) {
ExternalCommandConfig.Delete(command);
}
_itemPlugInRoot = new ToolStripMenuItem();
_itemPlugInRoot = new ToolStripMenuItem();
_itemPlugInRoot.Click += ConfigMenuClick;
OnIconSizeChanged(this, new PropertyChangedEventArgs("IconSize"));
OnLanguageChanged(this, null);
OnIconSizeChanged(this, new PropertyChangedEventArgs("IconSize"));
OnLanguageChanged(this, null);
PluginUtils.AddToContextMenu(_itemPlugInRoot);
Language.LanguageChanged += OnLanguageChanged;
CoreConfig.PropertyChanged += OnIconSizeChanged;
return true;
}
PluginUtils.AddToContextMenu(_itemPlugInRoot);
Language.LanguageChanged += OnLanguageChanged;
CoreConfig.PropertyChanged += OnIconSizeChanged;
return true;
}
/// <summary>
/// Fix icon reference
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnIconSizeChanged(object sender, PropertyChangedEventArgs e) {
if (e.PropertyName == "IconSize") {
try {
string exePath = PluginUtils.GetExePath("cmd.exe");
if (exePath != null && File.Exists(exePath)) {
_itemPlugInRoot.Image = PluginUtils.GetCachedExeIcon(exePath, 0);
}
} catch (Exception ex) {
Log.Warn("Couldn't get the cmd.exe image", ex);
}
}
}
/// <summary>
/// Fix icon reference
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnIconSizeChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IconSize")
{
try
{
string exePath = PluginUtils.GetExePath("cmd.exe");
if (exePath != null && File.Exists(exePath))
{
_itemPlugInRoot.Image = PluginUtils.GetCachedExeIcon(exePath, 0);
}
}
catch (Exception ex)
{
Log.Warn("Couldn't get the cmd.exe image", ex);
}
}
}
private void OnLanguageChanged(object sender, EventArgs e) {
if (_itemPlugInRoot != null) {
_itemPlugInRoot.Text = Language.GetString("externalcommand", "contextmenu_configure");
}
}
private void OnLanguageChanged(object sender, EventArgs e)
{
if (_itemPlugInRoot != null)
{
_itemPlugInRoot.Text = Language.GetString("externalcommand", "contextmenu_configure");
}
}
public virtual void Shutdown() {
Log.Debug("Shutdown");
}
public virtual void Shutdown()
{
Log.Debug("Shutdown");
}
private void ConfigMenuClick(object sender, EventArgs eventArgs) {
Configure();
}
private void ConfigMenuClick(object sender, EventArgs eventArgs)
{
Configure();
}
/// <summary>
/// Implementation of the IPlugin.Configure
/// </summary>
public virtual void Configure() {
Log.Debug("Configure called");
new SettingsForm().ShowDialog();
}
}
/// <summary>
/// Implementation of the IPlugin.Configure
/// </summary>
public virtual void Configure()
{
Log.Debug("Configure called");
new SettingsForm().ShowDialog();
}
}
}

View file

@ -21,15 +21,8 @@
namespace GreenshotFlickrPlugin {
public enum LangKey {
upload_menu_item,
settings_title,
label_upload_format,
upload_success,
upload_failure,
communication_wait,
Configure,
label_HiddenFromSearch,
label_SafetyLevel,
label_AfterUpload,
label_AfterUploadLinkToClipBoard
}
Configure
}
}

View file

@ -22,13 +22,8 @@ namespace GreenshotGooglePhotosPlugin {
public enum LangKey
{
upload_menu_item,
settings_title,
label_upload_format,
upload_success,
upload_failure,
communication_wait,
Configure,
label_AfterUpload,
label_AfterUploadLinkToClipBoard
Configure
}
}

View file

@ -22,19 +22,11 @@
namespace GreenshotImgurPlugin {
public enum LangKey {
upload_menu_item,
settings_title,
label_url,
label_upload_format,
label_clear,
OK,
CANCEL,
upload_success,
upload_failure,
communication_wait,
delete_question,
clear_question,
delete_title,
use_page_link,
history,
configure
}

View file

@ -80,39 +80,7 @@ namespace GreenshotJiraPlugin
return keyObject.ToString();
}
/// <summary>
/// Get an element from the cache, if this is not available call the create function.
/// </summary>
/// <param name="keyObject">object for the key</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>TResult</returns>
public async Task DeleteAsync(TKey keyObject, CancellationToken cancellationToken = default)
{
var key = CreateKey(keyObject);
await _semaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
_cache.Remove(key);
}
finally
{
_semaphoreSlim.Release();
}
}
/// <summary>
/// Get a task element from the cache, if this is not available return null.
/// You probably want to call GetOrCreateAsync
/// </summary>
/// <param name="keyObject">object for the key</param>
/// <returns>Task with TResult, null if no value</returns>
public Task<TResult> GetAsync(TKey keyObject)
{
var key = CreateKey(keyObject);
return _cache.Get(key) as Task<TResult> ?? EmptyValueTask;
}
/// <summary>
/// <summary>
/// Get a task element from the cache, if this is not available call the create function.
/// </summary>
/// <param name="keyObject">object for the key</param>
@ -124,20 +92,7 @@ namespace GreenshotJiraPlugin
return _cache.Get(key) as Task<TResult> ?? GetOrCreateInternalAsync(keyObject, null, cancellationToken);
}
/// <summary>
/// Get a task element from the cache, if this is not available call the create function.
/// </summary>
/// <param name="keyObject">object for the key</param>
/// <param name="cacheItemPolicy">CacheItemPolicy for when you want more control over the item</param>
/// <param name="cancellationToken">CancellationToken</param>
/// <returns>Task with TResult</returns>
public Task<TResult> GetOrCreateAsync(TKey keyObject, CacheItemPolicy cacheItemPolicy, CancellationToken cancellationToken = default)
{
var key = CreateKey(keyObject);
return _cache.Get(key) as Task<TResult> ?? GetOrCreateInternalAsync(keyObject, cacheItemPolicy, cancellationToken);
}
/// <summary>
/// <summary>
/// This takes care of the real async part of the code.
/// </summary>
/// <param name="keyObject"></param>
@ -213,7 +168,7 @@ namespace GreenshotJiraPlugin
/// Override to know when an item is removed, make sure to configure ActivateUpdateCallback / ActivateRemovedCallback
/// </summary>
/// <param name="cacheEntryRemovedArguments">CacheEntryRemovedArguments</param>
protected virtual void RemovedCallback(CacheEntryRemovedArguments cacheEntryRemovedArguments)
protected void RemovedCallback(CacheEntryRemovedArguments cacheEntryRemovedArguments)
{
_log.Verbose().WriteLine("Item {0} removed due to {1}.", cacheEntryRemovedArguments.CacheItem.Key, cacheEntryRemovedArguments.RemovedReason);
if (cacheEntryRemovedArguments.CacheItem.Value is IDisposable disposable)
@ -228,7 +183,7 @@ namespace GreenshotJiraPlugin
/// ActivateUpdateCallback / ActivateRemovedCallback
/// </summary>
/// <param name="cacheEntryUpdateArguments">CacheEntryUpdateArguments</param>
protected virtual void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments)
protected void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments)
{
_log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason);
}

View file

@ -34,10 +34,7 @@ namespace GreenshotJiraPlugin {
[IniProperty("Url", Description="Base url to Jira system, without anything else", DefaultValue=DefaultUrl)]
public string Url { get; set; }
[IniProperty("Timeout", Description="Session timeout in minutes", DefaultValue="30")]
public int Timeout { get; set; }
[IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
[IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
public OutputFormat UploadFormat { get; set; }
[IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]

View file

@ -30,16 +30,8 @@ namespace GreenshotJiraPlugin {
column_summary,
label_comment,
label_filename,
label_jira,
label_jirafilter,
login_error,
login_title,
settings_title,
label_url,
label_upload_format,
OK,
CANCEL,
upload_success,
upload_failure,
communication_wait,
}

View file

@ -1,513 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace GreenshotOCRCommand {
/// <summary>
/// Wraps a late-bound COM server.
/// </summary>
public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo {
private const int MK_E_UNAVAILABLE = -2147221021;
private const int CO_E_CLASSSTRING = -2147221005;
/// <summary>
/// Holds reference to the actual COM object which is wrapped by this proxy
/// </summary>
private readonly object _comObject;
/// <summary>
/// Type of the COM object, set on constructor after getting the COM reference
/// </summary>
private readonly Type _comType;
/// <summary>
/// The type of which method calls are intercepted and executed on the COM object.
/// </summary>
private readonly Type _interceptType;
/// <summary>
/// Gets a COM object and returns the transparent proxy which intercepts all calls to the object
/// </summary>
/// <typeparam name="T">Interface which defines the method and properties to intercept</typeparam>
/// <returns>Transparent proxy to the real proxy for the object</returns>
/// <remarks>T must be an interface decorated with the <see cref="ComProgIdAttribute"/>attribute.</remarks>
public static T GetInstance<T>() {
Type type = typeof(T);
if (null == type) {
throw new ArgumentNullException(nameof(T));
}
if (!type.IsInterface) {
throw new ArgumentException("The specified type must be an interface.", nameof(T));
}
ComProgIdAttribute progIdAttribute = ComProgIdAttribute.GetAttribute(type);
if (string.IsNullOrEmpty(progIdAttribute?.Value)) {
throw new ArgumentException("The specified type must define a ComProgId attribute.", nameof(T));
}
string progId = progIdAttribute.Value;
object comObject = null;
try {
comObject = Marshal.GetActiveObject(progId);
} catch (COMException comE) {
if (comE.ErrorCode == MK_E_UNAVAILABLE)
{
Debug.WriteLine($"No current instance of {progId} object available.");
}
else if (comE.ErrorCode == CO_E_CLASSSTRING)
{
Debug.WriteLine($"Unknown progId {progId}");
}
} catch (Exception ex) {
Debug.WriteLine($"Error getting active object for {progId} {ex.Message}");
}
if (comObject != null) {
COMWrapper wrapper = new COMWrapper(comObject, type);
return (T)wrapper.GetTransparentProxy();
}
return default;
}
/// <summary>
/// Gets or creates a COM object and returns the transparent proxy which intercepts all calls to the object
/// The ComProgId can be a normal ComProgId or a GUID prefixed with "clsid:"
/// </summary>
/// <typeparam name="T">Interface which defines the method and properties to intercept</typeparam>
/// <returns>Transparent proxy to the real proxy for the object</returns>
/// <remarks>The type must be an interface decorated with the <see cref="ComProgIdAttribute"/>attribute.</remarks>
public static T GetOrCreateInstance<T>() {
Type type = typeof(T);
if (null == type) {
throw new ArgumentNullException(nameof(T));
}
if (!type.IsInterface) {
throw new ArgumentException("The specified type must be an interface.", nameof(T));
}
ComProgIdAttribute progIdAttribute = ComProgIdAttribute.GetAttribute(type);
if (string.IsNullOrEmpty(progIdAttribute?.Value)) {
throw new ArgumentException("The specified type must define a ComProgId attribute.", nameof(T));
}
object comObject = null;
Type comType = null;
string progId = progIdAttribute.Value;
try {
comObject = Marshal.GetActiveObject(progId);
} catch (COMException comE) {
if (comE.ErrorCode == MK_E_UNAVAILABLE)
{
Debug.WriteLine($"No current instance of {progId} object available.");
}
else if (comE.ErrorCode == CO_E_CLASSSTRING)
{
Debug.WriteLine($"Unknown progId {progId}");
}
} catch (Exception ex) {
Debug.WriteLine($"Error getting active object for {progId} {ex.Message}");
}
// Did we get the current instance? If not, try to create a new
if (comObject == null) {
try {
comType = Type.GetTypeFromProgID(progId, true);
} catch (Exception) {
Debug.WriteLine($"Error getting type for {progId}");
}
if (comType != null) {
try {
comObject = Activator.CreateInstance(comType);
if (comObject != null) {
Debug.WriteLine($"Created new instance of {progId} object.");
}
} catch (Exception ex) {
Debug.WriteLine($"Error creating object for {progId} {ex.Message}");
}
}
}
if (comObject != null) {
COMWrapper wrapper = new COMWrapper(comObject, type);
return (T)wrapper.GetTransparentProxy();
}
return default;
}
/// <summary>
/// Wrap an object and return the transparent proxy which intercepts all calls to the object
/// </summary>
/// <param name="comObject">An object to intercept</param>
/// <param name="type">Interface which defines the method and properties to intercept</param>
/// <returns>Transparent proxy to the real proxy for the object</returns>
private static object Wrap(object comObject, Type type) {
if (null == comObject) {
throw new ArgumentNullException(nameof(comObject));
}
if (null == type) {
throw new ArgumentNullException(nameof(type));
}
COMWrapper wrapper = new COMWrapper(comObject, type);
return wrapper.GetTransparentProxy();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="comObject">
/// The COM object to wrap.
/// </param>
/// <param name="type">
/// The interface type to impersonate.
/// </param>
private COMWrapper(object comObject, Type type)
: base(type) {
_comObject = comObject;
_comType = comObject.GetType();
_interceptType = type;
}
/// <summary>
/// If <see cref="Dispose"/> is not called, we need to make
/// sure that the COM object is still cleaned up.
/// </summary>
~COMWrapper() {
Dispose(false);
}
/// <summary>
/// Cleans up the COM object.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Release the COM reference
/// </summary>
/// <param name="disposing">
/// <see langword="true"/> if this was called from the
/// <see cref="IDisposable"/> interface.
/// </param>
private void Dispose(bool disposing) {
if (disposing && null != _comObject) {
if (Marshal.IsComObject(_comObject)) {
try {
while (Marshal.ReleaseComObject(_comObject) > 0)
{
}
} catch (Exception ex) {
Debug.WriteLine($"Problem releasing {_comType}");
Debug.WriteLine("Error: " + ex);
}
}
}
}
/// <summary>
/// Returns a string representing the wrapped object.
/// </summary>
/// <returns>
/// The full name of the intercepted type.
/// </returns>
public override string ToString() {
return _interceptType.FullName;
}
/// <summary>
/// Returns the hash code of the wrapped object.
/// </summary>
/// <returns>
/// The hash code of the wrapped object.
/// </returns>
public override int GetHashCode() {
return _comObject.GetHashCode();
}
/// <summary>
/// Compares this object to another.
/// </summary>
/// <param name="value">
/// The value to compare to.
/// </param>
/// <returns>
/// <see langword="true"/> if the objects are equal.
/// </returns>
public override bool Equals(object value) {
if (null != value && RemotingServices.IsTransparentProxy(value)) {
if (RemotingServices.GetRealProxy(value) is COMWrapper wrapper) {
return _comObject == wrapper._comObject;
}
}
return base.Equals(value);
}
/// <summary>
/// Returns the base type for a reference type.
/// </summary>
/// <param name="byRefType">
/// The reference type.
/// </param>
/// <returns>
/// The base value type.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="byRefType"/> is <see langword="null"/>.
/// </exception>
private static Type GetByValType(Type byRefType) {
if (null == byRefType) {
throw new ArgumentNullException(nameof(byRefType));
}
if (byRefType.IsByRef) {
string name = byRefType.FullName;
name = name.Substring(0, name.Length - 1);
byRefType = byRefType.Assembly.GetType(name, true);
}
return byRefType;
}
/// <summary>
/// Intercept method calls
/// </summary>
/// <param name="myMessage">
/// Contains information about the method being called
/// </param>
/// <returns>
/// A <see cref="ReturnMessage"/>.
/// </returns>
public override IMessage Invoke(IMessage myMessage) {
IMethodCallMessage callMessage = myMessage as IMethodCallMessage;
MethodInfo method = callMessage?.MethodBase as MethodInfo;
if (method == null)
{
if (callMessage != null)
{
Debug.WriteLine($"Unrecognized Invoke call: {callMessage.MethodBase}");
}
return null;
}
object returnValue = null;
object[] outArgs = null;
int outArgsCount = 0;
string methodName = method.Name;
Type returnType = method.ReturnType;
BindingFlags flags = BindingFlags.InvokeMethod;
int argCount = callMessage.ArgCount;
ParameterModifier[] argModifiers = null;
ParameterInfo[] parameters = null;
if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) {
Dispose();
} else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) {
returnValue = ToString();
} else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) {
returnValue = _interceptType;
} else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) {
returnValue = GetHashCode();
} else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) {
returnValue = Equals(callMessage.Args[0]);
} else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) {
if (!(callMessage.InArgs[0] is Delegate handler)) {
return new ReturnMessage(new ArgumentNullException(nameof(handler)), callMessage);
}
} else {
var invokeObject = _comObject;
var invokeType = _comType;
ParameterInfo parameter;
object[] args;
if (methodName.StartsWith("get_")) {
// Property Get
methodName = methodName.Substring(4);
flags = BindingFlags.GetProperty;
args = callMessage.InArgs;
} else if (methodName.StartsWith("set_")) {
// Property Set
methodName = methodName.Substring(4);
flags = BindingFlags.SetProperty;
args = callMessage.InArgs;
} else {
args = callMessage.Args;
if (null != args && 0 != args.Length) {
// Modifiers for ref / out parameters
argModifiers = new ParameterModifier[1];
argModifiers[0] = new ParameterModifier(args.Length);
parameters = method.GetParameters();
for (int i = 0; i < parameters.Length; i++) {
parameter = parameters[i];
if (parameter.IsOut || parameter.ParameterType.IsByRef) {
argModifiers[0][i] = true;
outArgsCount++;
}
}
if (0 == outArgsCount) {
argModifiers = null;
}
}
}
// Un-wrap wrapped COM objects before passing to the method
COMWrapper[] originalArgs;
COMWrapper wrapper;
Type byValType;
if (null == args || 0 == args.Length) {
originalArgs = null;
} else {
originalArgs = new COMWrapper[args.Length];
for (int i = 0; i < args.Length; i++) {
if (null != args[i] && RemotingServices.IsTransparentProxy(args[i])) {
wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
if (null != wrapper) {
originalArgs[i] = wrapper;
args[i] = wrapper._comObject;
}
} else if (argModifiers != null && (0 != outArgsCount && argModifiers[0][i])) {
byValType = GetByValType(parameters[i].ParameterType);
if (byValType.IsInterface) {
// If we're passing a COM object by reference, and
// the parameter is null, we need to pass a
// DispatchWrapper to avoid a type mismatch exception.
if (null == args[i]) {
args[i] = new DispatchWrapper(null);
}
} else if (typeof(decimal) == byValType) {
// If we're passing a decimal value by reference,
// we need to pass a CurrencyWrapper to avoid a
// type mismatch exception.
// http://support.microsoft.com/?kbid=837378
args[i] = new CurrencyWrapper(args[i]);
}
}
}
}
try {
returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null);
} catch (Exception ex) {
return new ReturnMessage(ex, callMessage);
}
// Handle enum and interface return types
if (null != returnValue) {
if (returnType.IsInterface) {
// Wrap the returned value in an intercepting COM wrapper
if (Marshal.IsComObject(returnValue)) {
returnValue = Wrap(returnValue, returnType);
}
} else if (returnType.IsEnum) {
// Convert to proper Enum type
returnValue = Enum.Parse(returnType, returnValue.ToString());
}
}
// Handle out args
if (0 != outArgsCount) {
if (args != null && parameters != null)
{
outArgs = new object[args.Length];
for (int i = 0; i < parameters.Length; i++) {
if (argModifiers != null && !argModifiers[0][i]) {
continue;
}
var arg = args[i];
if (null == arg) {
continue;
}
parameter = parameters[i];
wrapper = null;
byValType = GetByValType(parameter.ParameterType);
if (typeof(decimal) == byValType) {
if (arg is CurrencyWrapper) {
arg = ((CurrencyWrapper)arg).WrappedObject;
}
} else if (byValType.IsEnum) {
arg = Enum.Parse(byValType, arg.ToString());
} else if (byValType.IsInterface) {
if (Marshal.IsComObject(arg)) {
if (originalArgs != null)
{
wrapper = originalArgs[i];
}
if (null != wrapper && wrapper._comObject != arg) {
wrapper.Dispose();
wrapper = null;
}
if (null == wrapper) {
wrapper = new COMWrapper(arg, byValType);
}
arg = wrapper.GetTransparentProxy();
}
}
outArgs[i] = arg;
}
}
}
}
return new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage);
}
/// <summary>
/// Implementation for the interface IRemotingTypeInfo
/// This makes it possible to cast the COMWrapper
/// </summary>
/// <param name="toType">Type to cast to</param>
/// <param name="o">object to cast</param>
/// <returns></returns>
public bool CanCastTo(Type toType, object o) {
bool returnValue = _interceptType.IsAssignableFrom(toType);
return returnValue;
}
/// <summary>
/// Implementation for the interface IRemotingTypeInfo
/// </summary>
public string TypeName {
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
}
}

View file

@ -1,78 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace GreenshotOCRCommand {
/// <summary>
/// An attribute to specifiy the ProgID of the COM class to create. (As suggested by Kristen Wegner)
/// </summary>
[AttributeUsage(AttributeTargets.Interface)]
public sealed class ComProgIdAttribute : Attribute {
/// <summary>
/// Extracts the attribute from the specified type.
/// </summary>
/// <param name="interfaceType">
/// The interface type.
/// </param>
/// <returns>
/// The <see cref="ComProgIdAttribute"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="interfaceType"/> is <see langword="null"/>.
/// </exception>
public static ComProgIdAttribute GetAttribute(Type interfaceType) {
if (null == interfaceType) {
throw new ArgumentNullException(nameof(interfaceType));
}
Type attributeType = typeof(ComProgIdAttribute);
object[] attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 == attributes.Length) {
Type[] interfaces = interfaceType.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++) {
interfaceType = interfaces[i];
attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 != attributes.Length) {
break;
}
}
}
if (0 == attributes.Length) {
return null;
}
return (ComProgIdAttribute)attributes[0];
}
/// <summary>Constructor</summary>
/// <param name="value">The COM ProgID.</param>
public ComProgIdAttribute(string value) {
Value = value;
}
/// <summary>
/// Returns the COM ProgID
/// </summary>
public string Value { get; }
}
}

View file

@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<RootNamespace>GreenshotOCRCommand</RootNamespace>
<AssemblyName>GreenshotOCRCommand</AssemblyName>
<OutputType>WinExe</OutputType>
</PropertyGroup>
<ItemGroup>
<Reference Include="CustomMarshalers" />
</ItemGroup>
<Target Name="PostBuild" BeforeTargets="PostBuildEvent" Condition="'$(BuildingInsideVisualStudio)' == 'true'">
<Exec Command="xcopy /q /y /d &quot;$(TargetDir)*.exe&quot; &quot;$(SolutionDir)$(SolutionName)\$(OutDir)&quot;" />
</Target>
</Project>

View file

@ -1,29 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
public enum CompressionLevel {
miCOMP_LEVEL_LOW = 0,
miCOMP_LEVEL_MEDIUM = 1,
miCOMP_LEVEL_HIGH = 2
}
}

View file

@ -1,30 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
public enum FileFormat {
miFILE_FORMAT_DEFAULTVALUE = -1,
miFILE_FORMAT_TIFF = 1,
miFILE_FORMAT_TIFF_LOSSLESS = 2,
miFILE_FORMAT_MDI = 4
}
}

View file

@ -1,32 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Base class for the common properties of the Modi interfaces
/// </summary>
public interface ICommon : IDisposable {
IDocument Application { get; }
}
}

View file

@ -1,33 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.CustomMarshalers;
namespace GreenshotOCRCommand.Modi {
[ComImport, Guid("00020400-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDispatch {
void Reserved();
[PreserveSig]
int GetTypeInfo(uint nInfo, int lcid, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(TypeToTypeInfoMarshaler))] out Type typeInfo);
}
}

View file

@ -1,79 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi {
/// <summary>
/// The MODI Document object represents an ordered collection of document images saved as a single file.
/// You can use the Create method to load an existing MDI or TIF file, or to create an empty document that you can populate with images from other documents.
/// The OCR method performs OCR on all pages in the document, and the OnOCRProgress event reports the status of the operation and allows the user to cancel it.
/// The Dirty property lets you know whether your document has unsaved OCR results or changes.
/// The SaveAs method allows you to specify an image file format and a compression level.
/// You can also use the PrintOut method to print the document to a printer or a file.
/// </summary>
[ComProgId("MODI.Document")]
public interface IDocument : ICommon {
/// <summary>
/// Closes the document.
/// </summary>
/// <param name="saveCall"></param>
void Close(bool saveCall);
/// <summary>
/// The document's collection of pages.
/// </summary>
IImages Images
{
get;
}
/// <summary>
/// Occurs periodically during an optical character recognition (OCR) operation. Returns the estimated percentage of the OCR operation that is complete, and allows the user to cancel the operation.
/// </summary>
// event OnOCRProgress { get; }
/// <summary>
/// Indicates whether the active document has unsaved changes.
/// </summary>
bool Dirty { get; }
/// <summary>
/// Creates a new document.
/// </summary>
/// <param name="file">Optional String. The path and filename of the optional document file that is to be loaded into the new document.</param>
void Create(string file);
/// <summary>
/// Performs optical character recognition (OCR) on the specified document or image.
/// </summary>
/// <param name="language">ModiLanguage</param>
/// <param name="orientimage">Optional Boolean. Specifies whether the OCR engine attempts to determine the orientation of the page. Default is true.</param>
/// <param name="straightenImage">Optional Boolean. Specifies whether the OCR engine attempts to "de-skew" the page to correct for small angles of misalignment from the vertical. Default is true.</param>
void OCR(ModiLanguage language, bool orientimage, bool straightenImage);
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <param name="fileFormat"></param>
/// <param name="compressionLevel"></param>
void SaveAs(string filename, FileFormat fileFormat, CompressionLevel compressionLevel);
}
}

View file

@ -1,41 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Describes the page in a scan
/// </summary>
public interface IImage : ICommon {
ILayout Layout {
get;
}
long BitsPerPixel { get; }
CompressionLevel Compression { get; }
//IPictureDisp Picture { get; }
int PixelHeight { get; }
int PixelWidth { get; }
//IPictureDisp Thumbnail { get; }
int XDPI { get; }
int YDPI { get; }
}
}

View file

@ -1,41 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Collections;
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Use the Images accessor property of the Document object to return an Images collection.
/// Use the Item property of the Images collection to return an Image object and gain access to its OCR Layout
/// (including recognized Text and Words), the properties that describe its dimensions and format (BitsPerPixel, Compression, PixelHeight, PixelWidth, XDPI, and YDPI),
/// and its Picture and Thumbnail images.
/// </summary>
public interface IImages : ICommon, IEnumerable {
int Count {
get;
}
IImage this [int index] {
get;
}
new IEnumerator GetEnumerator();
}
}

View file

@ -1,55 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Layout of the IImage
/// </summary>
public interface ILayout : ICommon {
/// <summary>
/// Returns the recognized text as a Unicode string.
/// </summary>
string Text {
get;
}
/// <summary>
/// An accessor property that returns the Words collection recognized in the text during an optical character recognition (OCR) operation.
/// </summary>
IWords Words { get; }
/// <summary>
/// Returns the number of characters in the recognized text.
/// </summary>
int NumChars { get; }
/// <summary>
/// Returns the number of words in the recognized text.
/// </summary>
int NumWords { get; }
/// <summary>
/// Returns the language identifier for the recognized text. Read-only Long.
/// </summary>
ModiLanguage Language { get; }
}
}

View file

@ -1,48 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Represents a bounding rectangle in the optical character recognition (OCR) layout.
/// </summary>
public interface IMiRect : ICommon {
/// <summary>
/// The Bottom property represent the distance in pixels from the top edge of the containing image.
/// </summary>
int Bottom { get; }
/// <summary>
/// The Left property represent the distance in pixels from the left edge of the containing image.
/// </summary>
int Left { get; }
/// <summary>
/// The Right property represent the distance in pixels from the left edge of the containing image.
/// </summary>
int Right { get; }
/// <summary>
/// The Top property represent the distance in pixels from the top edge of the containing image.
/// </summary>
int Top { get; }
}
}

View file

@ -1,38 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Collections;
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Represents the collection of bounding rectangles in the optical character recognition (OCR) layout. A collection of MiRect objects.
/// </summary>
public interface IMiRects : ICommon, IEnumerable {
int Count {
get;
}
IMiRect this [int index] {
get;
}
new IEnumerator GetEnumerator();
}
}

View file

@ -1,65 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// Represents a word recognized in the text during an optical character recognition (OCR) operation.
/// </summary>
public interface IWord : ICommon
{
/// <summary>
/// Returns the index of the specified word in the Words collection of the Layout or IMiSelectableItem object.
/// </summary>
long Id { get; }
/// <summary>
/// Returns the number of the region in the optical character recognition (OCR) layout where the word occurs.
/// </summary>
long RegionId { get; }
/// <summary>
/// Returns the number of the line in the optical character recognition (OCR) layout where the word occurs.
/// </summary>
long LineId { get; }
/// <summary>
/// Returns the recognized text as a Unicode string.
/// </summary>
string Text { get; }
/// <summary>
/// Returns the relative confidence factor reported by the optical character recognition (OCR) engine (on a scale of 0 to 999) after recognizing the specified word.
/// </summary>
short RecognitionConfidence { get; }
/// <summary>
/// Returns the index of the font used by the specified wordthis is the font that was recognized in the text during an optical character recognition (OCR) operation.
/// </summary>
long FontId { get; }
/// <summary>
/// Rectangles
/// </summary>
IMiRects Rects { get; }
}
}

View file

@ -1,43 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Collections;
namespace GreenshotOCRCommand.Modi
{
/// <summary>
/// The Words collection recognized in the text during an optical character recognition (OCR) operation.
/// </summary>
public interface IWords : ICommon, IEnumerable
{
int Count
{
get;
}
IWord this[int index]
{
get;
}
new IEnumerator GetEnumerator();
}
}

View file

@ -1,48 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRCommand.Modi
{
public enum ModiLanguage {
CHINESE_SIMPLIFIED = 2052,
CHINESE_TRADITIONAL = 1028,
CZECH = 5,
DANISH = 6,
DUTCH = 19,
ENGLISH = 9,
FINNISH = 11,
FRENCH = 12,
GERMAN = 7,
GREEK = 8,
HUNGARIAN = 14,
ITALIAN = 16,
JAPANESE = 17,
KOREAN = 18,
NORWEGIAN = 20,
POLISH = 21,
PORTUGUESE = 22,
RUSSIAN = 25,
SPANISH = 10,
SWEDISH = 29,
TURKISH = 31,
SYSDEFAULT = 2048
}
}

View file

@ -1,121 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using GreenshotOCRCommand.Modi;
namespace GreenshotOCRCommand {
public class Program {
private const string Usage = "<-c> | <path to image.bmp> [language] [orientimage] [straightenImage]";
public static int Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine(Usage);
return -1;
}
string filename = args[0];
ModiLanguage language = ModiLanguage.ENGLISH;
if (args.Length >= 2) {
language = (ModiLanguage)Enum.Parse(typeof(ModiLanguage), args[1]);
}
bool orientimage = true;
if (args.Length >= 3) {
orientimage = bool.Parse(args[2]);
}
bool straightenImage = true;
if (args.Length >= 4) {
straightenImage = bool.Parse(args[3]);
}
try {
if (File.Exists(filename) || "-c".Equals(filename))
{
using var document = COMWrapper.GetOrCreateInstance<IDocument>();
if (document == null) {
Console.WriteLine("MODI not installed");
return -2;
}
if ("-c".Equals(filename)) {
return 0;
}
document.Create(filename);
document.OCR(language, orientimage, straightenImage);
var modiImage = document.Images[0];
var layout = modiImage.Layout;
if (layout != null)
{
#if DEBUG
if (layout.Words != null)
{
foreach (var word in ToEnumerable(layout.Words))
{
if (word.Rects != null)
{
foreach (var rect in ToEnumerable(word.Rects))
{
Debug.WriteLine($"Rect {rect.Left},{rect.Top},{rect.Right},{rect.Bottom} - Word {word.Text} : Confidence: {word.RecognitionConfidence}");
}
}
}
}
#endif
if (layout.Text != null)
{
// For for BUG-1884:
// Although trim is done in the OCR Plugin, it does make sense in the command too.
Console.WriteLine(layout.Text.Trim());
}
}
document.Close(false);
return 0;
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
return -1;
}
/// <summary>
/// Helper method
/// </summary>
/// <returns>IEnumerable of IMiRect</returns>
private static IEnumerable<IMiRect> ToEnumerable(IMiRects rects)
{
for (int i = 0; i < rects.Count; i++)
{
yield return rects[i];
}
}
/// <summary>
/// Helper method
/// </summary>
/// <returns>IEnumerable of IWord</returns>
private static IEnumerable<IWord> ToEnumerable(IWords words)
{
for (int i = 0; i < words.Count; i++)
{
yield return words[i];
}
}
}
}

View file

@ -1,36 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyDescription("A small executable to OCR a bitmap")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("d7668e7e-3018-4d27-9aa0-21b1afade1b8")]

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>
</configuration>

View file

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<RootNamespace>GreenshotOCRPlugin</RootNamespace>
<AssemblyName>GreenshotOCRPlugin</AssemblyName>
</PropertyGroup>
<ItemGroup>
<None Include="Languages\language*.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\GreenshotPlugin\GreenshotPlugin.csproj" />
</ItemGroup>
</Project>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Czech" ietf="cs-CZ" version="1.1.0.2411" languagegroup="">
<resources>
<resource name="language">Jazyk pro OCR</resource>
<resource name="orient_image">Orientaci obrázku</resource>
<resource name="straighten_image">Srovnat obrázek</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Deutsch" ietf="de-DE" version="1.0.0">
<resources>
<resource name="language">
Sprache für OCR
</resource>
<resource name="orient_image">
Bild ausrichten
</resource>
<resource name="straighten_image">
Bild glätten
</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="English" ietf="en-US" version="1.0.0">
<resources>
<resource name="language">
Language for OCR
</resource>
<resource name="orient_image">
Orient image
</resource>
<resource name="straighten_image">
Straighten image
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Français" ietf="fr-FR" version="1.0.0" languagegroup="">
<resources>
<resource name="language">Langage pour l'OCR</resource>
<resource name="orient_image">Orienter l'image</resource>
<resource name="straighten_image">Redresser l'image</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Bahasa Indonesia" ietf="id-ID" version="1.0.0.0" languagegroup="">
<resources>
<resource name="language">Bahasa untuk OCR</resource>
<resource name="orient_image">Orientasikan gambar</resource>
<resource name="straighten_image">Rapikan gambar</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Italiano" ietf="it-IT" version="1.0.1">
<resources>
<resource name="language">
Lingua OCR
</resource>
<resource name="orient_image">
Orientamento immagine
</resource>
<resource name="straighten_image">
Raddrizza immagine
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="日本語" ietf="ja-JP" version="1.0.0">
<resources>
<resource name="language">OCRの言語</resource>
<resource name="orient_image">画像の向きを揃える</resource>
<resource name="straighten_image">画像の傾きを補正する</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Taqbaylit" ietf="kab-DZ" version="1.0.0" languagegroup="">
<resources>
<resource name="language">Tutlayt i OCR</resource>
<resource name="orient_image">Wehhi tugna</resource>
<resource name="straighten_image">Seggwem tugna</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="korean" ietf="ko-KR" version="1.0.0">
<resources>
<resource name="language">
OCR 언어
</resource>
<resource name="orient_image">
가로 이미지
</resource>
<resource name="straighten_image">
세로 이미지
</resource>
</resources>
</language>

View file

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Translated by Kārlis Kalviškis (eko@lanet.lv) 2014.12.17. -->
<language description="Latviski" ietf="lv-LV" version="0.1.0">
<resources>
<resource name="language">
OCR valoda
</resource>
<resource name="orient_image">
Pagriezt attēlu
</resource>
<resource name="straighten_image">
Iztaisnot attēlu
</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Nederlands" ietf="nl-NL" version="1.0.0">
<resources>
<resource name="language">
Taal voor OCR
</resource>
<resource name="orient_image">
Beeld richten
</resource>
<resource name="straighten_image">
Beeld vereffenen
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Polski" ietf="pl-PL" version="1.1.4" languagegroup="2">
<resources>
<resource name="language">Język dla OCR</resource>
<resource name="orient_image">Orientacja obrazu</resource>
<resource name="straighten_image">Wyprostowanie obrazów</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Portuguese (Portugal)" ietf="pt-PT" version="1.0.0">
<resources>
<resource name="language">Idioma para OCR</resource>
<resource name="orient_image">Orientar imagem</resource>
<resource name="straighten_image">Endireitar imagem</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Русский" ietf="ru-RU" version="1.1.4.2622" languagegroup="5">
<resources>
<resource name="language">Язык для OCR</resource>
<resource name="orient_image">Ориентация изображения</resource>
<resource name="straighten_image">Выпрямление изображения</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Slovenčina" ietf="sk-SK" version="1.0.0">
<resources>
<resource name="language">
Jazyk pre OCR
</resource>
<resource name="orient_image">
Orientácia obrázku
</resource>
<resource name="straighten_image">
Narovnať obrázok
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Српски" ietf="sr-RS" version="1.0.0" languagegroup="">
<resources>
<resource name="language">Језик за препознавање знакова</resource>
<resource name="orient_image">Усмери слику</resource>
<resource name="straighten_image">Исправи слику</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Svenska" ietf="sv-SE" version="1.0.0">
<resources>
<resource name="language">
Språk för OCR
</resource>
<resource name="orient_image">
Orientera bild
</resource>
<resource name="straighten_image">
Släta ut bild
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="Українська" ietf="uk-UA" version="1.0.0">
<resources>
<resource name="language">Мова для ОРТ</resource>
<resource name="orient_image">Орієнтувати зображення</resource>
<resource name="straighten_image">Випрямлення зображення</resource>
</resources>
</language>

View file

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="简体中文" ietf="zh-CN" version="1.0.0">
<resources>
<resource name="language">
OCR语言
</resource>
<resource name="orient_image">
图像定位
</resource>
<resource name="straighten_image">
图像矫正
</resource>
</resources>
</language>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<language description="正體中文" ietf="zh-TW" version="1.0.0" languagegroup="9">
<resources>
<resource name="language">OCR 語言</resource>
<resource name="orient_image">定向圖片</resource>
<resource name="straighten_image">拉直圖片</resource>
</resources>
</language>

View file

@ -1,50 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRPlugin
{
/// <summary>
/// Needed for the drop down, available languages for OCR
/// </summary>
public enum ModiLanguage {
CHINESE_SIMPLIFIED = 2052,
CHINESE_TRADITIONAL = 1028,
CZECH = 5,
DANISH = 6,
DUTCH = 19,
ENGLISH = 9,
FINNISH = 11,
FRENCH = 12,
GERMAN = 7,
GREEK = 8,
HUNGARIAN = 14,
ITALIAN = 16,
JAPANESE = 17,
KOREAN = 18,
NORWEGIAN = 20,
POLISH = 21,
PORTUGUESE = 22,
RUSSIAN = 25,
SPANISH = 10,
SWEDISH = 29,
TURKISH = 31,
SYSDEFAULT = 2048
}
}

View file

@ -1,37 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using GreenshotPlugin.IniFile;
namespace GreenshotOCRPlugin {
/// <summary>
/// Description of CoreConfiguration.
/// </summary>
[IniSection("OCR", Description="Greenshot OCR Plugin configuration")]
public class OCRConfiguration : IniSection {
[IniProperty("Language", Description="Language for OCR", DefaultValue="miLANG_ENGLISH")]
public string Language { get; set; }
[IniProperty("orientimage", Description="Orient image?", DefaultValue="true")]
public bool Orientimage { get; set; }
[IniProperty("straightenImage", Description="Straighten image?", DefaultValue="true")]
public bool StraightenImage { get; set; }
}
}

View file

@ -1,60 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System.Drawing;
using System.IO;
using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces;
namespace GreenshotOCRPlugin {
/// <summary>
/// Description of OCRDestination.
/// </summary>
public class OCRDestination : AbstractDestination {
private readonly OcrPlugin _plugin;
public override string Designation => "OCR";
public override string Description => "OCR";
public override Image DisplayIcon {
get {
string exePath = PluginUtils.GetExePath("MSPVIEW.EXE");
if (exePath != null && File.Exists(exePath)) {
return PluginUtils.GetCachedExeIcon(exePath, 0);
}
return null;
}
}
public OCRDestination(OcrPlugin plugin) {
_plugin = plugin;
}
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(Designation, Description)
{
ExportMade = _plugin.DoOcr(surface) != null
};
return exportInformation;
}
}
}

View file

@ -1,30 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using GreenshotPlugin.Controls;
namespace GreenshotOCRPlugin {
/// <summary>
/// This class is needed for design-time resolving of the language files
/// </summary>
public class OcrForm : GreenshotForm {
}
}

View file

@ -1,206 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.Effects;
using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
//using Microsoft.Win32;
namespace GreenshotOCRPlugin {
/// <summary>
/// OCR Plugin Greenshot
/// </summary>
[Plugin("Ocr", true)]
public class OcrPlugin : IGreenshotPlugin {
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OcrPlugin));
private string _ocrCommand;
private static OCRConfiguration _config;
private ToolStripMenuItem _ocrMenuItem = new ToolStripMenuItem();
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (!disposing) return;
if (_ocrMenuItem == null) return;
_ocrMenuItem.Dispose();
_ocrMenuItem = null;
}
/// <summary>
/// Implementation of the IGreenshotPlugin.Initialize
/// </summary>
/// <returns>true if plugin is initialized, false if not (doesn't show)</returns>
public bool Initialize() {
Log.Debug("Initialize called");
var ocrDirectory = Path.GetDirectoryName(GetType().Assembly.Location);
if (ocrDirectory == null)
{
return false;
}
_ocrCommand = Path.Combine(ocrDirectory, "greenshotocrcommand.exe");
if (!HasModi()) {
Log.Warn("No MODI found!");
return false;
}
// Provide the IDestination
SimpleServiceProvider.Current.AddService<IDestination>(new OCRDestination(this));
// Load configuration
_config = IniConfig.GetIniSection<OCRConfiguration>();
if (_config.Language != null) {
_config.Language = _config.Language.Replace("miLANG_", string.Empty).Replace("_"," ");
}
return true;
}
/// <summary>
/// Implementation of the IGreenshotPlugin.Shutdown
/// </summary>
public void Shutdown() {
Log.Debug("Shutdown");
}
/// <summary>
/// Implementation of the IPlugin.Configure
/// </summary>
public void Configure() {
if (!HasModi()) {
MessageBox.Show("Sorry, is seems that Microsoft Office Document Imaging (MODI) is not installed, therefor the OCR Plugin cannot work.");
return;
}
SettingsForm settingsForm = new SettingsForm(Enum.GetNames(typeof(ModiLanguage)), _config);
DialogResult result = settingsForm.ShowDialog();
if (result == DialogResult.OK) {
// "Re"set hotkeys
IniConfig.Save();
}
}
private const int MinWidth = 130;
private const int MinHeight = 130;
/// <summary>
/// Handling of the CaptureTaken "event" from the ICaptureHost
/// We do the OCR here!
/// </summary>
/// <param name="surface">Has the Image and the capture details</param>
public string DoOcr(ISurface surface) {
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(OutputFormat.bmp, 0, true)
{
ReduceColors = true,
SaveBackgroundOnly = true
};
// We only want the background
// Force Grayscale output
outputSettings.Effects.Add(new GrayscaleEffect());
// Also we need to check the size, resize if needed to 130x130 this is the minimum
if (surface.Image.Width < MinWidth || surface.Image.Height < MinHeight) {
int addedWidth = MinWidth - surface.Image.Width;
if (addedWidth < 0) {
addedWidth = 0;
}
int addedHeight = MinHeight - surface.Image.Height;
if (addedHeight < 0) {
addedHeight = 0;
}
IEffect effect = new ResizeCanvasEffect(addedWidth / 2, addedWidth / 2, addedHeight / 2, addedHeight / 2);
outputSettings.Effects.Add(effect);
}
var filePath = ImageOutput.SaveToTmpFile(surface, outputSettings, null);
Log.Debug("Saved tmp file to: " + filePath);
string text = "";
try {
ProcessStartInfo processStartInfo = new ProcessStartInfo(_ocrCommand, "\"" + filePath + "\" " + _config.Language + " " + _config.Orientimage + " " + _config.StraightenImage)
{
CreateNoWindow = true,
RedirectStandardOutput = true,
UseShellExecute = false
};
using Process process = Process.Start(processStartInfo);
if (process != null)
{
process.WaitForExit(30 * 1000);
if (process.ExitCode == 0) {
text = process.StandardOutput.ReadToEnd();
}
}
} catch (Exception e) {
Log.Error("Error while calling Microsoft Office Document Imaging (MODI) to OCR: ", e);
} finally {
if (File.Exists(filePath)) {
Log.Debug("Cleaning up tmp file: " + filePath);
File.Delete(filePath);
}
}
if (string.IsNullOrEmpty(text)) {
Log.Info("No text returned");
return null;
}
// For for BUG-1884:
text = text.Trim();
try {
Log.DebugFormat("Pasting OCR Text to Clipboard: {0}", text);
// Paste to Clipboard (the Plugin currently doesn't have access to the ClipboardHelper from Greenshot
IDataObject ido = new DataObject();
ido.SetData(DataFormats.Text, true, text);
Clipboard.SetDataObject(ido, true);
} catch (Exception e) {
Log.Error("Problem pasting text to clipboard: ", e);
}
return text;
}
private bool HasModi() {
try
{
using Process process = Process.Start(_ocrCommand, "-c");
if (process != null)
{
process.WaitForExit();
return process.ExitCode == 0;
}
} catch(Exception e) {
Log.DebugFormat("Error trying to initiate MODI: {0}", e.Message);
}
Log.InfoFormat("No Microsoft Office Document Imaging (MODI) found, disabling OCR");
return false;
}
}
}

View file

@ -1,146 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotOCRPlugin
{
partial class SettingsForm
{
/// <summary>
/// Designer variable used to keep track of non-visual components.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Disposes resources used by the form.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null) {
components.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent()
{
this.comboBox_languages = new System.Windows.Forms.ComboBox();
this.checkBox_orientImage = new GreenshotPlugin.Controls.GreenshotCheckBox();
this.checkBox_straightenImage = new GreenshotPlugin.Controls.GreenshotCheckBox();
this.label_language = new GreenshotPlugin.Controls.GreenshotLabel();
this.buttonOK = new GreenshotPlugin.Controls.GreenshotButton();
this.buttonCancel = new GreenshotPlugin.Controls.GreenshotButton();
this.SuspendLayout();
//
// comboBox_languages
//
this.comboBox_languages.FormattingEnabled = true;
this.comboBox_languages.Items.AddRange(new object[] {
"English",
"Deutsch"});
this.comboBox_languages.Location = new System.Drawing.Point(74, 12);
this.comboBox_languages.Name = "comboBox_languages";
this.comboBox_languages.Size = new System.Drawing.Size(153, 21);
this.comboBox_languages.TabIndex = 1;
//
// checkBox_orientImage
//
this.checkBox_orientImage.LanguageKey = "ocr.orient_image";
this.checkBox_orientImage.Location = new System.Drawing.Point(13, 68);
this.checkBox_orientImage.Name = "checkBox_orientImage";
this.checkBox_orientImage.PropertyName = "orientimage";
this.checkBox_orientImage.SectionName = "OCR";
this.checkBox_orientImage.Size = new System.Drawing.Size(104, 24);
this.checkBox_orientImage.TabIndex = 3;
this.checkBox_orientImage.UseVisualStyleBackColor = true;
//
// checkBox_straightenImage
//
this.checkBox_straightenImage.LanguageKey = "ocr.straighten_image";
this.checkBox_straightenImage.Location = new System.Drawing.Point(13, 41);
this.checkBox_straightenImage.Name = "checkBox_straightenImage";
this.checkBox_straightenImage.PropertyName = "straightenImage";
this.checkBox_straightenImage.SectionName = "OCR";
this.checkBox_straightenImage.Size = new System.Drawing.Size(109, 24);
this.checkBox_straightenImage.TabIndex = 2;
this.checkBox_straightenImage.UseVisualStyleBackColor = true;
//
// label_language
//
this.label_language.LanguageKey = "ocr.language";
this.label_language.Location = new System.Drawing.Point(13, 15);
this.label_language.Name = "label_language";
this.label_language.Size = new System.Drawing.Size(55, 23);
this.label_language.TabIndex = 3;
//
// buttonOK
//
this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOK.LanguageKey = "OK";
this.buttonOK.Location = new System.Drawing.Point(12, 98);
this.buttonOK.Name = "buttonOK";
this.buttonOK.Size = new System.Drawing.Size(104, 23);
this.buttonOK.TabIndex = 4;
this.buttonOK.UseVisualStyleBackColor = true;
this.buttonOK.Click += new System.EventHandler(this.ButtonOKClick);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.LanguageKey = "CANCEL";
this.buttonCancel.Location = new System.Drawing.Point(128, 98);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(104, 23);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.UseVisualStyleBackColor = true;
//
// SettingsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.ClientSize = new System.Drawing.Size(244, 135);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOK);
this.Controls.Add(this.label_language);
this.Controls.Add(this.checkBox_straightenImage);
this.Controls.Add(this.checkBox_orientImage);
this.Controls.Add(this.comboBox_languages);
this.LanguageKey = "settings_title";
this.Name = "SettingsForm";
this.ResumeLayout(false);
}
private GreenshotPlugin.Controls.GreenshotLabel label_language;
private GreenshotPlugin.Controls.GreenshotButton buttonCancel;
private GreenshotPlugin.Controls.GreenshotButton buttonOK;
private GreenshotPlugin.Controls.GreenshotCheckBox checkBox_orientImage;
private GreenshotPlugin.Controls.GreenshotCheckBox checkBox_straightenImage;
private System.Windows.Forms.ComboBox comboBox_languages;
}
}

View file

@ -1,65 +0,0 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace GreenshotOCRPlugin {
/// <summary>
/// Description of SettingsForm.
/// </summary>
public partial class SettingsForm : OcrForm {
private readonly OCRConfiguration _config;
public SettingsForm(string [] languages, OCRConfiguration config) {
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
this._config = config;
InitializeComponent();
AcceptButton = buttonOK;
CancelButton = buttonCancel;
comboBox_languages.Items.Clear();
int index=0;
// Preventing Tracker #3234560, although this should not happen...
string languageFromConfig = "ENGLISH";
if (config.Language != null) {
languageFromConfig = config.Language;
}
foreach(string availableLanguage in languages) {
string displayLanguage = availableLanguage.Substring(0, 1).ToUpper() + availableLanguage.Substring(1).ToLower();
comboBox_languages.Items.Add(displayLanguage);
if (availableLanguage.Equals(languageFromConfig, StringComparison.CurrentCultureIgnoreCase)) {
comboBox_languages.SelectedIndex = index;
}
index++;
}
}
private void ButtonOKClick(object sender, EventArgs e) {
string selectedString = (string) comboBox_languages.SelectedItem;
if (selectedString != null) {
_config.Language = selectedString.ToUpper();
}
}
}
}

View file

@ -27,21 +27,6 @@ namespace GreenshotOfficePlugin.Com
return clsId;
}
/// <summary>
/// This converts a clsid (Class ID) into a ProgID (program ID)
/// </summary>
/// <param name="clsId">Guid with the clsid (Class ID)</param>
/// <returns>string with the progid</returns>
public static string ProgIdFromClassId(Guid clsId)
{
if (ProgIDFromCLSID(ref clsId, out string progId).Succeeded())
{
return progId;
}
return null;
}
/// <summary>
/// See more <a href="https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-clsidfromprogid">here</a>
/// </summary>
@ -50,14 +35,5 @@ namespace GreenshotOfficePlugin.Com
/// <returns>HResult</returns>
[DllImport("ole32.dll", ExactSpelling = true)]
private static extern HResult CLSIDFromProgID([In] [MarshalAs(UnmanagedType.LPWStr)] string progId, [Out] out Guid clsId);
/// <summary>
/// See more <a href="https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-progidfromclsid">here</a>
/// </summary>
/// <param name="clsId">Guid The CLSID for which the ProgID is to be requested.</param>
/// <param name="lplpszProgId">string the ProgID string. The string that represents clsid includes enclosing braces.</param>
/// <returns>HResult</returns>
[DllImport("ole32.dll")]
private static extern HResult ProgIDFromCLSID([In] ref Guid clsId, [MarshalAs(UnmanagedType.LPWStr)] out string lplpszProgId);
}
}

View file

@ -29,14 +29,6 @@ namespace GreenshotOfficePlugin.OfficeInterop
/// </summary>
Office97 = 8,
/// <summary>
/// Office 2000
/// </summary>
Office2000 = 9,
/// <summary>
/// Office 2002
/// </summary>
Office2002 = 10,
/// <summary>
/// Office 2003
/// </summary>
Office2003 = 11,

View file

@ -22,13 +22,8 @@
namespace GreenshotPhotobucketPlugin {
public enum LangKey {
upload_menu_item,
settings_title,
label_upload_format,
label_clear,
upload_success,
upload_failure,
communication_wait,
use_page_link,
configure
}
}

View file

@ -47,12 +47,7 @@ namespace GreenshotPhotobucketPlugin {
[IniProperty("Username", Description = "The Photobucket api username", ExcludeIfNull = true)]
public string Username { get; set; }
public int Credits {
get;
set;
}
/// <summary>
/// <summary>
/// A form for username/password
/// </summary>
/// <returns>bool true if OK was pressed, false if cancel</returns>

View file

@ -20,7 +20,6 @@
*/
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using GreenshotPlugin.Core;
@ -30,23 +29,8 @@ namespace GreenshotPlugin.Controls {
/// </summary>
public sealed partial class BackgroundForm : Form {
private volatile bool _shouldClose;
private void BackgroundShowDialog() {
ShowDialog();
}
public static BackgroundForm ShowAndWait(string title, string text) {
BackgroundForm backgroundForm = new BackgroundForm(title, text);
// Show form in background thread
Thread backgroundTask = new Thread (backgroundForm.BackgroundShowDialog);
backgroundForm.Name = "Background form";
backgroundTask.IsBackground = true;
backgroundTask.SetApartmentState(ApartmentState.STA);
backgroundTask.Start();
return backgroundForm;
}
public BackgroundForm(string title, string text){
public BackgroundForm(string title, string text){
//
// The InitializeComponent() call is required for Windows Forms designer support.
//

View file

@ -426,11 +426,7 @@ namespace GreenshotPlugin.Controls {
_hotkeyHwnd = hWnd;
}
public static int RegisterHotKey(string hotkey, HotKeyHandler handler) {
return RegisterHotKey(HotkeyModifiersFromString(hotkey), HotkeyFromString(hotkey),handler);
}
/// <summary>
/// <summary>
/// Register a hotkey
/// </summary>
/// <param name="modifierKeyCode">The modifier, e.g.: Modifiers.CTRL, Modifiers.NONE or Modifiers.ALT</param>
@ -477,21 +473,7 @@ namespace GreenshotPlugin.Controls {
KeyHandlers.Clear();
}
public static void UnregisterHotkey(int hotkey) {
bool removeHotkey = false;
foreach(int availableHotkey in KeyHandlers.Keys) {
if (availableHotkey == hotkey) {
UnregisterHotKey(_hotkeyHwnd, hotkey);
removeHotkey = true;
}
}
if (removeHotkey) {
// Remove key handler
KeyHandlers.Remove(hotkey);
}
}
/// <summary>
/// <summary>
/// Handle WndProc messages for the hotkey
/// </summary>
/// <param name="m"></param>

View file

@ -53,11 +53,7 @@ namespace GreenshotPlugin.Controls {
}
}
public SaveImageFileDialog() {
Init();
}
public SaveImageFileDialog(ICaptureDetails captureDetails) {
public SaveImageFileDialog(ICaptureDetails captureDetails) {
_captureDetails = captureDetails;
Init();
}

View file

@ -22,6 +22,7 @@ using System;
using System.Windows.Forms;
using GreenshotPlugin.Core;
using System.Drawing;
using GreenshotPlugin.Core.Enums;
using GreenshotPlugin.IniFile;
using GreenshotPlugin.UnmanagedHelpers;
using GreenshotPlugin.UnmanagedHelpers.Enums;
@ -32,7 +33,7 @@ namespace GreenshotPlugin.Controls {
/// This form allows us to show a Thumbnail preview of a window near the context menu when selecting a window to capture.
/// Didn't make it completely "generic" yet, but at least most logic is in here so we don't have it in the mainform.
/// </summary>
public class ThumbnailForm : FormWithoutActivation {
public sealed class ThumbnailForm : FormWithoutActivation {
private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private IntPtr _thumbnailHandle = IntPtr.Zero;
@ -59,12 +60,13 @@ namespace GreenshotPlugin.Controls {
base.Hide();
}
private void UnregisterThumbnail() {
if (_thumbnailHandle != IntPtr.Zero) {
DWM.DwmUnregisterThumbnail(_thumbnailHandle);
_thumbnailHandle = IntPtr.Zero;
}
}
private void UnregisterThumbnail()
{
if (_thumbnailHandle == IntPtr.Zero) return;
DWM.DwmUnregisterThumbnail(_thumbnailHandle);
_thumbnailHandle = IntPtr.Zero;
}
/// <summary>
/// Show the thumbnail of the supplied window above (or under) the parent Control
@ -75,41 +77,60 @@ namespace GreenshotPlugin.Controls {
UnregisterThumbnail();
DWM.DwmRegisterThumbnail(Handle, window.Handle, out _thumbnailHandle);
if (_thumbnailHandle != IntPtr.Zero) {
DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out var sourceSize);
int thumbnailHeight = 200;
int thumbnailWidth = (int)(thumbnailHeight * (sourceSize.Width / (float)sourceSize.Height));
if (parentControl != null && thumbnailWidth > parentControl.Width) {
thumbnailWidth = parentControl.Width;
thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width));
}
Width = thumbnailWidth;
Height = thumbnailHeight;
// Prepare the displaying of the Thumbnail
DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES
{
Opacity = 255,
Visible = true,
SourceClientAreaOnly = false,
Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight)
};
DWM.DwmUpdateThumbnailProperties(_thumbnailHandle, ref props);
if (parentControl != null) {
AlignToControl(parentControl);
}
if (_thumbnailHandle == IntPtr.Zero) return;
if (!Visible) {
Show();
}
// Make sure it's on "top"!
if (parentControl != null) {
User32.SetWindowPos(Handle, parentControl.Handle, 0, 0, 0, 0, WindowPos.SWP_NOMOVE | WindowPos.SWP_NOSIZE | WindowPos.SWP_NOACTIVATE);
}
}
}
var result = DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out var sourceSize);
if (result.Failed())
{
DWM.DwmUnregisterThumbnail(_thumbnailHandle);
return;
}
if (sourceSize.IsEmpty)
{
DWM.DwmUnregisterThumbnail(_thumbnailHandle);
return;
}
int thumbnailHeight = 200;
int thumbnailWidth = (int)(thumbnailHeight * (sourceSize.Width / (float)sourceSize.Height));
if (parentControl != null && thumbnailWidth > parentControl.Width)
{
thumbnailWidth = parentControl.Width;
thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width));
}
Width = thumbnailWidth;
Height = thumbnailHeight;
// Prepare the displaying of the Thumbnail
var dwmThumbnailProperties = new DWM_THUMBNAIL_PROPERTIES
{
Opacity = 255,
Visible = true,
SourceClientAreaOnly = false,
Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight)
};
result = DWM.DwmUpdateThumbnailProperties(_thumbnailHandle, ref dwmThumbnailProperties);
if (result.Failed())
{
DWM.DwmUnregisterThumbnail(_thumbnailHandle);
return;
}
if (parentControl != null) {
AlignToControl(parentControl);
}
if (!Visible) {
Show();
}
// Make sure it's on "top"!
if (parentControl != null) {
User32.SetWindowPos(Handle, parentControl.Handle, 0, 0, 0, 0, WindowPos.SWP_NOMOVE | WindowPos.SWP_NOSIZE | WindowPos.SWP_NOACTIVATE);
}
}
public void AlignToControl(Control alignTo) {
Rectangle screenBounds = WindowCapture.GetScreenBounds();
var screenBounds = WindowCapture.GetScreenBounds();
if (screenBounds.Contains(alignTo.Left, alignTo.Top - Height)) {
Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height);
} else {

View file

@ -91,35 +91,7 @@ namespace GreenshotPlugin.Core {
}
}
public void ActivateIETab(string tabCaptionToActivate) {
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
foreach (var tab in child.Children) {
if (tab.Name == tabCaptionToActivate) {
tab.Activate();
return;
}
}
}
}
}
public void CloseIETab(string tabCaptionToClose) {
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
foreach (var tab in child.Children) {
if (tab.Name == tabCaptionToClose) {
foreach (var CloseTab in tab.Children) {
CloseTab.Activate();
}
return;
}
}
}
}
}
public void ActivateIETab(int tabIndexToActivate) {
public void ActivateIETab(int tabIndexToActivate) {
var index = 0;
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
@ -138,50 +110,7 @@ namespace GreenshotPlugin.Core {
}
}
public string IEActiveTabUrl {
get {
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
foreach (var tab in child.Children) {
object tabIndex = tab.accessible.get_accState(CHILDID_SELF);
if ((int)tabIndex == IE_ACTIVE_TAB) {
var description = tab.accessible.get_accDescription(CHILDID_SELF);
if (!string.IsNullOrEmpty(description)) {
if (description.Contains(Environment.NewLine)) {
var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim();
return url;
}
}
}
}
}
}
return string.Empty;
}
}
public int IEActiveTabIndex {
get {
var index = 0;
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
foreach (var tab in child.Children) {
object tabIndex = tab.accessible.get_accState(0);
if ((int)tabIndex == IE_ACTIVE_TAB) {
return index;
}
index++;
}
}
}
return -1;
}
}
public string IEActiveTabCaption {
public string IEActiveTabCaption {
get {
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
@ -238,21 +167,8 @@ namespace GreenshotPlugin.Core {
}
}
}
public int IETabCount {
get {
foreach (Accessible accessor in Children) {
foreach (var child in accessor.Children) {
foreach (var tab in child.Children) {
return child.ChildCount - 1;
}
}
}
return 0;
}
}
private Accessible(IAccessible acc) {
private Accessible(IAccessible acc) {
accessible = acc ?? throw new Exception();
}

View file

@ -1,5 +1,25 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using GreenshotPlugin.Interfaces;
@ -14,7 +34,6 @@ namespace GreenshotPlugin.Core
/// </summary>
public class Capture : ICapture {
private static readonly ILog Log = LogManager.GetLogger(typeof(Capture));
private List<ICaptureElement> _elements = new List<ICaptureElement>();
private Rectangle _screenBounds;
/// <summary>
@ -178,15 +197,6 @@ namespace GreenshotPlugin.Core
// TODO: Remove invisible lines/words?
CaptureDetails.OcrInformation?.Offset(-cropRectangle.Location.X, -cropRectangle.Location.Y);
// Remove invisible elements
var visibleElements = new List<ICaptureElement>();
foreach(var captureElement in _elements) {
if (captureElement.Bounds.IntersectsWith(cropRectangle)) {
visibleElements.Add(captureElement);
}
}
_elements = visibleElements;
return true;
}

View file

@ -1,3 +1,24 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2021 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* 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 1 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, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using GreenshotPlugin.Interfaces;

View file

@ -1,48 +0,0 @@
using System.Collections.Generic;
using System.Drawing;
using GreenshotPlugin.Interfaces;
namespace GreenshotPlugin.Core
{
/// <summary>
/// A class representing an element in the capture
/// </summary>
public class CaptureElement : ICaptureElement {
public CaptureElement(Rectangle bounds) {
Bounds = bounds;
}
public CaptureElement(string name) {
Name = name;
}
public CaptureElement(string name, Rectangle bounds) {
Name = name;
Bounds = bounds;
}
public List<ICaptureElement> Children { get; set; } = new List<ICaptureElement>();
public string Name {
get;
set;
}
public Rectangle Bounds {
get;
set;
}
// CaptureElements are regarded equal if their bounds are equal. this should be sufficient.
public override bool Equals(object obj) {
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return obj is CaptureElement other && Bounds.Equals(other.Bounds);
}
public override int GetHashCode() {
// TODO: Fix this, this is not right...
return Bounds.GetHashCode();
}
}
}

View file

@ -34,7 +34,9 @@ using System.Runtime.InteropServices;
using GreenshotPlugin.IniFile;
using GreenshotPlugin.Interfaces;
using GreenshotPlugin.Interfaces.Plugin;
using GreenshotPlugin.Interop;
using log4net;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;
namespace GreenshotPlugin.Core {
/// <summary>
@ -45,7 +47,8 @@ namespace GreenshotPlugin.Core {
private static readonly object ClipboardLockObject = new object();
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly string FORMAT_FILECONTENTS = "FileContents";
private static readonly string FORMAT_PNG = "PNG";
private static readonly string FORMAT_HTML = "text/html";
private static readonly string FORMAT_PNG = "PNG";
private static readonly string FORMAT_PNG_OFFICEART = "PNG+Office Art";
private static readonly string FORMAT_17 = "Format17";
private static readonly string FORMAT_JPG = "JPG";
@ -207,17 +210,8 @@ EndSelection:<<<<<<<4
}
return null;
}
/// <summary>
/// Wrapper for Clipboard.ContainsText, Created for Bug #3432313
/// </summary>
/// <returns>boolean if there is text on the clipboard</returns>
public static bool ContainsText() {
IDataObject clipboardData = GetDataObject();
return ContainsText(clipboardData);
}
/// <summary>
/// <summary>
/// Test if the IDataObject contains Text
/// </summary>
/// <param name="dataObject"></param>
@ -246,41 +240,124 @@ EndSelection:<<<<<<<4
/// <param name="dataObject"></param>
/// <returns>true if an image is there</returns>
public static bool ContainsImage(IDataObject dataObject) {
if (dataObject != null) {
if (dataObject.GetDataPresent(DataFormats.Bitmap)
|| dataObject.GetDataPresent(DataFormats.Dib)
|| dataObject.GetDataPresent(DataFormats.Tiff)
|| dataObject.GetDataPresent(DataFormats.EnhancedMetafile)
|| dataObject.GetDataPresent(FORMAT_PNG)
|| dataObject.GetDataPresent(FORMAT_17)
|| dataObject.GetDataPresent(FORMAT_JPG)
|| dataObject.GetDataPresent(FORMAT_JFIF)
|| dataObject.GetDataPresent(FORMAT_JPEG)
|| dataObject.GetDataPresent(FORMAT_GIF)) {
return true;
}
var imageFiles = GetImageFilenames(dataObject);
if (imageFiles.Any()) {
return true;
}
if (dataObject.GetDataPresent(FORMAT_FILECONTENTS)) {
try {
MemoryStream imageStream = dataObject.GetData(FORMAT_FILECONTENTS) as MemoryStream;
if (IsValidStream(imageStream)) {
using (ImageHelper.FromStream(imageStream))
{
// If we get here, there is an image
return true;
}
}
} catch (Exception) {
// Ignore
}
}
}
return false;
if (dataObject == null) return false;
if (dataObject.GetDataPresent(DataFormats.Bitmap)
|| dataObject.GetDataPresent(DataFormats.Dib)
|| dataObject.GetDataPresent(DataFormats.Tiff)
|| dataObject.GetDataPresent(DataFormats.EnhancedMetafile)
|| dataObject.GetDataPresent(FORMAT_PNG)
|| dataObject.GetDataPresent(FORMAT_17)
|| dataObject.GetDataPresent(FORMAT_JPG)
|| dataObject.GetDataPresent(FORMAT_JFIF)
|| dataObject.GetDataPresent(FORMAT_JPEG)
|| dataObject.GetDataPresent(FORMAT_GIF)) {
return true;
}
var imageFiles = GetImageFilenames(dataObject);
if (imageFiles.Any()) {
return true;
}
var fileDescriptor = (MemoryStream)dataObject.GetData("FileGroupDescriptorW");
var files = FileDescriptorReader.Read(fileDescriptor);
var fileIndex = 0;
foreach (var fileContentFile in files)
{
if ((fileContentFile.FileAttributes & FileAttributes.Directory) != 0)
{
//Do something with directories?
//Note that directories do not have FileContents
//And will throw if we try to read them
continue;
}
var fileData = FileDescriptorReader.GetFileContents(dataObject, fileIndex);
try
{
//Do something with the fileContent Stream
if (IsValidStream(fileData))
{
fileData.Position = 0;
using (ImageHelper.FromStream(fileData))
{
// If we get here, there is an image
return true;
}
}
}
finally
{
fileData?.Dispose();
}
fileIndex++;
}
if (dataObject.GetDataPresent(FORMAT_FILECONTENTS))
{
try
{
var clipboardContent = dataObject.GetData(FORMAT_FILECONTENTS, true);
var imageStream = clipboardContent as MemoryStream;
if (IsValidStream(imageStream))
{
using (ImageHelper.FromStream(imageStream))
{
// If we get here, there is an image
return true;
}
}
}
catch (Exception)
{
// Ignore
}
}
// Try to get the image from the HTML code
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
if (textObject != null)
{
var doc = new HtmlDocument();
doc.LoadHtml(textObject);
var imgNodes = doc.DocumentNode.SelectNodes("//img");
if (imgNodes != null)
{
foreach (var imgNode in imgNodes)
{
var srcAttribute = imgNode.Attributes["src"];
var imageUrl = srcAttribute.Value;
if (!string.IsNullOrEmpty(imageUrl))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Get the specified IDataObject format as a string
/// </summary>
/// <param name="dataObject">IDataObject</param>
/// <param name="format">string</param>
/// <param name="encoding">Encoding</param>
/// <returns>sting</returns>
private static string ContentAsString(IDataObject dataObject, string format, Encoding encoding = null)
{
encoding ??= Encoding.Unicode;
var objectAsFormat = dataObject.GetData(format);
return objectAsFormat switch
{
null => null,
string text => text,
MemoryStream ms => encoding.GetString(ms.ToArray()),
_ => null
};
}
/// <summary>
/// Simple helper to check the stream
/// </summary>
@ -348,9 +425,9 @@ EndSelection:<<<<<<<4
if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) {
// Outlook ??
Log.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
retrieveFormats = new[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JPEG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF };
retrieveFormats = new[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JPEG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF, FORMAT_HTML };
} else {
retrieveFormats = new[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JPEG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF };
retrieveFormats = new[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JPEG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF, FORMAT_HTML };
}
foreach (string currentFormat in retrieveFormats) {
if (formats != null && formats.Contains(currentFormat)) {
@ -376,8 +453,32 @@ EndSelection:<<<<<<<4
/// <param name="dataObject">IDataObject</param>
/// <returns>Image or null</returns>
private static Image GetImageForFormat(string format, IDataObject dataObject) {
if (format == FORMAT_HTML)
{
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
if (textObject != null)
{
var doc = new HtmlDocument();
doc.LoadHtml(textObject);
var imgNodes = doc.DocumentNode.SelectNodes("//img");
if (imgNodes != null)
{
foreach (var imgNode in imgNodes)
{
var srcAttribute = imgNode.Attributes["src"];
var imageUrl = srcAttribute.Value;
Log.Debug(imageUrl);
var image = NetworkHelper.DownloadImage(imageUrl);
if (image != null)
{
return image;
}
}
}
}
}
object clipboardObject = GetFromDataObject(dataObject, format);
MemoryStream imageStream = clipboardObject as MemoryStream;
var imageStream = clipboardObject as MemoryStream;
if (!IsValidStream(imageStream)) {
// TODO: add "HTML Format" support here...
return clipboardObject as Image;
@ -390,14 +491,14 @@ EndSelection:<<<<<<<4
{
byte[] dibBuffer = new byte[imageStream.Length];
imageStream.Read(dibBuffer, 0, dibBuffer.Length);
BITMAPINFOHEADER infoHeader = BinaryStructHelper.FromByteArray<BITMAPINFOHEADER>(dibBuffer);
var infoHeader = BinaryStructHelper.FromByteArray<BITMAPINFOHEADER>(dibBuffer);
if (!infoHeader.IsDibV5) {
Log.InfoFormat("Using special DIB <v5 format reader with biCompression {0}", infoHeader.biCompression);
int fileHeaderSize = Marshal.SizeOf(typeof(BITMAPFILEHEADER));
uint infoHeaderSize = infoHeader.biSize;
int fileSize = (int)(fileHeaderSize + infoHeader.biSize + infoHeader.biSizeImage);
BITMAPFILEHEADER fileHeader = new BITMAPFILEHEADER
var fileHeader = new BITMAPFILEHEADER
{
bfType = BITMAPFILEHEADER.BM,
bfSize = fileSize,
@ -408,7 +509,7 @@ EndSelection:<<<<<<<4
byte[] fileHeaderBytes = BinaryStructHelper.ToByteArray(fileHeader);
using MemoryStream bitmapStream = new MemoryStream();
using var bitmapStream = new MemoryStream();
bitmapStream.Write(fileHeaderBytes, 0, fileHeaderSize);
bitmapStream.Write(dibBuffer, 0, dibBuffer.Length);
bitmapStream.Seek(0, SeekOrigin.Begin);
@ -459,18 +560,11 @@ EndSelection:<<<<<<<4
} catch (Exception streamImageEx) {
Log.Error($"Problem retrieving {format} from clipboard.", streamImageEx);
}
return null;
}
/// <summary>
/// Wrapper for Clipboard.GetText created for Bug #3432313
/// </summary>
/// <returns>string if there is text on the clipboard</returns>
public static string GetText() {
return GetText(GetDataObject());
}
/// <summary>
/// <summary>
/// Get Text from the DataObject
/// </summary>
/// <returns>string if there is text on the clipboard</returns>
@ -706,16 +800,8 @@ EndSelection:<<<<<<<4
// Use false to make the object disappear when the application stops.
SetDataObject(dataObj, true);
}
/// <summary>
/// Retrieve a list of all formats currently on the clipboard
/// </summary>
/// <returns>List of strings with the current formats</returns>
public static List<string> GetFormats() {
return GetFormats(GetDataObject());
}
/// <summary>
/// <summary>
/// Retrieve a list of all formats currently in the IDataObject
/// </summary>
/// <returns>List of string with the current formats</returns>
@ -732,16 +818,7 @@ EndSelection:<<<<<<<4
return new List<string>();
}
/// <summary>
/// Check if there is currently something in the dataObject which has the supplied format
/// </summary>
/// <param name="format">string with format</param>
/// <returns>true if one the format is found</returns>
public static bool ContainsFormat(string format) {
return ContainsFormat(GetDataObject(), new[]{format});
}
/// <summary>
/// <summary>
/// Check if there is currently something on the clipboard which has the supplied format
/// </summary>
/// <param name="dataObject">IDataObject</param>
@ -781,17 +858,7 @@ EndSelection:<<<<<<<4
return formatFound;
}
/// <summary>
/// Get Object of type Type from the clipboard
/// </summary>
/// <param name="type">Type to get</param>
/// <returns>object from clipboard</returns>
public static object GetClipboardData(Type type) {
string format = type.FullName;
return GetClipboardData(format);
}
/// <summary>
/// <summary>
/// Get Object for format from IDataObject
/// </summary>
/// <param name="dataObj">IDataObject</param>
@ -837,14 +904,5 @@ EndSelection:<<<<<<<4
}
return null;
}
/// <summary>
/// Get Object for format from the clipboard
/// </summary>
/// <param name="format">format to get</param>
/// <returns>object from clipboard</returns>
public static object GetClipboardData(string format) {
return GetFromDataObject(GetDataObject(), format);
}
}
}
}

View file

@ -305,25 +305,7 @@ namespace GreenshotPlugin.Core {
[IniProperty("WebRequestReadWriteTimeout", Description = "The read/write timeout value for webrequets, these are seconds", DefaultValue = "100")]
public int WebRequestReadWriteTimeout { get; set; }
/// <summary>
/// Specifies what THIS build is
/// </summary>
public BuildStates BuildState {
get {
string informationalVersion = Application.ProductVersion;
if (informationalVersion != null) {
if (informationalVersion.ToLowerInvariant().Contains("-rc")) {
return BuildStates.RELEASE_CANDIDATE;
}
if (informationalVersion.ToLowerInvariant().Contains("-unstable")) {
return BuildStates.UNSTABLE;
}
}
return BuildStates.RELEASE;
}
}
public bool UseLargeIcons => IconSize.Width >= 32 || IconSize.Height >= 32;
public bool UseLargeIcons => IconSize.Width >= 32 || IconSize.Height >= 32;
/// <summary>
/// A helper method which returns true if the supplied experimental feature is enabled

Some files were not shown because too many files have changed in this diff Show more