Repository: akshinmustafayev/EasyJob
Branch: main
Commit: 2469fe858a77
Files: 80
Total size: 670.2 KB
Directory structure:
gitextract_cvrmxber/
├── EasyJob/
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── AssemblyInfo.cs
│ ├── Documentation/
│ │ └── HelpDocumentation.xml
│ ├── EasyJob.csproj
│ ├── EasyJob.csproj.user
│ ├── EasyJobPS/
│ │ ├── EasyJobPS.psd1
│ │ └── EasyJobPS.psm1
│ ├── LICENSE.txt
│ ├── MainWindow.xaml
│ ├── MainWindow.xaml.cs
│ ├── Serialization/
│ │ ├── AnswerDialog/
│ │ │ ├── Answer.cs
│ │ │ └── AnswerData.cs
│ │ ├── Config/
│ │ │ ├── Config.cs
│ │ │ ├── ConfigArgument.cs
│ │ │ ├── ConfigButton.cs
│ │ │ ├── ConfigRestrictions.cs
│ │ │ └── ConfigTab.cs
│ │ ├── TabItems/
│ │ │ ├── ActionButton.cs
│ │ │ └── TabData.cs
│ │ └── TasksList/
│ │ └── TaskListTask.cs
│ ├── Utils/
│ │ ├── CommonUtils.cs
│ │ ├── ConfigUtils.cs
│ │ └── ScrollViewerExtensions.cs
│ ├── Windows/
│ │ ├── AboutDialog.xaml
│ │ ├── AboutDialog.xaml.cs
│ │ ├── AddActionButtonDialog.xaml
│ │ ├── AddActionButtonDialog.xaml.cs
│ │ ├── AnswerDialog.xaml
│ │ ├── AnswerDialog.xaml.cs
│ │ ├── ColorTagsDialog.xaml
│ │ ├── ColorTagsDialog.xaml.cs
│ │ ├── ConfigurationDialog.xaml
│ │ ├── ConfigurationDialog.xaml.cs
│ │ ├── EditActionButtonDialog.xaml
│ │ ├── EditActionButtonDialog.xaml.cs
│ │ ├── HelpDialog.xaml
│ │ ├── HelpDialog.xaml.cs
│ │ ├── NewTabDialog.xaml
│ │ ├── NewTabDialog.xaml.cs
│ │ ├── RenameTabDialog.xaml
│ │ ├── RenameTabDialog.xaml.cs
│ │ ├── ReorderActionButtonsDialog.xaml
│ │ ├── ReorderActionButtonsDialog.xaml.cs
│ │ ├── ReorderTabsDialog.xaml
│ │ ├── ReorderTabsDialog.xaml.cs
│ │ ├── TroubleshootingWindow.xaml
│ │ └── TroubleshootingWindow.xaml.cs
│ └── config.json
├── EasyJob.sln
├── EasyJobPSTools/
│ ├── EasyJobPSTools.csproj
│ ├── EasyJobPSTools.psd1
│ ├── EasyJobPSTools.psm1
│ ├── EasyJobPSTools.sln
│ ├── Program.cs
│ ├── Properties/
│ │ ├── AssemblyInfo.cs
│ │ ├── Resources.Designer.cs
│ │ ├── Resources.resx
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── Utils/
│ │ └── CommonUtils.cs
│ ├── Windows/
│ │ ├── ShowEJInputBox.xaml
│ │ └── ShowEJInputBox.xaml.cs
│ └── app.config
├── LICENSE.txt
├── README.md
└── WpfRichText/
├── AttachedProperties/
│ └── RichTextboxAssistant.cs
├── Commands/
│ ├── CommandReference.cs
│ └── DelegateCommand.cs
├── Controls/
│ ├── RichTextEditor.xaml
│ └── RichTextEditor.xaml.cs
├── WpfRichText.csproj
├── WpfRichText.sln
└── XamlToHtmlParser/
├── HtmlCssParser.cs
├── HtmlFromXamlConverter.cs
├── HtmlLexicalAnalyzer.cs
├── HtmlParser.cs
├── HtmlSchema.cs
├── HtmlToXamlConverter.cs
└── HtmlTokenType.cs
================================================
FILE CONTENTS
================================================
================================================
FILE: EasyJob/App.xaml
================================================
================================================
FILE: EasyJob/App.xaml.cs
================================================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
namespace EasyJob
{
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SetDropDownMenuToBeRightAligned();
}
private static void SetDropDownMenuToBeRightAligned()
{
var menuDropAlignmentField = typeof(SystemParameters).GetField("_menuDropAlignment", BindingFlags.NonPublic | BindingFlags.Static);
Action setAlignmentValue = () =>
{
if (SystemParameters.MenuDropAlignment && menuDropAlignmentField != null) menuDropAlignmentField.SetValue(null, false);
};
setAlignmentValue();
SystemParameters.StaticPropertyChanged += (sender, e) =>
{
setAlignmentValue();
};
}
}
}
================================================
FILE: EasyJob/AssemblyInfo.cs
================================================
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
================================================
FILE: EasyJob/Documentation/HelpDocumentation.xml
================================================
-
HelpAddActionButtonText
Text
The button text. This is an actual name of your button which will be shown on the panel.
Example: "Restart server"
Adding button
-
HelpAddActionButtonDescription
Description
The button description. This parameter sets the description for the button which will be shown in tooltip when mouse is on the button.
Example: "This button restarts specified server"
Adding button
-
HelpAddActionButtonScript
Script
The button script file. This is used to set path to the script. Value may differ based on the Script Path Type parameter.
Example:
If Script Path Type parameter is Relative then script file must be put to the direction where is EasyJob is located and should look like: "restart_server.ps1".
If Script Path Type parameter is Absolute then script file must be put to any other direction and should look like: "C:\your\folder\name\restart_server.ps1"
Adding button
-
HelpAddActionButtonScriptPathType
Script path type
The button script path type. My be set to Relative or Absolute. Relative means that your script is in the same folder with an application executable. Absolute means that your script is located in any other folder in your system.
Example: "Relative"
Adding button
-
HelpAddActionButtonScriptType
Script type
The button script type. My be set to PowerShell or Batch script.
Example: "PowerShell"
Adding button
-
HelpAddActionButtonArguments
Arguments
The button arguments. You have to specify list of questions which will be asked when executiong your script.
Example: "Please specify server DNS name or IP address"
Adding button
-
HelpConfigurationDefaultPowershellPath
Default PowerShell path
Absolute path to PowerShell.exe. You can specify path to new versions of PowerShell.
Example: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
Configuration
-
HelpConfigurationDefaultCMDPath
Default CMD path
Absolute path to command promt.
Example: "C:\Windows\System32\cmd.exe"
Configuration
-
HelpConfigurationPowerShellArguments
PowerShell arguments
Additional parameters sent to PowerShell.
Example: -ExecutionPolicy Unrestricted
Configuration
-
HelpConfigurationConsoleBackground
Console background
Background color of the console.
Example: Black
Configuration
-
HelpConfigurationConsoleForeground
Console foreground
Color of the text in the console.
Example: Red
Configuration
-
HelpConfigurationConsoleIgnoreColorTags
Console ignore color tags
Determines if special color tags are ignored during output.
Example: No
Configuration
-
HelpConfigurationClearEventsWhenReload
Clear events when reload
Clear events on Events list after configuration reload from the File-> Reload config menu.
Example: Yes
Configuration
-
HelpConfigurationBlockTabsRemove
Block tabs remove
Hides "Remove Tab" context menu item from when Right click on the Tab.
Example: No
Configuration
-
HelpConfigurationBlockButtonsRemove
Block buttons remove
Hides "Remove button" context menu item when Right click on the buttons bar.
Example: No
Configuration
-
HelpConfigurationBlockTabsAdd
Block tabs add
Hides "Add tab" context menu item when Right Click on the Tab.
Example: No
Configuration
-
HelpConfigurationBlockButtonsAdd
Block buttons add
Hides "Add button" context menu item when Right click on the buttons bar.
Example: No
Configuration
-
HelpConfigurationBlockButtonsReorder
Block buttons reorder
Hides "Reorder buttons" context menu item when Right click on the buttons bar.
Example: No
Configuration
-
HelpConfigurationBlockButtonsEdit
Block buttons edit
Hides "Edit button" context menu item when Right click on the button.
Example: No
Configuration
-
HelpConfigurationBlockTabsRename
Block tabs rename
Hides "Rename tab" context menu item when Right click on the tab.
Example: No
Configuration
-
HelpConfigurationBlockButtonsPaste
Block buttons paste
Hides "Paste button" context menu item when Right click on the tab.
Example: No
Configuration
-
HelpConfigurationBlockButtonsCopy
Block buttons copy
Hides "Copy button" context menu item when Right click on the tab.
Example: No
Configuration
-
HelpConfigurationHideFileReloadConfig
Hide File->Reload config
Hides "File->Reload config" main menu item.
Example: No
Configuration
-
HelpConfigurationHideFileOpenAppFolder
Hide File->Open app folder
Hides "File->Open app folder" main menu item.
Example: No
Configuration
-
HelpConfigurationHideClearEventsList
Hide File->Clear events list
Hides "Hide File->Clear events list" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettings
Hide Settings
Hides "Hide Settings" main menu item.
Example: No
Note: In order to bring back Settings menu, you have to manually find "hide_menu_item_settings" parameter in config.json and change its value to "false"
Configuration
-
HelpConfigurationHideSettingsWorkflow
Hide Settings->Workflow
Hides "Hide Settings->Workflow" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsWorkflowReorderTabs
Hide Settings->Workflow->Reorder tabs
Hides "Hide Settings->Workflow->Reorder tabs" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsWorkflowAddTab
Hide Settings->Workflow->Add tab
Hides "Hide Settings->Workflow->Add tab" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsWorkflowRemoveCurrentTab
Hide Settings->Workflow->Remove current tab
Hides "Hide Settings->Workflow->Remove current tab" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsWorkflowRenameCurrentTab
Hide Settings->Workflow->Rename current tab
Hides "Hide Settings->Workflow->Rename current tab" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsWorkflowAddButtonToCurrentTab
Hide Settings->Workflow->Add button to current tab" main menu item.
Example: No
Hides "Hide Settings->Workflow->Add button to current tab
Configuration
-
HelpConfigurationHideSettingsWorkflowReorderButtonsInCurrentTab
Hide Settings->Workflow->Reorder buttons in current tab
Hides "Hide Settings->Workflow->Reorder buttons in current tab" main menu item.
Example: No
Configuration
-
HelpConfigurationHideSettingsConfiguration
Hide Settings->Configuration
Hides "Hide Settings->Configuration" main menu item.
Example: No
Note: In order to bring back Configuration menu, you have to manually find "hide_menu_item_settings_configuration" parameter in config.json and change its value to "false"
Configuration
-
HelpConfigurationHideHelp
Hide Help
Hides "Hide Help" main menu item.
Example: No
Configuration
-
HelpConfigurationHideTroubleshooting
Hide Help->Troubleshooting
Hides "Hide Help->Troubleshooting" main menu item.
Example: No
Configuration
-
HelpConfigurationHideColorTags
Hide Help->Troubleshooting
Hides "Hide Help->Color tags" main menu item.
Example: No
Configuration
-
HelpConfigurationHideAbout
Hide Help->About
Hides "Hide Help->About" main menu item.
Example: No
Configuration
================================================
FILE: EasyJob/EasyJob.csproj
================================================
WinExe
net5.0-windows
true
Images\icon.ico
1.1.9
Akshin Mustafayev
Keep and execute your PowerShell scripts from one interface
Akshin Mustafayev
https://github.com/akshinmustafayev/EasyJob
https://github.com/akshinmustafayev/EasyJob
Git
1.1.9.0
false
Auto
..\bin\Debug\
false
..\bin\Release\
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
Always
================================================
FILE: EasyJob/EasyJob.csproj.user
================================================
Designer
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Code
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
Designer
================================================
FILE: EasyJob/EasyJobPS/EasyJobPS.psd1
================================================
# Module manifest for module 'EasyJobPS'
# Generated by: Akshin Mustafayev
# Generated on: 10/8/2021
@{
# Script module or binary module file associated with this manifest.
RootModule = 'EasyJobPS.psm1'
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = 'd6c56376-ae08-4c23-b901-9bc75144e0c6'
# Author of this module
Author = 'Akshin Mustafayev'
# Company or vendor of this module
CompanyName = 'Akshin Mustafayev'
# Copyright statement for this module
Copyright = '(c) 2021 Akshin Mustafayev. Apache-2.0 license.'
# Description of the functionality provided by this module
Description = 'Module for implementing EasyJob additional helper functions'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Show-EJInputBox'
}
================================================
FILE: EasyJob/EasyJobPS/EasyJobPS.psm1
================================================
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
function Show-EJInputBox {
<#
.SYNOPSIS
Shows Input-Box for you script.
.DESCRIPTION
Shows Input-Box for you script. This might be necessary
when you want to get som input while executing your script,
since EasyJob does not support Read from console.
.PARAMETER Title
Specifies Title for message box.
.PARAMETER Message
Specifies Message for message box.
.INPUTS
None.
.OUTPUTS
String value of the input from the box.
.EXAMPLE
C:\PS> $Result = Show-EJInputBox -Title "Specify your name" -Message "What is your name?"
C:\PS> Write-Host "Your name is $Result"
Your name is test
.LINK
https://github.com/akshinmustafayev/EasyJob
#>
param (
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] [string]$Title,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] [string]$Message
)
$Result = [Microsoft.VisualBasic.Interaction]::InputBox($Message, $Title)
return $Result
}
================================================
FILE: EasyJob/LICENSE.txt
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: EasyJob/MainWindow.xaml
================================================
================================================
FILE: EasyJob/MainWindow.xaml.cs
================================================
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using EasyJob.Serialization;
using EasyJob.Serialization.AnswerDialog;
using EasyJob.Serialization.TasksList;
using EasyJob.TabItems;
using EasyJob.Utils;
using EasyJob.Windows;
using Newtonsoft.Json;
using WpfRichText;
namespace EasyJob
{
public partial class MainWindow : Window
{
ActionButton actionButtonForCopy = null;
TabData selectedTabItem = null;
ActionButton selectedActionButton = null;
ObservableCollection tasksList = new ObservableCollection();
public Config config;
public MainWindow()
{
InitializeComponent();
LoadConfig();
MainMenuItemsVisibility();
}
public void LoadConfig()
{
if (File.Exists(ConfigUtils.ConfigJsonPath))
{
try
{
string configJson = File.ReadAllText(ConfigUtils.ConfigJsonPath);
config = JsonConvert.DeserializeObject(configJson);
MainTab.ItemsSource = ConfigUtils.ConvertTabsFromConfigToUI(config);
AddTextToEventsList("Config loaded from file: " + ConfigUtils.ConfigJsonPath, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
AddTextToEventsList("Error occured while loading file: " + ex.Message, false);
}
}
else
{
MessageBox.Show("File " + ConfigUtils.ConfigJsonPath + " does not exist.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
public bool SaveConfig()
{
if (File.Exists(ConfigUtils.ConfigJsonPath))
{
try
{
IEnumerable tabs = (IEnumerable)MainTab.ItemsSource;
config.tabs.Clear();
List configTabs = new List();
List buttons = null;
List configArguments = null;
foreach (TabData tab in tabs)
{
buttons = new List();
foreach (ActionButton button in tab.TabActionButtons)
{
configArguments = new List();
foreach (Answer answer in button.ButtonArguments)
{
configArguments.Add(new ConfigArgument(answer.AnswerQuestion, answer.AnswerResult));
}
buttons.Add(new ConfigButton(button.ID, button.ButtonText, button.ButtonDescription, button.ButtonScript, button.ButtonScriptPathType, button.ButtonScriptType, configArguments));
}
configTabs.Add(new ConfigTab(tab.ID, tab.TabHeader, buttons));
}
config.tabs = configTabs;
if (ConfigUtils.SaveFromConfigToFile(config) == true)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
else
{
SaveConfig();
}
return false;
}
private void MainMenuItemsVisibility()
{
// File
if (config.restrictions.hide_menu_item_file_reload_config == true) { FileReloadConfigMenuItem.Visibility = Visibility.Collapsed; } else { FileReloadConfigMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_file_open_app_folder == true) { FileOpenAppFolderMenuItem.Visibility = Visibility.Collapsed; } else { FileOpenAppFolderMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_file_clear_events_list == true) { FileClearEventsLogListMenuItem.Visibility = Visibility.Collapsed; } else { FileClearEventsLogListMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_file_reload_config == true && config.restrictions.hide_menu_item_file_open_app_folder == true && config.restrictions.hide_menu_item_file_clear_events_list == true) { FileSeparator1.Visibility = Visibility.Collapsed; } else { FileSeparator1.Visibility = Visibility.Visible; }
// Settings
if (config.restrictions.hide_menu_item_settings == true) { SettingsMenuItem.Visibility = Visibility.Collapsed; } else { SettingsMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow == true) { SettingsWorkflowMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_reorder_tabs == true) { SettingsWorkflowReorderTabsMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowReorderTabsMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_add_tab == true) { SettingsWorkflowAddTabMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowAddTabMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_remove_current_tab == true) { SettingsWorkflowRemoveCurrentTabMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowRemoveCurrentTabMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_rename_current_tab == true) { SettingsWorkflowRenameCurrentTabMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowRenameCurrentTabMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_add_button_to_current_tab == true) { SettingsWorkflowAddButtonToCurrentTabMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowAddButtonToCurrentTabMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_workflow_reorder_buttons_in_current_tab == true) { SettingsWorkflowReorderButtonsInCurrentTabMenuItem.Visibility = Visibility.Collapsed; } else { SettingsWorkflowReorderButtonsInCurrentTabMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_settings_configuration == true) { SettingsConfigurationMenuItem.Visibility = Visibility.Collapsed; } else { SettingsConfigurationMenuItem.Visibility = Visibility.Visible; }
// Help
if (config.restrictions.hide_menu_item_help == true) { HelpMenuItem.Visibility = Visibility.Collapsed; } else { HelpMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_help_troubleshooting == true) { HelpTroubleshootingMenuItem.Visibility = Visibility.Collapsed; } else { HelpTroubleshootingMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_help_colortags == true) { HelpColorTagsMenuItem.Visibility = Visibility.Collapsed; } else { HelpColorTagsMenuItem.Visibility = Visibility.Visible; }
if (config.restrictions.hide_menu_item_help_about == true) { HelpAboutMenuItem.Visibility = Visibility.Collapsed; } else { HelpAboutMenuItem.Visibility = Visibility.Visible; }
}
private void AddTextToConsole (string Text, int OwnerTab)
{
if(Text == "" || Text == null || Text == "Error: ")
{
return;
}
if (config.console_ignore_color_tags == false)
{
Text = CommonUtils.ApplyConsoleColorTagsToText(Text);
}
//this.Dispatcher.Invoke(() =>
//{
TabData td = (TabData)MainTab.Items[OwnerTab];
td.TabTextBoxText = td.TabTextBoxText + "
" + Text;
//});
}
public void AddTextToEventsList(string Text, bool IsAsync)
{
if (Text == "" || Text == null || Text == "Error: ")
{
return;
}
if (IsAsync == true)
{
this.Dispatcher.Invoke(() =>
{
EventsList.Items.Add(Text);
EventsList.ScrollIntoView(EventsList.Items.Count - 1);
});
}
else
{
EventsList.Items.Add(Text);
EventsList.ScrollIntoView(EventsList.Items.Count - 1);
}
}
private void ScrollToBottomListBox(ListBox listBox, bool IsAsync)
{
if(listBox == null && listBox.Items.Count == 0)
{
return;
}
if (IsAsync == true)
{
this.Dispatcher.Invoke(() =>
{
if (listBox != null)
{
var border = (Border)VisualTreeHelper.GetChild(listBox, 0);
var scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
scrollViewer.ScrollToBottom();
}
});
}
else
{
if (listBox != null)
{
var border = (Border)VisualTreeHelper.GetChild(listBox, 0);
var scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
scrollViewer.ScrollToBottom();
}
}
}
private void RemoveTaskFromTasksList(int ProcessID, bool IsAsync)
{
if (IsAsync == true)
{
this.Dispatcher.Invoke(() =>
{
ObservableCollection taskListsNew = new ObservableCollection();
foreach (TaskListTask tlt in tasksList)
{
if (tlt.TaskID == ProcessID)
{
continue;
}
taskListsNew.Add(new TaskListTask { TaskID = tlt.TaskID });
}
tasksList = taskListsNew;
TasksList.ItemsSource = taskListsNew;
});
}
else
{
ObservableCollection taskListsNew = new ObservableCollection();
foreach (TaskListTask tlt in tasksList)
{
if (tlt.TaskID == ProcessID)
{
continue;
}
taskListsNew.Add(new TaskListTask { TaskID = tlt.TaskID });
}
tasksList = taskListsNew;
TasksList.ItemsSource = taskListsNew;
}
}
private void AddTaskToTasksList(int ProcessID, string ProcessFileName)
{
tasksList.Add(new TaskListTask { TaskID = ProcessID, TaskFile = ProcessFileName });
TasksList.ItemsSource = tasksList;
}
private string GetScriptPath(string ButtonScript, string ButtonScriptPathType)
{
string scriptPath = "";
if (ButtonScriptPathType.ToLower() == "absolute")
{
scriptPath = ButtonScript;
}
else if (ButtonScriptPathType.ToLower() == "relative")
{
scriptPath = AppDomain.CurrentDomain.BaseDirectory + ButtonScript;
}
else
{
scriptPath = ButtonScript;
}
return scriptPath;
}
private string GetPowerShellArguments(string Arguments)
{
string arguments = "";
if(Arguments.Length > 0)
{
arguments = " " + Arguments + " ";
}
return arguments;
}
private void ShowAddButtonDialog()
{
AddActionButtonDialog aabd = new AddActionButtonDialog();
if (aabd.ShowDialog() == true)
{
if (MainTab.Items[MainTab.SelectedIndex] is TabData button)
{
List answers = new List();
foreach (ConfigArgument ca in aabd.configButton.Arguments)
{
answers.Add(new Answer { AnswerQuestion = ca.ArgumentQuestion, AnswerResult = ca.ArgumentAnswer });
}
button.TabActionButtons.Add(new ActionButton { ButtonText = aabd.configButton.Text, ButtonDescription = aabd.configButton.Description, ButtonScript = aabd.configButton.Script, ButtonScriptPathType = aabd.configButton.ScriptPathType, ButtonScriptType = aabd.configButton.ScriptType, ButtonArguments = answers });
}
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
AddTextToEventsList("Button '" + aabd.configButton.Text + "' has been successfully added", false);
}
}
else
{
AddTextToEventsList("Adding button cancelled by user", false);
}
}
private void ShowRenameTabDialog(int SelectedTab, string SelectedTabHeader)
{
RenameTabDialog rtd = new RenameTabDialog(SelectedTabHeader);
if (rtd.ShowDialog() == true)
{
List newSourceTabs = new List();
foreach (TabData tab in MainTab.Items)
{
TabData currentTab = MainTab.Items[SelectedTab] as TabData;
if (tab == currentTab)
{
tab.TabHeader = rtd.NewTabName;
}
newSourceTabs.Add(tab);
}
MainTab.ItemsSource = null;
MainTab.ItemsSource = newSourceTabs;
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
else
{
AddTextToEventsList("Current tab rename cancelled by user", false);
}
}
private void ShowAddNewTabDialog()
{
NewTabDialog ntd = new NewTabDialog();
if(ntd.ShowDialog() == true)
{
LoadConfig();
MainTab.Items.Refresh();
this.UpdateLayout();
}
else
{
AddTextToEventsList("Adding new Tab cancelled by user", false);
}
}
private void ShowReorderActionButtonsDialog()
{
int currentTab = MainTab.SelectedIndex;
ReorderActionButtonsDialog rabd = new ReorderActionButtonsDialog(MainTab.SelectedIndex, config);
rabd.ShowDialog();
if (rabd.changesOccured)
{
LoadConfig();
MainTab.Items.Refresh();
this.UpdateLayout();
AddTextToEventsList("Reorder action buttons dialog ended!", false);
MainTab.SelectedIndex = currentTab;
}
else
{
AddTextToEventsList("Reorder action buttons dialog ended. No changes occured!", false);
}
}
public void ClearOutputButton_Click(object sender, RoutedEventArgs e)
{
TabData td = (TabData)MainTab.SelectedItem;
td.TabTextBoxText = "";
AddTextToEventsList("Output has been cleared!", false);
}
public AnswerData ConvertArgumentsToAnswers(List Answers)
{
AnswerData answerData = new AnswerData();
answerData.Answers = Answers;
return answerData;
}
public string ConvertArgumentsToPowerShell(List Answers)
{
string powerShellArguments = "";
foreach (Answer answer in Answers)
{
powerShellArguments = powerShellArguments + answer.AnswerResult + " ";
}
if (powerShellArguments.EndsWith(" "))
{
powerShellArguments = powerShellArguments.Remove(powerShellArguments.Length - 1);
}
return powerShellArguments;
}
public string ConvertArgumentsToCMD(List Answers)
{
string powerShellArguments = "";
foreach (Answer answer in Answers)
{
powerShellArguments = powerShellArguments + answer.AnswerResult + " ";
}
if (powerShellArguments.EndsWith(" "))
{
powerShellArguments = powerShellArguments.Remove(powerShellArguments.Length - 1);
}
return powerShellArguments;
}
public string RemoveScriptFileFromPath(string ScriptPath)
{
string[] scriptPathSplits = ScriptPath.Split("\\");
string newScriptPath = "";
if(scriptPathSplits.Length > 0)
{
for (int i = 0; i < scriptPathSplits.Length - 1; i++)
{
newScriptPath += scriptPathSplits[i] + "\\";
}
}
return newScriptPath;
}
public async void ActionButton_Click(object sender, RoutedEventArgs e)
{
Button actionButton = sender as Button;
string buttonScript = ((ActionButton)actionButton.DataContext).ButtonScript;
string buttonScriptPathType = ((ActionButton)actionButton.DataContext).ButtonScriptPathType;
string buttonScriptType = ((ActionButton)actionButton.DataContext).ButtonScriptType;
string scriptPath = GetScriptPath(buttonScript, buttonScriptPathType);
string powershellArguments = GetPowerShellArguments(config.powershell_arguments);
int ownerTab = MainTab.SelectedIndex;
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
try
{
Process.Start("explorer.exe", GetScriptPath(RemoveScriptFileFromPath(buttonScript), buttonScriptPathType));
AddTextToEventsList("Opened script location folder: " + GetScriptPath(RemoveScriptFileFromPath(buttonScript), buttonScriptPathType), false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
AddTextToEventsList("Could not open script location folder: " + ex.Message, false);
}
return;
}
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
{
try
{
Process.Start("explorer.exe", scriptPath);
AddTextToEventsList("Opened script : " + scriptPath, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
AddTextToEventsList("Could not open script: " + ex.Message, false);
}
return;
}
List buttonArguments = ((ActionButton)actionButton.DataContext).ButtonArguments;
AddTextToConsole("Start script: " + scriptPath + "
=====================================================================
", ownerTab);
AddTextToEventsList("Execution of " + scriptPath + " has been started.", false);
if (buttonArguments.Count == 0)
{
AddTextToEventsList("Starting script " + scriptPath, false);
if (buttonScriptType.ToLower() == "powershell")
{
await RunProcessAsync(config.default_powershell_path, powershellArguments + "-File \"" + scriptPath + "\"", ownerTab, buttonScript);
}
else
{
await RunProcessAsync(config.default_cmd_path, "/c \"" + scriptPath + "\"", ownerTab, buttonScript);
}
}
else
{
AnswerDialog dialog = new AnswerDialog(ConvertArgumentsToAnswers(buttonArguments));
if (dialog.ShowDialog() == true)
{
AddTextToEventsList("Starting script" + scriptPath, false);
if (buttonScriptType.ToLower() == "powershell")
{
await RunProcessAsync(config.default_powershell_path, powershellArguments + "-File \"" + scriptPath + "\" " + ConvertArgumentsToPowerShell(dialog.answerData.Answers), ownerTab, buttonScript);
}
else
{
await RunProcessAsync(config.default_cmd_path, powershellArguments + "/c \"" + scriptPath + "\" " + ConvertArgumentsToCMD(dialog.answerData.Answers), ownerTab, buttonScript);
}
}
else
{
AddTextToEventsList("Task cancelled by user", false);
AddTextToConsole("Task cancelled by user!", ownerTab);
}
}
}
public async Task RunProcessAsync(string FileName, string Args, int OwnerTab, string ScriptName)
{
using (var process = new Process
{
StartInfo =
{
FileName = FileName, Arguments = Args,
UseShellExecute = false, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardError = true
},
EnableRaisingEvents = true
})
{
return await RunProcessAsync(process, OwnerTab, ScriptName).ConfigureAwait(false);
}
}
private Task RunProcessAsync(Process process, int OwnerTab, string ScriptName)
{
var tcs = new TaskCompletionSource();
// Process Exited
process.Exited += (s, ea) =>
{
RemoveTaskFromTasksList(process.Id, true);
tcs.SetResult(process.ExitCode);
AddTextToConsole("
Task finished!
", OwnerTab);
AddTextToEventsList("Task " + process.StartInfo.Arguments.Replace("-File ", "") + " finished", true);
ScrollToBottomListBox(EventsList, true);
};
// Process Output data received
process.OutputDataReceived += (s, ea) => {
AddTextToConsole(ea.Data, OwnerTab);
};
// Process Error output received
process.ErrorDataReceived += (s, ea) => {
if (ea.Data != null)
{
if (ea.Data != "")
{
AddTextToConsole("Error: " + ea.Data + "", OwnerTab);
AddTextToEventsList("Task " + process.StartInfo.Arguments.Replace("-File ", "") + " failed", true);
}
}
};
// Start the process
bool started = process.Start();
if (!started)
{
throw new InvalidOperationException("Could not start process: " + process);
}
// Add to tasks list
AddTaskToTasksList(process.Id, ScriptName.Split("\\")[ScriptName.Split("\\").Length - 1]);
// Begin to read data from the output
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return tcs.Task;
}
private void TasksListStop_Click(object sender, RoutedEventArgs e)
{
try
{
Button buttonStop = sender as Button;
int processID = ((TaskListTask)buttonStop.DataContext).TaskID;
Process.GetProcessById(processID).Kill();
AddTextToEventsList("Process has been cancelled by user!", false);
RemoveTaskFromTasksList(processID, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
AddTextToEventsList("Process cancelled failed: " + ex.Message, false);
}
}
private void ScrollToTopButton_Click(object sender, RoutedEventArgs e)
{
try
{
RichTextEditor console = FindVisualChild(MainTab);
console.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
var scrollViewElement = console.Parent;
ScrollViewer scrollView = scrollViewElement as ScrollViewer;
scrollView.ScrollToTop();
}
catch { }
}
private void ScrollToBottomButton_Click(object sender, RoutedEventArgs e)
{
try
{
RichTextEditor console = FindVisualChild(MainTab);
console.MoveFocus(new TraversalRequest(FocusNavigationDirection.Last));
var scrollViewElement = console.Parent;
ScrollViewer scrollView = scrollViewElement as ScrollViewer;
scrollView.ScrollToBottom();
}
catch { }
}
private static T FindVisualChild(DependencyObject parent) where T : DependencyObject
{
for (int childCount = 0; childCount < VisualTreeHelper.GetChildrenCount(parent); childCount++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, childCount);
if (child != null && child is T)
return (T)child;
else
{
T childOfChild = FindVisualChild(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
#region MenuItems
private void ReloadConfigMenuItem_Click(object sender, RoutedEventArgs e)
{
try
{
if (config.clear_events_when_reload == true)
{
EventsList.Items.Clear();
}
else
{
AddTextToEventsList("Relading config!", false);
}
MainTab.ItemsSource = null;
LoadConfig();
if(MainTab.Items.Count > 0)
{
MainTab.SelectedIndex = 0;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
AddTextToEventsList("Relading config failed: " + ex.Message, false);
}
}
private void OpenAppFolderMenuItem_Click(object sender, RoutedEventArgs e)
{
try
{
Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
AddTextToEventsList("Opened application running folder", false);
}
}
private void ClearEventsLogListMenuItem_Click(object sender, RoutedEventArgs e)
{
EventsList.Items.Clear();
}
private void ReorderTabsMenuItem_Click(object sender, RoutedEventArgs e)
{
ReorderTabsDialog rtd = new ReorderTabsDialog(config);
rtd.ShowDialog();
if (rtd.changesOccured)
{
LoadConfig();
MainTab.Items.Refresh();
this.UpdateLayout();
AddTextToEventsList("Reorder tabs dialog ended!", false);
}
else
{
AddTextToEventsList("Reorder tabs dialog ended. No changes occured!", false);
}
}
private void ConfigurationMenuItem_Click(object sender, RoutedEventArgs e)
{
ConfigurationDialog cfg = new ConfigurationDialog(config);
cfg.ShowDialog();
LoadConfig();
MainTab.Items.Refresh();
MainMenuItemsVisibility();
this.UpdateLayout();
AddTextToEventsList("Configuration ended!", false);
}
private void AddTabMenuItem_Click(object sender, RoutedEventArgs e)
{
ShowAddNewTabDialog();
}
private void RemoveCurrentTabMenuItem_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Do you want to delete current tab?", "Please confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
List newSourceTabs = new List();
foreach (TabData tab in MainTab.Items)
{
TabData currentTab = MainTab.Items[MainTab.SelectedIndex] as TabData;
if (tab != currentTab)
{
newSourceTabs.Add(tab);
}
}
MainTab.ItemsSource = null;
MainTab.ItemsSource = newSourceTabs;
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
}
private void RenameCurrentTabMenuItem_Click(object sender, RoutedEventArgs e)
{
TabData tab = (TabData)MainTab.Items[MainTab.SelectedIndex];
ShowRenameTabDialog(MainTab.SelectedIndex, tab.TabHeader);
}
private void AddButtonToCurrentTabMenuItem_Click(object sender, RoutedEventArgs e)
{
ShowAddButtonDialog();
}
private void ReorderButtonsInCurrentTabMenuItem_Click(object sender, RoutedEventArgs e)
{
ShowReorderActionButtonsDialog();
}
private void ExitMenuItem_Click(object sender, RoutedEventArgs e)
{
if(tasksList.Count > 0)
{
if(MessageBox.Show("Task is still going. Do you want to exit? You will have to kill process manually if you exit", "Please confirm", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
{
Application.Current.Shutdown();
}
}
else
{
Application.Current.Shutdown();
}
}
private void MenuAbout_Click(object sender, RoutedEventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog();
}
private void MenuTroubleshooting_Click(object sender, RoutedEventArgs e)
{
TroubleshootingWindow troubleshootingDialog = new TroubleshootingWindow(config);
troubleshootingDialog.Show();
}
private void MenuColorTags_Click(object sender, RoutedEventArgs e)
{
ColorTagsDialog colorTagsDialog = new ColorTagsDialog();
colorTagsDialog.Show();
}
#endregion
#region ContextMenuItems
public void ActionButton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
selectedActionButton = ((Button)e.Source).DataContext as ActionButton;
ContextMenu cm = this.FindResource("OnActionButtonContextMenu") as ContextMenu;
if (e.Source is not ScrollViewer && e.OriginalSource is TextBlock)
{
if (config.restrictions.block_buttons_edit == true && config.restrictions.block_buttons_remove == true && config.restrictions.block_buttons_copy == true)
{
return;
}
else
{
if (config.restrictions.block_buttons_edit == false)
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_buttons_remove == false)
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_buttons_copy == false)
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Collapsed;
}
}
cm.PlacementTarget = sender as Button;
cm.IsOpen = true;
}
}
}
public void OnActionButtonPannel_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
ContextMenu cm = this.FindResource("OnActionButtonPannelContextMenu") as ContextMenu;
if (e.Source is ScrollViewer && e.OriginalSource is not TextBlock)
{
if (config.restrictions.block_buttons_add == true && config.restrictions.block_buttons_reorder == true && config.restrictions.block_buttons_paste == true)
{
return;
}
else
{
if (config.restrictions.block_buttons_add == false)
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_buttons_reorder == false)
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_buttons_paste == false)
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Visible;
if(actionButtonForCopy != null)
{
(cm.Items[2] as MenuItem).IsEnabled = true;
}
else
{
(cm.Items[2] as MenuItem).IsEnabled = false;
}
}
else
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Collapsed;
}
}
cm.PlacementTarget = sender as ScrollViewer;
cm.IsOpen = true;
}
}
}
private void OnTabHeader_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
selectedTabItem = ((Label)e.Source).DataContext as TabData;
ContextMenu cm = this.FindResource("OnTabContextMenu") as ContextMenu;
if (config.restrictions.block_tabs_add == true && config.restrictions.block_tabs_remove == true && config.restrictions.block_tabs_rename == true)
{
return;
}
else
{
if (config.restrictions.block_tabs_add == false)
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[0] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_tabs_remove == false)
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[1] as MenuItem).Visibility = Visibility.Collapsed;
}
if (config.restrictions.block_tabs_rename == false)
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Visible;
}
else
{
(cm.Items[2] as MenuItem).Visibility = Visibility.Collapsed;
}
}
cm.PlacementTarget = sender as Label;
cm.IsOpen = true;
}
}
private void ContextMenuRemoveTab_Click(object sender, RoutedEventArgs e)
{
if (selectedTabItem == null)
{
MessageBox.Show("Selected Tab is still null. Please try again.");
return;
}
List newSourceTabs = new List();
foreach (TabData tab in MainTab.Items)
{
if (tab != selectedTabItem)
{
newSourceTabs.Add(tab);
}
}
MainTab.ItemsSource = null;
MainTab.ItemsSource = newSourceTabs;
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
private void ContextMenuRenameTab_Click(object sender, RoutedEventArgs e)
{
if (selectedTabItem == null)
{
MessageBox.Show("Selected Tab is still null. Please try again.");
return;
}
int currentTabIndex = 0;
List newSourceTabs = new List();
foreach (TabData tab in MainTab.Items)
{
if (tab == selectedTabItem)
{
ShowRenameTabDialog(currentTabIndex, selectedTabItem.TabHeader);
return;
}
else
{
currentTabIndex = currentTabIndex + 1;
}
}
}
private void ContextMenuAddTab_Click(object sender, RoutedEventArgs e)
{
ShowAddNewTabDialog();
}
private void ContextMenuRemoveActionButton_Click(object sender, RoutedEventArgs e)
{
if (selectedActionButton == null)
{
MessageBox.Show("Selected Action button is still null. Please try again.");
return;
}
for (int i = 0; i < MainTab.Items.Count; i++)
{
if (MainTab.Items[i] is TabData button)
{
var item = button.TabActionButtons.Where(x => x.Equals(selectedActionButton)).FirstOrDefault();
if (item != null)
{
button.TabActionButtons.Remove(item);
}
}
}
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
private void ContextMenuCopyActionButton_Click(object sender, RoutedEventArgs e)
{
if (selectedActionButton == null)
{
MessageBox.Show("Selected Action button is still null. Please try again.");
return;
}
actionButtonForCopy = selectedActionButton;
}
private void ContextMenuEditActionButton_Click(object sender, RoutedEventArgs e)
{
if (selectedActionButton == null)
{
MessageBox.Show("Selected Action button is still null. Please try again.");
return;
}
EditActionButtonDialog eabd = new EditActionButtonDialog(selectedActionButton);
if(eabd.ShowDialog() == true)
{
for (int i = 0; i < MainTab.Items.Count; i++)
{
if (MainTab.Items[i] is TabData button)
{
var item = button.TabActionButtons.Where(x => x.Equals(selectedActionButton)).FirstOrDefault();
if (item != null)
{
item = eabd.actionButton;
}
}
}
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
else
{
AddTextToEventsList("Edit button cancelled by user", false);
}
}
private void ContextMenuAddActionButton_Click(object sender, RoutedEventArgs e)
{
ShowAddButtonDialog();
}
private void ContextMenuReorderActionButtons_Click(object sender, RoutedEventArgs e)
{
ShowReorderActionButtonsDialog();
}
private void ContextMenuPasteActionButton_Click(object sender, RoutedEventArgs e)
{
if (actionButtonForCopy == null)
{
return;
}
TabData tab = (TabData) MainTab.Items[MainTab.SelectedIndex];
actionButtonForCopy.ID = Guid.NewGuid();
tab.TabActionButtons.Add(actionButtonForCopy);
if (SaveConfig())
{
MainTab.Items.Refresh();
this.UpdateLayout();
}
}
#endregion
}
}
================================================
FILE: EasyJob/Serialization/AnswerDialog/Answer.cs
================================================
namespace EasyJob.Serialization.AnswerDialog
{
public class Answer
{
public string AnswerQuestion { get; set; }
public string AnswerResult { get; set; }
}
}
================================================
FILE: EasyJob/Serialization/AnswerDialog/AnswerData.cs
================================================
using System.Collections.Generic;
namespace EasyJob.Serialization.AnswerDialog
{
public class AnswerData
{
private List _Answers = new List();
public List Answers
{
get { return _Answers; }
set { _Answers = value; }
}
}
}
================================================
FILE: EasyJob/Serialization/Config/Config.cs
================================================
using System.Collections.Generic;
namespace EasyJob.Serialization
{
public class Config
{
public string default_powershell_path { get; set; }
public string default_cmd_path { get; set; }
public string powershell_arguments { get; set; }
public string console_background { get; set; }
public string console_foreground { get; set; }
public bool console_ignore_color_tags { get; set; }
public bool clear_events_when_reload { get; set; }
public ConfigRestrictions restrictions { get; set; }
public List tabs { get; set; }
}
}
================================================
FILE: EasyJob/Serialization/Config/ConfigArgument.cs
================================================
namespace EasyJob.Serialization
{
public class ConfigArgument
{
private string _argument_question;
private string _argument_answer;
///
/// Initializes a new instance of the class.
///
/// The argument question.
/// The argument answer.
public ConfigArgument(string argument_question, string argument_answer)
{
this._argument_question = argument_question;
this._argument_answer = argument_answer;
}
///
/// Gets or sets the argument question.
///
///
/// The argument question.
///
public string ArgumentQuestion { get => _argument_question; set => _argument_question = value; }
///
/// Gets or sets the argument answer.
///
///
/// The argument answer.
///
public string ArgumentAnswer { get => _argument_answer; set => _argument_answer = value; }
}
}
================================================
FILE: EasyJob/Serialization/Config/ConfigButton.cs
================================================
using System;
using System.Collections.Generic;
namespace EasyJob.Serialization
{
public class ConfigButton
{
private Guid _id;
private string _text;
private string _description;
private string _script;
private string _scriptpathtype;
private string _scripttype;
private List _arguments;
///
/// Initializes a new instance of the class.
///
/// The text.
/// The description.
/// The script.
/// The scriptpathtype.
/// The scripttype.
/// The arguments.
///
public ConfigButton(Guid id, string text, string description, string script, string scriptpathtype, string scripttype, List arguments)
{
this._id = id.Equals(Guid.Empty) ? Guid.NewGuid() : id;
this._text = text;
this._description = description;
this._script = script;
this._scriptpathtype = scriptpathtype;
this._scripttype = scripttype;
this._arguments = arguments;
}
///
/// Gets or sets the identifier.
///
///
/// The identifier.
///
public Guid Id { get => _id; set => _id = value; }
///
/// Gets or sets the text.
///
///
/// The text.
///
public string Text { get => _text; set => _text = value; }
///
/// Gets or sets the description.
///
///
/// The description.
///
public string Description { get => _description; set => _description = value; }
///
/// Gets or sets the script.
///
///
/// The script.
///
public string Script { get => _script; set => _script = value; }
///
/// Gets or sets the type of the script path.
///
///
/// The type of the script path.
///
public string ScriptPathType { get => _scriptpathtype; set => _scriptpathtype = value; }
///
/// Gets or sets the type of the script.
///
///
/// The type of the script.
///
public string ScriptType { get => _scripttype; set => _scripttype = value; }
///
/// Gets or sets the arguments.
///
///
/// The arguments.
///
public List Arguments { get => _arguments; set => _arguments = value; }
}
}
================================================
FILE: EasyJob/Serialization/Config/ConfigRestrictions.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EasyJob.Serialization
{
public class ConfigRestrictions
{
public bool block_tabs_remove { get; set; }
public bool block_buttons_remove { get; set; }
public bool block_tabs_add { get; set; }
public bool block_buttons_add { get; set; }
public bool block_buttons_reorder { get; set; }
public bool block_buttons_edit { get; set; }
public bool block_tabs_rename { get; set; }
public bool block_buttons_paste { get; set; }
public bool block_buttons_copy { get; set; }
public bool hide_menu_item_file_reload_config { get; set; }
public bool hide_menu_item_file_open_app_folder { get; set; }
public bool hide_menu_item_file_clear_events_list { get; set; }
public bool hide_menu_item_settings { get; set; }
public bool hide_menu_item_settings_workflow { get; set; }
public bool hide_menu_item_settings_workflow_reorder_tabs { get; set; }
public bool hide_menu_item_settings_workflow_add_tab { get; set; }
public bool hide_menu_item_settings_workflow_remove_current_tab { get; set; }
public bool hide_menu_item_settings_workflow_rename_current_tab { get; set; }
public bool hide_menu_item_settings_workflow_add_button_to_current_tab { get; set; }
public bool hide_menu_item_settings_workflow_reorder_buttons_in_current_tab { get; set; }
public bool hide_menu_item_settings_configuration { get; set; }
public bool hide_menu_item_help { get; set; }
public bool hide_menu_item_help_troubleshooting { get; set; }
public bool hide_menu_item_help_colortags { get; set; }
public bool hide_menu_item_help_about { get; set; }
}
}
================================================
FILE: EasyJob/Serialization/Config/ConfigTab.cs
================================================
using System;
using System.Collections.Generic;
namespace EasyJob.Serialization
{
public class ConfigTab
{
private Guid _id;
private string _header;
private List _buttons;
///
/// Initializes a new instance of the class.
///
/// The identifier.
/// The header.
/// The buttons.
public ConfigTab(Guid id, string header, List buttons)
{
this._id = id.Equals(Guid.Empty) ? Guid.NewGuid() : id;
this._header = header;
this._buttons = buttons;
}
///
/// Gets or sets the identifier.
///
///
/// The identifier.
///
public Guid ID { get => _id; set => _id = value; }
///
/// Gets or sets the header.
///
///
/// The header.
///
public string Header { get => _header; set => _header = value; }
///
/// Gets or sets the buttons.
///
///
/// The buttons.
///
public List Buttons { get => _buttons; set => _buttons = value; }
}
}
================================================
FILE: EasyJob/Serialization/TabItems/ActionButton.cs
================================================
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using EasyJob.Serialization.AnswerDialog;
namespace EasyJob.TabItems
{
public class ActionButton
{
///
/// Gets or sets the identifier.
///
///
/// The identifier.
///
public Guid ID { get; set; }
///
/// Gets or sets the button text.
///
///
/// The button text.
///
public string ButtonText { get; set; }
///
/// Gets or sets the button description.
///
///
/// The button description.
///
public string ButtonDescription { get; set; }
///
/// Gets or sets the button script.
///
///
/// The button script.
///
public string ButtonScript { get; set; }
///
/// Gets or sets the type of the button script path.
///
///
/// The type of the button script path.
///
public string ButtonScriptPathType { get; set; }
///
/// Gets or sets the type of the button script.
///
///
/// The type of the button script.
///
public string ButtonScriptType { get; set; }
///
/// Gets or sets the button arguments.
///
///
/// The button arguments.
///
public List ButtonArguments { get; set; }
///
/// Gets or sets the context menu.
///
///
/// The context menu.
///
public ContextMenu contextMenu { get; set; }
}
}
================================================
FILE: EasyJob/Serialization/TabItems/TabData.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
namespace EasyJob.TabItems
{
public class TabData : INotifyPropertyChanged
{
private string _TabTextBoxText;
///
/// Initializes a new instance of the class.
///
public TabData()
{
}
///
/// Initializes a new instance of the class.
///
/// The tab text box text.
public TabData(string tabTextBoxText)
{
this._TabTextBoxText = tabTextBoxText;
ID = Guid.NewGuid();
TabHeader = tabTextBoxText;
TabActionButtons = new List();
}
///
/// Gets or sets the identifier.
///
///
/// The identifier.
///
public Guid ID { get; set; }
///
/// Gets or sets the tab header.
///
///
/// The tab header.
///
public string TabHeader { get; set; }
///
/// Gets or sets the console background.
///
///
/// The console background.
///
public string ConsoleBackground { get; set; }
///
/// Gets or sets the console foreground.
///
///
/// The console foreground.
///
public string ConsoleForeground { get; set; }
///
/// Gets or sets the tab action buttons.
///
///
/// The tab action buttons.
///
public List TabActionButtons { get; set; }
///
/// Gets or sets the tab text box text.
///
///
/// The tab text box text.
///
public string TabTextBoxText {
get
{
return this._TabTextBoxText;
}
set
{
if (_TabTextBoxText != value)
{
_TabTextBoxText = value;
Task.Run(() => {
OnChange("TabTextBoxText");
});
}
}
}
///
/// Occurs when a property value changes.
///
public event PropertyChangedEventHandler PropertyChanged;
///
/// Called when [change].
///
/// The information.
protected void OnChange(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
================================================
FILE: EasyJob/Serialization/TasksList/TaskListTask.cs
================================================
namespace EasyJob.Serialization.TasksList
{
public class TaskListTask
{
public int TaskID { get; set; }
public string TaskFile { get; set; }
}
}
================================================
FILE: EasyJob/Utils/CommonUtils.cs
================================================
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
namespace EasyJob.Utils
{
public class CommonUtils
{
public static void OpenLinkInBrowser(string url)
{
try
{
Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = url;
proc.Start();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
public static string ReadAssemblyFile(string name)
{
// Determine path
var assembly = Assembly.GetExecutingAssembly();
string resourcePath = name;
// Format: "{Namespace}.{Folder}.{filename}.{Extension}"
if (!name.StartsWith(nameof(EasyJob)))
{
resourcePath = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith(name));
}
using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public static string ApplyConsoleColorTagsToText(string Text)
{
string[][] colorCodes = new string[][] {
new string[] { @"\c01EJ", "/c01EJ", "" },
new string[] { @"\c02EJ", "/c02EJ", "" },
new string[] { @"\c03EJ", "/c03EJ", "" },
new string[] { @"\c04EJ", "/c04EJ", "" },
new string[] { @"\c05EJ", "/c05EJ", "" },
new string[] { @"\c06EJ", "/c06EJ", "" },
new string[] { @"\c07EJ", "/c07EJ", "" },
new string[] { @"\c08EJ", "/c08EJ", "" },
new string[] { @"\c09EJ", "/c09EJ", "" },
new string[] { @"\c10EJ", "/c10EJ", "" },
new string[] { @"\c11EJ", "/c11EJ", "" },
new string[] { @"\c12EJ", "/c12EJ", "" },
new string[] { @"\c13EJ", "/c13EJ", "" },
new string[] { @"\c14EJ", "/c14EJ", "" }
};
for (int i = 0; i <= colorCodes.GetLength(0) - 1; i++)
{
if (Text.Contains(colorCodes[i][0]) == true && Text.Contains(colorCodes[i][1]) == false)
{
Text = Text.Replace(colorCodes[i][0], colorCodes[i][2]);
Text = Text + "";
}
else if (Text.Contains(colorCodes[i][0]) == false && Text.Contains(colorCodes[i][1]) == true)
{
Text = Text.Replace(colorCodes[i][1], "");
}
else if (Text.Contains(colorCodes[i][0]) == true && Text.Contains(colorCodes[i][1]) == true)
{
Text = Text.Replace(colorCodes[i][0], colorCodes[i][2]);
Text = Text.Replace(colorCodes[i][1], "");
}
}
return Text;
}
public static string ConvertPartToRelative(string Path)
{
Path = Path.Replace(AppDomain.CurrentDomain.BaseDirectory, "");
return Path;
}
public static string ApplicationStartupPath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
================================================
FILE: EasyJob/Utils/ConfigUtils.cs
================================================
using EasyJob.Serialization;
using EasyJob.Serialization.AnswerDialog;
using EasyJob.TabItems;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace EasyJob.Utils
{
public class ConfigUtils
{
public static string ConfigJsonPath = AppDomain.CurrentDomain.BaseDirectory + "config.json";
public static ObservableCollection ConvertTabsFromConfigToUI(Config config)
{
ObservableCollection tabs = new ObservableCollection();
foreach (ConfigTab configTab in config.tabs)
{
List actionButtons = new List();
foreach (ConfigButton configButton in configTab.Buttons)
{
List configArguments = new List();
foreach (ConfigArgument configArgument in configButton.Arguments)
{
configArguments.Add(new Answer { AnswerQuestion = configArgument.ArgumentQuestion, AnswerResult = configArgument.ArgumentAnswer });
}
actionButtons.Add(new ActionButton { ID = configButton.Id, ButtonText = configButton.Text, ButtonDescription = configButton.Description, ButtonScript = configButton.Script, ButtonScriptPathType = configButton.ScriptPathType, ButtonScriptType = configButton.ScriptType, ButtonArguments = configArguments });
}
tabs.Add(new TabData { ID = configTab.ID, TabHeader = configTab.Header, ConsoleBackground = config.console_background, ConsoleForeground = config.console_foreground, TabActionButtons = actionButtons, TabTextBoxText = "" });
}
return tabs;
}
///
/// Saves the configs.
///
/// The tabs.
///
public static List ConvertTabsFromUIToConfig(IEnumerable tabs)
{
List configTabs = new List();
List buttons = null;
List configArguments = null;
foreach (TabData tab in tabs)
{
buttons = new List();
foreach (ActionButton button in tab.TabActionButtons)
{
configArguments = new List();
foreach (Answer answer in button.ButtonArguments)
{
configArguments.Add(new ConfigArgument(answer.AnswerQuestion, answer.AnswerResult));
}
buttons.Add(new ConfigButton(button.ID, button.ButtonText, button.ButtonDescription, button.ButtonScript, button.ButtonScriptPathType, button.ButtonScriptType, configArguments));
}
configTabs.Add(new ConfigTab(tab.ID, tab.TabHeader, buttons));
}
return configTabs;
}
public static bool SaveFromConfigToFile(Config config)
{
try
{
string confifJson = JsonConvert.SerializeObject(config);
File.WriteAllText(ConfigJsonPath, confifJson, Encoding.UTF8);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
================================================
FILE: EasyJob/Utils/ScrollViewerExtensions.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace EasyJob.Utils
{
public class ScrollViewerExtensions
{
public static readonly DependencyProperty AlwaysScrollToEndProperty = DependencyProperty.RegisterAttached("AlwaysScrollToEnd", typeof(bool), typeof(ScrollViewerExtensions), new PropertyMetadata(false, AlwaysScrollToEndChanged));
private static bool _autoScroll;
private static void AlwaysScrollToEndChanged(object sender, DependencyPropertyChangedEventArgs e)
{
ScrollViewer scroll = sender as ScrollViewer;
if (scroll != null)
{
bool alwaysScrollToEnd = (e.NewValue != null) && (bool)e.NewValue;
if (alwaysScrollToEnd)
{
scroll.ScrollToEnd();
scroll.ScrollChanged += ScrollChanged;
}
else { scroll.ScrollChanged -= ScrollChanged; }
}
else { throw new InvalidOperationException("The attached AlwaysScrollToEnd property can only be applied to ScrollViewer instances."); }
}
public static bool GetAlwaysScrollToEnd(ScrollViewer scroll)
{
if (scroll == null) { throw new ArgumentNullException("scroll"); }
return (bool)scroll.GetValue(AlwaysScrollToEndProperty);
}
public static void SetAlwaysScrollToEnd(ScrollViewer scroll, bool alwaysScrollToEnd)
{
if (scroll == null) { throw new ArgumentNullException("scroll"); }
scroll.SetValue(AlwaysScrollToEndProperty, alwaysScrollToEnd);
}
private static void ScrollChanged(object sender, ScrollChangedEventArgs e)
{
ScrollViewer scroll = sender as ScrollViewer;
if (scroll == null) { throw new InvalidOperationException("The attached AlwaysScrollToEnd property can only be applied to ScrollViewer instances."); }
// User scroll event : set or unset autoscroll mode
if (e.ExtentHeightChange == 0) { _autoScroll = scroll.VerticalOffset == scroll.ScrollableHeight; }
// Content scroll event : autoscroll eventually
if (_autoScroll && e.ExtentHeightChange != 0) { scroll.ScrollToVerticalOffset(scroll.ExtentHeight); }
}
}
}
================================================
FILE: EasyJob/Windows/AboutDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/AboutDialog.xaml.cs
================================================
using EasyJob.Utils;
using HtmlAgilityPack;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
namespace EasyJob.Windows
{
///
/// Interaction logic for AboutDialog.xaml
///
public partial class AboutDialog : Window
{
///
/// Initializes a new instance of the class.
///
public AboutDialog()
{
InitializeComponent();
LoadDataInfoIntoTheForm();
}
public void LoadDataInfoIntoTheForm()
{
AboutTitle.Content = "EasyJob Executor " + Assembly.GetExecutingAssembly().GetName().Version.ToString();
AboutInfo.Content = "Author: Akshin Mustafayev. Contrubutions made to the project by the Github community";
string readme = CommonUtils.ReadAssemblyFile("LICENSE.txt");
RichTextBox1.Document.Blocks.Clear();
var plainText = ConvertToPlainText(readme);
RichTextBox1.AppendText(plainText);
}
private static void ConvertContentTo(HtmlNode node, TextWriter outText)
{
foreach (HtmlNode subnode in node.ChildNodes)
{
ConvertTo(subnode, outText);
}
}
///
/// Converts to plain text.
///
/// The HTML.
///
public static string ConvertToPlainText(string html)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
ConvertTo(doc.DocumentNode, sw);
sw.Flush();
return sw.ToString();
}
private static void ConvertTo(HtmlNode node, TextWriter outText)
{
string html;
switch (node.NodeType)
{
case HtmlNodeType.Comment:
// don't output comments
break;
case HtmlNodeType.Document:
ConvertContentTo(node, outText);
break;
case HtmlNodeType.Text:
// script and style must not be output
string parentName = node.ParentNode.Name;
if ((parentName == "script") || (parentName == "style"))
break;
// get text
html = ((HtmlTextNode)node).Text;
// is it in fact a special closing node output as text?
if (HtmlNode.IsOverlappedClosingElement(html))
break;
// check the text is meaningful and not a bunch of whitespaces
if (html.Trim().Length > 0)
{
outText.Write(HtmlEntity.DeEntitize(html));
}
break;
case HtmlNodeType.Element:
switch (node.Name)
{
case "p":
// treat paragraphs as crlf
outText.Write("\r\n");
break;
case "br":
outText.Write("\r\n");
break;
}
if (node.HasChildNodes)
{
ConvertContentTo(node, outText);
}
break;
}
}
private void GetInspirationButton_Click(object sender, RoutedEventArgs e)
{
CommonUtils.OpenLinkInBrowser("https://www.youtube.com/watch?v=l0U7SxXHkPY");
}
private void CheckNewReleasesButton_Click(object sender, RoutedEventArgs e)
{
CommonUtils.OpenLinkInBrowser("https://github.com/akshinmustafayev/EasyJob/releases");
}
private void GithubImage_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
CommonUtils.OpenLinkInBrowser("https://github.com/akshinmustafayev/EasyJob");
}
}
}
================================================
FILE: EasyJob/Windows/AddActionButtonDialog.xaml
================================================
Relative
Absolute
PowerShell
Batch
================================================
FILE: EasyJob/Windows/AddActionButtonDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.Serialization.AnswerDialog;
using EasyJob.Utils;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for AddActionButtonDialog.xaml
///
public partial class AddActionButtonDialog : Window
{
public ConfigButton configButton;
public AddActionButtonDialog()
{
InitializeComponent();
configButton = null;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
List configArguments = new List();
foreach (Answer answer in ButtonScriptArguments.Items) { configArguments.Add(new ConfigArgument(answer.AnswerQuestion, answer.AnswerResult)); };
string buttonScriptPathTypeValue = ConvertScriptPathTypeComboBoxToString(ButtonScriptPathType);
string buttonScriptTypeValue = ConvertScriptTypeComboBoxToString(ButtonScriptType);
ConfigButton newConfigButton = new ConfigButton(Guid.NewGuid() ,ButtonText.Text, ButtonDescription.Text, ButtonScript.Text, buttonScriptPathTypeValue, buttonScriptTypeValue, configArguments);
configButton = newConfigButton;
DialogResult = true;
}
private string ConvertScriptTypeComboBoxToString(ComboBox cb)
{
if(cb.SelectedIndex == 0)
{
return "powershell";
}
else
{
return "bat";
}
}
private string ConvertScriptPathTypeComboBoxToString(ComboBox cb)
{
if (cb.SelectedIndex == 0)
{
return "relative";
}
else
{
return "absolute";
}
}
private void CANCELButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void ADDButton_Click(object sender, RoutedEventArgs e)
{
try
{
ButtonScriptArguments.Items.Add(new Answer { AnswerQuestion = ButtonScriptArgumentText.Text, AnswerResult = "" });
ButtonScriptArgumentText.Text = "";
}
catch { }
}
private void DeleteArgumentButton_Click(object sender, RoutedEventArgs e)
{
try
{
Button btn = sender as Button;
ButtonScriptArguments.Items.Remove((Answer)btn.DataContext);
}
catch { }
}
private void HelpButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
HelpDialog hd = new HelpDialog(button.Name);
hd.ShowDialog();
}
private void SelectFileButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.InitialDirectory = CommonUtils.ApplicationStartupPath();
if (ofd.ShowDialog() == true)
{
if(ButtonScriptPathType.SelectedIndex == 0)
{
ButtonScript.Text = CommonUtils.ConvertPartToRelative(ofd.FileName);
}
else
{
ButtonScript.Text = ofd.FileName;
}
}
}
}
}
================================================
FILE: EasyJob/Windows/AnswerDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/AnswerDialog.xaml.cs
================================================
using EasyJob.Serialization.AnswerDialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for AnswerDialog.xaml
///
public partial class AnswerDialog : Window
{
public AnswerData answerData = null;
public AnswerDialog(AnswerData _answerData)
{
InitializeComponent();
answerData = _answerData;
if (_answerData != null)
{
foreach (Answer answer in _answerData.Answers)
{
answer.AnswerResult = "";
}
AnswerDialogItems.ItemsSource = _answerData.Answers;
}
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
bool AllowConfirm = true;
answerData.Answers = (List)AnswerDialogItems.ItemsSource;
foreach (Answer answer in answerData.Answers)
{
if(answer.AnswerResult == "" || answer.AnswerResult == null)
{
AllowConfirm = false;
}
}
if(AllowConfirm == false)
{
MessageBox.Show("Please provide value to all textboxes!", "Fill all data", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
DialogResult = true;
}
private void CANCELButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
================================================
FILE: EasyJob/Windows/ColorTagsDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/ColorTagsDialog.xaml.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for ColorTagsDialog.xaml
///
public partial class ColorTagsDialog : Window
{
public ColorTagsDialog()
{
InitializeComponent();
}
}
}
================================================
FILE: EasyJob/Windows/ConfigurationDialog.xaml
================================================
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
Yes
No
================================================
FILE: EasyJob/Windows/ConfigurationDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for Configuration.xaml
///
public partial class ConfigurationDialog : Window
{
private Config config;
public ConfigurationDialog(Config _config)
{
InitializeComponent();
config = _config;
LoadConfiguration();
}
private void LoadConfiguration()
{
// Common parameters
DefaultPowerShellPath.Text = config.default_powershell_path;
DefaultCMDPath.Text = config.default_cmd_path;
PowerShellArguments.Text = config.powershell_arguments;
ConsoleBackground.Text = config.console_background;
ConsoleForeground.Text = config.console_foreground;
SetComboBoxFromValue(ConsoleIgnoreColorTags, config.console_ignore_color_tags);
SetComboBoxFromValue(ClearEventsWhenReload, config.clear_events_when_reload);
// Restrictions
SetComboBoxFromValue(BlockTabsRemove, config.restrictions.block_tabs_remove);
SetComboBoxFromValue(BlockButtonsRemove, config.restrictions.block_buttons_remove);
SetComboBoxFromValue(BlockTabsAdd, config.restrictions.block_tabs_add);
SetComboBoxFromValue(BlockButtonsAdd, config.restrictions.block_buttons_add);
SetComboBoxFromValue(BlockButtonsReorder, config.restrictions.block_buttons_reorder);
SetComboBoxFromValue(BlockButtonsEdit, config.restrictions.block_buttons_edit);
SetComboBoxFromValue(BlockTabsRename, config.restrictions.block_tabs_rename);
SetComboBoxFromValue(BlockButtonsPaste, config.restrictions.block_buttons_paste);
SetComboBoxFromValue(BlockButtonsCopy, config.restrictions.block_buttons_copy);
SetComboBoxFromValue(HideFileReloadConfigMenuItem, config.restrictions.hide_menu_item_file_reload_config);
SetComboBoxFromValue(HideFileOpenAppFolderMenuItem, config.restrictions.hide_menu_item_file_open_app_folder);
SetComboBoxFromValue(HideFileClearEventsListMenuItem, config.restrictions.hide_menu_item_file_clear_events_list);
SetComboBoxFromValue(HideSettingsMenuItem, config.restrictions.hide_menu_item_settings);
SetComboBoxFromValue(HideSettingsWorkflowMenuItem, config.restrictions.hide_menu_item_settings_workflow);
SetComboBoxFromValue(HideSettingsWorkflowReorderTabsMenuItem, config.restrictions.hide_menu_item_settings_workflow_reorder_tabs);
SetComboBoxFromValue(HideSettingsWorkflowAddTabMenuItem, config.restrictions.hide_menu_item_settings_workflow_add_tab);
SetComboBoxFromValue(HideSettingsWorkflowRemoveCurrentTabMenuItem, config.restrictions.hide_menu_item_settings_workflow_remove_current_tab);
SetComboBoxFromValue(HideSettingsWorkflowRenameCurrentTabMenuItem, config.restrictions.hide_menu_item_settings_workflow_rename_current_tab);
SetComboBoxFromValue(HideSettingsWorkflowAddButtonToCurrentTabMenuItem, config.restrictions.hide_menu_item_settings_workflow_add_button_to_current_tab);
SetComboBoxFromValue(HideSettingsWorkflowReorderButtonsInCurrentTabMenuItem, config.restrictions.hide_menu_item_settings_workflow_reorder_buttons_in_current_tab);
SetComboBoxFromValue(HideSettingsConfigurationMenuItem, config.restrictions.hide_menu_item_settings_configuration);
SetComboBoxFromValue(HideHelpMenuItem, config.restrictions.hide_menu_item_help);
SetComboBoxFromValue(HideHelpTroubleshootingMenuItem, config.restrictions.hide_menu_item_help_troubleshooting);
SetComboBoxFromValue(HideHelpColorTagsMenuItem, config.restrictions.hide_menu_item_help_colortags);
SetComboBoxFromValue(HideHelpAboutMenuItem, config.restrictions.hide_menu_item_help_about);
}
private void SetComboBoxFromValue(ComboBox comboBox, bool value)
{
if(value == true)
{
comboBox.SelectedIndex = 0;
}
else
{
comboBox.SelectedIndex = 1;
}
}
private bool GetComboBoxValue(ComboBox comboBox)
{
if (comboBox.SelectedIndex == 0)
{
return true;
}
else
{
return false;
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
config.default_powershell_path = DefaultPowerShellPath.Text;
config.default_cmd_path = DefaultCMDPath.Text;
config.powershell_arguments = PowerShellArguments.Text;
config.console_background = ConsoleBackground.Text;
config.console_foreground = ConsoleForeground.Text;
config.console_ignore_color_tags = GetComboBoxValue(ConsoleIgnoreColorTags);
config.clear_events_when_reload = GetComboBoxValue(ClearEventsWhenReload);
config.restrictions.block_tabs_remove = GetComboBoxValue(BlockTabsRemove);
config.restrictions.block_buttons_remove = GetComboBoxValue(BlockButtonsRemove);
config.restrictions.block_tabs_add = GetComboBoxValue(BlockTabsAdd);
config.restrictions.block_buttons_add = GetComboBoxValue(BlockButtonsAdd);
config.restrictions.block_buttons_reorder = GetComboBoxValue(BlockButtonsReorder);
config.restrictions.block_buttons_edit = GetComboBoxValue(BlockButtonsEdit);
config.restrictions.block_tabs_rename = GetComboBoxValue(BlockTabsRename);
config.restrictions.block_buttons_paste = GetComboBoxValue(BlockButtonsPaste);
config.restrictions.block_buttons_copy = GetComboBoxValue(BlockButtonsCopy);
config.restrictions.hide_menu_item_file_reload_config = GetComboBoxValue(HideFileReloadConfigMenuItem);
config.restrictions.hide_menu_item_file_open_app_folder = GetComboBoxValue(HideFileOpenAppFolderMenuItem);
config.restrictions.hide_menu_item_file_clear_events_list = GetComboBoxValue(HideFileClearEventsListMenuItem);
config.restrictions.hide_menu_item_settings = GetComboBoxValue(HideSettingsMenuItem);
config.restrictions.hide_menu_item_settings_workflow = GetComboBoxValue(HideSettingsWorkflowMenuItem);
config.restrictions.hide_menu_item_settings_workflow_reorder_tabs = GetComboBoxValue(HideSettingsWorkflowReorderTabsMenuItem);
config.restrictions.hide_menu_item_settings_workflow_add_tab = GetComboBoxValue(HideSettingsWorkflowAddTabMenuItem);
config.restrictions.hide_menu_item_settings_workflow_remove_current_tab = GetComboBoxValue(HideSettingsWorkflowRemoveCurrentTabMenuItem);
config.restrictions.hide_menu_item_settings_workflow_rename_current_tab = GetComboBoxValue(HideSettingsWorkflowRenameCurrentTabMenuItem);
config.restrictions.hide_menu_item_settings_workflow_add_button_to_current_tab = GetComboBoxValue(HideSettingsWorkflowAddButtonToCurrentTabMenuItem);
config.restrictions.hide_menu_item_settings_workflow_reorder_buttons_in_current_tab = GetComboBoxValue(HideSettingsWorkflowReorderButtonsInCurrentTabMenuItem);
config.restrictions.hide_menu_item_settings_configuration = GetComboBoxValue(HideSettingsConfigurationMenuItem);
config.restrictions.hide_menu_item_help = GetComboBoxValue(HideHelpMenuItem);
config.restrictions.hide_menu_item_help_troubleshooting = GetComboBoxValue(HideHelpTroubleshootingMenuItem);
config.restrictions.hide_menu_item_help_colortags = GetComboBoxValue(HideHelpColorTagsMenuItem);
config.restrictions.hide_menu_item_help_about = GetComboBoxValue(HideHelpAboutMenuItem);
if(ConfigUtils.SaveFromConfigToFile(config) == true)
{
MessageBox.Show("Settings saved!", "Success", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void HelpButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
HelpDialog hd = new HelpDialog(button.Name);
hd.ShowDialog();
}
}
}
================================================
FILE: EasyJob/Windows/EditActionButtonDialog.xaml
================================================
Relative
Absolute
PowerShell
Batch
================================================
FILE: EasyJob/Windows/EditActionButtonDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.Serialization.AnswerDialog;
using EasyJob.TabItems;
using EasyJob.Utils;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for EditButtonDialog.xaml
///
public partial class EditActionButtonDialog : Window
{
public ActionButton actionButton = null;
public EditActionButtonDialog(ActionButton _actionButton)
{
InitializeComponent();
actionButton = _actionButton;
ButtonText.Text = actionButton.ButtonText;
ButtonDescription.Text = actionButton.ButtonDescription;
ButtonScript.Text = actionButton.ButtonScript;
if (actionButton.ButtonScriptPathType == "relative") { ButtonScriptPathType.SelectedIndex = 0; }
else { ButtonScriptPathType.SelectedIndex = 1; }
if (actionButton.ButtonScriptType == "powershell"){ ButtonScriptType.SelectedIndex = 0; }
else { ButtonScriptType.SelectedIndex = 1; }
List answers = actionButton.ButtonArguments;
foreach (Answer ans in answers)
{
ButtonScriptArguments.Items.Add(new Answer { AnswerQuestion = ans.AnswerQuestion, AnswerResult = ans.AnswerResult });
}
}
private string ConvertScriptTypeComboBoxToString(ComboBox cb)
{
if (cb.SelectedIndex == 0)
{
return "powershell";
}
else
{
return "bat";
}
}
private string ConvertScriptPathTypeComboBoxToString(ComboBox cb)
{
if (cb.SelectedIndex == 0)
{
return "relative";
}
else
{
return "absolute";
}
}
private void ADDButton_Click(object sender, RoutedEventArgs e)
{
try
{
ButtonScriptArguments.Items.Add(new Answer { AnswerQuestion = ButtonScriptArgumentText.Text, AnswerResult = "" });
ButtonScriptArgumentText.Text = "";
}
catch { }
}
private void DeleteArgumentButton_Click(object sender, RoutedEventArgs e)
{
try
{
Button btn = sender as Button;
ButtonScriptArguments.Items.Remove((Answer)btn.DataContext);
}
catch { }
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
actionButton.ButtonText = ButtonText.Text;
actionButton.ButtonDescription = ButtonDescription.Text;
actionButton.ButtonScript = ButtonScript.Text;
actionButton.ButtonScriptPathType = ConvertScriptPathTypeComboBoxToString(ButtonScriptPathType);
actionButton.ButtonScriptType = ConvertScriptTypeComboBoxToString(ButtonScriptType);
actionButton.ButtonArguments.Clear();
foreach (Answer ans in ButtonScriptArguments.Items)
{
actionButton.ButtonArguments.Add(new Answer { AnswerQuestion = ans.AnswerQuestion, AnswerResult = ans.AnswerResult });
}
DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void HelpButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
HelpDialog hd = new HelpDialog(button.Name);
hd.ShowDialog();
}
private void SelectFileButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
ofd.InitialDirectory = CommonUtils.ApplicationStartupPath();
if (ofd.ShowDialog() == true)
{
if (ButtonScriptPathType.SelectedIndex == 0)
{
ButtonScript.Text = CommonUtils.ConvertPartToRelative(ofd.FileName);
}
else
{
ButtonScript.Text = ofd.FileName;
}
}
}
}
}
================================================
FILE: EasyJob/Windows/HelpDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/HelpDialog.xaml.cs
================================================
using EasyJob.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
namespace EasyJob.Windows
{
///
/// Interaction logic for HelpDialog.xaml
///
public partial class HelpDialog : Window
{
public HelpDialog(string helpitem)
{
InitializeComponent();
LoadXml(helpitem);
}
private void LoadXml(string helpitem)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(CommonUtils.ReadAssemblyFile(@"EasyJob.Documentation.HelpDocumentation.xml"));
XmlNodeList nodeList = doc.SelectNodes("/items/item[name='" + helpitem + "']");
HelpHeading.Text = nodeList[0]["heading"].InnerText;
HelpUsed.Text = nodeList[0]["used"].InnerText;
HelpDescription.Text = nodeList[0]["description"].InnerText;
if (nodeList[0]["video"].InnerText != "" || nodeList[0]["video"].InnerText != null)
{
try
{
HelpVideo.HorizontalAlignment = HorizontalAlignment.Stretch;
HelpVideo.VerticalAlignment = VerticalAlignment.Stretch;
HelpVideo.Stretch = Stretch.Fill;
HelpVideo.Volume = 0;
HelpVideo.Source = new Uri(@"Documentation\Videos\" + nodeList[0]["video"].InnerText, UriKind.Relative);
HelpVideo.Position = TimeSpan.FromSeconds(0);
HelpVideo.Play();
}
catch { }
}
}
private void ReloadVideoButton_Click(object sender, RoutedEventArgs e)
{
HelpVideo.Position = TimeSpan.FromSeconds(0);
HelpVideo.Play();
}
private void StopVideoButton_Click(object sender, RoutedEventArgs e)
{
HelpVideo.Stop();
}
private void PlayVideoButton_Click(object sender, RoutedEventArgs e)
{
HelpVideo.Play();
}
}
}
================================================
FILE: EasyJob/Windows/NewTabDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/NewTabDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.TabItems;
using EasyJob.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for NewTabDialog.xaml
///
public partial class NewTabDialog : Window
{
public string configJson = "";
public Config config;
ObservableCollection TabItems = null;
public NewTabDialog()
{
InitializeComponent();
LoadConfig();
}
public void LoadConfig()
{
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "config.json"))
{
try
{
configJson = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "config.json");
config = JsonConvert.DeserializeObject(configJson);
TabItems = ConfigUtils.ConvertTabsFromConfigToUI(config);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("File " + AppDomain.CurrentDomain.BaseDirectory + "config.json does not exist.");
}
}
public bool SaveConfig()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "config.json";
if (File.Exists(path))
{
try
{
config.tabs.Clear();
config.tabs = ConfigUtils.ConvertTabsFromUIToConfig(TabItems);
if (ConfigUtils.SaveFromConfigToFile(config) == true)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
else
{
//SaveConfig();
}
return false;
}
private void CreateNewTabButton_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(CreateNewTabTextBox.Text))
{
TabData tabData = new TabData(CreateNewTabTextBox.Text);
TabItems.Add(tabData);
if (SaveConfig())
{
DialogResult = true;
}
else
{
MessageBox.Show("Error trying to save added Tab.");
}
}
else
{
MessageBox.Show("Tab header name should not be empty.");
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
================================================
FILE: EasyJob/Windows/RenameTabDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/RenameTabDialog.xaml.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for RenameTabDialog.xaml
///
public partial class RenameTabDialog : Window
{
public string NewTabName = "";
public RenameTabDialog(string SelectedTabHeader)
{
InitializeComponent();
RenameTabTextBox.Text = SelectedTabHeader;
}
private void CancelRenameButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void RenameTabButton_Click(object sender, RoutedEventArgs e)
{
if(RenameTabTextBox.Text.Length > 0)
{
NewTabName = RenameTabTextBox.Text;
DialogResult = true;
}
else
{
MessageBox.Show("Please specify new name for the tab");
}
}
}
}
================================================
FILE: EasyJob/Windows/ReorderActionButtonsDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/ReorderActionButtonsDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.TabItems;
using EasyJob.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJob.Windows
{
///
/// Interaction logic for ReorderActionButtonsDialog.xaml
///
public partial class ReorderActionButtonsDialog : Window
{
public Config config;
public int currentTabIndex = 0;
public bool changesOccured = false;
ObservableCollection TabItems = null;
ObservableCollection ActionButtons = null;
public ReorderActionButtonsDialog(int _currentTabIndex, Config _config)
{
InitializeComponent();
config = _config;
currentTabIndex = _currentTabIndex;
LoadConfig();
}
public void LoadConfig()
{
try
{
MainWindowActionButtonsList.ItemsSource = null;
TabItems = ConfigUtils.ConvertTabsFromConfigToUI(config);
List list = TabItems[currentTabIndex].TabActionButtons;
ObservableCollection collection = new ObservableCollection(list);
ActionButtons = collection;
MainWindowActionButtonsList.ItemsSource = ActionButtons;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public bool SaveConfig()
{
if (File.Exists(ConfigUtils.ConfigJsonPath))
{
try
{
config.tabs.Clear();
config.tabs = ConfigUtils.ConvertTabsFromUIToConfig(TabItems);
if (ConfigUtils.SaveFromConfigToFile(config) == true)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
else
{
SaveConfig();
}
return false;
}
private void ActionButtonsRedorderDown_Click(object sender, RoutedEventArgs e)
{
if (MainWindowActionButtonsList.SelectedIndex == -1)
{
MessageBox.Show("Please select item to reorder");
return;
}
var selectedIndex = MainWindowActionButtonsList.SelectedIndex;
if (selectedIndex + 1 < ActionButtons.Count)
{
var itemToMoveDown = ActionButtons[selectedIndex];
ActionButtons.RemoveAt(selectedIndex);
ActionButtons.Insert(selectedIndex + 1, itemToMoveDown);
MainWindowActionButtonsList.SelectedIndex = selectedIndex + 1;
List myList = new List(ActionButtons);
TabItems[currentTabIndex].TabActionButtons = myList;
}
changesOccured = true;
SaveConfig();
}
private void ActionButtonsReorderUp_Click(object sender, RoutedEventArgs e)
{
if (MainWindowActionButtonsList.SelectedIndex == -1)
{
MessageBox.Show("Please select item to reorder");
return;
}
var selectedIndex = MainWindowActionButtonsList.SelectedIndex;
if (selectedIndex > 0)
{
var itemToMoveUp = ActionButtons[selectedIndex];
ActionButtons.RemoveAt(selectedIndex);
ActionButtons.Insert(selectedIndex - 1, itemToMoveUp);
MainWindowActionButtonsList.SelectedIndex = selectedIndex - 1;
List myList = new List(ActionButtons);
TabItems[currentTabIndex].TabActionButtons = myList;
}
changesOccured = true;
SaveConfig();
}
}
}
================================================
FILE: EasyJob/Windows/ReorderTabsDialog.xaml
================================================
================================================
FILE: EasyJob/Windows/ReorderTabsDialog.xaml.cs
================================================
using EasyJob.Serialization;
using EasyJob.TabItems;
using EasyJob.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
namespace EasyJob.Windows
{
///
/// Interaction logic for ReorderTabsDialog.xaml
///
public partial class ReorderTabsDialog : Window
{
public Config config;
ObservableCollection TabItems = null;
public bool changesOccured = false;
public ReorderTabsDialog(Config _config)
{
InitializeComponent();
config = _config;
LoadConfig();
}
public void LoadConfig()
{
try
{
MainWindowTabsList.ItemsSource = null;
TabItems = ConfigUtils.ConvertTabsFromConfigToUI(config);
MainWindowTabsList.ItemsSource = TabItems;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public bool SaveConfig()
{
if (File.Exists(ConfigUtils.ConfigJsonPath))
{
try
{
config.tabs.Clear();
config.tabs = ConfigUtils.ConvertTabsFromUIToConfig(TabItems);
if (ConfigUtils.SaveFromConfigToFile(config) == true)
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
else
{
SaveConfig();
}
return false;
}
private void TabsRedorderDown_Click(object sender, RoutedEventArgs e)
{
if(MainWindowTabsList.SelectedIndex == -1)
{
MessageBox.Show("Please select item to reorder");
return;
}
var selectedIndex = MainWindowTabsList.SelectedIndex;
if (selectedIndex + 1 < TabItems.Count)
{
var itemToMoveDown = TabItems[selectedIndex];
TabItems.RemoveAt(selectedIndex);
TabItems.Insert(selectedIndex + 1, itemToMoveDown);
MainWindowTabsList.SelectedIndex = selectedIndex + 1;
}
changesOccured = true;
SaveConfig();
}
private void TabsReorderUp_Click(object sender, RoutedEventArgs e)
{
if (MainWindowTabsList.SelectedIndex == -1)
{
MessageBox.Show("Please select item to reorder");
return;
}
changesOccured = true;
var selectedIndex = MainWindowTabsList.SelectedIndex;
if (selectedIndex > 0)
{
var itemToMoveUp = TabItems[selectedIndex];
TabItems.RemoveAt(selectedIndex);
TabItems.Insert(selectedIndex - 1, itemToMoveUp);
MainWindowTabsList.SelectedIndex = selectedIndex - 1;
}
SaveConfig();
}
}
}
================================================
FILE: EasyJob/Windows/TroubleshootingWindow.xaml
================================================
================================================
FILE: EasyJob/Windows/TroubleshootingWindow.xaml.cs
================================================
using EasyJob.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace EasyJob.Windows
{
///
/// Interaction logic for TroubleshootingWindow.xaml
///
public partial class TroubleshootingWindow : Window
{
Config config = null;
public TroubleshootingWindow(Config _config)
{
InitializeComponent();
config = _config;
FillKnownData();
}
private void FillKnownData()
{
OSDescription.Text = RuntimeInformation.OSDescription;
FrameworkDescription.Text = RuntimeInformation.FrameworkDescription;
OsD.Text = RuntimeInformation.OSArchitecture.ToString();
PowerShellPath.Text = config.default_powershell_path;
if(config.powershell_arguments == "")
{
PowerShellArguments.Text = "empty";
PowerShellArguments.Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128));
}
else
{
PowerShellArguments.Text = config.powershell_arguments;
}
if(File.Exists(config.default_powershell_path))
{
try
{
var versionInfo = FileVersionInfo.GetVersionInfo(config.default_powershell_path);
PowerShellVersion.Text = versionInfo.FileVersion;
}
catch
{
PowerShellVersion.Text = "unable to get version";
PowerShellVersion.Foreground = new SolidColorBrush(Color.FromRgb(128, 128, 128));
}
}
if(Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files\WindowsPowerShell\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files\WindowsPowerShell\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
if (Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Windows\System32\WindowsPowerShell\v1.0\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Windows\System32\WindowsPowerShell\v1.0\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
if (Directory.Exists(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files (x86)\WindowsPowerShell\Modules"))
{
try
{
string[] dirs = Directory.GetDirectories(System.IO.Path.GetPathRoot(Environment.SystemDirectory) + @"Program Files (x86)\WindowsPowerShell\Modules", "*", SearchOption.TopDirectoryOnly);
foreach (string dir in dirs)
{
PowerShellModules.Text = PowerShellModules.Text + dir + Environment.NewLine;
}
}
catch { }
}
}
private void TroubleshootingWindow_Loaded(object sender, RoutedEventArgs e)
{
/*
try
{
Task.Factory.StartNew(() =>
{
string URL = "https://google.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "text/html";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
MessageBox.Show(reader.ReadToEnd());
}
}).ContinueWith((task) =>
{
// do this on the UI thread once the task has finished..
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
*/
}
}
}
================================================
FILE: EasyJob/config.json
================================================
{
"default_powershell_path": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"default_cmd_path": "C:\\Windows\\System32\\cmd.exe",
"powershell_arguments": "",
"console_background": "Black",
"console_foreground": "White",
"console_ignore_color_tags": false,
"clear_events_when_reload": true,
"restrictions": {
"block_tabs_remove": false,
"block_buttons_remove": false,
"block_tabs_add": false,
"block_buttons_add": false,
"block_buttons_reorder": false,
"block_buttons_edit": false,
"block_tabs_rename": false,
"block_buttons_paste": false,
"block_buttons_copy": false,
"hide_menu_item_file_reload_config": false,
"hide_menu_item_file_open_app_folder": false,
"hide_menu_item_file_clear_events_list": false,
"hide_menu_item_settings": false,
"hide_menu_item_settings_workflow": false,
"hide_menu_item_settings_workflow_reorder_tabs": false,
"hide_menu_item_settings_workflow_add_tab": false,
"hide_menu_item_settings_workflow_remove_current_tab": false,
"hide_menu_item_settings_workflow_rename_current_tab": false,
"hide_menu_item_settings_workflow_add_button_to_current_tab": false,
"hide_menu_item_settings_workflow_reorder_buttons_in_current_tab": false,
"hide_menu_item_settings_configuration": false,
"hide_menu_item_help": false,
"hide_menu_item_help_troubleshooting": false,
"hide_menu_item_help_colortags": false,
"hide_menu_item_help_about": false
},
"tabs": [
{
"ID": "357f9827-f4f7-439f-b62c-792e880fd06c",
"Header": "Common actions",
"Buttons": [
{
"Id": "5e371407-140f-4fa2-abf3-2cec4bb174b2",
"Text": "test01",
"Description": "Some test script",
"Script": "scripts\\common\\test01.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": []
},
{
"Id": "9159b485-39e5-42d6-adb4-275753db9027",
"Text": "test02",
"Description": "Some second test script",
"Script": "scripts\\test02.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": []
},
{
"Id": "eaaff0bf-2a9f-4037-bdd6-e8405830d90e",
"Text": "bat",
"Description": "Some second test script",
"Script": "scripts\\1.bat",
"ScriptPathType": "relative",
"ScriptType": "cmd",
"Arguments": []
},
{
"Id": "5ec086d9-7987-43ef-84fb-1d8481b05aea",
"Text": "Absolute script",
"Description": "",
"Script": "C:\\scripts\\absolute_script.ps1",
"ScriptPathType": "absolute",
"ScriptType": "powershell",
"Arguments": []
},
{
"Id": "a7b94662-4d66-4a8a-af33-b326a99215cf",
"Text": "test03",
"Description": "Some test 03 script with arguments",
"Script": "scripts\\common\\test03.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": [
{
"ArgumentQuestion": "Enter IP address or DNS name",
"ArgumentAnswer": ""
}
]
},
{
"Id": "aabc2bf5-e26c-4a73-8e89-e702f14eaa8b",
"Text": "test04",
"Description": "Some test 04 script with arguments",
"Script": "scripts\\common\\test04.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": [
{
"ArgumentQuestion": "What is your name?",
"ArgumentAnswer": ""
},
{
"ArgumentQuestion": "What is your surname",
"ArgumentAnswer": ""
},
{
"ArgumentQuestion": "No, really what is your name?",
"ArgumentAnswer": ""
}
]
}
]
},
{
"ID": "fa774e10-7772-4074-8d8e-c57b09e9377e",
"Header": "Second Tab",
"Buttons": [
{
"Id": "b3ebb860-7682-4613-8f82-0ca59226b0f9",
"Text": "Some button",
"Description": "no description",
"Script": "scripts\\some_button_script.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": []
},
{
"Id": "f9fc3c8f-fb36-432d-96c9-09c4169d540e",
"Text": "Test11",
"Description": "no description",
"Script": "scripts\\some_button_script2.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": []
}
]
},
{
"ID": "a744a5e3-4dc0-4f42-abac-ee67dd17c6a1",
"Header": "Third Tab",
"Buttons": [
{
"Id": "5839ed21-7c33-4aac-9b3c-663cc794e3f5",
"Text": "Some button 1",
"Description": "no description",
"Script": "scripts\\some_button_script.ps1",
"ScriptPathType": "relative",
"ScriptType": "powershell",
"Arguments": []
},
{
"Id": "7ecdea7a-8865-45d7-a037-0dd4dd1cb996",
"Text": "Button asd",
"Description": "",
"Script": "D:\\net50\\test04.ps1",
"ScriptPathType": "absolute",
"ScriptType": "powershell",
"Arguments": []
}
]
}
]
}
================================================
FILE: EasyJob.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyJob", "EasyJob\EasyJob.csproj", "{E4A73656-4B1A-4A18-AC41-6AC59E1C8EB3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WpfRichText", "WpfRichText\WpfRichText.csproj", "{BD7ECC34-44C8-4D3C-B0E5-0384E2F2DE02}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyJobPSTools", "EasyJobPSTools\EasyJobPSTools.csproj", "{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E4A73656-4B1A-4A18-AC41-6AC59E1C8EB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E4A73656-4B1A-4A18-AC41-6AC59E1C8EB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E4A73656-4B1A-4A18-AC41-6AC59E1C8EB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E4A73656-4B1A-4A18-AC41-6AC59E1C8EB3}.Release|Any CPU.Build.0 = Release|Any CPU
{BD7ECC34-44C8-4D3C-B0E5-0384E2F2DE02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BD7ECC34-44C8-4D3C-B0E5-0384E2F2DE02}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD7ECC34-44C8-4D3C-B0E5-0384E2F2DE02}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD7ECC34-44C8-4D3C-B0E5-0384E2F2DE02}.Release|Any CPU.Build.0 = Release|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {92C31FCF-A509-4155-9117-FDEC0F8333AD}
EndGlobalSection
EndGlobal
================================================
FILE: EasyJobPSTools/EasyJobPSTools.csproj
================================================
Debug
AnyCPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}
Library
EasyJobPSTools
EasyJobPSTools
v4.8
512
{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
4
true
AnyCPU
true
full
false
..\bin\Debug\EasyJobPSTools\
DEBUG;TRACE
prompt
4
false
AnyCPU
pdbonly
true
..\bin\Release\EasyJobPSTools\
TRACE
prompt
4
false
4.0
Code
True
True
Resources.resx
True
Settings.settings
True
ShowEJInputBox.xaml
ResXFileCodeGenerator
Resources.Designer.cs
Always
SettingsSingleFileGenerator
Settings.Designer.cs
Designer
MSBuild:Compile
0.9.4
4.7.0
4.5.0
Always
================================================
FILE: EasyJobPSTools/EasyJobPSTools.psd1
================================================
# Module manifest for module 'EasyJobPSTools'
# Generated by: Akshin Mustafayev
# Generated on: 10/8/2021
@{
# Script module or binary module file associated with this manifest.
RootModule = 'EasyJobPSTools.psm1'
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = 'd6c56376-ae08-4c23-b901-9bc75144e0c6'
# Author of this module
Author = 'Akshin Mustafayev'
# Company or vendor of this module
CompanyName = 'Akshin Mustafayev'
# Copyright statement for this module
Copyright = '(c) 2021 Akshin Mustafayev. GNU Affero General Public License v3.0.'
# Description of the functionality provided by this module
Description = 'Module for implementing EasyJob additional helper functions'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Show-EJInputBox', 'Show-EJSelectFileWindow', 'Show-EJSelectFolderWindow'
}
================================================
FILE: EasyJobPSTools/EasyJobPSTools.psm1
================================================
Add-Type -Path "$PSScriptRoot\ModernWpf.dll"
Add-Type -Path "$PSScriptRoot\EasyJobPSTools.dll"
function Show-EJInputBox {
<#
.SYNOPSIS
Shows Input-Box for you script.
.DESCRIPTION
Shows Input-Box for you script. This might be necessary
when you want to get some input while executing your script,
since EasyJob does not support Read from console.
.PARAMETER Header
Specifies Title for input box.
.PARAMETER Text
Specifies Text for the input box.
.PARAMETER AllowEmptyResult
Specifies if user can not enter any text and press OK.
.INPUTS
None.
.OUTPUTS
String value of the input from the box.
.EXAMPLE
C:\PS> $Result = Show-EJInputBox -Header "Specify your name" -Text "What is your name?" -AllowEmptyResult $false
C:\PS> Write-Host "Your name is $Result"
Your name is test
.LINK
https://github.com/akshinmustafayev/EasyJobPSTools
https://github.com/akshinmustafayev/EasyJob
#>
param (
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] [string]$Header,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] [string]$Text,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()] $AllowEmptyResult
)
$Result = [EasyJobPSTools.Program]::ShowEJInputBoxWindow($Header, $Text, $AllowEmptyResult)
return $Result
}
function Show-EJSelectFileWindow {
<#
.SYNOPSIS
Shows select file Window and returns selected file path.
.DESCRIPTION
Shows select file Window. This might be necessary
when you want to get selected file path and use it
in your script.
.PARAMETER FileType
Specifies File type which you would like for user to select.
This parameter may be empty. If it is empty then any file type is espected
.INPUTS
None.
.OUTPUTS
String path value of the selected file.
.EXAMPLE
C:\PS> $Result = Show-EJSelectFileWindow
D:\temp\excel_list.xlsx
.EXAMPLE
C:\PS> $Result = Show-EJSelectFileWindow -FileType "txt files (*.txt)|*.txt|All files (*.*)|*.*"
D:\temp\testfile.txt
.LINK
https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog.filter?view=windowsdesktop-5.0#System_Windows_Forms_FileDialog_Filter
https://github.com/akshinmustafayev/EasyJobPSTools
https://github.com/akshinmustafayev/EasyJob
#>
param (
[Parameter(Mandatory = $false)] [string]$FileType
)
if($null -eq $FileType){
$Result = [EasyJobPSTools.Program]::ShowEJSelectFileWindow()
return $Result
}
else{
$Result = [EasyJobPSTools.Program]::ShowEJSelectFileWindow($FileType)
return $Result
}
}
function Show-EJSelectFolderWindow {
<#
.SYNOPSIS
Shows select folder Window and returns selected folder path.
.DESCRIPTION
Shows select folder Window. This might be necessary
when you want to get selected folder path and use it
in your script.
.INPUTS
None.
.OUTPUTS
String path value of the selected folder.
.EXAMPLE
C:\PS> $Result = Show-EJSelectFolderWindow
D:\temp\
.LINK
https://github.com/akshinmustafayev/EasyJobPSTools
https://github.com/akshinmustafayev/EasyJob
#>
$Result = [EasyJobPSTools.Program]::ShowEJSelectFolderWindow()
return $Result
}
================================================
FILE: EasyJobPSTools/EasyJobPSTools.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyJobPSTools", "EasyJobPSTools.csproj", "{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4CD0099-4071-4516-8ADC-95ADCD8A7A4C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0D0B0E81-ED08-435B-82D0-A80FABEA9637}
EndGlobalSection
EndGlobal
================================================
FILE: EasyJobPSTools/Program.cs
================================================
using EasyJobPSTools.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EasyJobPSTools
{
public class Program
{
public static string ShowEJInputBoxWindow(string Header, string Text, bool AllowEmptyResult)
{
ShowEJInputBox sejib = new ShowEJInputBox(Header, Text, AllowEmptyResult);
if (sejib.ShowDialog() == true)
{
return sejib.windowResult;
}
else
{
return "";
}
}
public static string ShowEJSelectFileWindow()
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
return ofd.FileName;
}
else
{
return "";
}
}
public static string ShowEJSelectFileWindow(string fileType)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileType;
if (ofd.ShowDialog() == DialogResult.OK)
{
return ofd.FileName;
}
else
{
return "";
}
}
public static string ShowEJSelectFolderWindow()
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
return fbd.SelectedPath;
}
else
{
return "";
}
}
}
}
}
================================================
FILE: EasyJobPSTools/Properties/AssemblyInfo.cs
================================================
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EasyJobPSTools")]
[assembly: AssemblyDescription("PowerShell tools for the EasyJob")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Akshin Mustafayev")]
[assembly: AssemblyProduct("EasyJobPSTools")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("Akshin Mustafayev")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
//In order to begin building localizable applications, set
//CultureYouAreCodingWith in your .csproj file
//inside a . For example, if you are using US english
//in your source files, set the to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
================================================
FILE: EasyJobPSTools/Properties/Resources.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace EasyJobPSTools.Properties {
using System;
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
///
/// Returns the cached ResourceManager instance used by this class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EasyJobPSTools.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
================================================
FILE: EasyJobPSTools/Properties/Resources.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
================================================
FILE: EasyJobPSTools/Properties/Settings.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace EasyJobPSTools.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
================================================
FILE: EasyJobPSTools/Properties/Settings.settings
================================================
================================================
FILE: EasyJobPSTools/Utils/CommonUtils.cs
================================================
using ModernWpf;
using ModernWpf.Controls;
using System.Windows;
namespace EasyJobPSTools.Utils
{
public class CommonUtils
{
public static void FixModernWpfUI()
{
if (Application.Current is null)
{
var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
var themeResources = new ThemeResources();
themeResources.BeginInit();
app.Resources.MergedDictionaries.Add(themeResources);
themeResources.EndInit();
app.Resources.MergedDictionaries.Add(new XamlControlsResources());
}
}
}
}
================================================
FILE: EasyJobPSTools/Windows/ShowEJInputBox.xaml
================================================
================================================
FILE: EasyJobPSTools/Windows/ShowEJInputBox.xaml.cs
================================================
using EasyJobPSTools.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EasyJobPSTools.Windows
{
///
/// Interaction logic for ShowEJInputBox.xaml
///
public partial class ShowEJInputBox : Window
{
private string _Header;
private string _Text;
private bool _AllowEmptyResult;
public string windowResult = "";
public ShowEJInputBox(string Header, string Text, bool AllowEmptyResult)
{
CommonUtils.FixModernWpfUI();
InitializeComponent();
FormError.Visibility = Visibility.Collapsed;
_Header = Header;
_Text = Text;
_AllowEmptyResult = AllowEmptyResult;
this.Title = Header;
FormText.Text = Text;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
if (FormAnswer.Text.Length == 0 && _AllowEmptyResult == false)
{
FormError.Text = "Please input value";
FormError.Visibility = Visibility.Visible;
}
else
{
windowResult = FormAnswer.Text;
DialogResult = true;
}
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void FormAnswer_TextChanged(object sender, TextChangedEventArgs e)
{
if (_AllowEmptyResult == false)
{
if(FormAnswer.Text.Length > 0 && FormError.Visibility == Visibility.Visible)
{
FormError.Visibility = Visibility.Collapsed;
}
}
}
}
}
================================================
FILE: EasyJobPSTools/app.config
================================================
================================================
FILE: LICENSE.txt
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: README.md
================================================
#
EasyJob
## :newspaper: Description
EasyJob - keep and execute your PowerShell and BAT scripts from one interface
## :eye_speech_bubble: Overview




## :abacus: Features
* _Remove_, _Edit_ or _Copy_ button from the GUI by right mouse click on it and then select item in the context menu. Settings are automatically will be saved to your config.json file.

* _Remove_, _Rename_ or _Add_ tab from the GUI by right mouse click on it and then select Remove Tab in the context menu. Settings are automatically will be saved to your config.json file.

* _Add_ or _Paste_ button from the GUI by right mouse click on button bar.

* Reorder Tabs from the _Settings->Workflow->Reorder_ tabs window
* Add Tabs from the _Settings->Workflow->Add tab_ window
* Rename Tabs from the _Settings->Workflow->Remove current tab_ window
* Remove Tabs from the _Settings->Workflow->Rename current tab_ window
* Remove Add buttons from the _Settings->Workflow->Add button to current_ tab window
* Reorder buttons from the _Settings->Workflow->Reorder buttons in current_ tab window
* Change application settings from the _Settings->Configuration_ window
* Colored console support
## :red_circle: Color tags support
There are 14 available default tags which you may want to use
1.
__\c01EJ__ Some text __/c01EJ__
```PowerShell
Write-Host "\c01EJColor with tag 01/c01EJ"
```
2.
__\c02EJ__ Some text __/c02EJ__
```PowerShell
Write-Host "\c02EJColor with tag 02/c02EJ"
```
3.
__\c03EJ__ Some text __/c03EJ__
```PowerShell
Write-Host "\c03EJColor with tag 03/c03EJ"
```
4.
__\c04EJ__ Some text __/c04EJ__
```PowerShell
Write-Host "\c04EJColor with tag 04/c04EJ"
```
5.
__\c05EJ__ Some text __/c05EJ__
```PowerShell
Write-Host "\c05EJColor with tag 05/c05EJ"
```
6.
__\c06EJ__ Some text __/c06EJ__
```PowerShell
Write-Host "\c06EJColor with tag 06/c06EJ"
```
7.
__\c07EJ__ Some text __/c07EJ__
```PowerShell
Write-Host "\c07EJColor with tag 07/c07EJ"
```
8.
__\c08EJ__ Some text __/c08EJ__
```PowerShell
Write-Host "\c08EJColor with tag 08/c08EJ"
```
9.
__\c09EJ__ Some text __/c09EJ__
```PowerShell
Write-Host "\c09EJColor with tag 09/c09EJ"
```
10.
__\c10EJ__ Some text __/c10EJ__
```PowerShell
Write-Host "\c10EJColor with tag 10/c10EJ"
```
11.
__\c11EJ__ Some text __/c11EJ__
```PowerShell
Write-Host "\c11EJColor with tag 11/c11EJ"
```
12.
__\c12EJ__ Some text __/c12EJ__
```PowerShell
Write-Host "\c12EJColor with tag 12/c12EJ"
```
13.
__\c13EJ__ Some text __/c13EJ__
```PowerShell
Write-Host "\c13EJColor with tag 13/c13EJ"
```
13.
__\c14EJ__ Some text __/c14EJ__
```PowerShell
Write-Host "\c14EJColor with tag 14/c14EJ"
```
You can use tags inside other tags as well. Examples:
```PowerShell
Write-Host "\c14EJColor with \c12EJsome inside tag/c12EJ tag 14/c14EJ"
Write-Host "\c02EJColor with \c09EJsome inside tag/c09EJ tag 14/c02EJ"
Write-Host "\c02EJAnother \c04EJexample/c04EJ with \c08EJsome/c08EJ other inner blocks/c02EJ"
```
If you dont want to use tags, you can use HTML code inside your Write-Host. Examples:
```PowerShell
Write-Host "Some error alert!"
Write-Host "Some other color!"
Write-Host "Some other color!"
```
## :hammer: EasyJobPSTools
EasyJobPSTools - is a PowerShell Module which enables Graphic features for your scripts.
You can read more about it [Here](https://github.com/akshinmustafayev/EasyJobPSTools)
## :gear: Configuration
Configuration could be done from config.json file located with the app executable.
Here is an example:
```
{
"default_powershell_path": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"default_cmd_path": "C:\\Windows\\System32\\cmd.exe",
"powershell_arguments": "",
"console_background": "Black",
"console_foreground": "White",
"console_ignore_color_tags": false,
"clear_events_when_reload": true,
"restrictions": {
"block_tabs_remove": false,
"block_buttons_remove": false,
"block_tabs_add": false,
"block_buttons_add": false,
"block_buttons_reorder": false,
"block_buttons_edit": false,
"block_tabs_rename": false,
"block_buttons_paste": false,
"block_buttons_copy": false,
"hide_menu_item_file_reload_config": false,
"hide_menu_item_file_open_app_folder": false,
"hide_menu_item_file_clear_events_list": false,
"hide_menu_item_settings": false,
"hide_menu_item_settings_workflow": false,
"hide_menu_item_settings_workflow_reorder_tabs": false,
"hide_menu_item_settings_workflow_add_tab": false,
"hide_menu_item_settings_workflow_remove_current_tab": false,
"hide_menu_item_settings_workflow_rename_current_tab": false,
"hide_menu_item_settings_workflow_add_button_to_current_tab": false,
"hide_menu_item_settings_workflow_reorder_buttons_in_current_tab": false,
"hide_menu_item_settings_configuration": false,
"hide_menu_item_help": false,
"hide_menu_item_help_troubleshooting": false,
"hide_menu_item_help_colortags": false,
"hide_menu_item_help_about": false
},
"tabs": [
{
"ID": "2e5feab0-527c-451c-b83c-d838d22dacac",
"header": "Common actions",
"buttons": [
{
"Id": "01bf5871-442e-4f73-91a3-fa13855b609c",
"text": "test01",
"description": "Some test script",
"script": "scripts\\common\\test01.ps1",
"scriptpathtype": "relative",
"scripttype": "powershell",
"arguments": []
},
{
"Id": "9cdc38fa-fc32-4a9d-be78-cd2bfe264422",
"text": "Bat script",
"description": "Some BAT script",
"script": "scripts\\test02.bat",
"scriptpathtype": "relative",
"scripttype": "bat",
"arguments": []
},
{
"Id": "5ec086d9-7987-43ef-84fb-1d8481b05aea",
"text": "Absolute path script",
"description": "",
"script": "C:\\scripts\\absolute_script.ps1",
"scriptpathtype": "absolute",
"scripttype": "powershell",
"arguments": []
},
{
"Id": "c28abef3-494c-48f5-96d8-a5788ced1a23",
"text": "test04",
"description": "Some test 04 script with arguments",
"script": "scripts\\common\\test04.ps1",
"scriptpathtype": "relative",
"scripttype": "powershell",
"arguments": [
{
"argument_question": "What is your name?",
"argument_answer": ""
},
{
"argument_question": "What is your surname",
"argument_answer": ""
},
{
"argument_question": "No, really what is your name?",
"argument_answer": ""
}
]
}
]
},
{
"ID": "42f71e1a-32b9-4c16-8c7d-256cd589c52e",
"header": "Second Tab",
"buttons": [
{
"Id": "3476554c-77b1-4abd-914e-ab1db866fc5f",
"text": "And this is button too",
"description": "no description",
"script": "scripts\\some_button_script.ps1",
"scriptpathtype": "relative",
"scripttype": "powershell",
"arguments": []
}
]
}
]
}
```
_Note 1: Do not specify argument_answer value, since it will be ignored when executing script_
_Note 2: ID my be any other random GUID number. You may not specify it, application will regenerate it after changes if it is absent._
## :triangular_flag_on_post: Easy access
_CTRL+Left Mouse Click_ on the button will open folder where script attached to the button is located
_SHIFT+Left Mouse Click_ on the button will open the script attached to the button with your default ps1 text editor
## :electric_plug: Compilation
1. Download and install Visual Studio 2022
2. Open project in Visual Studio and build it
## :dart: Contributing
Contribution is very much appreciated. Hope that this tool might be useful for you!
Thanks to the contributors:
================================================
FILE: WpfRichText/AttachedProperties/RichTextboxAssistant.cs
================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Controls;
using System.IO;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Data;
namespace WpfRichText
{
///
public static class RichTextBoxAssistant
{
///
public static readonly DependencyProperty BoundDocument =
DependencyProperty.RegisterAttached("BoundDocument", typeof(string), typeof(RichTextBoxAssistant),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnBoundDocumentChanged)
);
private static void OnBoundDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RichTextBox box = d as RichTextBox;
if (box == null)
return;
RemoveEventHandler(box);
string newXAML = GetBoundDocument(d);
box.Document.Blocks.Clear();
if (!string.IsNullOrEmpty(newXAML))
{
using (MemoryStream xamlMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(newXAML)))
{
ParserContext parser = new ParserContext();
parser.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
//FlowDocument doc = new FlowDocument();
Section section = XamlReader.Load(xamlMemoryStream, parser) as Section;
box.Document.Blocks.Add(section);
}
}
AttachEventHandler(box);
}
private static void RemoveEventHandler(RichTextBox box)
{
Binding binding = BindingOperations.GetBinding(box, BoundDocument);
if (binding != null)
{
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
box.LostFocus -= HandleLostFocus;
}
else
{
box.TextChanged -= HandleTextChanged;
}
}
}
private static void AttachEventHandler(RichTextBox box)
{
Binding binding = BindingOperations.GetBinding(box, BoundDocument);
if (binding != null)
{
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
box.LostFocus += HandleLostFocus;
}
else
{
box.TextChanged += HandleTextChanged;
}
}
}
private static void HandleLostFocus(object sender, RoutedEventArgs e)
{
RichTextBox box = sender as RichTextBox;
TextRange tr = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
using (MemoryStream ms = new MemoryStream())
{
tr.Save(ms, DataFormats.Xaml);
string xamlText = Encoding.UTF8.GetString(ms.ToArray());
SetBoundDocument(box, xamlText);
}
}
private static void HandleTextChanged(object sender, RoutedEventArgs e)
{
// TODO: TextChanged is currently not working!
RichTextBox box = sender as RichTextBox;
TextRange tr = new TextRange(box.Document.ContentStart,
box.Document.ContentEnd);
using (MemoryStream ms = new MemoryStream())
{
tr.Save(ms, DataFormats.Xaml);
string xamlText = Encoding.UTF8.GetString(ms.ToArray());
SetBoundDocument(box, xamlText);
}
}
///
///
///
///
///
public static string GetBoundDocument(DependencyObject dependencyObject)
{
if (dependencyObject != null)
{
var html = dependencyObject.GetValue(BoundDocument) as string;
var xaml = string.Empty;
if (!string.IsNullOrEmpty(html))
xaml = HtmlToXamlConverter.ConvertHtmlToXaml(html, false);
return xaml;
}
return string.Empty;
}
///
///
///
///
///
public static void SetBoundDocument(DependencyObject dependencyObject, string value)
{
if (dependencyObject != null)
{
var xaml = value;
var html = HtmlFromXamlConverter.ConvertXamlToHtml(xaml, false);
dependencyObject.SetValue(BoundDocument, html);
}
}
}
}
================================================
FILE: WpfRichText/Commands/CommandReference.cs
================================================
using System;
using System.Windows;
using System.Windows.Input;
namespace WpfRichText
{
///
/// This class facilitates associating a key binding in XAML markup to a command
/// defined in a View Model by exposing a Command dependency property.
/// The class derives from Freezable to work around a limitation in WPF when data-binding from XAML.
///
public class CommandReference : Freezable, ICommand
{
///
public CommandReference()
{
// Blank
}
///
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));
///
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
#region ICommand Members
///
///
///
///
///
public bool CanExecute(object parameter)
{
if (Command != null)
return Command.CanExecute(parameter);
return false;
}
///
///
///
///
public void Execute(object parameter)
{
Command.Execute(parameter);
}
///
///
///
public event EventHandler CanExecuteChanged;
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandReference commandReference = d as CommandReference;
ICommand oldCommand = e.OldValue as ICommand;
ICommand newCommand = e.NewValue as ICommand;
if (oldCommand != null)
{
oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
}
if (newCommand != null)
{
newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
}
}
#endregion
#region Freezable
///
///
///
///
protected override Freezable CreateInstanceCore()
{
throw new NotImplementedException();
}
#endregion
}
}
================================================
FILE: WpfRichText/Commands/DelegateCommand.cs
================================================
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
namespace WpfRichText
{
///
/// This class allows delegating the commanding logic to methods passed as parameters,
/// and enables a View to bind commands to objects that are not part of the element tree.
///
public class DelegateCommand : ICommand
{
#region Constructors
///
/// Constructor
///
public DelegateCommand(Action executeMethod)
: this(executeMethod, null, false)
{
}
///
/// Constructor
///
public DelegateCommand(Action executeMethod, Func canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
///
/// Constructor
///
public DelegateCommand(Action executeMethod, Func canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
}
#endregion
#region Public Methods
///
/// Method to determine if the command can be executed
///
public bool CanExecute()
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod();
}
return true;
}
///
/// Execution of the command
///
public void Execute()
{
if (_executeMethod != null)
{
_executeMethod();
}
}
///
/// Property to enable or disable CommandManager's automatic requery on this command
///
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
///
/// Raises the CanExecuteChaged event
///
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
///
/// Protected virtual method to raise CanExecuteChanged event
///
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
#endregion
#region ICommand Members
///
/// ICommand.CanExecuteChanged implementation
///
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
Execute();
}
#endregion
#region Data
private readonly Action _executeMethod = null;
private readonly Func _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List _canExecuteChangedHandlers;
#endregion
}
///
/// This class allows delegating the commanding logic to methods passed as parameters,
/// and enables a View to bind commands to objects that are not part of the element tree.
///
/// Type of the parameter passed to the delegates
public class DelegateCommand : ICommand
{
#region Constructors
///
/// Constructor
///
public DelegateCommand(Action executeMethod)
: this(executeMethod, null, false)
{
}
///
/// Constructor
///
public DelegateCommand(Action executeMethod, Func canExecuteMethod)
: this(executeMethod, canExecuteMethod, false)
{
}
///
/// Constructor
///
public DelegateCommand(Action executeMethod, Func canExecuteMethod, bool isAutomaticRequeryDisabled)
{
if (executeMethod == null)
{
throw new ArgumentNullException("executeMethod");
}
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
_isAutomaticRequeryDisabled = isAutomaticRequeryDisabled;
}
#endregion
#region Public Methods
///
/// Method to determine if the command can be executed
///
public bool CanExecute(T parameter)
{
if (_canExecuteMethod != null)
{
return _canExecuteMethod(parameter);
}
return true;
}
///
/// Execution of the command
///
public void Execute(T parameter)
{
if (_executeMethod != null)
{
_executeMethod(parameter);
}
}
///
/// Raises the CanExecuteChaged event
///
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}
///
/// Protected virtual method to raise CanExecuteChanged event
///
protected virtual void OnCanExecuteChanged()
{
CommandManagerHelper.CallWeakReferenceHandlers(_canExecuteChangedHandlers);
}
///
/// Property to enable or disable CommandManager's automatic requery on this command
///
public bool IsAutomaticRequeryDisabled
{
get
{
return _isAutomaticRequeryDisabled;
}
set
{
if (_isAutomaticRequeryDisabled != value)
{
if (value)
{
CommandManagerHelper.RemoveHandlersFromRequerySuggested(_canExecuteChangedHandlers);
}
else
{
CommandManagerHelper.AddHandlersToRequerySuggested(_canExecuteChangedHandlers);
}
_isAutomaticRequeryDisabled = value;
}
}
}
#endregion
#region ICommand Members
///
/// ICommand.CanExecuteChanged implementation
///
public event EventHandler CanExecuteChanged
{
add
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested += value;
}
CommandManagerHelper.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2);
}
remove
{
if (!_isAutomaticRequeryDisabled)
{
CommandManager.RequerySuggested -= value;
}
CommandManagerHelper.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value);
}
}
bool ICommand.CanExecute(object parameter)
{
// if T is of value type and the parameter is not
// set yet, then return false if CanExecute delegate
// exists, else return true
if (parameter == null &&
typeof(T).IsValueType)
{
return (_canExecuteMethod == null);
}
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
#endregion
#region Data
private readonly Action _executeMethod = null;
private readonly Func _canExecuteMethod = null;
private bool _isAutomaticRequeryDisabled = false;
private List _canExecuteChangedHandlers;
#endregion
}
///
/// This class contains methods for the CommandManager that help avoid memory leaks by
/// using weak references.
///
internal static class CommandManagerHelper
{
internal static void CallWeakReferenceHandlers(List handlers)
{
if (handlers != null)
{
// Take a snapshot of the handlers before we call out to them since the handlers
// could cause the array to me modified while we are reading it.
EventHandler[] callees = new EventHandler[handlers.Count];
int count = 0;
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler handler = reference.Target as EventHandler;
if (handler == null)
{
// Clean up old handlers that have been collected
handlers.RemoveAt(i);
}
else
{
callees[count] = handler;
count++;
}
}
// Call the handlers that we snapshotted
for (int i = 0; i < count; i++)
{
EventHandler handler = callees[i];
handler(null, EventArgs.Empty);
}
}
}
internal static void AddHandlersToRequerySuggested(List handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested += handler;
}
}
}
}
internal static void RemoveHandlersFromRequerySuggested(List handlers)
{
if (handlers != null)
{
foreach (WeakReference handlerRef in handlers)
{
EventHandler handler = handlerRef.Target as EventHandler;
if (handler != null)
{
CommandManager.RequerySuggested -= handler;
}
}
}
}
//internal static void AddWeakReferenceHandler(ref List handlers, EventHandler handler)
//{
// AddWeakReferenceHandler(ref handlers, handler, -1);
//}
internal static void AddWeakReferenceHandler(ref List handlers, EventHandler handler, int defaultListSize)
{
if (handlers == null)
{
handlers = (defaultListSize > 0 ? new List(defaultListSize) : new List());
}
handlers.Add(new WeakReference(handler));
}
internal static void RemoveWeakReferenceHandler(List handlers, EventHandler handler)
{
if (handlers != null)
{
for (int i = handlers.Count - 1; i >= 0; i--)
{
WeakReference reference = handlers[i];
EventHandler existingHandler = reference.Target as EventHandler;
if ((existingHandler == null) || (existingHandler == handler))
{
// Clean up old handlers that have been collected
// in addition to the handler that is to be removed.
handlers.RemoveAt(i);
}
}
}
}
}
}
================================================
FILE: WpfRichText/Controls/RichTextEditor.xaml
================================================
================================================
FILE: WpfRichText/Controls/RichTextEditor.xaml.cs
================================================
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfRichText
{
///
/// Interaction logic for BindableRichTextbox.xaml
///
public partial class RichTextEditor : UserControl
{
///
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(RichTextEditor),
new PropertyMetadata(string.Empty));
///
public RichTextEditor()
{
InitializeComponent();
}
///
public string Text
{
get { return GetValue(TextProperty) as string; }
set
{
SetValue(TextProperty, value);
}
}
}
}
================================================
FILE: WpfRichText/WpfRichText.csproj
================================================
net5.0-windows
Library
false
true
true
false
Auto
..\bin\Debug\
false
..\bin\Release\
================================================
FILE: WpfRichText/WpfRichText.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31624.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WpfRichText", "WpfRichText\WpfRichText.csproj", "{78147C43-DB7B-4571-BC7A-E7F0075B4B78}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Debug|Any CPU.Build.0 = Debug|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Debug|x86.ActiveCfg = Debug|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Release|Any CPU.ActiveCfg = Release|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Release|Any CPU.Build.0 = Release|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{78147C43-DB7B-4571-BC7A-E7F0075B4B78}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1ADBABE2-7721-42E2-AE94-7B66D165C486}
EndGlobalSection
EndGlobal
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlCssParser.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Html - Xaml conversion
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
namespace WpfRichText
{
internal static class HtmlCssParser
{
// .................................................................
//
// Processing CSS Attributes
//
// .................................................................
internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List sourceContext)
{
string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext);
string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style");
// Combine styles from stylesheet and from inline attribute.
// The order is important - the latter styles will override the former.
string style = styleFromStylesheet != null ? styleFromStylesheet : null;
if (styleInline != null)
{
style = style == null ? styleInline : (style + ";" + styleInline);
}
// Apply local style to current formatting properties
if (style != null)
{
string[] styleValues = style.Split(';');
for (int i = 0; i < styleValues.Length; i++)
{
string[] styleNameValue;
styleNameValue = styleValues[i].Split(':');
if (styleNameValue.Length == 2)
{
string styleName = styleNameValue[0].Trim().ToLower(CultureInfo.InvariantCulture);
string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower(CultureInfo.InvariantCulture);
int nextIndex = 0;
switch (styleName)
{
case "font":
ParseCssFont(styleValue, localProperties);
break;
case "font-family":
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
break;
case "font-size":
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
break;
case "font-style":
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
break;
case "font-weight":
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
break;
case "font-variant":
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
break;
case "line-height":
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
break;
case "word-spacing":
// Implement word-spacing conversion
break;
case "letter-spacing":
// Implement letter-spacing conversion
break;
case "color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "color");
break;
case "text-decoration":
ParseCssTextDecoration(styleValue, ref nextIndex, localProperties);
break;
case "text-transform":
ParseCssTextTransform(styleValue, ref nextIndex, localProperties);
break;
case "background-color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color");
break;
case "background":
// TODO: need to parse composite background property
ParseCssBackground(styleValue, ref nextIndex, localProperties);
break;
case "text-align":
ParseCssTextAlign(styleValue, ref nextIndex, localProperties);
break;
case "vertical-align":
ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties);
break;
case "text-indent":
ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false);
break;
case "width":
case "height":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "margin": // top/right/bottom/left
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "margin-top":
case "margin-right":
case "margin-bottom":
case "margin-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "padding":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "padding-top":
case "padding-right":
case "padding-bottom":
case "padding-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "border":
ParseCssBorder(styleValue, ref nextIndex, localProperties);
break;
case "border-style":
case "border-width":
case "border-color":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "border-top":
case "border-right":
case "border-left":
case "border-bottom":
// Parse css border style
break;
// NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right)
// In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method
case "border-top-style":
case "border-right-style":
case "border-left-style":
case "border-bottom-style":
case "border-top-color":
case "border-right-color":
case "border-left-color":
case "border-bottom-color":
case "border-top-width":
case "border-right-width":
case "border-left-width":
case "border-bottom-width":
// Parse css border style
break;
case "display":
// Implement display style conversion
break;
case "float":
ParseCssFloat(styleValue, ref nextIndex, localProperties);
break;
case "clear":
ParseCssClear(styleValue, ref nextIndex, localProperties);
break;
default:
break;
}
}
}
}
}
// .................................................................
//
// Parsing CSS - Lexical Helpers
//
// .................................................................
// Skips whitespaces in style values
private static void ParseWhiteSpace(string styleValue, ref int nextIndex)
{
while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex]))
{
nextIndex++;
}
}
// Checks if the following character matches to a given word and advances nextIndex
// by the word's length in case of success.
// Otherwise leaves nextIndex in place (except for possible whitespaces).
// Returns true or false depending on success or failure of matching.
private static bool ParseWord(string word, string styleValue, ref int nextIndex)
{
ParseWhiteSpace(styleValue, ref nextIndex);
for (int i = 0; i < word.Length; i++)
{
if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i]))
{
return false;
}
}
if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length]))
{
return false;
}
nextIndex += word.Length;
return true;
}
// CHecks whether the following character sequence matches to one of the given words,
// and advances the nextIndex to matched word length.
// Returns null in case if there is no match or the word matched.
private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex)
{
for (int i = 0; i < words.Length; i++)
{
if (ParseWord(words[i], styleValue, ref nextIndex))
{
return words[i];
}
}
return null;
}
private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName)
{
string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex);
if (attributeValue != null)
{
localProperties[attributeName] = attributeValue;
}
}
private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative)
{
ParseWhiteSpace(styleValue, ref nextIndex);
int startIndex = nextIndex;
// Parse optional munis sign
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-')
{
nextIndex++;
}
if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex]))
{
while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.'))
{
nextIndex++;
}
string number = styleValue.Substring(startIndex, nextIndex - startIndex);
string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex);
if (unit == null)
{
unit = "px"; // Assuming pixels by default
}
if (mustBeNonNegative && styleValue[startIndex] == '-')
{
return "0";
}
else
{
return number + unit;
}
}
return null;
}
private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative)
{
string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative);
if (length != null)
{
localValues[propertyName] = length;
}
}
private static readonly string[] _colors = new string[]
{
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond",
"blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray",
"darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred",
"darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink",
"deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro",
"ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred",
"indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen",
"lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue",
"mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
"palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell",
"sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal",
"thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen",
};
private static readonly string[] _systemColors = new string[]
{
"activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow",
"buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption",
"inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow",
"threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext",
};
private static string ParseCssColor(string styleValue, ref int nextIndex)
{
// Implement color parsing
// rgb(100%,53.5%,10%)
// rgb(255,91,26)
// #FF5B1A
// black | silver | gray | ... | aqua
// transparent - for background-color
ParseWhiteSpace(styleValue, ref nextIndex);
string color = null;
if (nextIndex < styleValue.Length)
{
int startIndex = nextIndex;
char character = styleValue[nextIndex];
if (character == '#')
{
nextIndex++;
while (nextIndex < styleValue.Length)
{
character = Char.ToUpper(styleValue[nextIndex], CultureInfo.InvariantCulture);
if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F'))
{
break;
}
nextIndex++;
}
if (nextIndex > startIndex + 1)
{
color = styleValue.Substring(startIndex, nextIndex - startIndex);
}
}
else if (styleValue.Substring(nextIndex, 3).ToLower(CultureInfo.InvariantCulture) == "rbg")
{
// Implement real rgb() color parsing
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')')
{
nextIndex++;
}
if (nextIndex < styleValue.Length)
{
nextIndex++; // to skip ')'
}
color = "gray"; // return bogus color
}
else if (Char.IsLetter(character))
{
color = ParseWordEnumeration(_colors, styleValue, ref nextIndex);
if (color == null)
{
color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex);
if (color != null)
{
// Implement smarter system color converions into real colors
color = "black";
}
}
}
}
return color;
}
private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName)
{
string color = ParseCssColor(styleValue, ref nextIndex);
if (color != null)
{
localValues[propertyName] = color;
}
}
// .................................................................
//
// Pasring CSS font Property
//
// .................................................................
// CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size.
// An aggregated "font" property lets you specify in one action all the five in combination
// with additional line-height property.
//
// font-family: [,]* [ | ]
// generic-family: serif | sans-serif | monospace | cursive | fantasy
// The list of families sets priorities to choose fonts;
// Quotes not allowed around generic-family names
// font-style: normal | italic | oblique
// font-variant: normal | small-caps
// font-weight: normal | bold | bolder | lighter | 100 ... 900 |
// Default is "normal", normal==400
// font-size: | | |
// absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large
// relative-size: larger | smaller
// length: | | | | | | |
// Default: medium
// font: [ || || [ / ]?
private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" };
private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" };
private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" };
private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" };
private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" };
private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" };
// Parses CSS string fontStyle representing a value for css font attribute
private static void ParseCssFont(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/')
{
nextIndex++;
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
}
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
}
private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style");
}
private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant");
}
private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight");
}
private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties)
{
string fontFamilyList = null;
while (nextIndex < styleValue.Length)
{
// Try generic-family
string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex);
if (fontFamily == null)
{
// Try quoted font family name
if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\''))
{
char quote = styleValue[nextIndex];
nextIndex++;
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote)
{
nextIndex++;
}
fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"';
}
if (fontFamily == null)
{
// Try unquoted font family name
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';')
{
nextIndex++;
}
if (nextIndex > startIndex)
{
fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim();
if (fontFamily.Length == 0)
{
fontFamily = null;
}
}
}
}
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',')
{
nextIndex++;
}
if (fontFamily != null)
{
// css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names
// fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily;
if (fontFamilyList == null && fontFamily.Length > 0)
{
if (fontFamily[0] == '"' || fontFamily[0] == '\'')
{
// Unquote the font family name
fontFamily = fontFamily.Substring(1, fontFamily.Length - 2);
}
else
{
// Convert generic css family name
}
fontFamilyList = fontFamily;
}
}
else
{
break;
}
}
if (fontFamilyList != null)
{
localProperties["font-family"] = fontFamilyList;
}
}
// .................................................................
//
// Pasring CSS list-style Property
//
// .................................................................
// list-style: [ || || ]
private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" };
private static readonly string[] _listStylePositions = new string[] { "inside", "outside" };
private static void ParseCssListStyle(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
while (nextIndex < styleValue.Length)
{
string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex);
if (listStyleType != null)
{
localProperties["list-style-type"] = listStyleType;
}
else
{
string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex);
if (listStylePosition != null)
{
localProperties["list-style-position"] = listStylePosition;
}
else
{
string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex);
if (listStyleImage != null)
{
localProperties["list-style-image"] = listStyleImage;
}
else
{
// TODO: Process unrecognized list style value
break;
}
}
}
}
}
private static string ParseCssListStyleType(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex);
}
private static string ParseCssListStylePosition(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex);
}
private static string ParseCssListStyleImage(string styleValue, ref int nextIndex)
{
// TODO: Implement URL parsing for images
return null;
}
// .................................................................
//
// Pasring CSS text-decorations Property
//
// .................................................................
private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" };
private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Set default text-decorations:none;
for (int i = 1; i < _textDecorations.Length; i++)
{
localProperties["text-decoration-" + _textDecorations[i]] = "false";
}
// Parse list of decorations values
while (nextIndex < styleValue.Length)
{
string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex);
if (decoration == null || decoration == "none")
{
break;
}
localProperties["text-decoration-" + decoration] = "true";
}
}
// .................................................................
//
// Pasring CSS text-transform Property
//
// .................................................................
private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" };
private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform");
}
// .................................................................
//
// Pasring CSS text-align Property
//
// .................................................................
private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" };
private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align");
}
// .................................................................
//
// Pasring CSS vertical-align Property
//
// .................................................................
private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" };
private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Parse percentage value for vertical-align style
ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align");
}
// .................................................................
//
// Pasring CSS float Property
//
// .................................................................
private static readonly string[] _floats = new string[] { "left", "right", "none" };
private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float");
}
// .................................................................
//
// Pasring CSS clear Property
//
// .................................................................
private static readonly string[] _clears = new string[] { "none", "left", "right", "both" };
private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear");
}
// .................................................................
//
// Pasring CSS margin and padding Properties
//
// .................................................................
// Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color
private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName)
{
// CSS Spec:
// If only one value is set, then the value applies to all four sides;
// If two or three values are set, then missinng value(s) are taken fromm the opposite side(s).
// The order they are applied is: top/right/bottom/left
Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color");
string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-top"] = value;
localProperties[propertyName + "-bottom"] = value;
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-bottom"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-left"] = value;
}
}
}
return true;
}
return false;
}
// .................................................................
//
// Pasring CSS border Properties
//
// .................................................................
// border: [ || || ]
private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties)
{
while (
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color"))
{
}
}
// .................................................................
//
// Pasring CSS border-style Propertie
//
// .................................................................
private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" };
private static string ParseCssBorderStyle(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex);
}
// .................................................................
//
// What are these definitions doing here:
//
// .................................................................
private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" };
// .................................................................
//
// Pasring CSS Background Properties
//
// .................................................................
private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues)
{
// Implement parsing background attribute
}
}
internal class CssStylesheet
{
// Constructor
public CssStylesheet(XmlElement htmlElement)
{
if (htmlElement != null)
{
this.DiscoverStyleDefinitions(htmlElement);
}
}
// Recursively traverses an html tree, discovers STYLE elements and creates a style definition table
// for further cascading style application
public void DiscoverStyleDefinitions(XmlElement htmlElement)
{
if (htmlElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "link")
{
return;
// Add LINK elements processing for included stylesheets
//
}
if (htmlElement.LocalName.ToLower(CultureInfo.InvariantCulture) != "style")
{
// This is not a STYLE element. Recurse into it
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement)
{
this.DiscoverStyleDefinitions((XmlElement)htmlChildNode);
}
}
return;
}
// Add style definitions from this style.
// Collect all text from this style definition
StringBuilder stylesheetBuffer = new StringBuilder();
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlText || htmlChildNode is XmlComment)
{
stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value));
}
}
// CssStylesheet has the following syntactical structure:
// @import declaration;
// selector { definition }
// where "selector" is one of: ".classname", "tagname"
// It can contain comments in the following form: /*...*/
int nextCharacterIndex = 0;
while (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract selector
int selectorStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{')
{
// Skip declaration directive starting from @
if (stylesheetBuffer[nextCharacterIndex] == '@')
{
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';')
{
nextCharacterIndex++;
}
selectorStart = nextCharacterIndex + 1;
}
nextCharacterIndex++;
}
if (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract definition
int definitionStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}')
{
nextCharacterIndex++;
}
// Define a style
if (nextCharacterIndex - definitionStart > 2)
{
this.AddStyleDefinition(
stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart),
stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2));
}
// Skip closing brace
if (nextCharacterIndex < stylesheetBuffer.Length)
{
Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}');
nextCharacterIndex++;
}
}
}
}
// Returns a string with all c-style comments replaced by spaces
private string RemoveComments(string text)
{
int commentStart = text.IndexOf("/*", StringComparison.OrdinalIgnoreCase);
if (commentStart < 0)
{
return text;
}
int commentEnd = text.IndexOf("*/", commentStart + 2, StringComparison.OrdinalIgnoreCase);
if (commentEnd < 0)
{
return text.Substring(0, commentStart);
}
return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2));
}
public void AddStyleDefinition(string selector, string definition)
{
// Notrmalize parameter values
selector = selector.Trim().ToLower(CultureInfo.InvariantCulture);
definition = definition.Trim().ToLower(CultureInfo.InvariantCulture);
if (selector.Length == 0 || definition.Length == 0)
{
return;
}
if (_styleDefinitions == null)
{
_styleDefinitions = new List();
}
string[] simpleSelectors = selector.Split(',');
for (int i = 0; i < simpleSelectors.Length; i++)
{
string simpleSelector = simpleSelectors[i].Trim();
if (simpleSelector.Length > 0)
{
_styleDefinitions.Add(new StyleDefinition(simpleSelector, definition));
}
}
}
public string GetStyle(string elementName, List sourceContext)
{
Debug.Assert(sourceContext.Count > 0);
Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName);
// Add id processing for style selectors
if (_styleDefinitions != null)
{
for (int i = _styleDefinitions.Count - 1; i >= 0; i--)
{
string selector = _styleDefinitions[i].Selector;
string[] selectorLevels = selector.Split(' ');
int indexInSelector = selectorLevels.Length - 1;
//int indexInContext = sourceContext.Count - 1;
string selectorLevel = selectorLevels[indexInSelector].Trim();
if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1]))
{
return _styleDefinitions[i].Definition;
}
}
}
return null;
}
private static bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement)
{
if (selectorLevel.Length == 0)
{
return false;
}
int indexOfDot = selectorLevel.IndexOf('.');
int indexOfPound = selectorLevel.IndexOf('#');
string selectorClass = null;
string selectorId = null;
string selectorTag = null;
if (indexOfDot >= 0)
{
if (indexOfDot > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfDot);
}
selectorClass = selectorLevel.Substring(indexOfDot + 1);
}
else if (indexOfPound >= 0)
{
if (indexOfPound > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfPound);
}
selectorId = selectorLevel.Substring(indexOfPound + 1);
}
else
{
selectorTag = selectorLevel;
}
if (selectorTag != null && selectorTag != xmlElement.LocalName)
{
return false;
}
if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId)
{
return false;
}
if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass)
{
return false;
}
return true;
}
private class StyleDefinition
{
public StyleDefinition(string selector, string definition)
{
this.Selector = selector;
this.Definition = definition;
}
public string Selector;
public string Definition;
}
private List _styleDefinitions;
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlFromXamlConverter.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlFromXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Xaml - Html conversion
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
namespace WpfRichText
{
///
/// HtmlToXamlConverter is a static class that takes an HTML string
/// and converts it into XAML
///
internal static class HtmlFromXamlConverter
{
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
internal static string ConvertXamlToHtml(string xamlString)
{
return ConvertXamlToHtml(xamlString, true);
}
///
/// Main entry point for Xaml-to-Html converter.
/// Converts a xaml string into html string.
///
/// Xaml strinng to convert.
///
///
/// Html string produced from a source xaml.
///
internal static string ConvertXamlToHtml(string xamlString, bool asFlowDocument)
{
StringBuilder htmlStringBuilder;
XmlTextWriter htmlWriter;
if (!asFlowDocument)
{
xamlString = "" + xamlString + "";
}
using (XmlTextReader xamlReader = new XmlTextReader(new StringReader(xamlString)))
{
htmlStringBuilder = new StringBuilder(100);
using (StringWriter htmlStringWiter = new StringWriter(htmlStringBuilder, CultureInfo.InvariantCulture))
{
htmlWriter = new XmlTextWriter(htmlStringWiter);
if (!WriteFlowDocument(xamlReader, htmlWriter))
{
return "";
}
}
string htmlString = htmlStringBuilder.ToString();
return htmlString;
}
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
///
/// Processes a root level element of XAML (normally it's FlowDocument element).
///
///
/// XmlTextReader for a source xaml.
///
///
/// XmlTextWriter producing resulting html
///
private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter)
{
if (!ReadNextToken(xamlReader))
{
// Xaml content is empty - nothing to convert
return false;
}
if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDocument")
{
// Root FlowDocument elemet is missing
return false;
}
// Create a buffer StringBuilder for collecting css properties for inline STYLE attributes
// on every element level (it will be re-initialized on every level).
StringBuilder inlineStyle = new StringBuilder();
htmlWriter.WriteStartElement("HTML");
htmlWriter.WriteStartElement("BODY");
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
htmlWriter.WriteEndElement();
return true;
}
///
/// Reads attributes of the current xaml element and converts
/// them into appropriate html attributes or css styles.
///
///
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
/// The reader will remain at the same level after function complete.
///
///
/// XmlTextWriter for output html, which is expected to be in
/// after WriteStartElement state.
///
///
/// String builder for collecting css properties for inline STYLE attribute.
///
private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
// Clear string builder for the inline style
inlineStyle.Remove(0, inlineStyle.Length);
if (!xamlReader.HasAttributes)
{
return;
}
bool borderSet = false;
while (xamlReader.MoveToNextAttribute())
{
string css = null;
switch (xamlReader.Name)
{
// Character fomatting properties
// ------------------------------
case "Background":
css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "FontFamily":
css = "font-family:" + xamlReader.Value + ";";
break;
case "FontStyle":
css = "font-style:" + xamlReader.Value.ToLower(CultureInfo.InvariantCulture) + ";";
break;
case "FontWeight":
css = "font-weight:" + xamlReader.Value.ToLower(CultureInfo.InvariantCulture) + ";";
break;
case "FontStretch":
break;
case "FontSize":
css = "font-size:" + xamlReader.Value + ";";
break;
case "Foreground":
css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "TextDecorations":
css = "text-decoration:underline;";
break;
case "TextEffects":
break;
case "Emphasis":
break;
case "StandardLigatures":
break;
case "Variants":
break;
case "Capitals":
break;
case "Fraction":
break;
// Paragraph formatting properties
// -------------------------------
case "Padding":
css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "Margin":
css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "BorderThickness":
css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
borderSet = true;
break;
case "BorderBrush":
css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
borderSet = true;
break;
case "LineHeight":
break;
case "TextIndent":
css = "text-indent:" + xamlReader.Value + ";";
break;
case "TextAlignment":
css = "text-align:" + xamlReader.Value + ";";
break;
case "IsKeptTogether":
break;
case "IsKeptWithNext":
break;
case "ColumnBreakBefore":
break;
case "PageBreakBefore":
break;
case "FlowDirection":
break;
// Table attributes
// ----------------
case "Width":
css = "width:" + xamlReader.Value + ";";
break;
case "ColumnSpan":
htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
break;
case "RowSpan":
htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
break;
// Hyperlink Attributes
case "NavigateUri" :
htmlWriter.WriteAttributeString("HREF", xamlReader.Value);
break;
}
if (css != null)
{
inlineStyle.Append(css);
}
}
if (borderSet)
{
inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
}
// Return the xamlReader back to element level
xamlReader.MoveToElement();
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
}
private static string ParseXamlColor(string color)
{
if (color.StartsWith("#", StringComparison.OrdinalIgnoreCase))
{
// Remove transparancy value
color = "#" + color.Substring(3);
}
return color;
}
private static string ParseXamlThickness(string thickness)
{
string[] values = thickness.Split(',');
for (int i = 0; i < values.Length; i++)
{
double value;
if (double.TryParse(values[i], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
{
values[i] = Math.Ceiling(value).ToString(CultureInfo.InvariantCulture);
}
else
{
values[i] = "1";
}
}
string cssThickness;
switch (values.Length)
{
case 1:
cssThickness = thickness;
break;
case 2:
cssThickness = values[1] + " " + values[0];
break;
case 4:
cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0];
break;
default:
cssThickness = values[0];
break;
}
return cssThickness;
}
///
/// Reads a content of current xaml element, converts it
///
///
/// XmlTextReader which is expected to be at XmlNodeType.Element
/// (opening element tag) position.
///
///
/// May be null, in which case we are skipping the xaml element;
/// witout producing any output to html.
///
///
/// StringBuilder used for collecting css properties for inline STYLE attribute.
///
private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
bool elementContentStarted = false;
if (xamlReader.IsEmptyElement)
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
}
else
{
while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
{
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
if (xamlReader.Name.Contains("."))
{
AddComplexProperty(xamlReader, inlineStyle);
}
else
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
WriteElement(xamlReader, htmlWriter, inlineStyle);
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
break;
case XmlNodeType.Comment:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteComment(xamlReader.Value);
}
elementContentStarted = true;
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteString(xamlReader.Value);
}
elementContentStarted = true;
break;
}
}
Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement);
}
}
///
/// Conberts an element notation of complex property into
///
///
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
///
///
/// StringBuilder containing a value for STYLE attribute.
///
private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations", StringComparison.OrdinalIgnoreCase))
{
inlineStyle.Append("text-decoration:underline;");
}
// Skip the element representing the complex property
WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null);
}
///
/// Converts a xaml element into an appropriate html element.
///
///
/// On entry this XmlTextReader must be on Element start tag;
/// on exit - on EndElement tag.
///
///
/// May be null, in which case we are skipping xaml content
/// without producing any html output
///
///
/// StringBuilder used for collecting css properties for inline STYLE attributes on every level.
///
private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);
if (htmlWriter == null)
{
// Skipping mode; recurse into the xaml element without any output
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
else
{
string htmlElementName = null;
switch (xamlReader.Name)
{
case "Run" :
case "Span":
htmlElementName = "SPAN";
break;
case "InlineUIContainer":
htmlElementName = "SPAN";
break;
case "Bold":
htmlElementName = "B";
break;
case "Italic" :
htmlElementName = "I";
break;
case "Paragraph" :
htmlElementName = "P";
break;
case "BlockUIContainer":
htmlElementName = "DIV";
break;
case "Section":
htmlElementName = "DIV";
break;
case "Table":
htmlElementName = "TABLE";
break;
case "TableColumn":
htmlElementName = "COL";
break;
case "TableRowGroup" :
htmlElementName = "TBODY";
break;
case "TableRow" :
htmlElementName = "TR";
break;
case "TableCell" :
htmlElementName = "TD";
break;
case "List" :
string marker = xamlReader.GetAttribute("MarkerStyle");
if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box")
htmlElementName = "UL";
else
htmlElementName = "OL";
break;
case "ListItem" :
htmlElementName = "LI";
break;
case "Hyperlink" :
htmlElementName = "A";
break;
case "LineBreak" :
htmlWriter.WriteRaw("
");
break;
default :
htmlElementName = null; // Ignore the element
break;
}
if (htmlWriter != null && !String.IsNullOrEmpty(htmlElementName))
{
htmlWriter.WriteStartElement(htmlElementName);
WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle);
WriteElementContent(xamlReader, htmlWriter, inlineStyle);
htmlWriter.WriteEndElement();
}
else
{
// Skip this unrecognized xaml element
WriteElementContent(xamlReader, /*htmlWriter:*/null, null);
}
}
}
// Reader advance helpers
// ----------------------
///
/// Reads several items from xamlReader skipping all non-significant stuff.
///
///
/// XmlTextReader from tokens are being read.
///
///
/// True if new token is available; false if end of stream reached.
///
private static bool ReadNextToken(XmlReader xamlReader)
{
while (xamlReader.Read())
{
Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")");
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
case XmlNodeType.EndElement:
case XmlNodeType.None:
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.Whitespace:
if (xamlReader.XmlSpace == XmlSpace.Preserve)
{
return true;
}
// ignore insignificant whitespace
break;
case XmlNodeType.EndEntity:
case XmlNodeType.EntityReference:
// Implement entity reading
//xamlReader.ResolveEntity();
//xamlReader.Read();
//ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo);
break; // for now we ignore entities as insignificant stuff
case XmlNodeType.Comment:
return true;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
default:
// Ignorable stuff
break;
}
}
return false;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
#endregion Private Fields
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlLexicalAnalyzer.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlLexicalAnalyzer.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Lexical analyzer for Html-to-Xaml converter
//
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Text;
namespace WpfRichText
{
///
/// lexical analyzer class
/// recognizes tokens as groups of characters separated by arbitrary amounts of whitespace
/// also classifies tokens according to type
///
internal class HtmlLexicalAnalyzer : IDisposable
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
///
/// initializes the _inputStringReader member with the string to be read
/// also sets initial values for _nextCharacterCode and _nextTokenType
///
///
/// text string to be parsed for xml content
///
internal HtmlLexicalAnalyzer(string inputTextString)
{
_inputStringReader = new StringReader(inputTextString);
_nextCharacterCode = 0;
_nextCharacter = ' ';
_lookAheadCharacterCode = _inputStringReader.Read();
_lookAheadCharacter = (char)_lookAheadCharacterCode;
_previousCharacter = ' ';
_ignoreNextWhitespace = false;
_nextToken = new StringBuilder(100);
_nextTokenType = HtmlTokenType.Text;
// read the first character so we have some value for the NextCharacter property
this.GetNextCharacter();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal methods
//
// ---------------------------------------------------------------------
#region Internal Methods
///
/// retrieves next recognizable token from input string
/// and identifies its type
/// if no valid token is found, the output parameters are set to null
/// if end of stream is reached without matching any token, token type
/// paramter is set to EOF
///
internal void GetNextContentToken()
{
Debug.Assert(_nextTokenType != HtmlTokenType.EOF);
_nextToken.Length = 0;
if (this.IsAtEndOfStream)
{
_nextTokenType = HtmlTokenType.EOF;
return;
}
if (this.IsAtTagStart)
{
this.GetNextCharacter();
if (this.NextCharacter == '/')
{
_nextToken.Append("");
_nextTokenType = HtmlTokenType.ClosingTagStart;
// advance
this.GetNextCharacter();
_ignoreNextWhitespace = false; // Whitespaces after closing tags are significant
}
else
{
_nextTokenType = HtmlTokenType.OpeningTagStart;
_nextToken.Append("<");
_ignoreNextWhitespace = true; // Whitespaces after opening tags are insignificant
}
}
else if (this.IsAtDirectiveStart)
{
// either a comment or CDATA
this.GetNextCharacter();
if (_lookAheadCharacter == '[')
{
// cdata
this.ReadDynamicContent();
}
else if (_lookAheadCharacter == '-')
{
this.ReadComment();
}
else
{
// neither a comment nor cdata, should be something like DOCTYPE
// skip till the next tag ender
this.ReadUnknownDirective();
}
}
else
{
// read text content, unless you encounter a tag
_nextTokenType = HtmlTokenType.Text;
while (!this.IsAtTagStart && !this.IsAtEndOfStream && !this.IsAtDirectiveStart)
{
if (this.NextCharacter == '<' && !this.IsNextCharacterEntity && _lookAheadCharacter == '?')
{
// ignore processing directive
this.SkipProcessingDirective();
}
else
{
if (this.NextCharacter <= ' ')
{
// Respect xml:preserve or its equivalents for whitespace processing
if (_ignoreNextWhitespace)
{
// Changed by Akshin
_nextToken.Append(' ');
// Ignore repeated whitespaces
}
else
{
// Treat any control character sequence as one whitespace
_nextToken.Append(' ');
}
_ignoreNextWhitespace = true; // and keep ignoring the following whitespaces
}
else
{
_nextToken.Append(this.NextCharacter);
_ignoreNextWhitespace = false;
}
this.GetNextCharacter();
}
}
}
}
///
/// Unconditionally returns a token which is one of: TagEnd, EmptyTagEnd, Name, Atom or EndOfStream
/// Does not guarantee token reader advancing.
///
internal void GetNextTagToken()
{
_nextToken.Length = 0;
if (this.IsAtEndOfStream)
{
_nextTokenType = HtmlTokenType.EOF;
return;
}
this.SkipWhiteSpace();
if (this.NextCharacter == '>' && !this.IsNextCharacterEntity)
{
// > should not end a tag, so make sure it's not an entity
_nextTokenType = HtmlTokenType.TagEnd;
_nextToken.Append('>');
this.GetNextCharacter();
// Note: _ignoreNextWhitespace must be set appropriately on tag start processing
}
else if (this.NextCharacter == '/' && _lookAheadCharacter == '>')
{
// could be start of closing of empty tag
_nextTokenType = HtmlTokenType.EmptyTagEnd;
_nextToken.Append("/>");
this.GetNextCharacter();
this.GetNextCharacter();
_ignoreNextWhitespace = false; // Whitespace after no-scope tags are sifnificant
}
else if (IsGoodForNameStart(this.NextCharacter))
{
_nextTokenType = HtmlTokenType.Name;
// starts a name
// we allow character entities here
// we do not throw exceptions here if end of stream is encountered
// just stop and return whatever is in the token
// if the parser is not expecting end of file after this it will call
// the get next token function and throw an exception
while (IsGoodForName(this.NextCharacter) && !this.IsAtEndOfStream)
{
_nextToken.Append(this.NextCharacter);
this.GetNextCharacter();
}
}
else
{
// Unexpected type of token for a tag. Reprot one character as Atom, expecting that HtmlParser will ignore it.
_nextTokenType = HtmlTokenType.Atom;
_nextToken.Append(this.NextCharacter);
this.GetNextCharacter();
}
}
///
/// Unconditionally returns equal sign token. Even if there is no
/// real equal sign in the stream, it behaves as if it were there.
/// Does not guarantee token reader advancing.
///
internal void GetNextEqualSignToken()
{
Debug.Assert(_nextTokenType != HtmlTokenType.EOF);
_nextToken.Length = 0;
_nextToken.Append('=');
_nextTokenType = HtmlTokenType.EqualSign;
this.SkipWhiteSpace();
if (this.NextCharacter == '=')
{
// '=' is not in the list of entities, so no need to check for entities here
this.GetNextCharacter();
}
}
///
/// Unconditionally returns an atomic value for an attribute
/// Even if there is no appropriate token it returns Atom value
/// Does not guarantee token reader advancing.
///
internal void GetNextAtomToken()
{
Debug.Assert(_nextTokenType != HtmlTokenType.EOF);
_nextToken.Length = 0;
this.SkipWhiteSpace();
_nextTokenType = HtmlTokenType.Atom;
if ((this.NextCharacter == '\'' || this.NextCharacter == '"') && !this.IsNextCharacterEntity)
{
char startingQuote = this.NextCharacter;
this.GetNextCharacter();
// Consume all characters between quotes
while (!(this.NextCharacter == startingQuote && !this.IsNextCharacterEntity) && !this.IsAtEndOfStream)
{
_nextToken.Append(this.NextCharacter);
this.GetNextCharacter();
}
if (this.NextCharacter == startingQuote)
{
this.GetNextCharacter();
}
// complete the quoted value
// NOTE: our recovery here is different from IE's
// IE keeps reading until it finds a closing quote or end of file
// if end of file, it treats current value as text
// if it finds a closing quote at any point within the text, it eats everything between the quotes
// TODO: Suggestion:
// however, we could stop when we encounter end of file or an angle bracket of any kind
// and assume there was a quote there
// so the attribute value may be meaningless but it is never treated as text
}
else
{
while (!this.IsAtEndOfStream && !Char.IsWhiteSpace(this.NextCharacter) && this.NextCharacter != '>')
{
_nextToken.Append(this.NextCharacter);
this.GetNextCharacter();
}
}
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Internal Properties
//
// ---------------------------------------------------------------------
#region Internal Properties
internal HtmlTokenType NextTokenType
{
get
{
return _nextTokenType;
}
}
internal string NextToken
{
get
{
return _nextToken.ToString();
}
}
#endregion Internal Properties
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
///
/// Advances a reading position by one character code
/// and reads the next availbale character from a stream.
/// This character becomes available as NextCharacter property.
///
///
/// Throws InvalidOperationException if attempted to be called on EndOfStream
/// condition.
///
private void GetNextCharacter()
{
if (_nextCharacterCode == -1)
{
throw new InvalidOperationException("GetNextCharacter method called at the end of a stream");
}
_previousCharacter = _nextCharacter;
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
// next character not an entity as of now
_isNextCharacterEntity = false;
this.ReadLookAheadCharacter();
if (_nextCharacter == '&')
{
if (_lookAheadCharacter == '#')
{
// numeric entity - parse digits - DDDDD;
int entityCode;
entityCode = 0;
this.ReadLookAheadCharacter();
// largest numeric entity is 7 characters
for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++)
{
entityCode = 10 * entityCode + (_lookAheadCharacterCode - (int)'0');
this.ReadLookAheadCharacter();
}
if (_lookAheadCharacter == ';')
{
// correct format - advance
this.ReadLookAheadCharacter();
_nextCharacterCode = entityCode;
// if this is out of range it will set the character to '?'
_nextCharacter = (char)_nextCharacterCode;
// as far as we are concerned, this is an entity
_isNextCharacterEntity = true;
}
else
{
// not an entity, set next character to the current lookahread character
// we would have eaten up some digits
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
this.ReadLookAheadCharacter();
_isNextCharacterEntity = false;
}
}
else if (Char.IsLetter(_lookAheadCharacter))
{
// entity is written as a string
string entity = "";
// maximum length of string entities is 10 characters
for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++)
{
entity += _lookAheadCharacter;
this.ReadLookAheadCharacter();
}
if (_lookAheadCharacter == ';')
{
// advance
this.ReadLookAheadCharacter();
if (HtmlSchema.IsEntity(entity))
{
_nextCharacter = HtmlSchema.EntityCharacterValue(entity);
_nextCharacterCode = (int)_nextCharacter;
_isNextCharacterEntity = true;
}
else
{
// just skip the whole thing - invalid entity
// move on to the next character
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
this.ReadLookAheadCharacter();
// not an entity
_isNextCharacterEntity = false;
}
}
else
{
// skip whatever we read after the ampersand
// set next character and move on
_nextCharacter = _lookAheadCharacter;
this.ReadLookAheadCharacter();
_isNextCharacterEntity = false;
}
}
}
}
private void ReadLookAheadCharacter()
{
_lookAheadCharacterCode = _inputStringReader.Read();
if (_lookAheadCharacterCode != -1)
{
_lookAheadCharacter = (char)_lookAheadCharacterCode;
}
}
///
/// skips whitespace in the input string
/// leaves the first non-whitespace character available in the NextCharacter property
/// this may be the end-of-file character, it performs no checking
///
private void SkipWhiteSpace()
{
// TODO: handle character entities while processing comments, cdata, and directives
// TODO: SUGGESTION: we could check if lookahead and previous characters are entities also
while (true)
{
if (_nextCharacter == '<' && (_lookAheadCharacter == '?' || _lookAheadCharacter == '!'))
{
this.GetNextCharacter();
if (_lookAheadCharacter == '[')
{
// Skip CDATA block and DTDs(?)
while (!this.IsAtEndOfStream && !(_previousCharacter == ']' && _nextCharacter == ']' && _lookAheadCharacter == '>'))
{
this.GetNextCharacter();
}
if (_nextCharacter == '>')
{
this.GetNextCharacter();
}
}
else
{
// Skip processing instruction, comments
while (!this.IsAtEndOfStream && _nextCharacter != '>')
{
this.GetNextCharacter();
}
if (_nextCharacter == '>')
{
this.GetNextCharacter();
}
}
}
if (!Char.IsWhiteSpace(this.NextCharacter))
{
break;
}
this.GetNextCharacter();
}
}
///
/// checks if a character can be used to start a name
/// if this check is true then the rest of the name can be read
///
///
/// character value to be checked
///
///
/// true if the character can be the first character in a name
/// false otherwise
///
private static bool IsGoodForNameStart(char character)
{
return character == '_' || Char.IsLetter(character);
}
///
/// checks if a character can be used as a non-starting character in a name
/// uses the IsExtender and IsCombiningCharacter predicates to see
/// if a character is an extender or a combining character
///
///
/// character to be checked for validity in a name
///
///
/// true if the character can be a valid part of a name
///
private static bool IsGoodForName(char character)
{
// we are not concerned with escaped characters in names
// we assume that character entities are allowed as part of a name
return
HtmlLexicalAnalyzer.IsGoodForNameStart(character) ||
character == '.' ||
character == '-' ||
character == ':' ||
Char.IsDigit(character) ||
IsCombiningCharacter(character) ||
IsExtender(character);
}
///
/// identifies a character as being a combining character, permitted in a name
/// TODO: only a placeholder for now but later to be replaced with comparisons against
/// the list of combining characters in the XML documentation
///
///
/// character to be checked
///
///
/// true if the character is a combining character, false otherwise
///
private static bool IsCombiningCharacter(char character)
{
// TODO: put actual code with checks against all combining characters here
return false;
}
///
/// identifies a character as being an extender, permitted in a name
/// TODO: only a placeholder for now but later to be replaced with comparisons against
/// the list of extenders in the XML documentation
///
///
/// character to be checked
///
///
/// true if the character is an extender, false otherwise
///
private static bool IsExtender(char character)
{
// TODO: put actual code with checks against all extenders here
return false;
}
///
/// skips dynamic content starting with ![ and ending with ]
///
private void ReadDynamicContent()
{
// verify that we are at dynamic content, which may include CDATA
Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '[');
// Let's treat this as empty text
_nextTokenType = HtmlTokenType.Text;
_nextToken.Length = 0;
// advance twice, once to get the lookahead character and then to reach the start of the cdata
this.GetNextCharacter();
this.GetNextCharacter();
// NOTE: 10/12/2004: modified this function to check when called if's reading CDATA or something else
// some directives may start with a
// this function is modified to stop at the sequence ]> and not ]]>
// this means that CDATA and anything else expressed in their own set of [] within the
// directive cannot contain a ]> sequence. However it is doubtful that cdata could contain such
// sequence anyway, it probably stops at the first ]
while (!(_nextCharacter == ']' && _lookAheadCharacter == '>') && !this.IsAtEndOfStream)
{
// advance
this.GetNextCharacter();
}
if (!this.IsAtEndOfStream)
{
// advance, first to the last >
this.GetNextCharacter();
// then advance past it to the next character after processing directive
this.GetNextCharacter();
}
}
///
/// skips comments starting with !- and ending with --
/// NOTE: 10/06/2004: processing changed, will now skip anything starting with
/// the !- sequence and ending in ! or -, because in practice many html pages do not
/// use the full comment specifying conventions
///
private void ReadComment()
{
// verify that we are at a comment
Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && _lookAheadCharacter == '-');
// Initialize a token
_nextTokenType = HtmlTokenType.Comment;
_nextToken.Length = 0;
// advance to the next character, so that to be at the start of comment value
this.GetNextCharacter(); // get first '-'
this.GetNextCharacter(); // get second '-'
this.GetNextCharacter(); // get first character of comment content
while (true)
{
// Read text until end of comment
// Note that in many actual html pages comments end with "!>" (while xml standard is "-->")
while (!this.IsAtEndOfStream && !(_nextCharacter == '-' && _lookAheadCharacter == '-' || _nextCharacter == '!' && _lookAheadCharacter == '>'))
{
_nextToken.Append(this.NextCharacter);
this.GetNextCharacter();
}
// Finish comment reading
this.GetNextCharacter();
if (_previousCharacter == '-' && _nextCharacter == '-' && _lookAheadCharacter == '>')
{
// Standard comment end. Eat it and exit the loop
this.GetNextCharacter(); // get '>'
break;
}
else if (_previousCharacter == '!' && _nextCharacter == '>')
{
// Nonstandard but possible comment end - '!>'. Exit the loop
break;
}
else
{
// Not an end. Save character and continue continue reading
_nextToken.Append(_previousCharacter);
continue;
}
}
// Read end of comment combination
if (_nextCharacter == '>')
{
this.GetNextCharacter();
}
}
///
/// skips past unknown directives that start with ! but are not comments or Cdata
/// ignores content of such directives until the next character
/// applies to directives such as DOCTYPE, etc that we do not presently support
///
private void ReadUnknownDirective()
{
// verify that we are at an unknown directive
Debug.Assert(_previousCharacter == '<' && _nextCharacter == '!' && !(_lookAheadCharacter == '-' || _lookAheadCharacter == '['));
// Let's treat this as empty text
_nextTokenType = HtmlTokenType.Text;
_nextToken.Length = 0;
// advance to the next character
this.GetNextCharacter();
// skip to the first tag end we find
while (!(_nextCharacter == '>' && !IsNextCharacterEntity) && !this.IsAtEndOfStream)
{
this.GetNextCharacter();
}
if (!this.IsAtEndOfStream)
{
// advance past the tag end
this.GetNextCharacter();
}
}
///
/// skips processing directives starting with the characters ? and ending with ?
/// NOTE: 10/14/2004: IE also ends processing directives with a />, so this function is
/// being modified to recognize that condition as well
///
private void SkipProcessingDirective()
{
// verify that we are at a processing directive
Debug.Assert(_nextCharacter == '<' && _lookAheadCharacter == '?');
// advance twice, once to get the lookahead character and then to reach the start of the drective
this.GetNextCharacter();
this.GetNextCharacter();
while (!((_nextCharacter == '?' || _nextCharacter == '/') && _lookAheadCharacter == '>') && !this.IsAtEndOfStream)
{
// advance
// we don't need to check for entities here because '?' is not an entity
// and even though > is an entity there is no entity processing when reading lookahead character
this.GetNextCharacter();
}
if (!this.IsAtEndOfStream)
{
// advance, first to the last >
this.GetNextCharacter();
// then advance past it to the next character after processing directive
this.GetNextCharacter();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Properties
//
// ---------------------------------------------------------------------
#region Private Properties
private char NextCharacter
{
get
{
return _nextCharacter;
}
}
private bool IsAtEndOfStream
{
get
{
return _nextCharacterCode == -1;
}
}
private bool IsAtTagStart
{
get
{
return _nextCharacter == '<' && (_lookAheadCharacter == '/' || IsGoodForNameStart(_lookAheadCharacter)) && !_isNextCharacterEntity;
}
}
private bool IsAtTagEnd
{
// check if at end of empty tag or regular tag
get
{
return (_nextCharacter == '>' || (_nextCharacter == '/' && _lookAheadCharacter == '>')) && !_isNextCharacterEntity;
}
}
private bool IsAtDirectiveStart
{
get
{
return (_nextCharacter == '<' && _lookAheadCharacter == '!' && !this.IsNextCharacterEntity);
}
}
private bool IsNextCharacterEntity
{
// check if next character is an entity
get
{
return _isNextCharacterEntity;
}
}
#endregion Private Properties
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
// string reader which will move over input text
private StringReader _inputStringReader = null;
// next character code read from input that is not yet part of any token
// and the character it represents
private int _nextCharacterCode;
private char _nextCharacter;
private int _lookAheadCharacterCode;
private char _lookAheadCharacter;
private char _previousCharacter;
private bool _ignoreNextWhitespace;
private bool _isNextCharacterEntity;
// store token and type in local variables before copying them to output parameters
StringBuilder _nextToken;
HtmlTokenType _nextTokenType;
#endregion Private Fields
private bool isDisposing = false;
public void Dispose()
{
Dispose(isDisposing);
}
private void Dispose(bool disposing)
{
if (!disposing)
{
isDisposing = true;
if (this._inputStringReader != null)
{
this._inputStringReader.Dispose();
this._inputStringReader = null;
}
}
}
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlParser.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlParser.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Parser for Html-to-Xaml converter
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization; // StringBuilder
using System.Text;
using System.Xml;
// important TODOS:
// TODO 1. Start tags: The ParseXmlElement function has been modified to be called after both the
// angle bracket < and element name have been read, instead of just the < bracket and some valid name character,
// previously the case. This change was made so that elements with optional closing tags could read a new
// element's start tag and decide whether they were required to close. However, there is a question of whether to
// handle this in the parser or lexical analyzer. It is currently handled in the parser - the lexical analyzer still
// recognizes a start tag opener as a '<' + valid name start char; it is the parser that reads the actual name.
// this is correct behavior assuming that the name is a valid html name, because the lexical analyzer should not know anything
// about optional closing tags, etc. UPDATED: 10/13/2004: I am updating this to read the whole start tag of something
// that is not an HTML, treat it as empty, and add it to the tree. That way the converter will know it's there, but
// it will hvae no content. We could also partially recover by trying to look up and match names if they are similar
// TODO 2. Invalid element names: However, it might make sense to give the lexical analyzer the ability to identify
// a valid html element name and not return something as a start tag otherwise. For example, if we type , should
// the lexical analyzer return that it has found the start of an element when this is not the case in HTML? But this will
// require implementing a lookahead token in the lexical analyzer so that it can treat an invalid element name as text. One
// character of lookahead will not be enough.
// TODO 3. Attributes: The attribute recovery is poor when reading attribute values in quotes - if no closing quotes are found,
// the lexical analyzer just keeps reading and if it eventually reaches the end of file, it would have just skipped everything.
// There are a couple of ways to deal with this: 1) stop reading attributes when we encounter a '>' character - this doesn't allow
// the '>' character to be used in attribute values, but it can still be used as an entity. 2) Maintain a HTML-specific list
// of attributes and their values that each html element can take, and if we find correct attribute namesand values for an
// element we use them regardless of the quotes, this way we could just ignore something invalid. One more option: 3) Read ahead
// in the quoted value and if we find an end of file, we can return to where we were and process as text. However this requires
// a lot of lookahead and a resettable reader.
// TODO 4: elements with optional closing tags: For elements with optional closing tags, we always close the element if we find
// that one of it's ancestors has closed. This condition may be too broad and we should develop a better heuristic. We should also
// improve the heuristics for closing certain elements when the next element starts
// TODO 5. Nesting: Support for unbalanced nesting, e.g. : this is not presently supported. To support it we may need
// to maintain two xml elements, one the element that represents what has already been read and another represents what we are presently reading.
// Then if we encounter an unbalanced nesting tag we could close the element that was supposed to close, save the current element
// and store it in the list of already-read content, and then open a new element to which all tags that are currently open
// can be applied. Is there a better way to do this? Should we do it at all?
// TODO 6. Elements with optional starting tags: there are 4 such elements in the HTML 4 specification - html, tbody, body and head.
// The current recovery doesn;t do anything for any of these elements except the html element, because it's not critical - head
// and body elementscan be contained within html element, and tbody is contained within table. To extend this for XHTML
// extensions, and to recover in case other elements are missing start tags, we would need to insert an extra recursive call
// to ParseXmlElement for the missing start tag. It is suggested to do this by giving ParseXmlElement an argument that specifies
// a name to use. If this argument is null, it assumes its name is the next token from the lexical analyzer and continues
// exactly as it does now. However, if the argument contains a valid html element name then it takes that value as its name
// and continues as before. This way, if the next token is the element that should actually be its child, it will see
// the name in the next step and initiate a recursive call. We would also need to add some logic in the loop for when a start tag
// is found - if the start tag is not compatible with current context and indicates that a start tag has been missed, then we
// can initiate the extra recursive call and give it the name of the missed start tag. The issues are when to insert this logic,
// and if we want to support it over multiple missing start tags. If we insert it at the time a start tag is read in element
// text, then we can support only one missing start tag, since the extra call will read the next start tag and make a recursive
// call without checking the context. This is a conceptual problem, and the check should be made just before a recursive call,
// with the choice being whether we should supply an element name as argument, or leave it as NULL and read from the input
// TODO 7: Context: Is it appropriate to keep track of context here? For example, should we only expect td, tr elements when
// reading a table and ignore them otherwise? This may be too much of a load on the parser, I think it's better if the converter
// deals with it
namespace WpfRichText
{
///
/// HtmlParser class accepts a string of possibly badly formed Html, parses it and returns a string
/// of well-formed Html that is as close to the original string in content as possible
///
internal class HtmlParser : IDisposable
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
///
/// Constructor. Initializes the _htmlLexicalAnalayzer element with the given input string
///
///
/// string to parsed into well-formed Html
///
private HtmlParser(string inputString)
{
// Create an output xml document
_document = new XmlDocument();
// initialize open tag stack
_openedElements = new Stack();
_pendingInlineElements = new Stack();
// initialize lexical analyzer
_htmlLexicalAnalyzer = new HtmlLexicalAnalyzer(inputString);
// get first token from input, expecting text
_htmlLexicalAnalyzer.GetNextContentToken();
}
#endregion Constructors
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
///
/// Instantiates an HtmlParser element and calls the parsing function on the given input string
///
///
/// Input string of pssibly badly-formed Html to be parsed into well-formed Html
///
///
/// XmlElement rep
///
internal static XmlElement ParseHtml(string htmlString)
{
using (HtmlParser htmlParser = new HtmlParser(htmlString))
{
XmlElement htmlRootElement = htmlParser.ParseHtmlContent();
return htmlRootElement;
}
}
// .....................................................................
//
// Html Header on Clipboard
//
// .....................................................................
// Html header structure.
// Version:1.0
// StartHTML:000000000
// EndHTML:000000000
// StartFragment:000000000
// EndFragment:000000000
// StartSelection:000000000
// EndSelection:000000000
internal const string HtmlHeader = "Version:1.0\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\nStartSelection:{4:D10}\r\nEndSelection:{5:D10}\r\n";
internal const string HtmlStartFragmentComment = "";
internal const string HtmlEndFragmentComment = "";
///
/// Extracts Html string from clipboard data by parsing header information in htmlDataString
///
///
/// String representing Html clipboard data. This includes Html header
///
///
/// String containing only the Html data part of htmlDataString, without header
///
internal static string ExtractHtmlFromClipboardData(string htmlDataString)
{
int startHtmlIndex = htmlDataString.IndexOf("StartHTML:", StringComparison.OrdinalIgnoreCase);
if (startHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
startHtmlIndex = Int32.Parse(htmlDataString.Substring(startHtmlIndex + "StartHTML:".Length, "0123456789".Length), CultureInfo.InvariantCulture);
if (startHtmlIndex < 0 || startHtmlIndex > htmlDataString.Length)
{
return "ERROR: Urecognized html header";
}
int endHtmlIndex = htmlDataString.IndexOf("EndHTML:", StringComparison.OrdinalIgnoreCase);
if (endHtmlIndex < 0)
{
return "ERROR: Urecognized html header";
}
// TODO: We assume that indices represented by strictly 10 zeros ("0123456789".Length),
// which could be wrong assumption. We need to implement more flrxible parsing here
endHtmlIndex = Int32.Parse(htmlDataString.Substring(endHtmlIndex + "EndHTML:".Length, "0123456789".Length), CultureInfo.InvariantCulture);
if (endHtmlIndex > htmlDataString.Length)
{
endHtmlIndex = htmlDataString.Length;
}
return htmlDataString.Substring(startHtmlIndex, endHtmlIndex - startHtmlIndex);
}
///
/// Adds Xhtml header information to Html data string so that it can be placed on clipboard
///
///
/// Html string to be placed on clipboard with appropriate header
///
///
/// String wrapping htmlString with appropriate Html header
///
internal static string AddHtmlClipboardHeader(string htmlString)
{
StringBuilder stringBuilder = new StringBuilder();
// each of 6 numbers is represented by "{0:D10}" in the format string
// must actually occupy 10 digit positions ("0123456789")
int startHTML = HtmlHeader.Length + 6 * ("0123456789".Length - "{0:D10}".Length);
int endHTML = startHTML + htmlString.Length;
int startFragment = htmlString.IndexOf(HtmlStartFragmentComment, 0, StringComparison.OrdinalIgnoreCase);
if (startFragment >= 0)
{
startFragment = startHTML + startFragment + HtmlStartFragmentComment.Length;
}
else
{
startFragment = startHTML;
}
int endFragment = htmlString.IndexOf(HtmlEndFragmentComment, 0, StringComparison.OrdinalIgnoreCase);
if (endFragment >= 0)
{
endFragment = startHTML + endFragment;
}
else
{
endFragment = endHTML;
}
// Create HTML clipboard header string
stringBuilder.AppendFormat(CultureInfo.InvariantCulture,HtmlHeader, startHTML, endHTML, startFragment, endFragment, startFragment, endFragment);
// Append HTML body.
stringBuilder.Append(htmlString);
return stringBuilder.ToString();
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private methods
//
// ---------------------------------------------------------------------
#region Private Methods
private static void InvariantAssert(bool condition, string message)
{
if (!condition)
{
throw new ArgumentOutOfRangeException("Assertion error: " + message);
}
}
///
/// Parses the stream of html tokens starting
/// from the name of top-level element.
/// Returns XmlElement representing the top-level
/// html element
///
private XmlElement ParseHtmlContent()
{
// Create artificial root elelemt to be able to group multiple top-level elements
// We create "html" element which may be a duplicate of real HTML element, which is ok, as HtmlConverter will swallow it painlessly..
XmlElement htmlRootElement = _document.CreateElement("html", XhtmlNamespace);
OpenStructuringElement(htmlRootElement);
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF)
{
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.OpeningTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(CultureInfo.InvariantCulture);
_htmlLexicalAnalyzer.GetNextTagToken();
// Create an element
XmlElement htmlElement = _document.CreateElement(htmlElementName, XhtmlNamespace);
// Parse element attributes
ParseAttributes(htmlElement);
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.EmptyTagEnd || HtmlSchema.IsEmptyElement(htmlElementName))
{
// It is an element without content (because of explicit slash or based on implicit knowledge aboout html)
AddEmptyElement(htmlElement);
}
else if (HtmlSchema.IsInlineElement(htmlElementName))
{
// Elements known as formatting are pushed to some special
// pending stack, which allows them to be transferred
// over block tags - by doing this we convert
// overlapping tags into normal heirarchical element structure.
OpenInlineElement(htmlElement);
}
else if (HtmlSchema.IsBlockElement(htmlElementName) || HtmlSchema.IsKnownOpenableElement(htmlElementName))
{
// This includes no-scope elements
OpenStructuringElement(htmlElement);
}
else
{
// Do nothing. Skip the whole opening tag.
// Ignoring all unknown elements on their start tags.
// Thus we will ignore them on closinng tag as well.
// Anyway we don't know what to do withthem on conversion to Xaml.
}
}
else
{
// Note that the token following opening angle bracket must be a name - lexical analyzer must guarantee that.
// Otherwise - we skip the angle bracket and continue parsing the content as if it is just text.
// Add the following asserion here, right? or output "<" as a text run instead?:
// InvariantAssert(false, "Angle bracket without a following name is not expected");
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.ClosingTagStart)
{
_htmlLexicalAnalyzer.GetNextTagToken();
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string htmlElementName = _htmlLexicalAnalyzer.NextToken.ToLower(CultureInfo.InvariantCulture);
// Skip the name token. Assume that the following token is end of tag,
// but do not check this. If it is not true, we simply ignore one token
// - this is our recovery from bad xml in this case.
_htmlLexicalAnalyzer.GetNextTagToken();
CloseElement(htmlElementName);
}
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Text)
{
AddTextContent(_htmlLexicalAnalyzer.NextToken);
}
else if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Comment)
{
AddComment(_htmlLexicalAnalyzer.NextToken);
}
_htmlLexicalAnalyzer.GetNextContentToken();
}
// Get rid of the artificial root element
if (htmlRootElement.FirstChild is XmlElement &&
htmlRootElement.FirstChild == htmlRootElement.LastChild &&
htmlRootElement.FirstChild.LocalName.ToLower(CultureInfo.InvariantCulture) == "html")
{
htmlRootElement = (XmlElement)htmlRootElement.FirstChild;
}
return htmlRootElement;
}
private XmlElement CreateElementCopy(XmlElement htmlElement)
{
XmlElement htmlElementCopy = _document.CreateElement(htmlElement.LocalName, XhtmlNamespace);
for (int i = 0; i < htmlElement.Attributes.Count; i++)
{
XmlAttribute attribute = htmlElement.Attributes[i];
htmlElementCopy.SetAttribute(attribute.Name, attribute.Value);
}
return htmlElementCopy;
}
private void AddEmptyElement(XmlElement htmlEmptyElement)
{
InvariantAssert(_openedElements.Count > 0, "AddEmptyElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlEmptyElement);
}
private void OpenInlineElement(XmlElement htmlInlineElement)
{
_pendingInlineElements.Push(htmlInlineElement);
}
// Opens structurig element such as Div or Table etc.
private void OpenStructuringElement(XmlElement htmlElement)
{
// Close all pending inline elements
// All block elements are considered as delimiters for inline elements
// which forces all inline elements to be closed and re-opened in the following
// structural element (if any).
// By doing that we guarantee that all inline elements appear only within most nested blocks
if (HtmlSchema.IsBlockElement(htmlElement.LocalName))
{
while (_openedElements.Count > 0 && HtmlSchema.IsInlineElement(_openedElements.Peek().LocalName))
{
XmlElement htmlInlineElement = _openedElements.Pop();
InvariantAssert(_openedElements.Count > 0, "OpenStructuringElement: stack of opened elements cannot become empty here");
_pendingInlineElements.Push(CreateElementCopy(htmlInlineElement));
}
}
// Add this block element to its parent
if (_openedElements.Count > 0)
{
XmlElement htmlParent = _openedElements.Peek();
// Check some known block elements for auto-closing (LI and P)
if (HtmlSchema.ClosesOnNextElementStart(htmlParent.LocalName, htmlElement.LocalName))
{
_openedElements.Pop();
htmlParent = _openedElements.Count > 0 ? _openedElements.Peek() : null;
}
if (htmlParent != null)
{
// NOTE:
// Actually we never expect null - it would mean two top-level P or LI (without a parent).
// In such weird case we will loose all paragraphs except the first one...
htmlParent.AppendChild(htmlElement);
}
}
// Push it onto a stack
_openedElements.Push(htmlElement);
}
private bool IsElementOpened(string htmlElementName)
{
foreach (XmlElement openedElement in _openedElements)
{
if (openedElement.LocalName == htmlElementName)
{
return true;
}
}
return false;
}
private void CloseElement(string htmlElementName)
{
// Check if the element is opened and already added to the parent
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
// Check if the element is opened and still waiting to be added to the parent
if (_pendingInlineElements.Count > 0 && _pendingInlineElements.Peek().LocalName == htmlElementName)
{
// Closing an empty inline element.
// Note that HtmlConverter will skip empty inlines, but for completeness we keep them here on parser level.
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
InvariantAssert(_openedElements.Count > 0, "CloseElement: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
return;
}
else if (IsElementOpened(htmlElementName))
{
while (_openedElements.Count > 1) // we never pop the last element - the artificial root
{
// Close all unbalanced elements.
XmlElement htmlOpenedElement = _openedElements.Pop();
if (htmlOpenedElement.LocalName == htmlElementName)
{
return;
}
if (HtmlSchema.IsInlineElement(htmlOpenedElement.LocalName))
{
// Unbalances Inlines will be transfered to the next element content
_pendingInlineElements.Push(CreateElementCopy(htmlOpenedElement));
}
}
}
// If element was not opened, we simply ignore the unbalanced closing tag
return;
}
private void AddTextContent(string textContent)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddTextContent: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlText textNode = _document.CreateTextNode(textContent);
htmlParent.AppendChild(textNode);
}
private void AddComment(string comment)
{
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "AddComment: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
XmlComment xmlComment = _document.CreateComment(comment);
htmlParent.AppendChild(xmlComment);
}
// Moves all inline elements pending for opening to actual document
// and adds them to current open stack.
private void OpenPendingInlineElements()
{
if (_pendingInlineElements.Count > 0)
{
XmlElement htmlInlineElement = _pendingInlineElements.Pop();
OpenPendingInlineElements();
InvariantAssert(_openedElements.Count > 0, "OpenPendingInlineElements: Stack of opened elements cannot be empty, as we have at least one artificial root element");
XmlElement htmlParent = _openedElements.Peek();
htmlParent.AppendChild(htmlInlineElement);
_openedElements.Push(htmlInlineElement);
}
}
private void ParseAttributes(XmlElement xmlElement)
{
while (_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EOF && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.TagEnd && //
_htmlLexicalAnalyzer.NextTokenType != HtmlTokenType.EmptyTagEnd)
{
// read next attribute (name=value)
if (_htmlLexicalAnalyzer.NextTokenType == HtmlTokenType.Name)
{
string attributeName = _htmlLexicalAnalyzer.NextToken;
_htmlLexicalAnalyzer.GetNextEqualSignToken();
_htmlLexicalAnalyzer.GetNextAtomToken();
string attributeValue = _htmlLexicalAnalyzer.NextToken;
xmlElement.SetAttribute(attributeName, attributeValue);
}
_htmlLexicalAnalyzer.GetNextTagToken();
}
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
internal const string XhtmlNamespace = "http://www.w3.org/1999/xhtml";
private HtmlLexicalAnalyzer _htmlLexicalAnalyzer = null;
// document from which all elements are created
private XmlDocument _document;
// stack for open elements
Stack _openedElements;
Stack _pendingInlineElements;
#endregion Private Fields
private bool isDisposing = false;
public void Dispose()
{
Dispose(isDisposing);
}
private void Dispose(bool disposing)
{
if (!disposing)
{
isDisposing = true;
if (this._htmlLexicalAnalyzer != null)
{
this._htmlLexicalAnalyzer.Dispose();
this._htmlLexicalAnalyzer = null;
}
}
}
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlSchema.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlSchema.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Static information about HTML structure
//
//---------------------------------------------------------------------------
namespace WpfRichText
{
using System.Collections;
using System.Diagnostics;
using System.Globalization;
///
/// HtmlSchema class
/// maintains static information about HTML structure
/// can be used by HtmlParser to check conditions under which an element starts or ends, etc.
///
internal static class HtmlSchema
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
///
/// static constructor, initializes the ArrayLists
/// that hold the elements in various sub-components of the schema
/// e.g _htmlEmptyElements, etc.
///
static HtmlSchema()
{
// initializes the list of all html elements
InitializeInlineElements();
InitializeBlockElements();
InitializeOtherOpenableElements();
// initialize empty elements list
InitializeEmptyElements();
// initialize list of elements closing on the outer element end
InitializeElementsClosingOnParentElementEnd();
// initalize list of elements that close when a new element starts
InitializeElementsClosingOnNewElementStart();
// Initialize character entities
InitializeHtmlCharacterEntities();
}
#endregion Constructors;
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
///
/// returns true when xmlElementName corresponds to empty element
///
///
/// string representing name to test
///
internal static bool IsEmptyElement(string xmlElementName)
{
// convert to lowercase before we check
// because element names are not case sensitive
return _htmlEmptyElements.Contains(xmlElementName.ToLower(CultureInfo.InvariantCulture));
}
///
/// returns true if xmlElementName represents a block formattinng element.
/// It used in an algorithm of transferring inline elements over block elements
/// in HtmlParser
///
///
///
internal static bool IsBlockElement(string xmlElementName)
{
return _htmlBlockElements.Contains(xmlElementName);
}
///
/// returns true if the xmlElementName represents an inline formatting element
///
///
///
internal static bool IsInlineElement(string xmlElementName)
{
return _htmlInlineElements.Contains(xmlElementName);
}
///
/// It is a list of known html elements which we
/// want to allow to produce bt HTML parser,
/// but don'tt want to act as inline, block or no-scope.
/// Presence in this list will allow to open
/// elements during html parsing, and adding the
/// to a tree produced by html parser.
///
internal static bool IsKnownOpenableElement(string xmlElementName)
{
return _htmlOtherOpenableElements.Contains(xmlElementName);
}
///
/// returns true when xmlElementName closes when the outer element closes
/// this is true of elements with optional start tags
///
///
/// string representing name to test
///
internal static bool ClosesOnParentElementEnd(string xmlElementName)
{
// convert to lowercase when testing
return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower(CultureInfo.InvariantCulture));
}
///
/// returns true if the current element closes when the new element, whose name has just been read, starts
///
///
/// string representing current element name
///
///
/// string representing name of the next element that will start
internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
{
Debug.Assert(currentElementName == currentElementName.ToLower(CultureInfo.InvariantCulture));
switch (currentElementName)
{
case "colgroup":
return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dd":
return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "dt":
return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName);
case "li":
return _htmlElementsClosingLI.Contains(nextElementName);
case "p":
return HtmlSchema.IsBlockElement(nextElementName);
case "tbody":
return _htmlElementsClosingTbody.Contains(nextElementName);
case "tfoot":
return _htmlElementsClosingTfoot.Contains(nextElementName);
case "thead":
return _htmlElementsClosingThead.Contains(nextElementName);
case "tr":
return _htmlElementsClosingTR.Contains(nextElementName);
case "td":
return _htmlElementsClosingTD.Contains(nextElementName);
case "th":
return _htmlElementsClosingTH.Contains(nextElementName);
}
return false;
}
///
/// returns true if the string passed as argument is an Html entity name
///
///
/// string to be tested for Html entity name
///
internal static bool IsEntity(string entityName)
{
// we do not convert entity strings to lowercase because these names are case-sensitive
if (_htmlCharacterEntities.Contains(entityName))
{
return true;
}
else
{
return false;
}
}
///
/// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name
/// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise
///
///
/// string representing entity name whose character value is desired
///
internal static char EntityCharacterValue(string entityName)
{
if (_htmlCharacterEntities.Contains(entityName))
{
return (char) _htmlCharacterEntities[entityName];
}
else
{
return (char)0;
}
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Internal Properties
//
// ---------------------------------------------------------------------
#region Internal Properties
#endregion Internal Indexers
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
private static void InitializeInlineElements()
{
_htmlInlineElements = new ArrayList();
_htmlInlineElements.Add("a");
_htmlInlineElements.Add("abbr");
_htmlInlineElements.Add("acronym");
_htmlInlineElements.Add("address");
_htmlInlineElements.Add("b");
_htmlInlineElements.Add("bdo"); // ???
_htmlInlineElements.Add("big");
_htmlInlineElements.Add("button");
_htmlInlineElements.Add("code");
_htmlInlineElements.Add("del"); // deleted text
_htmlInlineElements.Add("dfn");
_htmlInlineElements.Add("em");
_htmlInlineElements.Add("font");
_htmlInlineElements.Add("i");
_htmlInlineElements.Add("ins"); // inserted text
_htmlInlineElements.Add("kbd"); // text to entered by a user
_htmlInlineElements.Add("label");
_htmlInlineElements.Add("legend"); // ???
_htmlInlineElements.Add("q"); // short inline quotation
_htmlInlineElements.Add("s"); // strike-through text style
_htmlInlineElements.Add("samp"); // Specifies a code sample
_htmlInlineElements.Add("small");
_htmlInlineElements.Add("span");
_htmlInlineElements.Add("strike");
_htmlInlineElements.Add("strong");
_htmlInlineElements.Add("sub");
_htmlInlineElements.Add("sup");
_htmlInlineElements.Add("u");
_htmlInlineElements.Add("var"); // indicates an instance of a program variable
}
private static void InitializeBlockElements()
{
_htmlBlockElements = new ArrayList();
_htmlBlockElements.Add("blockquote");
_htmlBlockElements.Add("body");
_htmlBlockElements.Add("caption");
_htmlBlockElements.Add("center");
_htmlBlockElements.Add("cite");
_htmlBlockElements.Add("dd");
_htmlBlockElements.Add("dir"); // treat as UL element
_htmlBlockElements.Add("div");
_htmlBlockElements.Add("dl");
_htmlBlockElements.Add("dt");
_htmlBlockElements.Add("form"); // Not a block according to XHTML spec
_htmlBlockElements.Add("h1");
_htmlBlockElements.Add("h2");
_htmlBlockElements.Add("h3");
_htmlBlockElements.Add("h4");
_htmlBlockElements.Add("h5");
_htmlBlockElements.Add("h6");
_htmlBlockElements.Add("html");
_htmlBlockElements.Add("li");
_htmlBlockElements.Add("menu"); // treat as UL element
_htmlBlockElements.Add("ol");
_htmlBlockElements.Add("p");
_htmlBlockElements.Add("pre"); // Renders text in a fixed-width font
_htmlBlockElements.Add("table");
_htmlBlockElements.Add("tbody");
_htmlBlockElements.Add("td");
_htmlBlockElements.Add("textarea");
_htmlBlockElements.Add("tfoot");
_htmlBlockElements.Add("th");
_htmlBlockElements.Add("thead");
_htmlBlockElements.Add("tr");
_htmlBlockElements.Add("tt");
_htmlBlockElements.Add("ul");
}
///
/// initializes _htmlEmptyElements with empty elements in HTML 4 spec at
/// http://www.w3.org/TR/REC-html40/index/elements.html
///
private static void InitializeEmptyElements()
{
// Build a list of empty (no-scope) elements
// (element not requiring closing tags, and not accepting any content)
_htmlEmptyElements = new ArrayList();
_htmlEmptyElements.Add("area");
_htmlEmptyElements.Add("base");
_htmlEmptyElements.Add("basefont");
_htmlEmptyElements.Add("br");
_htmlEmptyElements.Add("col");
_htmlEmptyElements.Add("frame");
_htmlEmptyElements.Add("hr");
_htmlEmptyElements.Add("img");
_htmlEmptyElements.Add("input");
_htmlEmptyElements.Add("isindex");
_htmlEmptyElements.Add("link");
_htmlEmptyElements.Add("meta");
_htmlEmptyElements.Add("param");
}
private static void InitializeOtherOpenableElements()
{
// It is a list of known html elements which we
// want to allow to produce bt HTML parser,
// but don'tt want to act as inline, block or no-scope.
// Presence in this list will allow to open
// elements during html parsing, and adding the
// to a tree produced by html parser.
_htmlOtherOpenableElements = new ArrayList();
_htmlOtherOpenableElements.Add("applet");
_htmlOtherOpenableElements.Add("base");
_htmlOtherOpenableElements.Add("basefont");
_htmlOtherOpenableElements.Add("colgroup");
_htmlOtherOpenableElements.Add("fieldset");
//_htmlOtherOpenableElements.Add("form"); --> treated as block
_htmlOtherOpenableElements.Add("frameset");
_htmlOtherOpenableElements.Add("head");
_htmlOtherOpenableElements.Add("iframe");
_htmlOtherOpenableElements.Add("map");
_htmlOtherOpenableElements.Add("noframes");
_htmlOtherOpenableElements.Add("noscript");
_htmlOtherOpenableElements.Add("object");
_htmlOtherOpenableElements.Add("optgroup");
_htmlOtherOpenableElements.Add("option");
_htmlOtherOpenableElements.Add("script");
_htmlOtherOpenableElements.Add("select");
_htmlOtherOpenableElements.Add("style");
_htmlOtherOpenableElements.Add("title");
}
///
/// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional
/// we assume that for any element for which closing tags are optional, the element closes when it's outer element
/// (in which it is nested) does
///
private static void InitializeElementsClosingOnParentElementEnd()
{
_htmlElementsClosingOnParentElementEnd = new ArrayList();
_htmlElementsClosingOnParentElementEnd.Add("body");
_htmlElementsClosingOnParentElementEnd.Add("colgroup");
_htmlElementsClosingOnParentElementEnd.Add("dd");
_htmlElementsClosingOnParentElementEnd.Add("dt");
_htmlElementsClosingOnParentElementEnd.Add("head");
_htmlElementsClosingOnParentElementEnd.Add("html");
_htmlElementsClosingOnParentElementEnd.Add("li");
_htmlElementsClosingOnParentElementEnd.Add("p");
_htmlElementsClosingOnParentElementEnd.Add("tbody");
_htmlElementsClosingOnParentElementEnd.Add("td");
_htmlElementsClosingOnParentElementEnd.Add("tfoot");
_htmlElementsClosingOnParentElementEnd.Add("thead");
_htmlElementsClosingOnParentElementEnd.Add("th");
_htmlElementsClosingOnParentElementEnd.Add("tr");
}
private static void InitializeElementsClosingOnNewElementStart()
{
_htmlElementsClosingColgroup = new ArrayList();
_htmlElementsClosingColgroup.Add("colgroup");
_htmlElementsClosingColgroup.Add("tr");
_htmlElementsClosingColgroup.Add("thead");
_htmlElementsClosingColgroup.Add("tfoot");
_htmlElementsClosingColgroup.Add("tbody");
_htmlElementsClosingDD = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingDT = new ArrayList();
_htmlElementsClosingDD.Add("dd");
_htmlElementsClosingDD.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingLI = new ArrayList();
_htmlElementsClosingLI.Add("li");
// TODO: more complex recovery
_htmlElementsClosingTbody = new ArrayList();
_htmlElementsClosingTbody.Add("tbody");
_htmlElementsClosingTbody.Add("thead");
_htmlElementsClosingTbody.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTR = new ArrayList();
// NOTE: tr should not really close on a new thead
// because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
// and thead can't come after tbody
// however, if we do encounter this, it's probably best to end the row and ignore the thead or treat
// it as part of the table
_htmlElementsClosingTR.Add("thead");
_htmlElementsClosingTR.Add("tfoot");
_htmlElementsClosingTR.Add("tbody");
_htmlElementsClosingTR.Add("tr");
// TODO: more complex recovery
_htmlElementsClosingTD = new ArrayList();
_htmlElementsClosingTD.Add("td");
_htmlElementsClosingTD.Add("th");
_htmlElementsClosingTD.Add("tr");
_htmlElementsClosingTD.Add("tbody");
_htmlElementsClosingTD.Add("tfoot");
_htmlElementsClosingTD.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingTH = new ArrayList();
_htmlElementsClosingTH.Add("td");
_htmlElementsClosingTH.Add("th");
_htmlElementsClosingTH.Add("tr");
_htmlElementsClosingTH.Add("tbody");
_htmlElementsClosingTH.Add("tfoot");
_htmlElementsClosingTH.Add("thead");
// TODO: more complex recovery
_htmlElementsClosingThead = new ArrayList();
_htmlElementsClosingThead.Add("tbody");
_htmlElementsClosingThead.Add("tfoot");
// TODO: more complex recovery
_htmlElementsClosingTfoot = new ArrayList();
_htmlElementsClosingTfoot.Add("tbody");
// although thead comes before tfoot, we add it because if it is found the tfoot should close
// and some recovery processing be done on the thead
_htmlElementsClosingTfoot.Add("thead");
// TODO: more complex recovery
}
///
/// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
///
private static void InitializeHtmlCharacterEntities()
{
_htmlCharacterEntities = new Hashtable();
_htmlCharacterEntities["Aacute"] = (char)193;
_htmlCharacterEntities["aacute"] = (char)225;
_htmlCharacterEntities["Acirc"] = (char)194;
_htmlCharacterEntities["acirc"] = (char)226;
_htmlCharacterEntities["acute"] = (char)180;
_htmlCharacterEntities["AElig"] = (char)198;
_htmlCharacterEntities["aelig"] = (char)230;
_htmlCharacterEntities["Agrave"] = (char)192;
_htmlCharacterEntities["agrave"] = (char)224;
_htmlCharacterEntities["alefsym"] = (char)8501;
_htmlCharacterEntities["Alpha"] = (char)913;
_htmlCharacterEntities["alpha"] = (char)945;
_htmlCharacterEntities["amp"] = (char)38;
_htmlCharacterEntities["and"] = (char)8743;
_htmlCharacterEntities["ang"] = (char)8736;
_htmlCharacterEntities["Aring"] = (char)197;
_htmlCharacterEntities["aring"] = (char)229;
_htmlCharacterEntities["asymp"] = (char)8776;
_htmlCharacterEntities["Atilde"] = (char)195;
_htmlCharacterEntities["atilde"] = (char)227;
_htmlCharacterEntities["Auml"] = (char)196;
_htmlCharacterEntities["auml"] = (char)228;
_htmlCharacterEntities["bdquo"] = (char)8222;
_htmlCharacterEntities["Beta"] = (char)914;
_htmlCharacterEntities["beta"] = (char)946;
_htmlCharacterEntities["brvbar"] = (char)166;
_htmlCharacterEntities["bull"] = (char)8226;
_htmlCharacterEntities["cap"] = (char)8745;
_htmlCharacterEntities["Ccedil"] = (char)199;
_htmlCharacterEntities["ccedil"] = (char)231;
_htmlCharacterEntities["cent"] = (char)162;
_htmlCharacterEntities["Chi"] = (char)935;
_htmlCharacterEntities["chi"] = (char)967;
_htmlCharacterEntities["circ"] = (char)710;
_htmlCharacterEntities["clubs"] = (char)9827;
_htmlCharacterEntities["cong"] = (char)8773;
_htmlCharacterEntities["copy"] = (char)169;
_htmlCharacterEntities["crarr"] = (char)8629;
_htmlCharacterEntities["cup"] = (char)8746;
_htmlCharacterEntities["curren"] = (char)164;
_htmlCharacterEntities["dagger"] = (char)8224;
_htmlCharacterEntities["Dagger"] = (char)8225;
_htmlCharacterEntities["darr"] = (char)8595;
_htmlCharacterEntities["dArr"] = (char)8659;
_htmlCharacterEntities["deg"] = (char)176;
_htmlCharacterEntities["Delta"] = (char)916;
_htmlCharacterEntities["delta"] = (char)948;
_htmlCharacterEntities["diams"] = (char)9830;
_htmlCharacterEntities["divide"] = (char)247;
_htmlCharacterEntities["Eacute"] = (char)201;
_htmlCharacterEntities["eacute"] = (char)233;
_htmlCharacterEntities["Ecirc"] = (char)202;
_htmlCharacterEntities["ecirc"] = (char)234;
_htmlCharacterEntities["Egrave"] = (char)200;
_htmlCharacterEntities["egrave"] = (char)232;
_htmlCharacterEntities["empty"] = (char)8709;
_htmlCharacterEntities["emsp"] = (char)8195;
_htmlCharacterEntities["ensp"] = (char)8194;
_htmlCharacterEntities["Epsilon"] = (char)917;
_htmlCharacterEntities["epsilon"] = (char)949;
_htmlCharacterEntities["equiv"] = (char)8801;
_htmlCharacterEntities["Eta"] = (char)919;
_htmlCharacterEntities["eta"] = (char)951;
_htmlCharacterEntities["ETH"] = (char)208;
_htmlCharacterEntities["eth"] = (char)240;
_htmlCharacterEntities["Euml"] = (char)203;
_htmlCharacterEntities["euml"] = (char)235;
_htmlCharacterEntities["euro"] = (char)8364;
_htmlCharacterEntities["exist"] = (char)8707;
_htmlCharacterEntities["fnof"] = (char)402;
_htmlCharacterEntities["forall"] = (char)8704;
_htmlCharacterEntities["frac12"] = (char)189;
_htmlCharacterEntities["frac14"] = (char)188;
_htmlCharacterEntities["frac34"] = (char)190;
_htmlCharacterEntities["frasl"] = (char)8260;
_htmlCharacterEntities["Gamma"] = (char)915;
_htmlCharacterEntities["gamma"] = (char)947;
_htmlCharacterEntities["ge"] = (char)8805;
_htmlCharacterEntities["gt"] = (char)62;
_htmlCharacterEntities["harr"] = (char)8596;
_htmlCharacterEntities["hArr"] = (char)8660;
_htmlCharacterEntities["hearts"] = (char)9829;
_htmlCharacterEntities["hellip"] = (char)8230;
_htmlCharacterEntities["Iacute"] = (char)205;
_htmlCharacterEntities["iacute"] = (char)237;
_htmlCharacterEntities["Icirc"] = (char)206;
_htmlCharacterEntities["icirc"] = (char)238;
_htmlCharacterEntities["iexcl"] = (char)161;
_htmlCharacterEntities["Igrave"] = (char)204;
_htmlCharacterEntities["igrave"] = (char)236;
_htmlCharacterEntities["image"] = (char)8465;
_htmlCharacterEntities["infin"] = (char)8734;
_htmlCharacterEntities["int"] = (char)8747;
_htmlCharacterEntities["Iota"] = (char)921;
_htmlCharacterEntities["iota"] = (char)953;
_htmlCharacterEntities["iquest"] = (char)191;
_htmlCharacterEntities["isin"] = (char)8712;
_htmlCharacterEntities["Iuml"] = (char)207;
_htmlCharacterEntities["iuml"] = (char)239;
_htmlCharacterEntities["Kappa"] = (char)922;
_htmlCharacterEntities["kappa"] = (char)954;
_htmlCharacterEntities["Lambda"] = (char)923;
_htmlCharacterEntities["lambda"] = (char)955;
_htmlCharacterEntities["lang"] = (char)9001;
_htmlCharacterEntities["laquo"] = (char)171;
_htmlCharacterEntities["larr"] = (char)8592;
_htmlCharacterEntities["lArr"] = (char)8656;
_htmlCharacterEntities["lceil"] = (char)8968;
_htmlCharacterEntities["ldquo"] = (char)8220;
_htmlCharacterEntities["le"] = (char)8804;
_htmlCharacterEntities["lfloor"] = (char)8970;
_htmlCharacterEntities["lowast"] = (char)8727;
_htmlCharacterEntities["loz"] = (char)9674;
_htmlCharacterEntities["lrm"] = (char)8206;
_htmlCharacterEntities["lsaquo"] = (char)8249;
_htmlCharacterEntities["lsquo"] = (char)8216;
_htmlCharacterEntities["lt"] = (char)60;
_htmlCharacterEntities["macr"] = (char)175;
_htmlCharacterEntities["mdash"] = (char)8212;
_htmlCharacterEntities["micro"] = (char)181;
_htmlCharacterEntities["middot"] = (char)183;
_htmlCharacterEntities["minus"] = (char)8722;
_htmlCharacterEntities["Mu"] = (char)924;
_htmlCharacterEntities["mu"] = (char)956;
_htmlCharacterEntities["nabla"] = (char)8711;
_htmlCharacterEntities["nbsp"] = (char)160;
_htmlCharacterEntities["ndash"] = (char)8211;
_htmlCharacterEntities["ne"] = (char)8800;
_htmlCharacterEntities["ni"] = (char)8715;
_htmlCharacterEntities["not"] = (char)172;
_htmlCharacterEntities["notin"] = (char)8713;
_htmlCharacterEntities["nsub"] = (char)8836;
_htmlCharacterEntities["Ntilde"] = (char)209;
_htmlCharacterEntities["ntilde"] = (char)241;
_htmlCharacterEntities["Nu"] = (char)925;
_htmlCharacterEntities["nu"] = (char)957;
_htmlCharacterEntities["Oacute"] = (char)211;
_htmlCharacterEntities["ocirc"] = (char)244;
_htmlCharacterEntities["OElig"] = (char)338;
_htmlCharacterEntities["oelig"] = (char)339;
_htmlCharacterEntities["Ograve"] = (char)210;
_htmlCharacterEntities["ograve"] = (char)242;
_htmlCharacterEntities["oline"] = (char)8254;
_htmlCharacterEntities["Omega"] = (char)937;
_htmlCharacterEntities["omega"] = (char)969;
_htmlCharacterEntities["Omicron"] = (char)927;
_htmlCharacterEntities["omicron"] = (char)959;
_htmlCharacterEntities["oplus"] = (char)8853;
_htmlCharacterEntities["or"] = (char)8744;
_htmlCharacterEntities["ordf"] = (char)170;
_htmlCharacterEntities["ordm"] = (char)186;
_htmlCharacterEntities["Oslash"] = (char)216;
_htmlCharacterEntities["oslash"] = (char)248;
_htmlCharacterEntities["Otilde"] = (char)213;
_htmlCharacterEntities["otilde"] = (char)245;
_htmlCharacterEntities["otimes"] = (char)8855;
_htmlCharacterEntities["Ouml"] = (char)214;
_htmlCharacterEntities["ouml"] = (char)246;
_htmlCharacterEntities["para"] = (char)182;
_htmlCharacterEntities["part"] = (char)8706;
_htmlCharacterEntities["permil"] = (char)8240;
_htmlCharacterEntities["perp"] = (char)8869;
_htmlCharacterEntities["Phi"] = (char)934;
_htmlCharacterEntities["phi"] = (char)966;
_htmlCharacterEntities["pi"] = (char)960;
_htmlCharacterEntities["piv"] = (char)982;
_htmlCharacterEntities["plusmn"] = (char)177;
_htmlCharacterEntities["pound"] = (char)163;
_htmlCharacterEntities["prime"] = (char)8242;
_htmlCharacterEntities["Prime"] = (char)8243;
_htmlCharacterEntities["prod"] = (char)8719;
_htmlCharacterEntities["prop"] = (char)8733;
_htmlCharacterEntities["Psi"] = (char)936;
_htmlCharacterEntities["psi"] = (char)968;
_htmlCharacterEntities["quot"] = (char)34;
_htmlCharacterEntities["radic"] = (char)8730;
_htmlCharacterEntities["rang"] = (char)9002;
_htmlCharacterEntities["raquo"] = (char)187;
_htmlCharacterEntities["rarr"] = (char)8594;
_htmlCharacterEntities["rArr"] = (char)8658;
_htmlCharacterEntities["rceil"] = (char)8969;
_htmlCharacterEntities["rdquo"] = (char)8221;
_htmlCharacterEntities["real"] = (char)8476;
_htmlCharacterEntities["reg"] = (char)174;
_htmlCharacterEntities["rfloor"] = (char)8971;
_htmlCharacterEntities["Rho"] = (char)929;
_htmlCharacterEntities["rho"] = (char)961;
_htmlCharacterEntities["rlm"] = (char)8207;
_htmlCharacterEntities["rsaquo"] = (char)8250;
_htmlCharacterEntities["rsquo"] = (char)8217;
_htmlCharacterEntities["sbquo"] = (char)8218;
_htmlCharacterEntities["Scaron"] = (char)352;
_htmlCharacterEntities["scaron"] = (char)353;
_htmlCharacterEntities["sdot"] = (char)8901;
_htmlCharacterEntities["sect"] = (char)167;
_htmlCharacterEntities["shy"] = (char)173;
_htmlCharacterEntities["Sigma"] = (char)931;
_htmlCharacterEntities["sigma"] = (char)963;
_htmlCharacterEntities["sigmaf"] = (char)962;
_htmlCharacterEntities["sim"] = (char)8764;
_htmlCharacterEntities["spades"] = (char)9824;
_htmlCharacterEntities["sub"] = (char)8834;
_htmlCharacterEntities["sube"] = (char)8838;
_htmlCharacterEntities["sum"] = (char)8721;
_htmlCharacterEntities["sup"] = (char)8835;
_htmlCharacterEntities["sup1"] = (char)185;
_htmlCharacterEntities["sup2"] = (char)178;
_htmlCharacterEntities["sup3"] = (char)179;
_htmlCharacterEntities["supe"] = (char)8839;
_htmlCharacterEntities["szlig"] = (char)223;
_htmlCharacterEntities["Tau"] = (char)932;
_htmlCharacterEntities["tau"] = (char)964;
_htmlCharacterEntities["there4"] = (char)8756;
_htmlCharacterEntities["Theta"] = (char)920;
_htmlCharacterEntities["theta"] = (char)952;
_htmlCharacterEntities["thetasym"] = (char)977;
_htmlCharacterEntities["thinsp"] = (char)8201;
_htmlCharacterEntities["THORN"] = (char)222;
_htmlCharacterEntities["thorn"] = (char)254;
_htmlCharacterEntities["tilde"] = (char)732;
_htmlCharacterEntities["times"] = (char)215;
_htmlCharacterEntities["trade"] = (char)8482;
_htmlCharacterEntities["Uacute"] = (char)218;
_htmlCharacterEntities["uacute"] = (char)250;
_htmlCharacterEntities["uarr"] = (char)8593;
_htmlCharacterEntities["uArr"] = (char)8657;
_htmlCharacterEntities["Ucirc"] = (char)219;
_htmlCharacterEntities["ucirc"] = (char)251;
_htmlCharacterEntities["Ugrave"] = (char)217;
_htmlCharacterEntities["ugrave"] = (char)249;
_htmlCharacterEntities["uml"] = (char)168;
_htmlCharacterEntities["upsih"] = (char)978;
_htmlCharacterEntities["Upsilon"] = (char)933;
_htmlCharacterEntities["upsilon"] = (char)965;
_htmlCharacterEntities["Uuml"] = (char)220;
_htmlCharacterEntities["uuml"] = (char)252;
_htmlCharacterEntities["weierp"] = (char)8472;
_htmlCharacterEntities["Xi"] = (char)926;
_htmlCharacterEntities["xi"] = (char)958;
_htmlCharacterEntities["Yacute"] = (char)221;
_htmlCharacterEntities["yacute"] = (char)253;
_htmlCharacterEntities["yen"] = (char)165;
_htmlCharacterEntities["Yuml"] = (char)376;
_htmlCharacterEntities["yuml"] = (char)255;
_htmlCharacterEntities["Zeta"] = (char)918;
_htmlCharacterEntities["zeta"] = (char)950;
_htmlCharacterEntities["zwj"] = (char)8205;
_htmlCharacterEntities["zwnj"] = (char)8204;
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
// html element names
// this is an array list now, but we may want to make it a hashtable later for better performance
private static ArrayList _htmlInlineElements;
private static ArrayList _htmlBlockElements;
private static ArrayList _htmlOtherOpenableElements;
// list of html empty element names
private static ArrayList _htmlEmptyElements;
// names of html elements for which closing tags are optional, and close when the outer nested element closes
private static ArrayList _htmlElementsClosingOnParentElementEnd;
// names of elements that close certain optional closing tag elements when they start
// names of elements closing the colgroup element
private static ArrayList _htmlElementsClosingColgroup;
// names of elements closing the dd element
private static ArrayList _htmlElementsClosingDD;
// names of elements closing the dt element
private static ArrayList _htmlElementsClosingDT;
// names of elements closing the li element
private static ArrayList _htmlElementsClosingLI;
// names of elements closing the tbody element
private static ArrayList _htmlElementsClosingTbody;
// names of elements closing the td element
private static ArrayList _htmlElementsClosingTD;
// names of elements closing the tfoot element
private static ArrayList _htmlElementsClosingTfoot;
// names of elements closing the thead element
private static ArrayList _htmlElementsClosingThead;
// names of elements closing the th element
private static ArrayList _htmlElementsClosingTH;
// names of elements closing the tr element
private static ArrayList _htmlElementsClosingTR;
// html character entities hashtable
private static Hashtable _htmlCharacterEntities;
#endregion Private Fields
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlToXamlConverter.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Html - Xaml conversion
//
//---------------------------------------------------------------------------
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Globalization;
namespace WpfRichText
{
///
/// HtmlToXamlConverter is a static class that takes an HTML string
/// and converts it into XAML
///
public static class HtmlToXamlConverter
{
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
///
/// Converts an html string into xaml string.
///
///
/// Input html which may be badly formated xml.
///
///
/// true indicates that we need a FlowDocument as a root element;
/// false means that Section or Span elements will be used
/// dependeing on StartFragment/EndFragment comments locations.
///
///
/// Well-formed xml representing XAML equivalent for the input html string.
///
public static string ConvertHtmlToXaml(string htmlString, bool asFlowDocument)
{
// Create well-formed Xml from Html string
XmlElement htmlElement = HtmlParser.ParseHtml(htmlString);
// Decide what name to use as a root
string rootElementName = asFlowDocument ? HtmlToXamlConverter.XamlFlowDocument : HtmlToXamlConverter.XamlSection;
// Create an XmlDocument for generated xaml
XmlDocument xamlTree = new XmlDocument();
XmlElement xamlFlowDocumentElement = xamlTree.CreateElement(null, rootElementName, _xamlNamespace);
// Extract style definitions from all STYLE elements in the document
CssStylesheet stylesheet = new CssStylesheet(htmlElement);
// Source context is a stack of all elements - ancestors of a parentElement
List sourceContext = new List(10);
// Clear fragment parent
InlineFragmentParentElement = null;
// convert root html element
AddBlock(xamlFlowDocumentElement, htmlElement, new Hashtable(), stylesheet, sourceContext);
// In case if the selected fragment is inline, extract it into a separate Span wrapper
if (!asFlowDocument)
{
xamlFlowDocumentElement = ExtractInlineFragment(xamlFlowDocumentElement);
}
// Return a string representing resulting Xaml
xamlFlowDocumentElement.SetAttribute("xml:space", "preserve");
string xaml = xamlFlowDocumentElement.OuterXml;
return xaml;
}
///
/// Returns a value for an attribute by its name (ignoring casing)
///
///
/// XmlElement in which we are trying to find the specified attribute
///
///
/// String representing the attribute name to be searched for
///
///
internal static string GetAttribute(XmlElement element, string attributeName)
{
if (!String.IsNullOrEmpty(attributeName) && element != null)
{
attributeName = attributeName.ToLower(CultureInfo.InvariantCulture);
foreach (XmlAttribute item in element.Attributes)
if (item.Name.ToLower(CultureInfo.InvariantCulture) == attributeName)
return item.Value;
//for (int i = 0; i < element.Attributes.Count; i++)
//{
// if (element.Attributes[i].Name.ToLower(CultureInfo.InvariantCulture) == attributeName)
// {
// return element.Attributes[i].Value;
// }
//}
}
return null;
}
///
/// Returns string extracted from quotation marks
///
///
/// String representing value enclosed in quotation marks
///
internal static string UnQuote(string value)
{
if (value.StartsWith("\"", StringComparison.OrdinalIgnoreCase) && value.EndsWith("\"", StringComparison.OrdinalIgnoreCase) || value.StartsWith("'", StringComparison.OrdinalIgnoreCase) && value.EndsWith("'", StringComparison.OrdinalIgnoreCase))
{
value = value.Substring(1, value.Length - 2).Trim();
}
return value;
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
///
/// Analyzes the given htmlElement expecting it to be converted
/// into some of xaml Block elements and adds the converted block
/// to the children collection of xamlParentElement.
///
/// Analyzes the given XmlElement htmlElement, recognizes it as some HTML element
/// and adds it as a child to a xamlParentElement.
/// In some cases several following siblings of the given htmlElement
/// will be consumed too (e.g. LIs encountered without wrapping UL/OL,
/// which must be collected together and wrapped into one implicit List element).
///
///
/// Parent xaml element, to which new converted element will be added
///
///
/// Source html element subject to convert to xaml.
///
///
/// Properties inherited from an outer context.
///
///
///
///
/// Last processed html node. Normally it should be the same htmlElement
/// as was passed as a paramater, but in some irregular cases
/// it could one of its following siblings.
/// The caller must use this node to get to next sibling from it.
///
private static XmlNode AddBlock(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
if (htmlNode is XmlComment)
{
DefineInlineFragmentParent((XmlComment)htmlNode, /*xamlParentElement:*/null);
}
else if (htmlNode is XmlText)
{
htmlNode = AddImplicitParagraph(xamlParentElement, htmlNode, inheritedProperties, stylesheet, sourceContext);
}
else if (htmlNode is XmlElement)
{
// Identify element name
XmlElement htmlElement = (XmlElement)htmlNode;
string htmlElementName = htmlElement.LocalName; // Keep the name case-sensitive to check xml names
string htmlElementNamespace = htmlElement.NamespaceURI;
if (htmlElementNamespace != HtmlParser.XhtmlNamespace)
{
// Non-html element. skip it
// Isn't it too agressive? What if this is just an error in html tag name?
// TODO: Consider skipping just a wparrer in recursing into the element tree,
// which may produce some garbage though coming from xml fragments.
return htmlElement;
}
// Put source element to the stack
sourceContext.Add(htmlElement);
// Convert the name to lowercase, because html elements are case-insensitive
htmlElementName = htmlElementName.ToLower(CultureInfo.InvariantCulture);
// Switch to an appropriate kind of processing depending on html element name
switch (htmlElementName)
{
// Sections:
case "html":
case "body":
case "div":
case "form": // not a block according to xhtml spec
case "pre": // Renders text in a fixed-width font
case "blockquote":
case "caption":
case "center":
case "cite":
AddSection(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
// Paragraphs:
case "p":
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
case "nsrtitle":
case "textarea":
case "dd": // ???
case "dl": // ???
case "dt": // ???
case "tt": // ???
AddParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "ol":
case "ul":
case "dir": // treat as UL element
case "menu": // treat as UL element
// List element conversion
AddList(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "li":
// LI outside of OL/UL
// Collect all sibling LIs, wrap them into a List and then proceed with the element following the last of LIs
htmlNode = AddOrphanListItems(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "img":
// TODO: Add image processing
AddImage(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "table":
// hand off to table parsing function which will perform special table syntax checks
AddTable(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "tbody":
case "tfoot":
case "thead":
case "tr":
case "td":
case "th":
// Table stuff without table wrapper
// TODO: add special-case processing here for elements that should be within tables when the
// parent element is NOT a table. If the parent element is a table they can be processed normally.
// we need to compare against the parent element here, we can't just break on a switch
goto default; // Thus we will skip this element as unknown, but still recurse into it.
case "style": // We already pre-processed all style elements. Ignore it now
case "meta":
case "head":
case "title":
case "script":
// Ignore these elements
break;
default:
// Wrap a sequence of inlines into an implicit paragraph
htmlNode = AddImplicitParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
}
// Remove the element from the stack
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlElement);
sourceContext.RemoveAt(sourceContext.Count - 1);
}
// Return last processed node
return htmlNode;
}
// .............................................................
//
// Line Breaks
//
// .............................................................
private static void AddBreak(XmlElement xamlParentElement, string htmlElementName)
{
// Create new xaml element corresponding to this html element
XmlElement xamlLineBreak = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_LineBreak, _xamlNamespace);
xamlParentElement.AppendChild(xamlLineBreak);
if (htmlElementName == "hr")
{
XmlText xamlHorizontalLine = xamlParentElement.OwnerDocument.CreateTextNode("----------------------");
xamlParentElement.AppendChild(xamlHorizontalLine);
xamlLineBreak = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_LineBreak, _xamlNamespace);
xamlParentElement.AppendChild(xamlLineBreak);
}
}
// .............................................................
//
// Text Flow Elements
//
// .............................................................
///
/// Generates Section or Paragraph element from DIV depending whether it contains any block elements or not
///
///
/// XmlElement representing Xaml parent to which the converted element should be added
///
///
/// XmlElement representing Html element to be converted
///
///
/// properties inherited from parent context
///
///
///
/// true indicates that a content added by this call contains at least one block element
///
private static void AddSection(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Analyze the content of htmlElement to decide what xaml element to choose - Section or Paragraph.
// If this Div has at least one block child then we need to use Section, otherwise use Paragraph
bool htmlElementContainsBlocks = false;
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement)
{
string htmlChildName = ((XmlElement)htmlChildNode).LocalName.ToLower(CultureInfo.InvariantCulture);
if (HtmlSchema.IsBlockElement(htmlChildName))
{
htmlElementContainsBlocks = true;
break;
}
}
}
if (!htmlElementContainsBlocks)
{
// The Div does not contain any block elements, so we can treat it as a Paragraph
AddParagraph(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
}
else
{
// The Div has some nested blocks, so we treat it as a Section
// Create currentProperties as a compilation of local and inheritedProperties, set localProperties
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// Create a XAML element corresponding to this html element
XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.XamlSection, _xamlNamespace);
ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/true);
// Decide whether we can unwrap this element as not having any formatting significance.
if (!xamlElement.HasAttributes)
{
// This elements is a group of block elements whitout any additional formatting.
// We can add blocks directly to xamlParentElement and avoid
// creating unnecessary Sections nesting.
xamlElement = xamlParentElement;
}
// Recurse into element subtree
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null)
{
htmlChildNode = AddBlock(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
// Add the new element to the parent.
if (xamlElement != xamlParentElement)
{
xamlParentElement.AppendChild(xamlElement);
}
}
}
///
/// Generates Paragraph element from P, H1-H7, Center etc.
///
///
/// XmlElement representing Xaml parent to which the converted element should be added
///
///
/// XmlElement representing Html element to be converted
///
///
/// properties inherited from parent context
///
///
///
/// true indicates that a content added by this call contains at least one block element
///
private static void AddParagraph(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Create currentProperties as a compilation of local and inheritedProperties, set localProperties
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// Create a XAML element corresponding to this html element
XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Paragraph, _xamlNamespace);
ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/true);
// Recurse into element subtree
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
// Add the new element to the parent.
xamlParentElement.AppendChild(xamlElement);
}
///
/// Creates a Paragraph element and adds all nodes starting from htmlNode
/// converted to appropriate Inlines.
///
///
/// XmlElement representing Xaml parent to which the converted element should be added
///
///
/// XmlNode starting a collection of implicitly wrapped inlines.
///
///
/// properties inherited from parent context
///
///
///
/// true indicates that a content added by this call contains at least one block element
///
///
/// The last htmlNode added to the implicit paragraph
///
private static XmlNode AddImplicitParagraph(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Collect all non-block elements and wrap them into implicit Paragraph
XmlElement xamlParagraph = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.Xaml_Paragraph, _xamlNamespace);
XmlNode lastNodeProcessed = null;
while (htmlNode != null)
{
if (htmlNode is XmlComment)
{
DefineInlineFragmentParent((XmlComment)htmlNode, /*xamlParentElement:*/null);
}
else if (htmlNode is XmlText)
{
if (htmlNode.Value.Trim().Length > 0)
{
AddTextRun(xamlParagraph, htmlNode.Value);
}
}
else if (htmlNode is XmlElement)
{
string htmlChildName = ((XmlElement)htmlNode).LocalName.ToLower(CultureInfo.InvariantCulture);
if (HtmlSchema.IsBlockElement(htmlChildName))
{
// The sequence of non-blocked inlines ended. Stop implicit loop here.
break;
}
else
{
AddInline(xamlParagraph, (XmlElement)htmlNode, inheritedProperties, stylesheet, sourceContext);
}
}
// Store last processed node to return it at the end
lastNodeProcessed = htmlNode;
htmlNode = htmlNode.NextSibling;
}
// Add the Paragraph to the parent
// If only whitespaces and commens have been encountered,
// then we have nothing to add in implicit paragraph; forget it.
if (xamlParagraph.FirstChild != null)
{
xamlParentElement.AppendChild(xamlParagraph);
}
// Need to return last processed node
return lastNodeProcessed;
}
// .............................................................
//
// Inline Elements
//
// .............................................................
private static void AddInline(XmlElement xamlParentElement, XmlNode htmlNode, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
if (htmlNode is XmlComment)
{
DefineInlineFragmentParent((XmlComment)htmlNode, xamlParentElement);
}
else if (htmlNode is XmlText)
{
AddTextRun(xamlParentElement, htmlNode.Value);
}
else if (htmlNode is XmlElement)
{
XmlElement htmlElement = (XmlElement)htmlNode;
// Check whether this is an html element
if (htmlElement.NamespaceURI != HtmlParser.XhtmlNamespace)
{
return; // Skip non-html elements
}
// Identify element name
string htmlElementName = htmlElement.LocalName.ToLower(CultureInfo.InvariantCulture);
// Put source element to the stack
sourceContext.Add(htmlElement);
switch (htmlElementName)
{
case "a":
AddHyperlink(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "img":
AddImage(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
break;
case "br":
case "hr":
AddBreak(xamlParentElement, htmlElementName);
break;
default:
if (HtmlSchema.IsInlineElement(htmlElementName) || HtmlSchema.IsBlockElement(htmlElementName))
{
// Note: actually we do not expect block elements here,
// but if it happens to be here, we will treat it as a Span.
AddSpanOrRun(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
}
break;
}
// Ignore all other elements non-(block/inline/image)
// Remove the element from the stack
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlElement);
sourceContext.RemoveAt(sourceContext.Count - 1);
}
}
private static void AddSpanOrRun(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Decide what XAML element to use for this inline element.
// Check whether it contains any nested inlines
bool elementHasChildren = false;
for (XmlNode htmlNode = htmlElement.FirstChild; htmlNode != null; htmlNode = htmlNode.NextSibling)
{
if (htmlNode is XmlElement)
{
string htmlChildName = ((XmlElement)htmlNode).LocalName.ToLower(CultureInfo.InvariantCulture);
if (HtmlSchema.IsInlineElement(htmlChildName) || HtmlSchema.IsBlockElement(htmlChildName) ||
htmlChildName == "img" || htmlChildName == "br" || htmlChildName == "hr")
{
elementHasChildren = true;
break;
}
}
}
string xamlElementName = elementHasChildren ? HtmlToXamlConverter.XamlSpan : HtmlToXamlConverter.XamlRun;
// Create currentProperties as a compilation of local and inheritedProperties, set localProperties
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// Create a XAML element corresponding to this html element
XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/xamlElementName, _xamlNamespace);
ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/false);
// Recurse into element subtree
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
// Add the new element to the parent.
xamlParentElement.AppendChild(xamlElement);
}
// Adds a text run to a xaml tree
private static void AddTextRun(XmlElement xamlElement, string textData)
{
// Remove control characters
for (int i = 0; i < textData.Length; i++)
{
if (Char.IsControl(textData[i]))
{
textData = textData.Remove(i--, 1); // decrement i to compensate for character removal
}
}
// Replace No-Breaks by spaces (160 is a code of entity in html)
// This is a work around the bug in Avalon which does not render nbsp.
textData = textData.Replace((char)160, ' ');
if (textData.Length > 0)
{
xamlElement.AppendChild(xamlElement.OwnerDocument.CreateTextNode(textData));
}
}
private static void AddHyperlink(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Convert href attribute into NavigateUri and TargetName
string href = GetAttribute(htmlElement, "href");
if (href == null)
{
// When href attribute is missing - ignore the hyperlink
AddSpanOrRun(xamlParentElement, htmlElement, inheritedProperties, stylesheet, sourceContext);
}
else
{
// Create currentProperties as a compilation of local and inheritedProperties, set localProperties
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// Create a XAML element corresponding to this html element
XmlElement xamlElement = xamlParentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.XamlHyperlink, _xamlNamespace);
ApplyLocalProperties(xamlElement, localProperties, /*isBlock:*/false);
string[] hrefParts = href.Split(new char[] { '#' });
if (hrefParts.Length > 0 && hrefParts[0].Trim().Length > 0)
{
xamlElement.SetAttribute(HtmlToXamlConverter.XamlHyperlinkNavigateUri, hrefParts[0].Trim());
}
if (hrefParts.Length == 2 && hrefParts[1].Trim().Length > 0)
{
xamlElement.SetAttribute(HtmlToXamlConverter.XamlHyperlinkTargetName, hrefParts[1].Trim());
}
// Recurse into element subtree
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
AddInline(xamlElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
// Add the new element to the parent.
xamlParentElement.AppendChild(xamlElement);
}
}
// Stores a parent xaml element for the case when selected fragment is inline.
private static XmlElement InlineFragmentParentElement;
// Called when html comment is encountered to store a parent element
// for the case when the fragment is inline - to extract it to a separate
// Span wrapper after the conversion.
private static void DefineInlineFragmentParent(XmlComment htmlComment, XmlElement xamlParentElement)
{
if (htmlComment.Value == "StartFragment")
{
InlineFragmentParentElement = xamlParentElement;
}
else if (htmlComment.Value == "EndFragment")
{
if (InlineFragmentParentElement == null && xamlParentElement != null)
{
// Normally this cannot happen if comments produced by correct copying code
// in Word or IE, but when it is produced manually then fragment boundary
// markers can be inconsistent. In this case StartFragment takes precedence,
// but if it is not set, then we get the value from EndFragment marker.
InlineFragmentParentElement = xamlParentElement;
}
}
}
// Extracts a content of an element stored as InlineFragmentParentElement
// into a separate Span wrapper.
// Note: when selected content does not cross paragraph boundaries,
// the fragment is marked within
private static XmlElement ExtractInlineFragment(XmlElement xamlFlowDocumentElement)
{
if (InlineFragmentParentElement != null)
{
if (InlineFragmentParentElement.LocalName == HtmlToXamlConverter.XamlSpan)
{
xamlFlowDocumentElement = InlineFragmentParentElement;
}
else
{
xamlFlowDocumentElement = xamlFlowDocumentElement.OwnerDocument.CreateElement(/*prefix:*/null, /*localName:*/HtmlToXamlConverter.XamlSpan, _xamlNamespace);
while (InlineFragmentParentElement.FirstChild != null)
{
XmlNode copyNode = InlineFragmentParentElement.FirstChild;
InlineFragmentParentElement.RemoveChild(copyNode);
xamlFlowDocumentElement.AppendChild(copyNode);
}
}
}
return xamlFlowDocumentElement;
}
// .............................................................
//
// Images
//
// .............................................................
private static void AddImage(XmlElement xamlParentElement, XmlElement htmlElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Implement images
}
// .............................................................
//
// Lists
//
// .............................................................
///
/// Converts Html ul or ol element into Xaml list element. During conversion if the ul/ol element has any children
/// that are not li elements, they are ignored and not added to the list element
///
///
/// XmlElement representing Xaml parent to which the converted element should be added
///
///
/// XmlElement representing Html ul/ol element to be converted
///
///
/// properties inherited from parent context
///
///
///
private static void AddList(XmlElement xamlParentElement, XmlElement htmlListElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
string htmlListElementName = htmlListElement.LocalName.ToLower(CultureInfo.InvariantCulture);
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlListElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// Create Xaml List element
XmlElement xamlListElement = xamlParentElement.OwnerDocument.CreateElement(null, XamlList, _xamlNamespace);
// Set default list markers
if (htmlListElementName == "ol")
{
// Ordered list
xamlListElement.SetAttribute(HtmlToXamlConverter.XamlListMarkerStyle, Xaml_List_MarkerStyle_Decimal);
}
else
{
// Unordered list - all elements other than OL treated as unordered lists
xamlListElement.SetAttribute(HtmlToXamlConverter.XamlListMarkerStyle, Xaml_List_MarkerStyle_Disc);
}
// Apply local properties to list to set marker attribute if specified
// TODO: Should we have separate list attribute processing function?
ApplyLocalProperties(xamlListElement, localProperties, /*isBlock:*/true);
// Recurse into list subtree
for (XmlNode htmlChildNode = htmlListElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "li")
{
sourceContext.Add((XmlElement)htmlChildNode);
AddListItem(xamlListElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext);
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);
}
else
{
// Not an li element. Add it to previous ListBoxItem
// We need to append the content to the end
// of a previous list item.
}
}
// Add the List element to xaml tree - if it is not empty
if (xamlListElement.HasChildNodes)
{
xamlParentElement.AppendChild(xamlListElement);
}
}
///
/// If li items are found without a parent ul/ol element in Html string, creates xamlListElement as their parent and adds
/// them to it. If the previously added node to the same xamlParentElement was a List, adds the elements to that list.
/// Otherwise, we create a new xamlListElement and add them to it. Elements are added as long as li elements appear sequentially.
/// The first non-li or text node stops the addition.
///
///
/// Parent element for the list
///
///
/// Start Html li element without parent list
///
///
/// Properties inherited from parent context
///
///
///
///
/// XmlNode representing the first non-li node in the input after one or more li's have been processed.
///
private static XmlElement AddOrphanListItems(XmlElement xamlParentElement, XmlElement htmlLIElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
Debug.Assert(htmlLIElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "li");
XmlElement lastProcessedListItemElement = null;
// Find out the last element attached to the xamlParentElement, which is the previous sibling of this node
XmlNode xamlListItemElementPreviousSibling = xamlParentElement.LastChild;
XmlElement xamlListElement;
if (xamlListItemElementPreviousSibling != null && xamlListItemElementPreviousSibling.LocalName == XamlList)
{
// Previously added Xaml element was a list. We will add the new li to it
xamlListElement = (XmlElement)xamlListItemElementPreviousSibling;
}
else
{
// No list element near. Create our own.
xamlListElement = xamlParentElement.OwnerDocument.CreateElement(null, XamlList, _xamlNamespace);
xamlParentElement.AppendChild(xamlListElement);
}
XmlNode htmlChildNode = htmlLIElement;
string htmlChildNodeName = htmlChildNode == null ? null : htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture);
// Current element properties missed here.
//currentProperties = GetElementProperties(htmlLIElement, inheritedProperties, out localProperties, stylesheet);
// Add li elements to the parent xamlListElement we created as long as they appear sequentially
// Use properties inherited from xamlParentElement for context
while (htmlChildNode != null && htmlChildNodeName == "li")
{
AddListItem(xamlListElement, (XmlElement)htmlChildNode, inheritedProperties, stylesheet, sourceContext);
lastProcessedListItemElement = (XmlElement)htmlChildNode;
htmlChildNode = htmlChildNode.NextSibling;
htmlChildNodeName = htmlChildNode == null ? null : htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture);
}
return lastProcessedListItemElement;
}
///
/// Converts htmlLIElement into Xaml ListItem element, and appends it to the parent xamlListElement
///
///
/// XmlElement representing Xaml List element to which the converted td/th should be added
///
///
/// XmlElement representing Html li element to be converted
///
///
/// Properties inherited from parent context
///
///
///
private static void AddListItem(XmlElement xamlListElement, XmlElement htmlLIElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Parameter validation
Debug.Assert(xamlListElement != null);
Debug.Assert(xamlListElement.LocalName == XamlList);
Debug.Assert(htmlLIElement != null);
Debug.Assert(htmlLIElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "li");
Debug.Assert(inheritedProperties != null);
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlLIElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
XmlElement xamlListItemElement = xamlListElement.OwnerDocument.CreateElement(null, Xaml_ListItem, _xamlNamespace);
// TODO: process local properties for li element
// Process children of the ListItem
for (XmlNode htmlChildNode = htmlLIElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null)
{
htmlChildNode = AddBlock(xamlListItemElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
// Add resulting ListBoxItem to a xaml parent
xamlListElement.AppendChild(xamlListItemElement);
}
// .............................................................
//
// Tables
//
// .............................................................
///
/// Converts htmlTableElement to a Xaml Table element. Adds tbody elements if they are missing so
/// that a resulting Xaml Table element is properly formed.
///
///
/// Parent xaml element to which a converted table must be added.
///
///
/// XmlElement reprsenting the Html table element to be converted
///
///
/// Hashtable representing properties inherited from parent context.
///
///
///
private static void AddTable(XmlElement xamlParentElement, XmlElement htmlTableElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
// Parameter validation
Debug.Assert(htmlTableElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "table");
Debug.Assert(xamlParentElement != null);
Debug.Assert(inheritedProperties != null);
// Create current properties to be used by children as inherited properties, set local properties
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlTableElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// TODO: process localProperties for tables to override defaults, decide cell spacing defaults
// Check if the table contains only one cell - we want to take only its content
XmlElement singleCell = GetCellFromSingleCellTable(htmlTableElement);
if (singleCell != null)
{
// Need to push skipped table elements onto sourceContext
sourceContext.Add(singleCell);
// Add the cell's content directly to parent
for (XmlNode htmlChildNode = singleCell.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null)
{
htmlChildNode = AddBlock(xamlParentElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == singleCell);
sourceContext.RemoveAt(sourceContext.Count - 1);
}
else
{
// Create xamlTableElement
XmlElement xamlTableElement = xamlParentElement.OwnerDocument.CreateElement(null, Xaml_Table, _xamlNamespace);
// Analyze table structure for column widths and rowspan attributes
ArrayList columnStarts = AnalyzeTableStructure(htmlTableElement, stylesheet);
// Process COLGROUP & COL elements
AddColumnInformation(htmlTableElement, xamlTableElement, columnStarts, currentProperties, stylesheet, sourceContext);
// Process table body - TBODY and TR elements
XmlNode htmlChildNode = htmlTableElement.FirstChild;
while (htmlChildNode != null)
{
string htmlChildName = htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture);
// Process the element
if (htmlChildName == "tbody" || htmlChildName == "thead" || htmlChildName == "tfoot")
{
// Add more special processing for TableHeader and TableFooter
XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableRowGroup, _xamlNamespace);
xamlTableElement.AppendChild(xamlTableBodyElement);
sourceContext.Add((XmlElement)htmlChildNode);
// Get properties of Html tbody element
Hashtable tbodyElementLocalProperties;
Hashtable tbodyElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tbodyElementLocalProperties, stylesheet, sourceContext);
// TODO: apply local properties for tbody
// Process children of htmlChildNode, which is tbody, for tr elements
AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode.FirstChild, tbodyElementCurrentProperties, columnStarts, stylesheet, sourceContext);
if (xamlTableBodyElement.HasChildNodes)
{
xamlTableElement.AppendChild(xamlTableBodyElement);
// else: if there is no TRs in this TBody, we simply ignore it
}
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);
htmlChildNode = htmlChildNode.NextSibling;
}
else if (htmlChildName == "tr")
{
// Tbody is not present, but tr element is present. Tr is wrapped in tbody
XmlElement xamlTableBodyElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableRowGroup, _xamlNamespace);
// We use currentProperties of xamlTableElement when adding rows since the tbody element is artificially created and has
// no properties of its own
htmlChildNode = AddTableRowsToTableBody(xamlTableBodyElement, htmlChildNode, currentProperties, columnStarts, stylesheet, sourceContext);
if (xamlTableBodyElement.HasChildNodes)
{
xamlTableElement.AppendChild(xamlTableBodyElement);
}
}
else
{
// Element is not tbody or tr. Ignore it.
// TODO: add processing for thead, tfoot elements and recovery for td elements
htmlChildNode = htmlChildNode.NextSibling;
}
}
if (xamlTableElement.HasChildNodes)
{
xamlParentElement.AppendChild(xamlTableElement);
}
}
}
private static XmlElement GetCellFromSingleCellTable(XmlElement htmlTableElement)
{
XmlElement singleCell = null;
for (XmlNode tableChild = htmlTableElement.FirstChild; tableChild != null; tableChild = tableChild.NextSibling)
{
string elementName = tableChild.LocalName.ToLower(CultureInfo.InvariantCulture);
if (elementName == "tbody" || elementName == "thead" || elementName == "tfoot")
{
if (singleCell != null)
{
return null;
}
for (XmlNode tbodyChild = tableChild.FirstChild; tbodyChild != null; tbodyChild = tbodyChild.NextSibling)
{
if (tbodyChild.LocalName.ToLower(CultureInfo.InvariantCulture) == "tr")
{
if (singleCell != null)
{
return null;
}
for (XmlNode trChild = tbodyChild.FirstChild; trChild != null; trChild = trChild.NextSibling)
{
string cellName = trChild.LocalName.ToLower(CultureInfo.InvariantCulture);
if (cellName == "td" || cellName == "th")
{
if (singleCell != null)
{
return null;
}
singleCell = (XmlElement)trChild;
}
}
}
}
}
else if (tableChild.LocalName.ToLower(CultureInfo.InvariantCulture) == "tr")
{
if (singleCell != null)
{
return null;
}
for (XmlNode trChild = tableChild.FirstChild; trChild != null; trChild = trChild.NextSibling)
{
string cellName = trChild.LocalName.ToLower(CultureInfo.InvariantCulture);
if (cellName == "td" || cellName == "th")
{
if (singleCell != null)
{
return null;
}
singleCell = (XmlElement)trChild;
}
}
}
}
return singleCell;
}
///
/// Processes the information about table columns - COLGROUP and COL html elements.
///
///
/// XmlElement representing a source html table.
///
///
/// XmlElement repesenting a resulting xaml table.
///
///
/// Array of doubles - column start coordinates.
/// Can be null, which means that column size information is not available
/// and we must use source colgroup/col information.
/// In case wneh it's not null, we will ignore source colgroup/col information.
///
///
///
///
private static void AddColumnInformation(XmlElement htmlTableElement, XmlElement xamlTableElement, ArrayList columnStartsAllRows, Hashtable currentProperties, CssStylesheet stylesheet, List sourceContext)
{
// Add column information
if (columnStartsAllRows != null)
{
// We have consistent information derived from table cells; use it
// The last element in columnStarts represents the end of the table
for (int columnIndex = 0; columnIndex < columnStartsAllRows.Count - 1; columnIndex++)
{
XmlElement xamlColumnElement;
xamlColumnElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableColumn, _xamlNamespace);
xamlColumnElement.SetAttribute(Xaml_Width, ((double)columnStartsAllRows[columnIndex + 1] - (double)columnStartsAllRows[columnIndex]).ToString(CultureInfo.InvariantCulture));
xamlTableElement.AppendChild(xamlColumnElement);
}
}
else
{
// We do not have consistent information from table cells;
// Translate blindly colgroups from html.
for (XmlNode htmlChildNode = htmlTableElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "colgroup")
{
// TODO: add column width information to this function as a parameter and process it
AddTableColumnGroup(xamlTableElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext);
}
else if (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "col")
{
AddTableColumn(xamlTableElement, (XmlElement)htmlChildNode, currentProperties, stylesheet, sourceContext);
}
else if (htmlChildNode is XmlElement)
{
// Some element which belongs to table body. Stop column loop.
break;
}
}
}
}
///
/// Converts htmlColgroupElement into Xaml TableColumnGroup element, and appends it to the parent
/// xamlTableElement
///
///
/// XmlElement representing Xaml Table element to which the converted column group should be added
///
///
/// XmlElement representing Html colgroup element to be converted
///
///
/// Properties inherited from parent context
///
///
///
private static void AddTableColumnGroup(XmlElement xamlTableElement, XmlElement htmlColgroupElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlColgroupElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
// TODO: process local properties for colgroup
// Process children of colgroup. Colgroup may contain only col elements.
for (XmlNode htmlNode = htmlColgroupElement.FirstChild; htmlNode != null; htmlNode = htmlNode.NextSibling)
{
if (htmlNode is XmlElement && htmlNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "col")
{
AddTableColumn(xamlTableElement, (XmlElement)htmlNode, currentProperties, stylesheet, sourceContext);
}
}
}
///
/// Converts htmlColElement into Xaml TableColumn element, and appends it to the parent
/// xamlTableColumnGroupElement
///
///
///
/// XmlElement representing Html col element to be converted
///
///
/// properties inherited from parent context
///
///
///
private static void AddTableColumn(XmlElement xamlTableElement, XmlElement htmlColElement, Hashtable inheritedProperties, CssStylesheet stylesheet, List sourceContext)
{
Hashtable localProperties;
Hashtable currentProperties = GetElementProperties(htmlColElement, inheritedProperties, out localProperties, stylesheet, sourceContext);
XmlElement xamlTableColumnElement = xamlTableElement.OwnerDocument.CreateElement(null, Xaml_TableColumn, _xamlNamespace);
// TODO: process local properties for TableColumn element
// Col is an empty element, with no subtree
xamlTableElement.AppendChild(xamlTableColumnElement);
}
///
/// Adds TableRow elements to xamlTableBodyElement. The rows are converted from Html tr elements that
/// may be the children of an Html tbody element or an Html table element with tbody missing
///
///
/// XmlElement representing Xaml TableRowGroup element to which the converted rows should be added
///
///
/// XmlElement representing the first tr child of the tbody element to be read
///
///
/// Hashtable representing current properties of the tbody element that are generated and applied in the
/// AddTable function; to be used as inheritedProperties when adding tr elements
///
///
///
///
///
/// XmlNode representing the current position of the iterator among tr elements
///
private static XmlNode AddTableRowsToTableBody(XmlElement xamlTableBodyElement, XmlNode htmlTRStartNode, Hashtable currentProperties, ArrayList columnStarts, CssStylesheet stylesheet, List sourceContext)
{
// Parameter validation
Debug.Assert(xamlTableBodyElement.LocalName == Xaml_TableRowGroup);
Debug.Assert(currentProperties != null);
// Initialize child node for iteratimg through children to the first tr element
XmlNode htmlChildNode = htmlTRStartNode;
ArrayList activeRowSpans = null;
if (columnStarts != null)
{
activeRowSpans = new ArrayList();
InitializeActiveRowSpans(activeRowSpans, columnStarts.Count);
}
while (htmlChildNode != null && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) != "tbody")
{
if (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "tr")
{
XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace);
sourceContext.Add((XmlElement)htmlChildNode);
// Get tr element properties
Hashtable trElementLocalProperties;
Hashtable trElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out trElementLocalProperties, stylesheet, sourceContext);
// TODO: apply local properties to tr element
AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode.FirstChild, trElementCurrentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext);
if (xamlTableRowElement.HasChildNodes)
{
xamlTableBodyElement.AppendChild(xamlTableRowElement);
}
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);
// Advance
htmlChildNode = htmlChildNode.NextSibling;
}
else if (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "td")
{
// Tr element is not present. We create one and add td elements to it
XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace);
// This is incorrect formatting and the column starts should not be set in this case
Debug.Assert(columnStarts == null);
htmlChildNode = AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode, currentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext);
if (xamlTableRowElement.HasChildNodes)
{
xamlTableBodyElement.AppendChild(xamlTableRowElement);
}
}
else
{
// Not a tr or td element. Ignore it.
// TODO: consider better recovery here
htmlChildNode = htmlChildNode.NextSibling;
}
}
return htmlChildNode;
}
///
/// Adds TableCell elements to xamlTableRowElement.
///
///
/// XmlElement representing Xaml TableRow element to which the converted cells should be added
///
///
/// XmlElement representing the child of tr or tbody element from which we should start adding td elements
///
///
/// properties of the current html tr element to which cells are to be added
///
///
///
///
///
///
/// XmlElement representing the current position of the iterator among the children of the parent Html tbody/tr element
///
private static XmlNode AddTableCellsToTableRow(XmlElement xamlTableRowElement, XmlNode htmlTDStartNode, Hashtable currentProperties, ArrayList columnStarts, ArrayList activeRowSpans, CssStylesheet stylesheet, List sourceContext)
{
// parameter validation
Debug.Assert(xamlTableRowElement.LocalName == Xaml_TableRow);
Debug.Assert(currentProperties != null);
if (columnStarts != null)
{
Debug.Assert(activeRowSpans.Count == columnStarts.Count);
}
XmlNode htmlChildNode = htmlTDStartNode;
double columnStart = 0;
double columnWidth = 0;
int columnIndex = 0;
int columnSpan = 0;
while (htmlChildNode != null && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) != "tr" && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) != "tbody" && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) != "thead" && htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) != "tfoot")
{
if (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "td" || htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "th")
{
XmlElement xamlTableCellElement = xamlTableRowElement.OwnerDocument.CreateElement(null, Xaml_TableCell, _xamlNamespace);
sourceContext.Add((XmlElement)htmlChildNode);
Hashtable tdElementLocalProperties;
Hashtable tdElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tdElementLocalProperties, stylesheet, sourceContext);
// TODO: determine if localProperties can be used instead of htmlChildNode in this call, and if they can,
// make necessary changes and use them instead.
ApplyPropertiesToTableCellElement((XmlElement)htmlChildNode, xamlTableCellElement);
if (columnStarts != null)
{
Debug.Assert(columnIndex < columnStarts.Count - 1);
while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0)
{
activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1;
Debug.Assert((int)activeRowSpans[columnIndex] >= 0);
columnIndex++;
}
Debug.Assert(columnIndex < columnStarts.Count - 1);
columnStart = (double)columnStarts[columnIndex];
columnWidth = GetColumnWidth((XmlElement)htmlChildNode);
columnSpan = CalculateColumnSpan(columnIndex, columnWidth, columnStarts);
int rowSpan = GetRowSpan((XmlElement)htmlChildNode);
// Column cannot have no span
Debug.Assert(columnSpan > 0);
Debug.Assert(columnIndex + columnSpan < columnStarts.Count);
xamlTableCellElement.SetAttribute(Xaml_TableCell_ColumnSpan, columnSpan.ToString());
// Apply row span
for (int spannedColumnIndex = columnIndex; spannedColumnIndex < columnIndex + columnSpan; spannedColumnIndex++)
{
Debug.Assert(spannedColumnIndex < activeRowSpans.Count);
activeRowSpans[spannedColumnIndex] = (rowSpan - 1);
Debug.Assert((int)activeRowSpans[spannedColumnIndex] >= 0);
}
columnIndex = columnIndex + columnSpan;
}
AddDataToTableCell(xamlTableCellElement, htmlChildNode.FirstChild, tdElementCurrentProperties, stylesheet, sourceContext);
if (xamlTableCellElement.HasChildNodes)
{
xamlTableRowElement.AppendChild(xamlTableCellElement);
}
Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);
htmlChildNode = htmlChildNode.NextSibling;
}
else
{
// Not td element. Ignore it.
// TODO: Consider better recovery
htmlChildNode = htmlChildNode.NextSibling;
}
}
return htmlChildNode;
}
///
/// adds table cell data to xamlTableCellElement
///
///
/// XmlElement representing Xaml TableCell element to which the converted data should be added
///
///
/// XmlElement representing the start element of data to be added to xamlTableCellElement
///
///
/// Current properties for the html td/th element corresponding to xamlTableCellElement
///
///
///
private static void AddDataToTableCell(XmlElement xamlTableCellElement, XmlNode htmlDataStartNode, Hashtable currentProperties, CssStylesheet stylesheet, List sourceContext)
{
// Parameter validation
Debug.Assert(xamlTableCellElement.LocalName == Xaml_TableCell);
Debug.Assert(currentProperties != null);
for (XmlNode htmlChildNode = htmlDataStartNode; htmlChildNode != null; htmlChildNode = htmlChildNode != null ? htmlChildNode.NextSibling : null)
{
// Process a new html element and add it to the td element
htmlChildNode = AddBlock(xamlTableCellElement, htmlChildNode, currentProperties, stylesheet, sourceContext);
}
}
///
/// Performs a parsing pass over a table to read information about column width and rowspan attributes. This information
/// is used to determine the starting point of each column.
///
///
/// XmlElement representing Html table whose structure is to be analyzed
///
///
///
/// ArrayList of type double which contains the function output. If analysis is successful, this ArrayList contains
/// all the points which are the starting position of any column in the table, ordered from left to right.
/// In case if analisys was impossible we return null.
///
private static ArrayList AnalyzeTableStructure(XmlElement htmlTableElement, CssStylesheet stylesheet)
{
// Parameter validation
Debug.Assert(htmlTableElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "table");
if (!htmlTableElement.HasChildNodes)
{
return null;
}
bool columnWidthsAvailable = true;
ArrayList columnStarts = new ArrayList();
ArrayList activeRowSpans = new ArrayList();
Debug.Assert(columnStarts.Count == activeRowSpans.Count);
XmlNode htmlChildNode = htmlTableElement.FirstChild;
double tableWidth = 0; // Keep track of table width which is the width of its widest row
// Analyze tbody and tr elements
while (htmlChildNode != null && columnWidthsAvailable)
{
Debug.Assert(columnStarts.Count == activeRowSpans.Count);
switch (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture))
{
case "tbody":
// Tbody element, we should analyze its children for trows
double tbodyWidth = AnalyzeTbodyStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tableWidth, stylesheet);
if (tbodyWidth > tableWidth)
{
// Table width must be increased to supported newly added wide row
tableWidth = tbodyWidth;
}
else if (tbodyWidth == 0)
{
// Tbody analysis may return 0, probably due to unprocessable format.
// We should also fail.
columnWidthsAvailable = false; // interrupt the analisys
}
break;
case "tr":
// Table row. Analyze column structure within row directly
double trWidth = AnalyzeTRStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tableWidth, stylesheet);
if (trWidth > tableWidth)
{
tableWidth = trWidth;
}
else if (trWidth == 0)
{
columnWidthsAvailable = false; // interrupt the analisys
}
break;
case "td":
// Incorrect formatting, too deep to analyze at this level. Return null.
// TODO: implement analysis at this level, possibly by creating a new tr
columnWidthsAvailable = false; // interrupt the analisys
break;
default:
// Element should not occur directly in table. Ignore it.
break;
}
htmlChildNode = htmlChildNode.NextSibling;
}
if (columnWidthsAvailable)
{
// Add an item for whole table width
columnStarts.Add(tableWidth);
VerifyColumnStartsAscendingOrder(columnStarts);
}
else
{
columnStarts = null;
}
return columnStarts;
}
///
/// Performs a parsing pass over a tbody to read information about column width and rowspan attributes. Information read about width
/// attributes is stored in the reference ArrayList parameter columnStarts, which contains a list of all starting
/// positions of all columns in the table, ordered from left to right. Row spans are taken into consideration when
/// computing column starts
///
///
/// XmlElement representing Html tbody whose structure is to be analyzed
///
///
/// ArrayList of type double which contains the function output. If analysis fails, this parameter is set to null
///
///
/// Current width of the table. This is used to determine if a new column when added to the end of table should
/// come after the last column in the table or is actually splitting the last column in two. If it is only splitting
/// the last column it should inherit row span for that column
///
///
///
///
/// Calculated width of a tbody.
/// In case of non-analizable column width structure return 0;
///
private static double AnalyzeTbodyStructure(XmlElement htmlTbodyElement, ArrayList columnStarts, ArrayList activeRowSpans, double tableWidth, CssStylesheet stylesheet)
{
// Parameter validation
Debug.Assert(htmlTbodyElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "tbody");
Debug.Assert(columnStarts != null);
double tbodyWidth = 0;
bool columnWidthsAvailable = true;
if (!htmlTbodyElement.HasChildNodes)
{
return tbodyWidth;
}
// Set active row spans to 0 - thus ignoring row spans crossing tbody boundaries
ClearActiveRowSpans(activeRowSpans);
XmlNode htmlChildNode = htmlTbodyElement.FirstChild;
// Analyze tr elements
while (htmlChildNode != null && columnWidthsAvailable)
{
switch (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture))
{
case "tr":
double trWidth = AnalyzeTRStructure((XmlElement)htmlChildNode, columnStarts, activeRowSpans, tbodyWidth, stylesheet);
if (trWidth > tbodyWidth)
{
tbodyWidth = trWidth;
}
break;
case "td":
columnWidthsAvailable = false; // interrupt the analisys
break;
default:
break;
}
htmlChildNode = htmlChildNode.NextSibling;
}
// Set active row spans to 0 - thus ignoring row spans crossing tbody boundaries
ClearActiveRowSpans(activeRowSpans);
return columnWidthsAvailable ? tbodyWidth : 0;
}
///
/// Performs a parsing pass over a tr element to read information about column width and rowspan attributes.
///
///
/// XmlElement representing Html tr element whose structure is to be analyzed
///
///
/// ArrayList of type double which contains the function output. If analysis is successful, this ArrayList contains
/// all the points which are the starting position of any column in the tr, ordered from left to right. If analysis fails,
/// the ArrayList is set to null
///
///
/// ArrayList representing all columns currently spanned by an earlier row span attribute. These columns should
/// not be used for data in this row. The ArrayList actually contains notation for all columns in the table, if the
/// active row span is set to 0 that column is not presently spanned but if it is > 0 the column is presently spanned
///
///
/// Double value representing the current width of the table.
/// Return 0 if analisys was insuccessful.
///
///
private static double AnalyzeTRStructure(XmlElement htmlTRElement, ArrayList columnStarts, ArrayList activeRowSpans, double tableWidth, CssStylesheet stylesheet)
{
double columnWidth;
// Parameter validation
Debug.Assert(htmlTRElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "tr");
Debug.Assert(columnStarts != null);
Debug.Assert(activeRowSpans != null);
Debug.Assert(columnStarts.Count == activeRowSpans.Count);
if (!htmlTRElement.HasChildNodes)
{
return 0;
}
bool columnWidthsAvailable = true;
double columnStart = 0; // starting position of current column
XmlNode htmlChildNode = htmlTRElement.FirstChild;
int columnIndex = 0;
double trWidth = 0;
// Skip spanned columns to get to real column start
if (columnIndex < activeRowSpans.Count)
{
Debug.Assert((double)columnStarts[columnIndex] >= columnStart);
if ((double)columnStarts[columnIndex] == columnStart)
{
// The new column may be in a spanned area
while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0)
{
activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1;
Debug.Assert((int)activeRowSpans[columnIndex] >= 0);
columnIndex++;
columnStart = (double)columnStarts[columnIndex];
}
}
}
while (htmlChildNode != null && columnWidthsAvailable)
{
Debug.Assert(columnStarts.Count == activeRowSpans.Count);
VerifyColumnStartsAscendingOrder(columnStarts);
switch (htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture))
{
case "td":
Debug.Assert(columnIndex <= columnStarts.Count);
if (columnIndex < columnStarts.Count)
{
Debug.Assert(columnStart <= (double)columnStarts[columnIndex]);
if (columnStart < (double)columnStarts[columnIndex])
{
columnStarts.Insert(columnIndex, columnStart);
// There can be no row spans now - the column data will appear here
// Row spans may appear only during the column analysis
activeRowSpans.Insert(columnIndex, 0);
}
}
else
{
// Column start is greater than all previous starts. Row span must still be 0 because
// we are either adding after another column of the same row, in which case it should not inherit
// the previous column's span. Otherwise we are adding after the last column of some previous
// row, and assuming the table widths line up, we should not be spanned by it. If there is
// an incorrect tbale structure where a columns starts in the middle of a row span, we do not
// guarantee correct output
columnStarts.Add(columnStart);
activeRowSpans.Add(0);
}
columnWidth = GetColumnWidth((XmlElement)htmlChildNode);
if (columnWidth != -1)
{
int nextColumnIndex;
int rowSpan = GetRowSpan((XmlElement)htmlChildNode);
nextColumnIndex = GetNextColumnIndex(columnIndex, columnWidth, columnStarts, activeRowSpans);
if (nextColumnIndex != -1)
{
// Entire column width can be processed without hitting conflicting row span. This means that
// column widths line up and we can process them
Debug.Assert(nextColumnIndex <= columnStarts.Count);
// Apply row span to affected columns
for (int spannedColumnIndex = columnIndex; spannedColumnIndex < nextColumnIndex; spannedColumnIndex++)
{
activeRowSpans[spannedColumnIndex] = rowSpan - 1;
Debug.Assert((int)activeRowSpans[spannedColumnIndex] >= 0);
}
columnIndex = nextColumnIndex;
// Calculate columnsStart for the next cell
columnStart = columnStart + columnWidth;
if (columnIndex < activeRowSpans.Count)
{
Debug.Assert((double)columnStarts[columnIndex] >= columnStart);
if ((double)columnStarts[columnIndex] == columnStart)
{
// The new column may be in a spanned area
while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0)
{
activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1;
Debug.Assert((int)activeRowSpans[columnIndex] >= 0);
columnIndex++;
columnStart = (double)columnStarts[columnIndex];
}
}
// else: the new column does not start at the same time as a pre existing column
// so we don't have to check it for active row spans, it starts in the middle
// of another column which has been checked already by the GetNextColumnIndex function
}
}
else
{
// Full column width cannot be processed without a pre existing row span.
// We cannot analyze widths
columnWidthsAvailable = false;
}
}
else
{
// Incorrect column width, stop processing
columnWidthsAvailable = false;
}
break;
default:
break;
}
htmlChildNode = htmlChildNode.NextSibling;
}
// The width of the tr element is the position at which it's last td element ends, which is calculated in
// the columnStart value after each td element is processed
if (columnWidthsAvailable)
{
trWidth = columnStart;
}
else
{
trWidth = 0;
}
return trWidth;
}
///
/// Gets row span attribute from htmlTDElement. Returns an integer representing the value of the rowspan attribute.
/// Default value if attribute is not specified or if it is invalid is 1
///
///
/// Html td element to be searched for rowspan attribute
///
private static int GetRowSpan(XmlElement htmlTDElement)
{
string rowSpanAsString;
int rowSpan;
rowSpanAsString = GetAttribute((XmlElement)htmlTDElement, "rowspan");
if (rowSpanAsString != null)
{
if (!Int32.TryParse(rowSpanAsString, out rowSpan))
{
// Ignore invalid value of rowspan; treat it as 1
rowSpan = 1;
}
}
else
{
// No row span, default is 1
rowSpan = 1;
}
return rowSpan;
}
///
/// Gets index at which a column should be inseerted into the columnStarts ArrayList. This is
/// decided by the value columnStart. The columnStarts ArrayList is ordered in ascending order.
/// Returns an integer representing the index at which the column should be inserted
///
///
/// Array list representing starting coordinates of all columns in the table
///
///
///
///
/// Int representing the current column index. This acts as a clue while finding the insertion index.
/// If the value of columnStarts at columnIndex is the same as columnStart, then this position alrady exists
/// in the array and we can jsut return columnIndex.
///
///
///
private static int GetNextColumnIndex(int columnIndex, double columnWidth, ArrayList columnStarts, ArrayList activeRowSpans)
{
double columnStart;
int spannedColumnIndex;
// Parameter validation
Debug.Assert(columnStarts != null);
Debug.Assert(0 <= columnIndex && columnIndex <= columnStarts.Count);
Debug.Assert(columnWidth > 0);
columnStart = (double)columnStarts[columnIndex];
spannedColumnIndex = columnIndex + 1;
while (spannedColumnIndex < columnStarts.Count && (double)columnStarts[spannedColumnIndex] < columnStart + columnWidth && spannedColumnIndex != -1)
{
if ((int)activeRowSpans[spannedColumnIndex] > 0)
{
// The current column should span this area, but something else is already spanning it
// Not analyzable
spannedColumnIndex = -1;
}
else
{
spannedColumnIndex++;
}
}
return spannedColumnIndex;
}
///
/// Used for clearing activeRowSpans array in the beginning/end of each tbody
///
///
/// ArrayList representing currently active row spans
///
private static void ClearActiveRowSpans(ArrayList activeRowSpans)
{
for (int columnIndex = 0; columnIndex < activeRowSpans.Count; columnIndex++)
{
activeRowSpans[columnIndex] = 0;
}
}
///
/// Used for initializing activeRowSpans array in the before adding rows to tbody element
///
///
/// ArrayList representing currently active row spans
///
///
/// Size to be give to array list
///
private static void InitializeActiveRowSpans(ArrayList activeRowSpans, int count)
{
for (int columnIndex = 0; columnIndex < count; columnIndex++)
{
activeRowSpans.Add(0);
}
}
///
/// Calculates width of next TD element based on starting position of current element and it's width, which
/// is calculated byt he function
///
///
/// XmlElement representing Html td element whose width is to be read
///
///
/// Starting position of current column
///
private static double GetNextColumnStart(XmlElement htmlTDElement, double columnStart)
{
double columnWidth;
double nextColumnStart;
// Parameter validation
Debug.Assert(htmlTDElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "td" || htmlTDElement.LocalName.ToLower(CultureInfo.InvariantCulture) == "th");
Debug.Assert(columnStart >= 0);
nextColumnStart = -1; // -1 indicates inability to calculate columnStart width
columnWidth = GetColumnWidth(htmlTDElement);
if (columnWidth == -1)
{
nextColumnStart = -1;
}
else
{
nextColumnStart = columnStart + columnWidth;
}
return nextColumnStart;
}
private static double GetColumnWidth(XmlElement htmlTDElement)
{
string columnWidthAsString;
double columnWidth;
columnWidthAsString = null;
columnWidth = -1;
// Get string valkue for the width
columnWidthAsString = GetAttribute(htmlTDElement, "width");
if (columnWidthAsString == null)
{
columnWidthAsString = GetCssAttribute(GetAttribute(htmlTDElement, "style"), "width");
}
// We do not allow column width to be 0, if specified as 0 we will fail to record it
if (!TryGetLengthValue(columnWidthAsString, out columnWidth) || columnWidth == 0)
{
columnWidth = -1;
}
return columnWidth;
}
///
/// Calculates column span based the column width and the widths of all other columns. Returns an integer representing
/// the column span
///
///
/// Index of the current column
///
///
/// Width of the current column
///
///
/// ArrayList repsenting starting coordinates of all columns
///
private static int CalculateColumnSpan(int columnIndex, double columnWidth, ArrayList columnStarts)
{
// Current status of column width. Indicates the amount of width that has been scanned already
double columnSpanningValue;
int columnSpanningIndex;
int columnSpan;
double subColumnWidth; // Width of the smallest-grain columns in the table
Debug.Assert(columnStarts != null);
Debug.Assert(columnIndex < columnStarts.Count - 1);
Debug.Assert((double)columnStarts[columnIndex] >= 0);
Debug.Assert(columnWidth > 0);
columnSpanningIndex = columnIndex;
columnSpanningValue = 0;
columnSpan = 0;
subColumnWidth = 0;
while (columnSpanningValue < columnWidth && columnSpanningIndex < columnStarts.Count - 1)
{
subColumnWidth = (double)columnStarts[columnSpanningIndex + 1] - (double)columnStarts[columnSpanningIndex];
Debug.Assert(subColumnWidth > 0);
columnSpanningValue += subColumnWidth;
columnSpanningIndex++;
}
// Now, we have either covered the width we needed to cover or reached the end of the table, in which
// case the column spans all the columns until the end
columnSpan = columnSpanningIndex - columnIndex;
Debug.Assert(columnSpan > 0);
return columnSpan;
}
///
/// Verifies that values in columnStart, which represent starting coordinates of all columns, are arranged
/// in ascending order
///
///
/// ArrayList representing starting coordinates of all columns
///
private static void VerifyColumnStartsAscendingOrder(ArrayList columnStarts)
{
Debug.Assert(columnStarts != null);
double columnStart;
columnStart = -0.01;
for (int columnIndex = 0; columnIndex < columnStarts.Count; columnIndex++)
{
Debug.Assert(columnStart < (double)columnStarts[columnIndex]);
columnStart = (double)columnStarts[columnIndex];
}
}
// .............................................................
//
// Attributes and Properties
//
// .............................................................
///
/// Analyzes local properties of Html element, converts them into Xaml equivalents, and applies them to xamlElement
///
///
/// XmlElement representing Xaml element to which properties are to be applied
///
///
/// Hashtable representing local properties of Html element that is converted into xamlElement
///
///
private static void ApplyLocalProperties(XmlElement xamlElement, Hashtable localProperties, bool isBlock)
{
bool marginSet = false;
string marginTop = "0";
string marginBottom = "0";
string marginLeft = "0";
string marginRight = "0";
bool paddingSet = false;
string paddingTop = "0";
string paddingBottom = "0";
string paddingLeft = "0";
string paddingRight = "0";
string borderColor = null;
bool borderThicknessSet = false;
string borderThicknessTop = "0";
string borderThicknessBottom = "0";
string borderThicknessLeft = "0";
string borderThicknessRight = "0";
IDictionaryEnumerator propertyEnumerator = localProperties.GetEnumerator();
while (propertyEnumerator.MoveNext())
{
switch ((string)propertyEnumerator.Key)
{
case "font-family":
// Convert from font-family value list into xaml FontFamily value
xamlElement.SetAttribute(Xaml_FontFamily, (string)propertyEnumerator.Value);
break;
case "font-style":
xamlElement.SetAttribute(Xaml_FontStyle, (string)propertyEnumerator.Value);
break;
case "font-variant":
// Convert from font-variant into xaml property
break;
case "font-weight":
xamlElement.SetAttribute(Xaml_FontWeight, (string)propertyEnumerator.Value);
break;
case "font-size":
// Convert from css size into FontSize
xamlElement.SetAttribute(Xaml_FontSize, (string)propertyEnumerator.Value);
break;
case "color":
SetPropertyValue(xamlElement, TextElement.ForegroundProperty, (string)propertyEnumerator.Value);
break;
case "background-color":
SetPropertyValue(xamlElement, TextElement.BackgroundProperty, (string)propertyEnumerator.Value);
break;
case "text-decoration-underline":
if (!isBlock)
{
if ((string)propertyEnumerator.Value == "true")
{
xamlElement.SetAttribute(Xaml_TextDecorations, Xaml_TextDecorations_Underline);
}
}
break;
case "text-decoration-none":
case "text-decoration-overline":
case "text-decoration-line-through":
case "text-decoration-blink":
// Convert from all other text-decorations values
if (!isBlock)
{
}
break;
case "text-transform":
// Convert from text-transform into xaml property
break;
case "text-indent":
if (isBlock)
{
xamlElement.SetAttribute(Xaml_TextIndent, (string)propertyEnumerator.Value);
}
break;
case "text-align":
if (isBlock)
{
xamlElement.SetAttribute(Xaml_TextAlignment, (string)propertyEnumerator.Value);
}
break;
case "width":
case "height":
// Decide what to do with width and height propeties
break;
case "margin-top":
marginSet = true;
marginTop = (string)propertyEnumerator.Value;
break;
case "margin-right":
marginSet = true;
marginRight = (string)propertyEnumerator.Value;
break;
case "margin-bottom":
marginSet = true;
marginBottom = (string)propertyEnumerator.Value;
break;
case "margin-left":
marginSet = true;
marginLeft = (string)propertyEnumerator.Value;
break;
case "padding-top":
paddingSet = true;
paddingTop = (string)propertyEnumerator.Value;
break;
case "padding-right":
paddingSet = true;
paddingRight = (string)propertyEnumerator.Value;
break;
case "padding-bottom":
paddingSet = true;
paddingBottom = (string)propertyEnumerator.Value;
break;
case "padding-left":
paddingSet = true;
paddingLeft = (string)propertyEnumerator.Value;
break;
// NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right)
// In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method
case "border-color-top":
borderColor = (string)propertyEnumerator.Value;
break;
case "border-color-right":
borderColor = (string)propertyEnumerator.Value;
break;
case "border-color-bottom":
borderColor = (string)propertyEnumerator.Value;
break;
case "border-color-left":
borderColor = (string)propertyEnumerator.Value;
break;
case "border-style-top":
case "border-style-right":
case "border-style-bottom":
case "border-style-left":
// Implement conversion from border style
break;
case "border-width-top":
borderThicknessSet = true;
borderThicknessTop = (string)propertyEnumerator.Value;
break;
case "border-width-right":
borderThicknessSet = true;
borderThicknessRight = (string)propertyEnumerator.Value;
break;
case "border-width-bottom":
borderThicknessSet = true;
borderThicknessBottom = (string)propertyEnumerator.Value;
break;
case "border-width-left":
borderThicknessSet = true;
borderThicknessLeft = (string)propertyEnumerator.Value;
break;
case "list-style-type":
if (xamlElement.LocalName == XamlList)
{
string markerStyle;
switch (((string)propertyEnumerator.Value).ToLower(CultureInfo.InvariantCulture))
{
case "disc":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Disc;
break;
case "circle":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Circle;
break;
case "none":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_None;
break;
case "square":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Square;
break;
case "box":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Box;
break;
case "lower-latin":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_LowerLatin;
break;
case "upper-latin":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_UpperLatin;
break;
case "lower-roman":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_LowerRoman;
break;
case "upper-roman":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_UpperRoman;
break;
case "decimal":
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Decimal;
break;
default:
markerStyle = HtmlToXamlConverter.Xaml_List_MarkerStyle_Disc;
break;
}
xamlElement.SetAttribute(HtmlToXamlConverter.XamlListMarkerStyle, markerStyle);
}
break;
case "float":
case "clear":
if (isBlock)
{
// Convert float and clear properties
}
break;
case "display":
break;
}
}
if (isBlock)
{
if (marginSet)
{
ComposeThicknessProperty(xamlElement, Xaml_Margin, marginLeft, marginRight, marginTop, marginBottom);
}
if (paddingSet)
{
ComposeThicknessProperty(xamlElement, Xaml_Padding, paddingLeft, paddingRight, paddingTop, paddingBottom);
}
if (borderColor != null)
{
// We currently ignore possible difference in brush colors on different border sides. Use the last colored side mentioned
xamlElement.SetAttribute(Xaml_BorderBrush, borderColor);
}
if (borderThicknessSet)
{
ComposeThicknessProperty(xamlElement, Xaml_BorderThickness, borderThicknessLeft, borderThicknessRight, borderThicknessTop, borderThicknessBottom);
}
}
}
// Create syntactically optimized four-value Thickness
private static void ComposeThicknessProperty(XmlElement xamlElement, string propertyName, string left, string right, string top, string bottom)
{
// Xaml syntax:
// We have a reasonable interpreation for one value (all four edges), two values (horizontal, vertical),
// and four values (left, top, right, bottom).
// switch (i) {
// case 1: return new Thickness(lengths[0]);
// case 2: return new Thickness(lengths[0], lengths[1], lengths[0], lengths[1]);
// case 4: return new Thickness(lengths[0], lengths[1], lengths[2], lengths[3]);
// }
string thickness;
// We do not accept negative margins
if (left[0] == '0' || left[0] == '-') left = "0";
if (right[0] == '0' || right[0] == '-') right = "0";
if (top[0] == '0' || top[0] == '-') top = "0";
if (bottom[0] == '0' || bottom[0] == '-') bottom = "0";
if (left == right && top == bottom)
{
if (left == top)
{
thickness = left;
}
else
{
thickness = left + "," + top;
}
}
else
{
thickness = left + "," + top + "," + right + "," + bottom;
}
// Need safer processing for a thickness value
xamlElement.SetAttribute(propertyName, thickness);
}
private static void SetPropertyValue(XmlElement xamlElement, DependencyProperty property, string stringValue)
{
System.ComponentModel.TypeConverter typeConverter = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
try
{
object convertedValue = typeConverter.ConvertFromInvariantString(stringValue);
if (convertedValue != null)
{
xamlElement.SetAttribute(property.Name, stringValue);
}
}
catch(Exception)
{
}
}
///
/// Analyzes the tag of the htmlElement and infers its associated formatted properties.
/// After that parses style attribute and adds all inline css styles.
/// The resulting style attributes are collected in output parameter localProperties.
///
///
///
///
/// set of properties inherited from ancestor elements. Currently not used in the code. Reserved for the future development.
///
///
/// returns all formatting properties defined by this element - implied by its tag, its attributes, or its css inline style
///
///
///
///
/// returns a combination of previous context with local set of properties.
/// This value is not used in the current code - inntended for the future development.
///
private static Hashtable GetElementProperties(XmlElement htmlElement, Hashtable inheritedProperties, out Hashtable localProperties, CssStylesheet stylesheet, List sourceContext)
{
// Start with context formatting properties
Hashtable currentProperties = new Hashtable();
IDictionaryEnumerator propertyEnumerator = inheritedProperties.GetEnumerator();
while (propertyEnumerator.MoveNext())
{
currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value;
}
// Identify element name
string elementName = htmlElement.LocalName.ToLower(CultureInfo.InvariantCulture);
string elementNamespace = htmlElement.NamespaceURI;
// update current formatting properties depending on element tag
localProperties = new Hashtable();
switch (elementName)
{
// Character formatting
case "i":
case "italic":
case "em":
localProperties["font-style"] = "italic";
break;
case "b":
case "bold":
case "strong":
case "dfn":
localProperties["font-weight"] = "bold";
break;
case "u":
case "underline":
localProperties["text-decoration-underline"] = "true";
break;
case "font":
string attributeValue = GetAttribute(htmlElement, "face");
if (attributeValue != null)
{
localProperties["font-family"] = attributeValue;
}
attributeValue = GetAttribute(htmlElement, "size");
if (attributeValue != null)
{
double fontSize = double.Parse(attributeValue, CultureInfo.InvariantCulture) * (12.0 / 3.0);
if (fontSize < 1.0)
{
fontSize = 1.0;
}
else if (fontSize > 1000.0)
{
fontSize = 1000.0;
}
localProperties["font-size"] = fontSize.ToString(CultureInfo.InvariantCulture);
}
attributeValue = GetAttribute(htmlElement, "color");
if (attributeValue != null)
{
localProperties["color"] = attributeValue;
}
break;
case "samp":
localProperties["font-family"] = "Courier New"; // code sample
localProperties["font-size"] = Xaml_FontSize_XXSmall;
localProperties["text-align"] = "Left";
break;
case "sub":
break;
case "sup":
break;
// Hyperlinks
case "a": // href, hreflang, urn, methods, rel, rev, title
// Set default hyperlink properties
break;
case "acronym":
break;
// Paragraph formatting:
case "p":
// Set default paragraph properties
break;
case "div":
// Set default div properties
break;
case "pre":
localProperties["font-family"] = "Courier New"; // renders text in a fixed-width font
localProperties["font-size"] = Xaml_FontSize_XXSmall;
localProperties["text-align"] = "Left";
break;
case "blockquote":
localProperties["margin-left"] = "16";
break;
case "h1":
localProperties["font-size"] = Xaml_FontSize_XXLarge;
break;
case "h2":
localProperties["font-size"] = Xaml_FontSize_XLarge;
break;
case "h3":
localProperties["font-size"] = Xaml_FontSize_Large;
break;
case "h4":
localProperties["font-size"] = Xaml_FontSize_Medium;
break;
case "h5":
localProperties["font-size"] = Xaml_FontSize_Small;
break;
case "h6":
localProperties["font-size"] = Xaml_FontSize_XSmall;
break;
// List properties
case "ul":
localProperties["list-style-type"] = "disc";
break;
case "ol":
localProperties["list-style-type"] = "decimal";
break;
case "table":
case "body":
case "html":
break;
}
// Override html defaults by css attributes - from stylesheets and inline settings
HtmlCssParser.GetElementPropertiesFromCssAttributes(htmlElement, elementName, stylesheet, localProperties, sourceContext);
// Combine local properties with context to create new current properties
propertyEnumerator = localProperties.GetEnumerator();
while (propertyEnumerator.MoveNext())
{
currentProperties[propertyEnumerator.Key] = propertyEnumerator.Value;
}
return currentProperties;
}
///
/// Extracts a value of css attribute from css style definition.
///
///
/// Source csll style definition
///
///
/// A name of css attribute to extract
///
///
/// A string rrepresentation of an attribute value if found;
/// null if there is no such attribute in a given string.
///
private static string GetCssAttribute(string cssStyle, string attributeName)
{
// This is poor man's attribute parsing. Replace it by real css parsing
if (cssStyle != null)
{
string[] styleValues;
attributeName = attributeName.ToLower(CultureInfo.InvariantCulture);
// Check for width specification in style string
styleValues = cssStyle.Split(';');
for (int styleValueIndex = 0; styleValueIndex < styleValues.Length; styleValueIndex++)
{
string[] styleNameValue;
styleNameValue = styleValues[styleValueIndex].Split(':');
if (styleNameValue.Length == 2)
{
if (styleNameValue[0].Trim().ToLower(CultureInfo.InvariantCulture) == attributeName)
{
return styleNameValue[1].Trim();
}
}
}
}
return null;
}
///
/// Converts a length value from string representation to a double.
///
///
/// Source string value of a length.
///
///
///
private static bool TryGetLengthValue(string lengthAsString, out double length)
{
length = Double.NaN;
if (lengthAsString != null)
{
lengthAsString = lengthAsString.Trim().ToLower(CultureInfo.InvariantCulture);
// We try to convert currentColumnWidthAsString into a double. This will eliminate widths of type "50%", etc.
if (lengthAsString.EndsWith("pt", StringComparison.OrdinalIgnoreCase))
{
lengthAsString = lengthAsString.Substring(0, lengthAsString.Length - 2);
if (Double.TryParse(lengthAsString, out length))
{
length = (length * 96.0) / 72.0; // convert from points to pixels
}
else
{
length = Double.NaN;
}
}
else if (lengthAsString.EndsWith("px", StringComparison.OrdinalIgnoreCase))
{
lengthAsString = lengthAsString.Substring(0, lengthAsString.Length - 2);
if (!Double.TryParse(lengthAsString, out length))
{
length = Double.NaN;
}
}
else
{
if (!Double.TryParse(lengthAsString, out length)) // Assuming pixels
{
length = Double.NaN;
}
}
}
return !Double.IsNaN(length);
}
// .................................................................
//
// Pasring Color Attribute
//
// .................................................................
private static string GetColorValue(string colorValue)
{
// TODO: Implement color conversion
return colorValue;
}
///
/// Applies properties to xamlTableCellElement based on the html td element it is converted from.
///
///
/// Html td/th element to be converted to xaml
///
///
/// XmlElement representing Xaml element for which properties are to be processed
///
///
/// TODO: Use the processed properties for htmlChildNode instead of using the node itself
///
private static void ApplyPropertiesToTableCellElement(XmlElement htmlChildNode, XmlElement xamlTableCellElement)
{
// Parameter validation
Debug.Assert(htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "td" || htmlChildNode.LocalName.ToLower(CultureInfo.InvariantCulture) == "th");
Debug.Assert(xamlTableCellElement.LocalName == Xaml_TableCell);
// set default border thickness for xamlTableCellElement to enable gridlines
xamlTableCellElement.SetAttribute(Xaml_TableCell_BorderThickness, "1,1,1,1");
xamlTableCellElement.SetAttribute(Xaml_TableCell_BorderBrush, Xaml_Brushes_Black);
string rowSpanString = GetAttribute((XmlElement)htmlChildNode, "rowspan");
if (rowSpanString != null)
{
xamlTableCellElement.SetAttribute(Xaml_TableCell_RowSpan, rowSpanString);
}
}
#endregion Private Methods
// ----------------------------------------------------------------
//
// Internal Constants
//
// ----------------------------------------------------------------
// The constants reprtesent all Xaml names used in a conversion
///
public const string XamlFlowDocument = "FlowDocument";
///
public const string XamlRun = "Run";
///
public const string XamlSpan = "Span";
///
public const string XamlHyperlink = "Hyperlink";
///
public const string XamlHyperlinkNavigateUri = "NavigateUri";
///
public const string XamlHyperlinkTargetName = "TargetName";
///
public const string XamlSection = "Section";
///
public const string XamlList = "List";
///
public const string XamlListMarkerStyle = "MarkerStyle";
///
public const string Xaml_List_MarkerStyle_None = "None";
///
public const string Xaml_List_MarkerStyle_Decimal = "Decimal";
///
public const string Xaml_List_MarkerStyle_Disc = "Disc";
///
public const string Xaml_List_MarkerStyle_Circle = "Circle";
///
public const string Xaml_List_MarkerStyle_Square = "Square";
///
public const string Xaml_List_MarkerStyle_Box = "Box";
///
public const string Xaml_List_MarkerStyle_LowerLatin = "LowerLatin";
///
public const string Xaml_List_MarkerStyle_UpperLatin = "UpperLatin";
///
public const string Xaml_List_MarkerStyle_LowerRoman = "LowerRoman";
///
public const string Xaml_List_MarkerStyle_UpperRoman = "UpperRoman";
///
public const string Xaml_ListItem = "ListItem";
///
public const string Xaml_LineBreak = "LineBreak";
///
public const string Xaml_Paragraph = "Paragraph";
///
public const string Xaml_Margin = "Margin";
///
public const string Xaml_Padding = "Padding";
///
public const string Xaml_BorderBrush = "BorderBrush";
///
public const string Xaml_BorderThickness = "BorderThickness";
///
public const string Xaml_Table = "Table";
///
public const string Xaml_TableColumn = "TableColumn";
///
public const string Xaml_TableRowGroup = "TableRowGroup";
///
public const string Xaml_TableRow = "TableRow";
///
public const string Xaml_TableCell = "TableCell";
///
public const string Xaml_TableCell_BorderThickness = "BorderThickness";
///
public const string Xaml_TableCell_BorderBrush = "BorderBrush";
///
public const string Xaml_TableCell_ColumnSpan = "ColumnSpan";
///
public const string Xaml_TableCell_RowSpan = "RowSpan";
///
public const string Xaml_Width = "Width";
///
public const string Xaml_Brushes_Black = "Black";
///
public const string Xaml_FontFamily = "FontFamily";
///
public const string Xaml_FontSize = "FontSize";
///
public const string Xaml_FontSize_XXLarge = "22pt"; // "XXLarge";
///
public const string Xaml_FontSize_XLarge = "20pt"; // "XLarge";
///
public const string Xaml_FontSize_Large = "18pt"; // "Large";
///
public const string Xaml_FontSize_Medium = "16pt"; // "Medium";
///
public const string Xaml_FontSize_Small = "12pt"; // "Small";
///
public const string Xaml_FontSize_XSmall = "10pt"; // "XSmall";
///
public const string Xaml_FontSize_XXSmall = "8pt"; // "XXSmall";
///
public const string Xaml_FontWeight = "FontWeight";
///
public const string Xaml_FontWeight_Bold = "Bold";
///
public const string Xaml_FontStyle = "FontStyle";
///
public const string Xaml_Foreground = "Foreground";
///
public const string Xaml_Background = "Background";
///
public const string Xaml_TextDecorations = "TextDecorations";
///
public const string Xaml_TextDecorations_Underline = "Underline";
///
public const string Xaml_TextIndent = "TextIndent";
///
public const string Xaml_TextAlignment = "TextAlignment";
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
static string _xamlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
#endregion Private Fields
}
}
================================================
FILE: WpfRichText/XamlToHtmlParser/HtmlTokenType.cs
================================================
//---------------------------------------------------------------------------
//
// File: HtmlTokenType.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Definition of token types supported by HtmlLexicalAnalyzer
//
//---------------------------------------------------------------------------
namespace WpfRichText
{
///
/// types of lexical tokens for html-to-xaml converter
///
internal enum HtmlTokenType
{
OpeningTagStart,
ClosingTagStart,
TagEnd,
EmptyTagEnd,
EqualSign,
Name,
Atom, // any attribute value not in quotes
Text, //text content when accepting text
Comment,
EOF,
}
}