using PaintDotNet.Actions;
using PaintDotNet.Annotation.Enum;
using PaintDotNet.Base.CommTool;
using PaintDotNet.Base.SettingModel;
using PaintDotNet.SystemLayer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security;
using System.Threading;
using System.Windows.Forms;
using PaintDotNet.SystemLayer.FileDlgExtenders.FileDialogExtenders;
using PaintDotNet.Annotation.Measure;
using PaintDotNet.Base.Functionodel;
using OpenCvSharp;
using PaintDotNet.Setting;
using PaintDotNet.ImageLabel;
using PaintDotNet.Measuring;
using Metis.Measuring;
using PaintDotNet.DbOpreate.DbModel;
using PaintDotNet.Annotation;
namespace PaintDotNet
{
internal class DocumentWorkspace : DocumentView
{
///
/// 主控件
///
private AppWorkspace appWorkspace;
///
/// 缩放模式
///
private ZoomBasis zoomBasis;
///
/// 文件路径
///
public string filePath = null;
///
/// 文件名
///
public string fileText = null;
///
/// 文件类型
///
//private FileType fileType = null;
///
/// 文件 - 批量保存自动配置
///
public BatchSaveAutoModel batchSaveAutoModel;
//private SaveConfigToken saveConfigToken = null;
private ImageResource statusIcon = null;
public ZipHandleHelper zipHandleHelper;//zip对象
public ZipXmlModel zipXmlModel;//zip的图片列表xml
public string picName;//zip包当前显示的图片名
public bool needBackup = true;//判断图片是否需要备份
private bool openInScriptRunning = false;//判断图片是否脚本执行过程中打开
#region 底部按钮选中状态
///
/// 最佳
///
public bool best = false;
///
/// 最大最小
///
public bool maxMin = false;
///
/// 原始状态
///
public bool origin = true;
///
/// 伽马0.45
///
public bool gamma45 = false;
///
/// 移动模式
///
public bool mobileMode = false;
///
/// 指针模式
///
public bool cursorMode = true;
///
/// MainForm
///
#endregion
public int buttonType;
///
/// 更新按钮文字
///
///
public void UpdateDw2buttonName(string buttonName)
{
if (appWorkspace != null)
appWorkspace.toolBar.DocumentStrip.SetDw2buttonName(this, buttonName);
}
public ImageResource StatusIcon
{
get
{
return this.statusIcon;
}
}
///
/// 判断图片是否脚本执行过程中打开
///
public bool OpenInScriptRunning
{
set
{
this.openInScriptRunning = value;
}
get
{
return this.openInScriptRunning;
}
}
public string StatusText
{
get
{
if (!string.IsNullOrEmpty(filePath))
{
try
{
FileInfo fi = new FileInfo(filePath);
return fi.CreationTime + "、" + FileOperationHelper.GetLength(fi.Length) + "、" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Width + "*" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Height;
}
catch (Exception)
{
}
}
return "";
}
}
public event EventHandler StatusChanged;
protected virtual void OnStatusChanged()
{
if (StatusChanged != null)
{
StatusChanged(this, EventArgs.Empty);
}
}
protected override void OnSizeChanged(EventArgs e)
{
PerformLayout();
base.OnSizeChanged(e);
}
protected override void OnLayout(LayoutEventArgs e)
{
if (this.zoomBasis == ZoomBasis.FitToWindow)
{
ZoomToWindow();
// This bizarre ordering of setting PanelAutoScroll prevents some very weird layout/scroll-without-scrollbars stuff.
PanelAutoScroll = true;
PanelAutoScroll = false;
}
base.OnLayout(e);
}
protected override void OnResize(EventArgs e)
{
if (this.zoomBasis == ZoomBasis.FitToWindow)
{
PerformLayout();
}
base.OnResize(e);
}
protected override string[] startUpRules(Dictionary rules)
{
string[] result = new string[5];
result[0] = Startup.instance.measurementUnit.ToString();
result[1] = InvariantData.unitsDictionary[(int)Startup.instance.measurementUnit];
result[2] = InvariantData.unitSymbolsDictionary[(int)Startup.instance.measurementUnit];
if (rules != null)
{
result[3] = (rules[Startup.instance.measurementUnit]).ToString();
result[4] = (rules[MeasurementUnit.Micron]).ToString();
}
else
{
result[3] = (Startup.instance.rules[Startup.instance.measurementUnit]).ToString();
result[4] = (Startup.instance.rules[MeasurementUnit.Micron]).ToString();
}
return result;
}
protected override List Mic_rulersAll()
{
return Startup.instance.mic_rulersAll;
}
public DocumentWorkspace(AppWorkspace appWorkspace)
{
this.AppWorkspaceTop = appWorkspace;
this.InitToolsAndManager();
InitializeComponent();
this.ShowContextMenuStrip1();
this.panel.MouseDown += new MouseEventHandler(this.ShowContextMenuStrip2);
this.RulersEnabled = Settings.CurrentUser.GetBoolean(SettingNames.Rulers, true);
this.zoomBasis = ZoomBasis.FitToWindow;
}
private void ShowContextMenuStrip2(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
this.ShowContextMenuStrip1();
}
protected override void OnUnitsChanged()
{
base.OnUnitsChanged();
}
private void InitializeComponent()
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
public override void ZoomIn()
{
this.ZoomBasis = ZoomBasis.ScaleFactor;
base.ZoomIn();
}
public override void ZoomIn(double factor)
{
this.ZoomBasis = ZoomBasis.ScaleFactor;
base.ZoomIn(factor);
}
public override void ZoomOut()
{
this.ZoomBasis = ZoomBasis.ScaleFactor;
base.ZoomOut();
}
public override void ZoomOut(double factor)
{
this.ZoomBasis = ZoomBasis.ScaleFactor;
base.ZoomOut(factor);
}
public event EventHandler ZoomBasisChanging;
protected virtual void OnZoomBasisChanging()
{
if (ZoomBasisChanging != null)
{
ZoomBasisChanging(this, EventArgs.Empty);
}
}
public event EventHandler ZoomBasisChanged;
protected virtual void OnZoomBasisChanged()
{
if (ZoomBasisChanged != null)
{
ZoomBasisChanged(this, EventArgs.Empty);
}
}
public ZoomBasis ZoomBasis
{
get
{
return this.zoomBasis;
}
set
{
if (this.zoomBasis != value)
{
OnZoomBasisChanging();
this.zoomBasis = value;
switch (this.zoomBasis)
{
//合适大小(完整显示图像)
case ZoomBasis.FitToWindow:
ZoomToWindow();
// Enable PanelAutoScroll only long enough to recenter the view
PanelAutoScroll = true;
PanelAutoScroll = false;
// this would be unset by the scalefactor changes in ZoomToWindow
this.zoomBasis = ZoomBasis.FitToWindow;
break;
//实际大小
case ZoomBasis.ScaleFactor:
PanelAutoScroll = true;
break;
//合适宽度
case ZoomBasis.FitToWidth:
ZoomToWidth();
PanelAutoScroll = true;
this.zoomBasis = ZoomBasis.FitToWidth;
break;
//合适高度
case ZoomBasis.FitToHeight:
ZoomToHeight();
PanelAutoScroll = true;
this.zoomBasis = ZoomBasis.FitToHeight;
break;
default:
throw new InvalidEnumArgumentException();
}
OnZoomBasisChanged();
}
}
}
protected override void HandleMouseWheel(Control sender, MouseEventArgs e)
{
if (Control.ModifierKeys == Keys.Control)
{
double mouseDelta = (double)e.Delta / 120.0f;
Rectangle visibleDocBoundsStart = this.VisibleDocumentBounds;
System.Drawing.Point mouseDocPt = this.MouseToDocument(sender, new System.Drawing.Point(e.X, e.Y));
RectangleF visibleDocDocRect1 = this.VisibleDocumentRectangleF;
PointF mouseNPt = new PointF(
(mouseDocPt.X - visibleDocDocRect1.X) / visibleDocDocRect1.Width,
(mouseDocPt.Y - visibleDocDocRect1.Y) / visibleDocDocRect1.Height);
Rectangle rc = this.PanelClientRectangle;
int width = this.SurfaceScrollableWidth;
int height = this.SurfaceScrollableHeight;
//获取鼠标在图像中的坐标定位
double originX = 0.5;
double originY = 0.5;
double ptxInDoc = mouseDocPt.X * this.ScaleRatio;
double ptyInDoc = mouseDocPt.Y * this.ScaleRatio;
if (rc.Width < width)
{
originX = (ptxInDoc + this.PanelScrollPosition.X - 0.0) / width;
}
if (rc.Height < height)
{
originY = (ptyInDoc + this.PanelScrollPosition.Y - 0.0) / height;
}
const double factor = 1.12;
double mouseFactor = Math.Pow(factor, Math.Abs(mouseDelta));
if (e.Delta > 0)
{
this.ZoomIn(mouseFactor);
}
else if (e.Delta < 0)
{
this.ZoomOut(mouseFactor);
}
RectangleF visibleDocDocRect2 = this.VisibleDocumentRectangleF;
PointF scrollPt2 = new PointF(
mouseDocPt.X - visibleDocDocRect2.Width * mouseNPt.X,
mouseDocPt.Y - visibleDocDocRect2.Height * mouseNPt.Y);
this.DocumentScrollPositionF = scrollPt2;
int width2 = this.SurfaceScrollableWidth;
int height2 = this.SurfaceScrollableHeight;
if ((rc.Width < width2 || rc.Height < height2) && (rc.Width < width || rc.Height < height))
{
//根据鼠标在图像中的坐标重新定位放大后的图像
this.PanelScrollPosition = new System.Drawing.Point(
(int)(width2 * originX - ptxInDoc + 0),
(int)(height2 * originY - ptyInDoc + 0));
}
else if (rc.Width < width2 || rc.Height < height2)
{
this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0);
}
else
{
this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0);
}
Rectangle visibleDocBoundsEnd = this.VisibleDocumentBounds;
if (visibleDocBoundsEnd != visibleDocBoundsStart)
{
// Make sure the screen updates, otherwise it can get a little funky looking
this.Update();
}
}
base.HandleMouseWheel(sender, e);
}
public void UpdateAuxiliaryLineEnabled()
{
this.AuxiliaryLineEnabled = this.AuxiliaryLineEnabled;
}
public void UpdateGridLineEnabled()
{
this.GridLineEnabled = this.GridLineEnabled;
}
protected override void OnLoad(EventArgs e)
{
if (this.appWorkspace == null)
{
throw new InvalidOperationException("Must set the Workspace property");
}
base.OnLoad(e);
}
public event EventHandler ActiveLayerChanging;
protected void OnLayerChanging()
{
if (ActiveLayerChanging != null)
{
ActiveLayerChanging(this, EventArgs.Empty);
}
}
public event EventHandler ActiveLayerChanged;
protected void OnLayerChanged()
{
this.Focus();
if (ActiveLayerChanged != null)
{
ActiveLayerChanged(this, EventArgs.Empty);
}
}
public event EventHandler ToolChanging;
protected void OnToolChanging()
{
if (ToolChanging != null)
{
ToolChanging(this, EventArgs.Empty);
}
}
public event EventHandler ToolChanged;
protected void OnToolChanged()
{
if (ToolChanged != null)
{
ToolChanged(this, EventArgs.Empty);
}
}
public AppWorkspace AppWorkspace
{
get
{
return this.appWorkspace;
}
set
{
this.appWorkspace = value;
}
}
public event EventHandler FilePathChanged;
protected virtual void OnFilePathChanged()
{
if (FilePathChanged != null)
{
FilePathChanged(this, EventArgs.Empty);
}
}
public string FilePath
{
get
{
return this.filePath;
}
}
public string GetFriendlyName()
{
string friendlyName;
if (this.filePath != null)
{
friendlyName = Path.GetFileName(this.filePath);
}
else if (this.fileText != null)
{
friendlyName = this.fileText;
}
else
{
friendlyName = PdnResources.GetString("Untitled.FriendlyName");
}
return friendlyName;
}
/*public FileType FileType
{
get
{
return this.fileType;
}
}*/
public event EventHandler SaveOptionsChanged;
protected virtual void OnSaveOptionsChanged()
{
if (SaveOptionsChanged != null)
{
SaveOptionsChanged(this, EventArgs.Empty);
}
}
///
/// Sets the FileType and SaveConfigToken parameters that are used if the
/// user chooses "Save" from the File menu. These are not used by the
/// DocumentControl class and should be used by whoever actually goes
/// to save the Document instance.
///
///
///
public void SetDocumentSaveOptions(string newFilePath/*, FileType newFileType, SaveConfigToken newSaveConfigToken*/)
{
this.filePath = newFilePath;
OnFilePathChanged();
/*this.fileType = newFileType;
if (newSaveConfigToken == null)
{
this.saveConfigToken = null;
}
else
{
this.saveConfigToken = (SaveConfigToken)newSaveConfigToken.Clone();
}*/
OnSaveOptionsChanged();
}
public void GetDocumentSaveOptions(out string filePathResult /*,out FileType fileTypeResult out SaveConfigToken saveConfigTokenResult,*/)
{
filePathResult = this.filePath;
/*fileTypeResult = this.fileType;
if (this.saveConfigToken == null)
{
saveConfigTokenResult = null;
}
else
{
saveConfigTokenResult = (SaveConfigToken)this.saveConfigToken.Clone();
}*/
}
///
/// Updates any pertinent EXIF tags, such as "Creation Software", to be
/// relevant or up-to-date.
///
///
private void UpdateExifTags(Document document)
{
// I have verified that other image editing software overwrites this tag,
// and does not just add it when it does not exist.
PropertyItem pi = Exif.CreateAscii(ExifTagID.Software, PdnInfo.GetProductName(false));
document.Metadata.ReplaceExifValues(ExifTagID.Software, new PropertyItem[1] { pi });
}
private ZoomBasis savedZb;
private ScaleFactor savedSf;
protected override void OnDocumentChanging(Document newDocument)
{
base.OnDocumentChanging(newDocument);
this.savedZb = this.ZoomBasis;
this.savedSf = ScaleFactor;
if (newDocument != null)
{
UpdateExifTags(newDocument);
}
}
protected override void OnDocumentChanged()
{
if (this.Document != null)
{
bool oldDirty = this.Document.Dirty;
this.Document.Invalidate();
this.Document.Dirty = oldDirty;
this.ZoomBasis = this.savedZb;
if (this.savedZb == ZoomBasis.ScaleFactor)
{
ScaleFactor = this.savedSf;
}
}
AutoScrollPosition = new System.Drawing.Point(0, 0);
base.OnDocumentChanged();
}
///
/// Takes the current Document from this DocumentWorkspace instance and adds it to the MRU list.
///
///
public void AddToMruList()
{
string fullFileName = Path.GetFullPath(this.FilePath);
MostRecentFile mrf = new MostRecentFile(fullFileName, null);
if (AppWorkspace.MostRecentFiles.Contains(fullFileName))
{
AppWorkspace.MostRecentFiles.Remove(fullFileName);
}
AppWorkspace.MostRecentFiles.Add(mrf);
AppWorkspace.MostRecentFiles.SaveMruList();
}
///
/// Shows an OpenFileDialog or SaveFileDialog and populates the InitialDirectory from the global
/// settings repository if possible.
///
/// The FileDialog to show.
///
/// The FileDialog should already have its InitialDirectory populated as a suggestion of where to start.
///
public static DialogResult ShowFileDialog(Control owner, IFileDialog fd)
{
string initialDirectory = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, fd.InitialDirectory);
bool dirExists = false;
try
{
DirectoryInfo dirInfo = new DirectoryInfo(initialDirectory);
using (new WaitCursorChanger(owner))
{
dirExists = dirInfo.Exists;
if (!dirInfo.Exists)
{
initialDirectory = fd.InitialDirectory;
}
}
}
catch (Exception)
{
initialDirectory = fd.InitialDirectory;
}
fd.InitialDirectory = initialDirectory;
OurFileDialogUICallbacks ouc = new OurFileDialogUICallbacks();
DialogResult result = fd.ShowDialog(owner, ouc);
if (result == DialogResult.OK)
{
string fileName;
if (fd is IFileOpenDialog)
{
string[] fileNames = ((IFileOpenDialog)fd).FileNames;
if (fileNames.Length > 0)
{
fileName = fileNames[0];
}
else
{
fileName = null;
}
}
else if (fd is IFileSaveDialog)
{
fileName = ((IFileSaveDialog)fd).FileName;
}
else
{
throw new InvalidOperationException();
}
if (fileName != null)
{
string newDir = Path.GetDirectoryName(fileName);
Settings.CurrentUser.SetString(SettingNames.LastFileDialogDirectory, newDir);
}
else
{
throw new FileNotFoundException();
}
}
return result;
}
private sealed class OurFileDialogUICallbacks
: IFileDialogUICallbacks
{
public FileOverwriteAction ShowOverwritePrompt(IWin32Window owner, string pathName)
{
FileOverwriteAction returnVal;
string title = PdnResources.GetString("SaveAs.OverwriteConfirmation.Title");
string textFormat = PdnResources.GetString("SaveAs.OverwriteConfirmation.Text.Format");
string fileName;
try
{
fileName = Path.GetFileName(pathName);
}
catch (Exception)
{
fileName = pathName;
}
string text = string.Format(textFormat, fileName);
DialogResult result = MessageBox.Show(owner, text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
switch (result)
{
case DialogResult.Yes:
returnVal = FileOverwriteAction.Overwrite;
break;
case DialogResult.No:
returnVal = FileOverwriteAction.Cancel;
break;
default:
throw new InvalidEnumArgumentException();
}
return returnVal;
}
public bool ShowError(IWin32Window owner, string filePath, Exception ex)
{
if (ex is PathTooLongException)
{
string title = PdnInfo.GetBareProductName();
string message = PdnResources.GetString("FileDialog.PathTooLongException.Message");
MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
return true;
}
else
{
return false;
}
}
public IFileTransferProgressEvents CreateFileTransferProgressEvents()
{
return new OurProgressEvents();
}
}
private sealed class OurProgressEvents
: IFileTransferProgressEvents
{
private TransferProgressDialog progressDialog;
private ICancelable cancelSink;
private int itemCount = 0;
private int itemOrdinal = 0;
private string itemName = string.Empty;
private long totalWork;
private long totalProgress;
private const int maxPBValue = 200; // granularity of progress bar. 100 means 1%, 200 means 0.5%, etc.
private bool cancelRequested = false;
private ManualResetEvent operationEnded = new ManualResetEvent(false);
public OurProgressEvents()
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "cancelSink")]
public void BeginOperation(IWin32Window owner, EventHandler callWhenUIShown, ICancelable cancelSink)
{
if (this.progressDialog != null)
{
throw new InvalidOperationException("Operation already in progress");
}
this.progressDialog = new TransferProgressDialog();
this.progressDialog.Text = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.TransferProgress.Title");
this.progressDialog.Icon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileOpenIcon.png").Reference);
this.progressDialog.Title = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Initializing");
this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
this.progressDialog.ProgressBar.Maximum = maxPBValue;
this.progressDialog.CancelClicked +=
delegate (object sender, EventArgs e)
{
this.cancelRequested = true;
this.cancelSink.RequestCancel();
UpdateUI();
};
EventHandler progressDialog_Shown =
delegate (object sender, EventArgs e)
{
callWhenUIShown(this, EventArgs.Empty);
};
this.cancelSink = cancelSink;
this.itemOrdinal = 0;
this.cancelRequested = false;
this.itemName = string.Empty;
this.itemCount = 0;
this.itemOrdinal = 0;
this.totalProgress = 0;
this.totalWork = 0;
this.progressDialog.Shown += progressDialog_Shown;
this.progressDialog.ShowDialog(owner);
this.progressDialog.Shown -= progressDialog_Shown;
this.progressDialog.Dispose();
this.progressDialog = null;
this.cancelSink = null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemCount")]
public void SetItemCount(int itemCount)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(SetItemCount), new object[] { itemCount });
}
else
{
this.itemCount = itemCount;
UpdateUI();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemOrdinal")]
public void SetItemOrdinal(int itemOrdinal)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(SetItemOrdinal), new object[] { itemOrdinal });
}
else
{
this.itemOrdinal = itemOrdinal;
this.totalWork = 0;
this.totalProgress = 0;
UpdateUI();
}
}
public void SetItemInfo(string itemInfo)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(SetItemInfo), new object[] { itemInfo });
}
else
{
this.itemName = itemInfo;
UpdateUI();
}
}
public void BeginItem()
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(BeginItem), null);
}
else
{
this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalWork")]
public void SetItemWorkTotal(long totalWork)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(SetItemWorkTotal), new object[] { totalWork });
}
else
{
this.totalWork = totalWork;
UpdateUI();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalProgress")]
public void SetItemWorkProgress(long totalProgress)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(SetItemWorkProgress), new object[] { totalProgress });
}
else
{
this.totalProgress = totalProgress;
UpdateUI();
}
}
public void EndItem(WorkItemResult result)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(EndItem), new object[] { result });
}
else
{
}
}
public void EndOperation(OperationResult result)
{
if (this.progressDialog.InvokeRequired)
{
this.progressDialog.BeginInvoke(new Procedure(EndOperation), new object[] { result });
}
else
{
this.progressDialog.Close();
}
}
public WorkItemFailureAction ReportItemFailure(Exception ex)
{
if (this.progressDialog.InvokeRequired)
{
object result = this.progressDialog.Invoke(
new Function(ReportItemFailure),
new object[] { ex });
return (WorkItemFailureAction)result;
}
else
{
WorkItemFailureAction result;
result = ShowFileTransferFailedDialog(ex);
return result;
}
}
private WorkItemFailureAction ShowFileTransferFailedDialog(Exception ex)
{
WorkItemFailureAction result;
Icon formIcon = this.progressDialog.Icon;
string formTitle = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.Title");
Image taskImage = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference;
string introTextFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.IntroText.Format");
string introText = string.Format(introTextFormat, ex.Message);
TaskButton retryTB = new TaskButton(
PdnResources.GetImageResource("Icons.MenuImageRotate90CWIcon.png").Reference,
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ActionText"),
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ExplanationText"));
TaskButton skipTB = new TaskButton(
PdnResources.GetImageResource("Icons.HistoryFastForwardIcon.png").Reference,
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ActionText"),
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ExplanationText"));
TaskButton cancelTB = new TaskButton(
PdnResources.GetImageResource("Icons.CancelIcon.png").Reference,
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ActionText"),
PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ExplanationText"));
List taskButtons = new List();
taskButtons.Add(retryTB);
// Only have the Skip button if there is more than 1 item being transferred.
// If only 1 item is begin transferred, Skip and Cancel are essentially synonymous.
if (this.itemCount > 1)
{
taskButtons.Add(skipTB);
}
taskButtons.Add(cancelTB);
int width96 = (TaskDialog.DefaultPixelWidth96Dpi * 4) / 3; // 33% wider
TaskButton clickedTB = TaskDialog.Show(
this.progressDialog,
formIcon,
formTitle,
taskImage,
true,
introText,
taskButtons.ToArray(),
retryTB,
cancelTB,
width96,
false,
0,
out bool unuse);
if (clickedTB == retryTB)
{
result = WorkItemFailureAction.RetryItem;
}
else if (clickedTB == skipTB)
{
result = WorkItemFailureAction.SkipItem;
}
else
{
result = WorkItemFailureAction.CancelOperation;
}
return result;
}
private void UpdateUI()
{
int itemCount2 = Math.Max(1, this.itemCount);
double startValue = (double)this.itemOrdinal / (double)itemCount2;
double endValue = (double)(this.itemOrdinal + 1) / (double)itemCount2;
long totalWork2 = Math.Max(1, this.totalWork);
double lerp = (double)this.totalProgress / (double)totalWork2;
double newValue = Utility.Lerp(startValue, endValue, lerp);
int newValueInt = (int)Math.Ceiling(maxPBValue * newValue);
if (this.cancelRequested)
{
this.progressDialog.CancelEnabled = false;
this.progressDialog.Title = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling");
this.progressDialog.ProcessMsg = string.Empty;
this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
}
else
{
this.progressDialog.CancelEnabled = true;
this.progressDialog.Title = this.itemName;
string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format");
string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount);
this.progressDialog.ProcessMsg = progressText;
this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
this.progressDialog.ProgressBar.Value = newValueInt;
}
}
}
public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect, string startingDir)
{
//FileTypeCollection fileTypes = FileTypes.GetFileTypes();
using (IFileOpenDialog ofd = new ClassicFileOpenDialog())
{
if (startingDir != null)
{
ofd.InitialDirectory = startingDir;
}
else
{
ofd.InitialDirectory = GetDefaultSavePath();
}
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.Multiselect = multiselect;
ofd.Filter = "所有图片类型(*.bmp, *.gif, *.jpg, *.jpeg, *.jpe, *.jfif, *.png, *.tif, *.tiff, *.tga)|*.bmp;*.gif;*.jpg;*.jpeg;*.jpe;*.jfif;*.png;*.tif;*.tiff;*.tga|BMP (*.bmp)|*.bmp|GIF (*.gif)|*.gif|JPEG (*.jpg; *.jpeg; *.jpe; *.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|PNG (*.png)|*.png|TIFF (*.tif; *.tiff)|*.tif;*.tiff|TGA (*.tga)|*.tga";
//ofd.Filter = fileTypes.ToString(true, PdnResources.GetString("FileDialog.Types.AllImages"), false, true);
ofd.FilterIndex = 0;
DialogResult result = ShowFileDialog(owner, ofd);
if (result == DialogResult.OK)
{
fileNames = ofd.FileNames;
if (fileNames.Length > 0)
{
string filePath = fileNames[0];
int index = 0;
if (filePath.Contains("\\"))
{
index = filePath.LastIndexOf('\\');
filePath = filePath.Substring(0, index);
Startup.instance.configModel.FileOpenPath = filePath;
////另存为XML
//string configModelXml = XmlSerializeHelper.XmlSerialize(Startup.instance.configModel);
//string Path = Application.StartupPath + @"\Config\Default\SetUp\GuideStyle.xml";
//FileOperationHelper.WriteStringToFile(configModelXml, Path, FileMode.Create);
}
}
}
else
{
fileNames = new string[0];
}
return result;
}
}
private static string GetDefaultSavePath()
{
string myPics;
try
{
myPics = Shell.GetVirtualPath(VirtualFolderName.UserPictures, false);
DirectoryInfo dirInfo = new DirectoryInfo(myPics); // validate
}
catch (Exception)
{
myPics = "";
}
string dir = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, null);
if (dir == null)
{
dir = myPics;
}
else
{
try
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (!dirInfo.Exists)
{
dir = myPics;
}
}
catch (Exception)
{
dir = myPics;
}
}
return dir;
}
///
/// 图片保存,保存当前激活图片,用来替换原框架的保存
/// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1)
/// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果
/// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为:
/// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像
///
///
public bool DoSaveNew()
{
//判断是否是从硬盘打开,以下是原来的代码,是根据文件名判断的
string newFileName;
//FileType newFileType;
//SaveConfigToken newSaveConfigToken;
GetDocumentSaveOptions(out newFileName/*, out newFileType, out newSaveConfigToken*/);
if (zipHandleHelper != null)
newFileName = zipHandleHelper.zipName;
// 如果没有指定文件名(不是从硬盘打开,是生成或从相机获得),则执行另存为
if (newFileName == null)
{
return DoSaveAsNew();
}
else
{
try
{
//获取文件后缀名
string extension = Path.GetExtension(newFileName);
//保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像、不保存相
using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
{
//保存图片
if (!extension.Equals(".tga"))//不是压缩包
{
ImageCodecInfo icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
if (extension.Equals(".jpg"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
}
else if (extension.Equals(".bmp"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Bmp);
}
else if (extension.Equals("TIFF"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Tiff);
}
EncoderParameters parms = new EncoderParameters(1);
EncoderParameter parm = new EncoderParameter(Encoder.Quality, 100L);
parms.Param[0] = parm;
bitmap.Save(newFileName, icf, parms);
}
//生成配置文件
if (true)
{
//组织配置文件的数据
PicConfigModel picConfigModel = new PicConfigModel();
picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
//picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
picConfigModel.hardware = new PicConfigModel.Hardware();
//picConfigModel.hardware.microscope = "显微镜";
//picConfigModel.hardware.objective = "物镜";
//picConfigModel.hardware.magnificationChanger = "变倍器";
//picConfigModel.hardware.exposureTime = "曝光时间";
//相机参数赋值
GetCameraParameters(picConfigModel);
if (!extension.Equals(".tga"))//压缩包不清楚是否要保存基础和标尺等信息
{
picConfigModel.meta = new PicConfigModel.Meta();
picConfigModel.rule = new PicConfigModel.Rule();
picConfigModel.meta.format = extension;
picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
{
picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
}
else
{
if (Startup.instance.ruleDB != null)
{
picConfigModel.rule.ruler_name = Startup.instance.ruleDB.ruler_name;
picConfigModel.rule.gain_multiple = Startup.instance.ruleDB.gain_multiple;
picConfigModel.rule.pixel_length = (int)Startup.instance.ruleDB.pixel_length;
picConfigModel.rule.physical_length = Startup.instance.ruleDB.physical_length;
picConfigModel.rule.ruler_units = Startup.instance.ruleDB.ruler_units;
}
}
FileInfo fileInfo = new FileInfo(newFileName);
long lengthOfDocument = fileInfo.Length;
picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument); ;
//获取图像所在的目录
string directoryPath = Path.GetDirectoryName(newFileName);
//获取不带后缀的文件名
string noExtension = Path.GetFileNameWithoutExtension(newFileName);
picConfigModel.meta.text = noExtension;
//按路径和名称保存xml文件
string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel);
//xml保存路径
string filePath = directoryPath + "\\" + noExtension + ".xml";
//保存xml
FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
}
else
{
if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
}
}
this.Document.Dirty = false;
}
}
catch (Exception)
{
MessageBox.Show(PdnResources.GetString("Menu.Imagesavefailed.text"));
return false;
}
}
return true;
}
///
/// 获取批量保存中设置的参数,按生成规律提取文件名称
///
/// 文件名称
///
public bool GetParameters(out string file_Name)
{
file_Name = string.Empty;
batchSaveAutoModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml", FileMode.Open));
if (batchSaveAutoModel.Whether)
{
file_Name = batchSaveAutoModel.prefix + batchSaveAutoModel.fileName + "_" + batchSaveAutoModel.startNum + batchSaveAutoModel.suffix;
batchSaveAutoModel.startNum = batchSaveAutoModel.startNum + 1;
//另存为XML
string stageModelXml = XmlSerializeHelper.XmlSerialize(batchSaveAutoModel);
string filePath = Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml";
FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create);
}
return batchSaveAutoModel.Whether;
}
///
/// 文件另存,用来替换原框架的保存
/// 1)将图片另存到其他位置,即变化不保存在原图像上
/// 2)点击另存为,打开保存路径窗口(图1)
/// 3)并根据(图1)中对应的设置判断是否关闭打开的图像
/// 4)若名称重复,则弹出对应提示,查看效果可点击图1中的【保存】按钮
///
///
public bool DoSaveAsNew(int mode = 0)
{
//判断是否是压缩包文件
bool isZipFile = false;
if (zipHandleHelper != null)
isZipFile = true;
using (SaveFileDialog saveDialog = new SaveFileDialog())
{
ConfigModel configModel = Startup.instance.configModel;//获取另存窗口几个选项的配置
File.MySaveDialogControl saveDialogCtrl = new File.MySaveDialogControl(@"C:\Users\dlrj\Desktop\晶粒度-冷轧薄板晶粒度评级2 - 副本.JPG"/*lblFilePath.Text*/, this);
//saveDialogCtrl.FileDlgInitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
string friendName = this.GetFriendlyName();
string imgType = GetImgType(friendName);
int filterIndex = FilterIndex(imgType);
//生成配置文件选中状态
if (configModel.WhetherGenerateConfig == 0)
saveDialogCtrl.checkBox1.Checked = false;
//关闭图像选中状态
if (configModel.WhetherCloseAfterSave == 0)
saveDialogCtrl.checkBox2.Checked = false;
if (isZipFile)
{
saveDialog.Filter = "Tga(*.tga)|*.tga";
saveDialog.DefaultExt = "tga";
saveDialogCtrl.checkBox3.Visible = false;
saveDialogCtrl.checkBox4.Visible = false;
saveDialogCtrl.checkBox5.Visible = false;
saveDialogCtrl.checkBox6.Visible = false;
saveDialogCtrl.numericUpDown1.Visible = false;
saveDialogCtrl.label1.Visible = false;
}
else
{
if (mode > 0)
{
saveDialogCtrl.checkBox2.Checked = false;
saveDialogCtrl.checkBox2.Enabled = false;
saveDialogCtrl.checkBox6.Enabled = false;
}
//保存网格选中状态
if (configModel.WhetherSaveGridData == 1)
saveDialogCtrl.checkBox3.Checked = true;
//标注测量嵌入图像选中状态
if (configModel.WhetherLabelMeasureInsert == 1)
saveDialogCtrl.checkBox4.Checked = true;
if (configModel.PhaseInsert == 1)
saveDialogCtrl.checkBox6.Checked = true;
//压缩比例选中状态
if (configModel.WhetherCompression == 1)
saveDialogCtrl.checkBox5.Checked = true;
saveDialogCtrl.numericUpDown1.Value = configModel.CompressionRatio;//压缩比例数值
saveDialog.Filter = "Jpeg(*.jpg)|*.jpg|Tiff(*.tiff)|*.tiff|Bmp(*.bmp)|*.bmp|Png(*.png)|*.png";
saveDialog.DefaultExt = imgType;
}
saveDialog.FilterIndex = filterIndex;
saveDialog.CheckFileExists = false;// true;
saveDialog.AddExtension = true;
string m_FileName = Path.GetFileNameWithoutExtension(friendName);//friendName.Substring(friendName.LastIndexOf('\\') + 1, friendName.LastIndexOf('.') - friendName.LastIndexOf('\\') - 1);
string suffixName = Path.GetExtension(friendName);//friendName.Substring(friendName.LastIndexOf(".") + 1, (friendName.Length - friendName.LastIndexOf(".") - 1)); ;
//判断是否有保存参数,有则获取,无则使用原始文件名
//if (!GetParameters(out file_Name))
//{
// saveDialog.FileName = file_Name;
//}
//else
//{
if (mode >= 0)
{
saveDialog.FileName = m_FileName /*+ " - " + PdnResources.GetString("Menu.Acopyofth.Text") */+ suffixName;
}
else
{
saveDialog.FileName = m_FileName + " - " + PdnResources.GetString("Menu.Acopyofth.Text") + suffixName;
}
//}
saveDialog.DereferenceLinks = true;
//saveDialog.ShowHelp = true;
if (Environment.OSVersion.Version.Major < 6)
saveDialog.SetPlaces(new object[] { (int)Places.Desktop, (int)Places.Printers, (int)Places.Favorites, (int)Places.Programs, (int)Places.Fonts, });
string path = "";
if (saveDialog.ShowDialog(saveDialogCtrl, this) == DialogResult.OK)
{
//文件路径
path = saveDialog.FileName;
string fileText = string.Empty;
if (path.Contains("\\"))
{
int index = path.LastIndexOf('\\');
fileText = path.Substring(0, index);
}
this.fileText = fileText;
this.filePath = saveDialog.FileName;
Startup.instance.configModel.HardFilePath = this.fileText;
AppWorkspace.Widgets.ImageIndexDialog.PreviewRefresh();
//是否生成配置文件
bool createConfig = saveDialogCtrl.checkBox1.Checked;
//保存后是否关闭图像
bool afterSaveClost = saveDialogCtrl.checkBox2.Checked;
//保存时是否保存网格数据
bool saveGridLine = saveDialogCtrl.checkBox3.Checked;
//标注及测量信息是否嵌入图像
bool implantLabelAndMeasure = saveDialogCtrl.checkBox4.Checked;
//相信息是否嵌入图像
bool implantPhase = saveDialogCtrl.checkBox6.Checked;
//是否压缩
bool compress = saveDialogCtrl.checkBox5.Checked;
//压缩比例
decimal compressRate = saveDialogCtrl.numericUpDown1.Value;
//重新保存选项到配置文件
if (createConfig)
configModel.WhetherGenerateConfig = 1;
else
configModel.WhetherGenerateConfig = 0;
if (afterSaveClost)
configModel.WhetherCloseAfterSave = 1;
else
configModel.WhetherCloseAfterSave = 0;
if (saveGridLine)
configModel.WhetherSaveGridData = 1;
else
configModel.WhetherSaveGridData = 0;
if (implantLabelAndMeasure)
configModel.WhetherLabelMeasureInsert = 1;
else
configModel.WhetherLabelMeasureInsert = 0;
if (implantPhase)
configModel.PhaseInsert = 1;
else
configModel.PhaseInsert = 0;
if (compress)
configModel.WhetherCompression = 1;
else
configModel.WhetherCompression = 0;
configModel.CompressionRatio = compressRate;
string configModelXml = XmlSerializeHelper.XmlSerialize(configModel);
FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" +
Startup.instance.SettingPrefix + "\\Config.xml", FileMode.Create);
//保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
{
//获取文件后缀名
string extension = Path.GetExtension(path);
if (!extension.Equals(".tga"))
{
using (Bitmap dstBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat))
{
Graphics graphics = Graphics.FromImage(dstBitmap);
//判断保存时是否保存相信息
if (implantPhase)
{
if (this.phaseModels != null && this.phaseModels.Count > 0)
{
foreach (PhaseModel model in this.phaseModels)
{
if (model.choise)
{
graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(model.mat), 0, 0, bitmap.Width, bitmap.Height);
}
}
}
}
//判断保存时是否保存网格数据,是则嵌入图像
if (saveGridLine)
{
DrawRulerHelper.drawGrid(AppWorkspace.GetGridModel(), graphics, this.CompositionSurface.Width, this.CompositionSurface.Height);
}
//判断标注及测量信息是否嵌入图像
//this.SurfaceBox.Surface.CreateAliasedBitmapWithLayer(true, true);
if (implantLabelAndMeasure)
{
if (this.GraphicsList != null && this.GraphicsList.Count > 0)
{
GraphicsList.UnselectAll();
this.GraphicsList.Draw(graphics);
}
}
//保存图片
ImageCodecInfo icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
if (extension.Equals(".jpg"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
}
else if (extension.Equals(".bmp"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Bmp);
}
else if (extension.Equals(".tiff"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Tiff);
}
EncoderParameters parms = new EncoderParameters(1);
EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
parms.Param[0] = parm;
dstBitmap.Save(path, icf, parms);
}
}
else
{
//另存的路径与原zip路径不相同,则copy一份;相同不做处理
if (!path.Equals(zipHandleHelper.zipName))
{
System.IO.File.Copy(zipHandleHelper.zipName, path, true);
}
}
//保存配置文件
if (createConfig)
{
//组织配置文件的数据
PicConfigModel picConfigModel = new PicConfigModel();
if (!implantLabelAndMeasure) picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
if (!implantLabelAndMeasure) picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
//picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
picConfigModel.hardware = new PicConfigModel.Hardware();
//相机参数赋值
GetCameraParameters(picConfigModel);
picConfigModel.meta = new PicConfigModel.Meta();
picConfigModel.rule = new PicConfigModel.Rule();
picConfigModel.meta.format = extension;
picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
{
picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
}
else
{
if (Startup.instance.ruleDB != null)
{
picConfigModel.rule.ruler_name = Startup.instance.ruleDB.ruler_name;
picConfigModel.rule.gain_multiple = Startup.instance.ruleDB.gain_multiple;
picConfigModel.rule.pixel_length = (int)Startup.instance.ruleDB.pixel_length;
picConfigModel.rule.physical_length = Startup.instance.ruleDB.physical_length;
picConfigModel.rule.ruler_units = Startup.instance.ruleDB.ruler_units;
}
}
FileInfo fileInfo = new FileInfo(path);
long lengthOfDocument = fileInfo.Length;
picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument);
//获取图像所在的目录
string directoryPath = Path.GetDirectoryName(path);
//获取不带后缀的文件名
string noExtension = Path.GetFileNameWithoutExtension(path);
picConfigModel.meta.text = noExtension;
//按路径和名称保存xml文件
string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel);
//xml保存路径
string filePath = directoryPath + "\\" + noExtension + ".xml";
//保存xml
FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
if (extension.Equals(".tga"))
{
//copy了新的zip包,则修改新zip包内的xml
if (!path.Equals(zipHandleHelper.zipName))
{
ZipHandleHelper newZipFile = new ZipHandleHelper(path);
if (newZipFile != null)
{
if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel))
MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
}
}
//没有copy,修改旧zip包的xml
else
{
if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
}
}
}
if (this.Document != null)
{
this.Document.Dirty = false;
}
if (mode <= 0)
{
//保存后是否关闭图像
if (afterSaveClost)
{
this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
}
else
{
this.filePath = path;
this.fileText = this.GetFriendlyName();
this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
}
}
}
}
else
{
return false;
}
}
return true;
}
///
/// 获取图片类型
///
/// 文件路径
///
public string GetImgType(string filePath)
{
string imgType = string.Empty;
if (filePath.Contains("."))
{
int index = filePath.LastIndexOf('.');
imgType = filePath.Substring(index + 1);
}
else
{
imgType = "jpg";
}
return imgType;
}
///
/// 获取图片另存默认保存类型
///
/// 图片类型
///
public int FilterIndex(string imgType)
{
string[] vs = new string[] { "Jpeg", "jpg", "tiff", "bmp", "png" };
int filterIndex = 1;
for (int i = 0; i < vs.Length; i++)
{
if (string.Compare(imgType, vs[i], true) == 0)
{
filterIndex = i;
break;
}
}
if (filterIndex == 0) filterIndex = 1;
return filterIndex;
}
///
/// 相机参数赋值
///
/// 图片对应的XML配置
public void GetCameraParameters(PicConfigModel picConfigModel)
{
if (this.hardware != null)
{
picConfigModel.hardware.microscope = this.hardware.microscope;
picConfigModel.hardware.objective = this.hardware.objective;
picConfigModel.hardware.magnificationChanger = this.hardware.magnificationChanger;
picConfigModel.hardware.exposureTime = this.hardware.cameraParamModel.parame.LNExposure.ToString();
picConfigModel.hardware.Resolution = this.hardware.cameraParamModel.parame.Resolution;
picConfigModel.hardware.GlobalGain = this.hardware.cameraParamModel.parame.GlobalGain;
picConfigModel.hardware.Brightness = this.hardware.cameraParamModel.parame.Brightness;
picConfigModel.hardware.ATExposure = this.hardware.cameraParamModel.parame.ATExposure;
picConfigModel.hardware.WhiteBalance = this.hardware.cameraParamModel.parame.WhiteBalance;
picConfigModel.hardware.BlackBalance = this.hardware.cameraParamModel.parame.BlackBalance;
picConfigModel.hardware.Monochromatic = this.hardware.cameraParamModel.parame.Monochromatic;
picConfigModel.hardware.FlatFieldCorrection = this.hardware.cameraParamModel.parame.FlatFieldCorrection;
picConfigModel.hardware.Sharpness = this.hardware.cameraParamModel.parame.Sharpness;
picConfigModel.hardware.HDR = this.hardware.cameraParamModel.parame.HDR;
picConfigModel.hardware.AreaWhiteBalanceEnable = this.hardware.cameraParamModel.parame.AreaWhiteBalanceEnable;
picConfigModel.hardware.Gamma = this.hardware.cameraParamModel.parame.Gamma;
picConfigModel.hardware.Contrast = this.hardware.cameraParamModel.parame.Contrast;
picConfigModel.hardware.Saturation = this.hardware.cameraParamModel.parame.Saturation;
picConfigModel.hardware.RedChannel = this.hardware.cameraParamModel.parame.RedChannel;
picConfigModel.hardware.GreenChannel = this.hardware.cameraParamModel.parame.GreenChannel;
picConfigModel.hardware.BlueChannel = this.hardware.cameraParamModel.parame.BlueChannel;
picConfigModel.hardware.ColorTemperature = this.hardware.cameraParamModel.parame.ColorTemperature;
picConfigModel.hardware.Horizontal = this.hardware.cameraParamModel.parame.Horizontal;
picConfigModel.hardware.Vertical = this.hardware.cameraParamModel.parame.Vertical;
picConfigModel.hardware.VerticalCorrection = this.hardware.cameraParamModel.parame.VerticalCorrection;
picConfigModel.hardware.ChannelsSelect = this.hardware.cameraParamModel.parame.ChannelsSelect;
picConfigModel.hardware.RotateR90 = this.hardware.cameraParamModel.parame.RotateR90;
picConfigModel.hardware.RotateL90 = this.hardware.cameraParamModel.parame.RotateL90;
picConfigModel.hardware.Rotate = this.hardware.cameraParamModel.parame.Rotate;
picConfigModel.hardware.Hue = this.hardware.cameraParamModel.parame.Hue;
}
}
///
/// 批量保存
///
/// 文件名
/// 是否生成配置文件
/// 保存后是否关闭图像
/// 保存时是否保存网格数据
/// 标注及测量信息是否嵌入图像
/// 是否压缩
/// 压缩比例
///
public bool SaveForBatch(string fileName, bool createConfig, bool afterSaveClost, bool saveGridLine, bool implantLabelAndMeasure, bool compress, decimal compressRate, bool implantPhase)
{
//保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
{
Graphics graphics = Graphics.FromImage(bitmap);
if (implantPhase)
{
if (this.phaseModels != null && this.phaseModels.Count > 0)
{
foreach (PhaseModel model in this.phaseModels)
{
if (model.choise)
{
graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(model.mat), 0, 0, bitmap.Width, bitmap.Height);
}
}
}
}
//判断保存时是否保存网格数据,是则嵌入图像
if (saveGridLine)
{
DrawRulerHelper.drawGrid(AppWorkspace.GetGridModel(), graphics, this.CompositionSurface.Width, this.CompositionSurface.Height);
}
//判断标注及测量信息是否嵌入图像
//this.SurfaceBox.Surface.CreateAliasedBitmapWithLayer(true, true);
if (implantLabelAndMeasure)
{
if (this.GraphicsList != null && this.GraphicsList.Count > 0)
{
this.GraphicsList.Draw(graphics);
}
}
//获取文件后缀名
string extension = Path.GetExtension(fileName);
//保存图片
ImageCodecInfo icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
if (extension.Equals(".jpg"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Jpeg);
}
else if (extension.Equals(".bmp"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Bmp);
}
else if (extension.Equals(".tiff"))
{
icf = FileOperationHelper.GetImageCodecInfo(ImageFormat.Tiff);
}
EncoderParameters parms = new EncoderParameters(1);
EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
parms.Param[0] = parm;
bitmap.Save(fileName, icf, parms);
//保存配置文件
if (createConfig)
{
//组织配置文件的数据
PicConfigModel picConfigModel = new PicConfigModel();
picConfigModel.hardware = new PicConfigModel.Hardware();
if (!implantLabelAndMeasure) picConfigModel.labels = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Label);
if (!implantLabelAndMeasure) picConfigModel.measures = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Measure);
//picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
picConfigModel.meta = new PicConfigModel.Meta();
picConfigModel.rule = new PicConfigModel.Rule();
picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
GetCameraParameters(picConfigModel);
//获取图像所在的目录
string directoryPath = Path.GetDirectoryName(fileName);
//获取不带后缀的文件名
string noExtension = Path.GetFileNameWithoutExtension(fileName);
//按路径和名称保存xml文件
string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel);
//xml保存路径
string filePath = directoryPath + "\\" + noExtension + ".xml";
//保存xml
FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
}
if (this.Document != null)
{
this.Document.Dirty = false;
}
//保存后是否关闭图像
if (afterSaveClost)
{
this.Document.Dirty = false;
this.AppWorkspace.toRemoveDocumentWorkspaceIndex = this.AppWorkspace.DocumentWorkspaces.Length - 1;
this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
}
else
{
this.filePath = fileName;
this.fileText = this.GetFriendlyName();
this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
}
}
return true;
}
//public static Document LoadDocument(Control owner, string fileName, /*out FileType fileTypeResult,*/ ProgressEventHandler progressCallback)
//{
//return Document.FromMat(new Mat(fileName));
/*FileTypeCollection fileTypes;
int ftIndex;
FileType fileType;
fileTypeResult = null;
try
{
fileTypes = FileTypes.GetFileTypes();
ftIndex = fileTypes.IndexOfExtension(Path.GetExtension(fileName));
if (ftIndex == -1)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ImageTypeNotRecognized"));
return null;
}
fileType = fileTypes[ftIndex];
fileTypeResult = fileType;
}
catch (ArgumentException)
{
string format = PdnResources.GetString("LoadImage.Error.InvalidFileName.Format");
string error = string.Format(format, fileName);
Utility.ErrorBox(owner, error);
return null;
}
Document document = null;
using (new WaitCursorChanger(owner))
{
Utility.GCFullCollect();
Stream stream = null;
OpenCvSharp.Mat tempMat = null;
try
{
try
{
tempMat = new Mat(fileName);
stream = tempMat.ToMemoryStream(Path.GetExtension(fileName));
//stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long totalBytes = 0;
SiphonStream siphonStream = new SiphonStream(stream);
IOEventHandler ioEventHandler = null;
ioEventHandler =
delegate (object sender, IOEventArgs e)
{
if (progressCallback != null)
{
totalBytes += (long)e.Count;
double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
progressCallback(null, new ProgressEventArgs(percent));
}
};
siphonStream.IOFinished += ioEventHandler;
using (new WaitCursorChanger(owner))
{
document = fileType.Load(siphonStream);
if (progressCallback != null)
{
progressCallback(null, new ProgressEventArgs(100.0));
}
}
siphonStream.IOFinished -= ioEventHandler;
siphonStream.Close();
GC.Collect();
}
catch (WorkerThreadException ex)
{
Type innerExType = ex.InnerException.GetType();
ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });
if (ci == null)
{
throw;
}
else
{
Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
throw ex2;
}
}
}
catch (ArgumentException)
{
if (fileName.Length == 0)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
}
else
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
}
}
catch (UnauthorizedAccessException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
}
catch (SecurityException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
}
catch (FileNotFoundException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
}
catch (DirectoryNotFoundException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
}
catch (PathTooLongException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
}
catch (IOException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
}
catch (SerializationException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
}
catch (OutOfMemoryException)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
}
catch (Exception)
{
Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
}
finally
{
if (stream != null)
{
stream.Close();
stream = null;
}
if (tempMat != null)
{
tempMat.Dispose();
tempMat = null;
}
}
}
return document;*/
//}
///
/// 更新测量单位,刷新UI
///
///
public void UpdateMeasureUnit(MeasurementUnit measurementUnit)
{
//循环所有测量,更新单位
if (this.GraphicsList != null
&& this.GraphicsList.Count > 0)
{
int count = this.GraphicsList.Count;
for (int i = 0; i < count; i++)
{
if (this.GraphicsList[i].objectType == DrawClass.Measure)
{
((MeasureDrawObject)(this.GraphicsList[i])).MeasurementUnit = measurementUnit;
}
if (this.GraphicsList[i].objectType == DrawClass.Label)
{
}
}
}
this.Refresh();
}
public override void ToolStripMenuItem1_Click(object sender, EventArgs e)
{
using (MeasureSettingDialog af = new MeasureSettingDialog(AppWorkspace))
{
af.StartPosition = FormStartPosition.CenterScreen;
af.ShowDialog();
}
}
public override void ToolStripMenuItem2_Click(object sender, EventArgs e)
{
using (LabelSettingDialog af = new LabelSettingDialog(AppWorkspace))
{
af.StartPosition = FormStartPosition.CenterScreen;
af.ShowDialog();
}
}
public override void ToolStripMenuItem3_Click(object sender, EventArgs e)
{
//using (MeasureListSetDialog dialog = new MeasureListSetDialog(this.appWorkspace, MeasureListDialog.drawNodes
// , MeasureListDialog.dataNodes, MeasureListDialog.allDrawNodes, MeasureListDialog.allDataNodes))
//{
// dialog.StartPosition = FormStartPosition.CenterParent;
// dialog.ShowDialog();
//}
for (int i = 0; i < this.GraphicsList.Count; i++)
{
if (GraphicsList[i].Selected)
{
MeasurementPropertiesDialog measurementPropertiesDialog = new MeasurementPropertiesDialog(this.appWorkspace, this.GraphicsList[i]);
measurementPropertiesDialog.StartPosition = FormStartPosition.CenterScreen;
measurementPropertiesDialog.ShowDialog();
this.Refresh();
}
}
}
public override void ToolStripMenuItem4_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.GraphicsList.Count; i++)
{
if (this.GraphicsList[i].Selected)
{
//判断如果是水印
if (this.GraphicsList[i].drawToolType == DrawToolType.DrawWaterMark)
{
LabelWaterMarkStyleDialog labelWaterMarkStyleDialog = new LabelWaterMarkStyleDialog(this.appWorkspace, this.GraphicsList[i]);
labelWaterMarkStyleDialog.StartPosition = FormStartPosition.CenterScreen;
labelWaterMarkStyleDialog.ShowDialog();
}
//判断如果是工字线
else if (this.GraphicsList[i].drawToolType == DrawToolType.DrawWorkType)
{
LabelWorkTypeStyleDialog labelWorkTypeStyleDialog = new LabelWorkTypeStyleDialog(this.appWorkspace, this.GraphicsList[i]);
labelWorkTypeStyleDialog.StartPosition = FormStartPosition.CenterScreen;
labelWorkTypeStyleDialog.ShowDialog();
}
//如果是标尺
else if (this.GraphicsList[i].drawToolType == DrawToolType.DrawAutoRuler || this.GraphicsList[i].drawToolType ==
DrawToolType.DrawHandModeRuler || this.GraphicsList[i].drawToolType == DrawToolType.DrawPrestoredRuler)
{
LabelRulerStyleDialog labelRulerStyleDialog = new LabelRulerStyleDialog(this.appWorkspace, this.GraphicsList[i]);
labelRulerStyleDialog.StartPosition = FormStartPosition.CenterParent;
labelRulerStyleDialog.ShowDialog();
}
//如果是其它
else
{
LabelStyleChangeDialog labelStyleChangeDialog = new LabelStyleChangeDialog(this.appWorkspace, this.GraphicsList[i]);
labelStyleChangeDialog.StartPosition = FormStartPosition.CenterScreen;
labelStyleChangeDialog.ShowDialog();
}
}
}
}
DateTime _time;
protected override void MouseEvent_Move(object sender, MouseEventArgs e)
{
if (this.AppWorkspaceTop != null && this.compositionSurface != null && this.pixelTrackingEnabled)
{
if ((DateTime.Now - _time).TotalMilliseconds > 20)
{
(this.AppWorkspaceTop as AppWorkspace).SetImageAndData(this.CalcPixelPoint(e.Location), this);
_time = DateTime.Now;
}
base.MouseEvent_Move(sender, e);
}
}
}
}