12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168 |
- 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
- {
- /// <summary>
- /// 主控件
- /// </summary>
- private AppWorkspace appWorkspace;
- /// <summary>
- /// 缩放模式
- /// </summary>
- private ZoomBasis zoomBasis;
- /// <summary>
- /// 文件路径
- /// </summary>
- public string filePath = null;
- /// <summary>
- /// 文件名
- /// </summary>
- public string fileText = null;
- /// <summary>
- /// 文件类型
- /// </summary>
- //private FileType fileType = null;
- /// <summary>
- /// 文件 - 批量保存自动配置
- /// </summary>
- 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 底部按钮选中状态
- /// <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 int buttonType;
- /// <summary>
- /// 更新按钮文字
- /// </summary>
- /// <param name="buttonName"></param>
- public void UpdateDw2buttonName(string buttonName)
- {
- if (appWorkspace != null)
- appWorkspace.toolBar.DocumentStrip.SetDw2buttonName(this, buttonName);
- }
- public ImageResource StatusIcon
- {
- get
- {
- return this.statusIcon;
- }
- }
- /// <summary>
- /// 判断图片是否脚本执行过程中打开
- /// </summary>
- 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<MeasurementUnit, double> 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_rulers> 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);
- }
- }
- /// <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/*, 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();
- }*/
- }
- /// <summary>
- /// Updates any pertinent EXIF tags, such as "Creation Software", to be
- /// relevant or up-to-date.
- /// </summary>
- /// <param name="document"></param>
- 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();
- }
- /// <summary>
- /// Takes the current Document from this DocumentWorkspace instance and adds it to the MRU list.
- /// </summary>
- /// <param name="fileName"></param>
- 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();
- }
- /// <summary>
- /// Shows an OpenFileDialog or SaveFileDialog and populates the InitialDirectory from the global
- /// settings repository if possible.
- /// </summary>
- /// <param name="fd">The FileDialog to show.</param>
- /// <remarks>
- /// The FileDialog should already have its InitialDirectory populated as a suggestion of where to start.
- /// </remarks>
- 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<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; // 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<GuideStyleModel>(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;
- }
- /// <summary>
- /// 图片保存,保存当前激活图片,用来替换原框架的保存
- /// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1)
- /// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果
- /// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为:
- /// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像
- /// </summary>
- /// <returns></returns>
- 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>(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;
- }
- /// <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(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>(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>(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;
- }
- /// <summary>
- /// 获取图片类型
- /// </summary>
- /// <param name="filePath">文件路径</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 获取图片另存默认保存类型
- /// </summary>
- /// <param name="imgType">图片类型</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 相机参数赋值
- /// </summary>
- /// <param name="picConfigModel">图片对应的XML配置</param>
- 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;
- }
- }
- /// <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);
- 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>(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;*/
- //}
- /// <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;
- }
- 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);
- }
- }
- }
- }
|