1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678 |
- using OpenCvSharp;
- using Resources;
- using SmartCoalApplication.Actions;
- using SmartCoalApplication.Annotation.Enum;
- using SmartCoalApplication.Annotation.Measure;
- using SmartCoalApplication.Base;
- using SmartCoalApplication.Base.CommTool;
- using SmartCoalApplication.Base.Enum;
- using SmartCoalApplication.Base.SettingModel;
- using SmartCoalApplication.Core;
- using SmartCoalApplication.Core.DbOpreate.DbModel;
- using SmartCoalApplication.Measure;
- using SmartCoalApplication.Resources;
- using SmartCoalApplication.SystemLayer;
- using SmartCoalApplication.SystemLayer.FileDlgExtenders.FileDialogExtenders;
- 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.Windows.Forms;
- namespace SmartCoalApplication
- {
- internal class DocumentWorkspace : DocumentView
- {
- /// <summary>
- /// 主控件
- /// </summary>
- private AppWorkspace appWorkspace;
- /// <summary>
- /// 缩放模式
- /// </summary>
- private ZoomBasis zoomBasis;
- /// <summary>
- /// 文件路径
- /// </summary>
- private string filePath = null;
- /// <summary>
- /// 文件名
- /// </summary>
- public string fileText = null;
- private ImageResource statusIcon = null;
- public ZipHandleHelper zipHandleHelper;//zip对象
- public BatchSaveAutoModel batchSaveAutoModel;
- #region 底部按钮选中状态
- /// <summary>
- /// 最佳
- /// </summary>
- public bool best = false;
- /// <summary>
- /// 最大最小
- /// </summary>
- public bool maxMin = false;
- /// <summary>
- /// 原始状态
- /// </summary>
- public bool origin = true;
- /// <summary>
- /// 伽马0.45
- /// </summary>
- public bool gamma45 = false;
- /// <summary>
- /// 移动模式
- /// </summary>
- public bool mobileMode = false;
- /// <summary>
- /// 指针模式
- /// </summary>
- public bool cursorMode = true;
- /// <summary>
- /// MainForm
- /// </summary>
- #endregion
- public ImageResource StatusIcon
- {
- get
- {
- return this.statusIcon;
- }
- }
- 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);
- }
- public DocumentWorkspace(AppWorkspace appWorkspace)
- {
- this.AppWorkspaceTop = appWorkspace;
- InitializeComponent();
- this.InitToolsAndManager();
- 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();
- PanelAutoScroll = true;
- PanelAutoScroll = false;
- 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 - 150.0) / width;
- }
- if (rc.Height < height)
- {
- originY = (ptyInDoc + this.PanelScrollPosition.Y - 75.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 + 150),
- (int)(height2 * originY - ptyInDoc + 75));
- }
- else if (rc.Width < width2 || rc.Height < height2)
- {
- this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 150, (int)(height2 - rc.Height) / 2 + 75);
- }
- 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()
- {
- }
- 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 event EventHandler SaveOptionsChanged;
- protected virtual void OnSaveOptionsChanged()
- {
- if (SaveOptionsChanged != null)
- {
- SaveOptionsChanged(this, EventArgs.Empty);
- }
- }
- /// <summary>
- /// 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.
- /// </summary>
- /// <param name="fileType"></param>
- /// <param name="saveParameters"></param>
- public void SetDocumentSaveOptions(string newFilePath)
- {
- this.filePath = newFilePath;
- OnFilePathChanged();
- OnSaveOptionsChanged();
- }
- public void GetDocumentSaveOptions(out string filePathResult)
- {
- filePathResult = this.filePath;
- }
- private ZoomBasis savedZb;
- private ScaleFactor savedSf;
- protected override void OnDocumentChanging(Document newDocument)
- {
- base.OnDocumentChanging(newDocument);
- this.savedZb = this.ZoomBasis;
- this.savedSf = ScaleFactor;
- }
- 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();
- }
- 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();
- }
- 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;
- 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.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<int>(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<int>(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<string>(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<long>(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<long>(SetItemWorkProgress), new object[] { totalProgress });
- }
- else
- {
- this.totalProgress = totalProgress;
- UpdateUI();
- }
- }
- public void EndItem(WorkItemResult result)
- {
- if (this.progressDialog.InvokeRequired)
- {
- this.progressDialog.BeginInvoke(new Procedure<WorkItemResult>(EndItem), new object[] { result });
- }
- else
- {
- }
- }
- public void EndOperation(OperationResult result)
- {
- if (this.progressDialog.InvokeRequired)
- {
- this.progressDialog.BeginInvoke(new Procedure<OperationResult>(EndOperation), new object[] { result });
- }
- else
- {
- this.progressDialog.Close();
- }
- }
- public WorkItemFailureAction ReportItemFailure(Exception ex)
- {
- if (this.progressDialog.InvokeRequired)
- {
- object result = this.progressDialog.Invoke(
- new Function<WorkItemFailureAction, Exception>(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<TaskButton> taskButtons = new List<TaskButton>();
- 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;
- 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.ItemText = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling");
- //this.progressDialog.OperationProgress = string.Empty;
- this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
- }
- else
- {
- this.progressDialog.CancelEnabled = true;
- //this.progressDialog.ItemText = this.itemName;
- string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format");
- string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount);
- //this.progressDialog.OperationProgress = 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)
- {
- using (IFileOpenDialog ofd = new ClassicFileOpenDialog())
- {
- ofd.InitialDirectory = "";
- if (startingDir != null)
- {
- ofd.InitialDirectory = startingDir;
- }
- ofd.CheckFileExists = true;
- ofd.CheckPathExists = true;
- ofd.Multiselect = multiselect;
- ofd.Filter = PdnResources.GetString("NewRasterData") + "(*.tif,*.tiff,*.jpg,*.jpeg,*.png,*.bmp)|*.tif;*.tiff;*.jpg;*.jpeg;*.png;*.bmp";
- ofd.FilterIndex = 0;
- DialogResult result = ShowFileDialog(owner, ofd);
- if (result == DialogResult.OK)
- {
- fileNames = ofd.FileNames;
- }
- else
- {
- fileNames = new string[0];
- }
- return result;
- }
- }
- /// <summary>
- /// 图片保存,保存当前激活图片,用来替换原框架的保存
- /// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1)
- /// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果
- /// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为:
- /// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像
- /// </summary>
- /// <returns></returns>
- public bool DoSaveNew()
- {
- string newFileName;
- GetDocumentSaveOptions(out newFileName);
- // 如果没有指定文件名(不是从硬盘打开,是生成或从相机获得),则执行另存为
- if (newFileName == null)
- {
- return DoSaveAsNew();
- }
- else
- {
- try
- {
- //获取文件后缀名
- string extension = Path.GetExtension(newFileName);
- //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像、不保存相
- using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
- {
- //保存图片
- if (!extension.Equals(".tga"))//不是压缩包
- {
- ImageCodecInfo icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg);
- if (extension.Equals(".jpg"))
- {
- icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg);
- }
- else if (extension.Equals(".bmp"))
- {
- icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Bmp);
- }
- else if (extension.Equals("TIFF"))
- {
- icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Tiff);
- }
- EncoderParameters parms = new EncoderParameters(1);
- EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
- parms.Param[0] = parm;
- bitmap.Save(newFileName, icf, parms);
- }
- }
- }
- catch (Exception)
- {
- MessageBox.Show(PdnResources.GetString("Menu.Imagesavefailed.text"));
- return false;
- }
- }
- return true;
- }
- /// <summary>
- /// 获取批量保存中设置的参数,按生成规律提取文件名称
- /// </summary>
- /// <param name="file_Name">文件名称</param>
- /// <returns></returns>
- public bool GetParameters(out string file_Name)
- {
- file_Name = string.Empty;
- batchSaveAutoModel = XmlSerializeHelper.DESerializer<BatchSaveAutoModel>(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>(batchSaveAutoModel);
- string filePath = Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml";
- FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create);
- }
- return batchSaveAutoModel.Whether;
- }
- /// <summary>
- /// 文件另存,用来替换原框架的保存
- /// 1)将图片另存到其他位置,即变化不保存在原图像上
- /// 2)点击另存为,打开保存路径窗口(图1)
- /// 3)并根据(图1)中对应的设置判断是否关闭打开的图像
- /// 4)若名称重复,则弹出对应提示,查看效果可点击图1中的【保存】按钮
- /// </summary>
- /// <returns></returns>
- public bool DoSaveAsNew()
- {
- //获取批量保存中设置的参数,提取文件名称
- string file_Name;
- //判断是否是压缩包文件
- bool isZipFile = false;
- if (zipHandleHelper != null)
- isZipFile = true;
- using (SaveFileDialog saveDialog = new SaveFileDialog())
- {
- ConfigModel configModel = Program.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);
- //生成配置文件选中状态
- 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.checkBox5.Visible = false;
- saveDialogCtrl.numericUpDown1.Visible = false;
- saveDialogCtrl.label1.Visible = false;
- }
- else
- {
- //压缩比例选中状态
- if (configModel.WhetherCompression == 1)
- saveDialogCtrl.checkBox5.Checked = true;
- saveDialogCtrl.numericUpDown1.Value = configModel.CompressionRatio;//压缩比例数值
- saveDialog.Filter = "Jpeg(*.jpg)|*.jpg|Tiff(*.tiff)|*.tiff|Bmp(*.bmp)|*.bmp";
- saveDialog.DefaultExt = "jpg";
- }
- saveDialog.FilterIndex = 1;
- saveDialog.CheckFileExists = false;// true;
- saveDialog.AddExtension = true;
- string friendName = AppWorkspace.ActiveDocumentWorkspace.GetFriendlyName();
- 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
- {
- 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;
- //是否生成配置文件
- bool createConfig = saveDialogCtrl.checkBox1.Checked;
- //保存后是否关闭图像
- bool afterSaveClost = saveDialogCtrl.checkBox2.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 (compress)
- configModel.WhetherCompression = 1;
- else
- configModel.WhetherCompression = 0;
- configModel.CompressionRatio = compressRate;
- string configModelXml = XmlSerializeHelper.XmlSerialize<ConfigModel>(configModel);
- FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" +
- Program.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);
- //保存图片
- ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
- if (extension.Equals(".jpg"))
- {
- icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
- }
- else if (extension.Equals(".bmp"))
- {
- icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
- }
- else if (extension.Equals(".tiff"))
- {
- icf = GdiPlusFileType.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();
- //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 (Program.instance.ruleDB != null)
- {
- picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name;
- picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple;
- picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length;
- picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length;
- picConfigModel.rule.ruler_units = Program.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>(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 (!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 != 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 (Program.instance.ruleDB != null)
- // {
- // picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name;
- // picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple;
- // picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length;
- // picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length;
- // picConfigModel.rule.ruler_units = Program.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>(picConfigModel);
- // //xml保存路径
- // string filePath = directoryPath + "\\" + noExtension + ".xml";
- // //保存xml
- // FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
- //}
- //else
- //{
- // //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 (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 static Document LoadDocument(Control owner, string fileName, ProgressEventHandler progressCallback)
- {
- Document document = null;
- using (new WaitCursorChanger(owner))
- {
- //Utility.GCFullCollect();
- //Stream stream = null;
- using (OpenCvSharp.Mat tempMat = new Mat(fileName))
- {
- try
- {
- try
- {
- //stream = tempMat.ToMemoryStream(Path.GetExtension(fileName));
- //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 = Document.FromMat(tempMat);// 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();
- }*/
- }
- }
- }
- return document;
- }
- /// <summary>
- /// 批量保存
- /// </summary>
- /// <param name="fileName">文件名</param>
- /// <param name="createConfig">是否生成配置文件</param>
- /// <param name="afterSaveClost">保存后是否关闭图像</param>
- /// <param name="saveGridLine">保存时是否保存网格数据</param>
- /// <param name="implantLabelAndMeasure">标注及测量信息是否嵌入图像</param>
- /// <param name="compress">是否压缩</param>
- /// <param name="compressRate">压缩比例</param>
- /// <returns></returns>
- 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);
- //获取文件后缀名
- string extension = Path.GetExtension(fileName);
- //保存图片
- ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
- if (extension.Equals(".jpg"))
- {
- icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
- }
- else if (extension.Equals(".bmp"))
- {
- icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
- }
- else if (extension.Equals(".tiff"))
- {
- icf = GdiPlusFileType.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();
- //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
- picConfigModel.meta = new PicConfigModel.Meta();
- picConfigModel.rule = new PicConfigModel.Rule();
- if (this.xmlSaveModel != null)
- {
- 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>(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;
- }
- /// <summary>
- /// 更新测量单位,刷新UI
- /// </summary>
- /// <param name="measurementUnit"></param>
- 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;
- }
- }
- }
- this.Refresh();
- }
- protected override string[] startUpRules(Dictionary<MeasurementUnit, double> rules)
- {
- string[] result = new string[5];
- result[0] = Program.instance.measurementUnit.ToString();
- result[1] = InvariantData.unitsDictionary[(int)Program.instance.measurementUnit];
- result[2] = InvariantData.unitSymbolsDictionary[(int)Program.instance.measurementUnit];
- if (rules != null)
- {
- result[3] = (rules[Program.instance.measurementUnit]).ToString();
- result[4] = (rules[MeasurementUnit.Micron]).ToString();
- }
- else
- {
- result[3] = (Program.instance.rules[Program.instance.measurementUnit]).ToString();
- result[4] = (Program.instance.rules[MeasurementUnit.Micron]).ToString();
- }
- return result;
- }
- public override void ToolStripMenuItem1_Click(object sender, EventArgs e)
- {
- using (MeasureSettingDialog af = new MeasureSettingDialog(AppWorkspace))
- {
- af.StartPosition = FormStartPosition.CenterScreen;
- af.ShowDialog();
- }
- }
- public override void ToolStripMenuItem3_Click(object sender, EventArgs e)
- {
- 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();
- }
- }
- }
- }
- }
|