DocumentWorkspace.cs 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. using OpenCvSharp;
  2. using Resources;
  3. using SmartCoalApplication.Actions;
  4. using SmartCoalApplication.Annotation.Enum;
  5. using SmartCoalApplication.Annotation.Measure;
  6. using SmartCoalApplication.Base;
  7. using SmartCoalApplication.Base.CommTool;
  8. using SmartCoalApplication.Base.Enum;
  9. using SmartCoalApplication.Base.SettingModel;
  10. using SmartCoalApplication.Core;
  11. using SmartCoalApplication.Core.DbOpreate.DbModel;
  12. using SmartCoalApplication.Measure;
  13. using SmartCoalApplication.Resources;
  14. using SmartCoalApplication.SystemLayer;
  15. using SmartCoalApplication.SystemLayer.FileDlgExtenders.FileDialogExtenders;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.Drawing;
  20. using System.Drawing.Imaging;
  21. using System.IO;
  22. using System.Reflection;
  23. using System.Runtime.Serialization;
  24. using System.Security;
  25. using System.Windows.Forms;
  26. namespace SmartCoalApplication
  27. {
  28. internal class DocumentWorkspace : DocumentView
  29. {
  30. /// <summary>
  31. /// 主控件
  32. /// </summary>
  33. private AppWorkspace appWorkspace;
  34. /// <summary>
  35. /// 缩放模式
  36. /// </summary>
  37. private ZoomBasis zoomBasis;
  38. /// <summary>
  39. /// 文件路径
  40. /// </summary>
  41. private string filePath = null;
  42. /// <summary>
  43. /// 文件名
  44. /// </summary>
  45. public string fileText = null;
  46. private ImageResource statusIcon = null;
  47. public ZipHandleHelper zipHandleHelper;//zip对象
  48. public BatchSaveAutoModel batchSaveAutoModel;
  49. #region 底部按钮选中状态
  50. /// <summary>
  51. /// 最佳
  52. /// </summary>
  53. public bool best = false;
  54. /// <summary>
  55. /// 最大最小
  56. /// </summary>
  57. public bool maxMin = false;
  58. /// <summary>
  59. /// 原始状态
  60. /// </summary>
  61. public bool origin = true;
  62. /// <summary>
  63. /// 伽马0.45
  64. /// </summary>
  65. public bool gamma45 = false;
  66. /// <summary>
  67. /// 移动模式
  68. /// </summary>
  69. public bool mobileMode = false;
  70. /// <summary>
  71. /// 指针模式
  72. /// </summary>
  73. public bool cursorMode = true;
  74. /// <summary>
  75. /// MainForm
  76. /// </summary>
  77. #endregion
  78. public ImageResource StatusIcon
  79. {
  80. get
  81. {
  82. return this.statusIcon;
  83. }
  84. }
  85. public string StatusText
  86. {
  87. get
  88. {
  89. if (!string.IsNullOrEmpty(filePath))
  90. {
  91. try
  92. {
  93. FileInfo fi = new FileInfo(filePath);
  94. return fi.CreationTime + "、" + FileOperationHelper.GetLength(fi.Length) + "、" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Width + "*" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Height;
  95. }
  96. catch (Exception)
  97. {
  98. }
  99. }
  100. return "";
  101. }
  102. }
  103. public event EventHandler StatusChanged;
  104. protected virtual void OnStatusChanged()
  105. {
  106. if (StatusChanged != null)
  107. {
  108. StatusChanged(this, EventArgs.Empty);
  109. }
  110. }
  111. protected override void OnSizeChanged(EventArgs e)
  112. {
  113. PerformLayout();
  114. base.OnSizeChanged(e);
  115. }
  116. protected override void OnLayout(LayoutEventArgs e)
  117. {
  118. if (this.zoomBasis == ZoomBasis.FitToWindow)
  119. {
  120. ZoomToWindow();
  121. // This bizarre ordering of setting PanelAutoScroll prevents some very weird layout/scroll-without-scrollbars stuff.
  122. PanelAutoScroll = true;
  123. PanelAutoScroll = false;
  124. }
  125. base.OnLayout(e);
  126. }
  127. protected override void OnResize(EventArgs e)
  128. {
  129. if (this.zoomBasis == ZoomBasis.FitToWindow)
  130. {
  131. PerformLayout();
  132. }
  133. base.OnResize(e);
  134. }
  135. public DocumentWorkspace(AppWorkspace appWorkspace)
  136. {
  137. this.AppWorkspaceTop = appWorkspace;
  138. InitializeComponent();
  139. this.InitToolsAndManager();
  140. this.ShowContextMenuStrip1();
  141. this.panel.MouseDown += new MouseEventHandler(this.ShowContextMenuStrip2);
  142. this.RulersEnabled = Settings.CurrentUser.GetBoolean(SettingNames.Rulers, true);
  143. this.zoomBasis = ZoomBasis.FitToWindow;
  144. }
  145. private void ShowContextMenuStrip2(object sender, MouseEventArgs e)
  146. {
  147. if (e.Button == MouseButtons.Right)
  148. this.ShowContextMenuStrip1();
  149. }
  150. protected override void OnUnitsChanged()
  151. {
  152. base.OnUnitsChanged();
  153. }
  154. private void InitializeComponent()
  155. {
  156. }
  157. protected override void Dispose(bool disposing)
  158. {
  159. base.Dispose(disposing);
  160. }
  161. public override void ZoomIn()
  162. {
  163. this.ZoomBasis = ZoomBasis.ScaleFactor;
  164. base.ZoomIn();
  165. }
  166. public override void ZoomIn(double factor)
  167. {
  168. this.ZoomBasis = ZoomBasis.ScaleFactor;
  169. base.ZoomIn(factor);
  170. }
  171. public override void ZoomOut()
  172. {
  173. this.ZoomBasis = ZoomBasis.ScaleFactor;
  174. base.ZoomOut();
  175. }
  176. public override void ZoomOut(double factor)
  177. {
  178. this.ZoomBasis = ZoomBasis.ScaleFactor;
  179. base.ZoomOut(factor);
  180. }
  181. public event EventHandler ZoomBasisChanging;
  182. protected virtual void OnZoomBasisChanging()
  183. {
  184. if (ZoomBasisChanging != null)
  185. {
  186. ZoomBasisChanging(this, EventArgs.Empty);
  187. }
  188. }
  189. public event EventHandler ZoomBasisChanged;
  190. protected virtual void OnZoomBasisChanged()
  191. {
  192. if (ZoomBasisChanged != null)
  193. {
  194. ZoomBasisChanged(this, EventArgs.Empty);
  195. }
  196. }
  197. public ZoomBasis ZoomBasis
  198. {
  199. get
  200. {
  201. return this.zoomBasis;
  202. }
  203. set
  204. {
  205. if (this.zoomBasis != value)
  206. {
  207. OnZoomBasisChanging();
  208. this.zoomBasis = value;
  209. switch (this.zoomBasis)
  210. {
  211. //合适大小(完整显示图像)
  212. case ZoomBasis.FitToWindow:
  213. ZoomToWindow();
  214. PanelAutoScroll = true;
  215. PanelAutoScroll = false;
  216. this.zoomBasis = ZoomBasis.FitToWindow;
  217. break;
  218. //实际大小
  219. case ZoomBasis.ScaleFactor:
  220. PanelAutoScroll = true;
  221. break;
  222. //合适宽度
  223. case ZoomBasis.FitToWidth:
  224. ZoomToWidth();
  225. PanelAutoScroll = true;
  226. this.zoomBasis = ZoomBasis.FitToWidth;
  227. break;
  228. //合适高度
  229. case ZoomBasis.FitToHeight:
  230. ZoomToHeight();
  231. PanelAutoScroll = true;
  232. this.zoomBasis = ZoomBasis.FitToHeight;
  233. break;
  234. default:
  235. throw new InvalidEnumArgumentException();
  236. }
  237. OnZoomBasisChanged();
  238. }
  239. }
  240. }
  241. protected override void HandleMouseWheel(Control sender, MouseEventArgs e)
  242. {
  243. if (Control.ModifierKeys == Keys.Control)
  244. {
  245. double mouseDelta = (double)e.Delta / 120.0f;
  246. Rectangle visibleDocBoundsStart = this.VisibleDocumentBounds;
  247. System.Drawing.Point mouseDocPt = this.MouseToDocument(sender, new System.Drawing.Point(e.X, e.Y));
  248. RectangleF visibleDocDocRect1 = this.VisibleDocumentRectangleF;
  249. PointF mouseNPt = new PointF(
  250. (mouseDocPt.X - visibleDocDocRect1.X) / visibleDocDocRect1.Width,
  251. (mouseDocPt.Y - visibleDocDocRect1.Y) / visibleDocDocRect1.Height);
  252. Rectangle rc = this.PanelClientRectangle;
  253. int width = this.SurfaceScrollableWidth;
  254. int height = this.SurfaceScrollableHeight;
  255. //获取鼠标在图像中的坐标定位
  256. double originX = 0.5;
  257. double originY = 0.5;
  258. double ptxInDoc = mouseDocPt.X * this.ScaleRatio;
  259. double ptyInDoc = mouseDocPt.Y * this.ScaleRatio;
  260. if (rc.Width < width)
  261. {
  262. originX = (ptxInDoc + this.PanelScrollPosition.X - 150.0) / width;
  263. }
  264. if (rc.Height < height)
  265. {
  266. originY = (ptyInDoc + this.PanelScrollPosition.Y - 75.0) / height;
  267. }
  268. const double factor = 1.12;
  269. double mouseFactor = Math.Pow(factor, Math.Abs(mouseDelta));
  270. if (e.Delta > 0)
  271. {
  272. this.ZoomIn(mouseFactor);
  273. }
  274. else if (e.Delta < 0)
  275. {
  276. this.ZoomOut(mouseFactor);
  277. }
  278. RectangleF visibleDocDocRect2 = this.VisibleDocumentRectangleF;
  279. PointF scrollPt2 = new PointF(
  280. mouseDocPt.X - visibleDocDocRect2.Width * mouseNPt.X,
  281. mouseDocPt.Y - visibleDocDocRect2.Height * mouseNPt.Y);
  282. this.DocumentScrollPositionF = scrollPt2;
  283. int width2 = this.SurfaceScrollableWidth;
  284. int height2 = this.SurfaceScrollableHeight;
  285. if ((rc.Width < width2 || rc.Height < height2) && (rc.Width < width || rc.Height < height))
  286. {
  287. //根据鼠标在图像中的坐标重新定位放大后的图像
  288. this.PanelScrollPosition = new System.Drawing.Point(
  289. (int)(width2 * originX - ptxInDoc + 150),
  290. (int)(height2 * originY - ptyInDoc + 75));
  291. }
  292. else if (rc.Width < width2 || rc.Height < height2)
  293. {
  294. this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 150, (int)(height2 - rc.Height) / 2 + 75);
  295. }
  296. else
  297. {
  298. this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0);
  299. }
  300. Rectangle visibleDocBoundsEnd = this.VisibleDocumentBounds;
  301. if (visibleDocBoundsEnd != visibleDocBoundsStart)
  302. {
  303. // Make sure the screen updates, otherwise it can get a little funky looking
  304. this.Update();
  305. }
  306. }
  307. base.HandleMouseWheel(sender, e);
  308. }
  309. public void UpdateAuxiliaryLineEnabled()
  310. {
  311. }
  312. public void UpdateGridLineEnabled()
  313. {
  314. this.GridLineEnabled = this.GridLineEnabled;
  315. }
  316. protected override void OnLoad(EventArgs e)
  317. {
  318. if (this.appWorkspace == null)
  319. {
  320. throw new InvalidOperationException("Must set the Workspace property");
  321. }
  322. base.OnLoad(e);
  323. }
  324. public event EventHandler ActiveLayerChanging;
  325. protected void OnLayerChanging()
  326. {
  327. if (ActiveLayerChanging != null)
  328. {
  329. ActiveLayerChanging(this, EventArgs.Empty);
  330. }
  331. }
  332. public event EventHandler ActiveLayerChanged;
  333. protected void OnLayerChanged()
  334. {
  335. this.Focus();
  336. if (ActiveLayerChanged != null)
  337. {
  338. ActiveLayerChanged(this, EventArgs.Empty);
  339. }
  340. }
  341. public event EventHandler ToolChanging;
  342. protected void OnToolChanging()
  343. {
  344. if (ToolChanging != null)
  345. {
  346. ToolChanging(this, EventArgs.Empty);
  347. }
  348. }
  349. public event EventHandler ToolChanged;
  350. protected void OnToolChanged()
  351. {
  352. if (ToolChanged != null)
  353. {
  354. ToolChanged(this, EventArgs.Empty);
  355. }
  356. }
  357. public AppWorkspace AppWorkspace
  358. {
  359. get
  360. {
  361. return this.appWorkspace;
  362. }
  363. set
  364. {
  365. this.appWorkspace = value;
  366. }
  367. }
  368. public event EventHandler FilePathChanged;
  369. protected virtual void OnFilePathChanged()
  370. {
  371. if (FilePathChanged != null)
  372. {
  373. FilePathChanged(this, EventArgs.Empty);
  374. }
  375. }
  376. public string FilePath
  377. {
  378. get
  379. {
  380. return this.filePath;
  381. }
  382. }
  383. public string GetFriendlyName()
  384. {
  385. string friendlyName;
  386. if (this.filePath != null)
  387. {
  388. friendlyName = Path.GetFileName(this.filePath);
  389. }
  390. else if (this.fileText != null)
  391. {
  392. friendlyName = this.fileText;
  393. }
  394. else
  395. {
  396. friendlyName = PdnResources.GetString("Untitled.FriendlyName");
  397. }
  398. return friendlyName;
  399. }
  400. public event EventHandler SaveOptionsChanged;
  401. protected virtual void OnSaveOptionsChanged()
  402. {
  403. if (SaveOptionsChanged != null)
  404. {
  405. SaveOptionsChanged(this, EventArgs.Empty);
  406. }
  407. }
  408. /// <summary>
  409. /// Sets the FileType and SaveConfigToken parameters that are used if the
  410. /// user chooses "Save" from the File menu. These are not used by the
  411. /// DocumentControl class and should be used by whoever actually goes
  412. /// to save the Document instance.
  413. /// </summary>
  414. /// <param name="fileType"></param>
  415. /// <param name="saveParameters"></param>
  416. public void SetDocumentSaveOptions(string newFilePath)
  417. {
  418. this.filePath = newFilePath;
  419. OnFilePathChanged();
  420. OnSaveOptionsChanged();
  421. }
  422. public void GetDocumentSaveOptions(out string filePathResult)
  423. {
  424. filePathResult = this.filePath;
  425. }
  426. private ZoomBasis savedZb;
  427. private ScaleFactor savedSf;
  428. protected override void OnDocumentChanging(Document newDocument)
  429. {
  430. base.OnDocumentChanging(newDocument);
  431. this.savedZb = this.ZoomBasis;
  432. this.savedSf = ScaleFactor;
  433. }
  434. protected override void OnDocumentChanged()
  435. {
  436. if (this.Document != null)
  437. {
  438. bool oldDirty = this.Document.Dirty;
  439. this.Document.Invalidate();
  440. this.Document.Dirty = oldDirty;
  441. this.ZoomBasis = this.savedZb;
  442. if (this.savedZb == ZoomBasis.ScaleFactor)
  443. {
  444. ScaleFactor = this.savedSf;
  445. }
  446. }
  447. AutoScrollPosition = new System.Drawing.Point(0, 0);
  448. base.OnDocumentChanged();
  449. }
  450. public void AddToMruList()
  451. {
  452. string fullFileName = Path.GetFullPath(this.FilePath);
  453. MostRecentFile mrf = new MostRecentFile(fullFileName, null);
  454. if (AppWorkspace.MostRecentFiles.Contains(fullFileName))
  455. {
  456. AppWorkspace.MostRecentFiles.Remove(fullFileName);
  457. }
  458. AppWorkspace.MostRecentFiles.Add(mrf);
  459. AppWorkspace.MostRecentFiles.SaveMruList();
  460. }
  461. public static DialogResult ShowFileDialog(Control owner, IFileDialog fd)
  462. {
  463. string initialDirectory = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, fd.InitialDirectory);
  464. bool dirExists = false;
  465. try
  466. {
  467. DirectoryInfo dirInfo = new DirectoryInfo(initialDirectory);
  468. using (new WaitCursorChanger(owner))
  469. {
  470. dirExists = dirInfo.Exists;
  471. if (!dirInfo.Exists)
  472. {
  473. initialDirectory = fd.InitialDirectory;
  474. }
  475. }
  476. }
  477. catch (Exception)
  478. {
  479. initialDirectory = fd.InitialDirectory;
  480. }
  481. fd.InitialDirectory = initialDirectory;
  482. OurFileDialogUICallbacks ouc = new OurFileDialogUICallbacks();
  483. DialogResult result = fd.ShowDialog(owner, ouc);
  484. if (result == DialogResult.OK)
  485. {
  486. string fileName;
  487. if (fd is IFileOpenDialog)
  488. {
  489. string[] fileNames = ((IFileOpenDialog)fd).FileNames;
  490. if (fileNames.Length > 0)
  491. {
  492. fileName = fileNames[0];
  493. }
  494. else
  495. {
  496. fileName = null;
  497. }
  498. }
  499. else if (fd is IFileSaveDialog)
  500. {
  501. fileName = ((IFileSaveDialog)fd).FileName;
  502. }
  503. else
  504. {
  505. throw new InvalidOperationException();
  506. }
  507. if (fileName != null)
  508. {
  509. string newDir = Path.GetDirectoryName(fileName);
  510. Settings.CurrentUser.SetString(SettingNames.LastFileDialogDirectory, newDir);
  511. }
  512. else
  513. {
  514. throw new FileNotFoundException();
  515. }
  516. }
  517. return result;
  518. }
  519. private sealed class OurFileDialogUICallbacks : IFileDialogUICallbacks
  520. {
  521. public FileOverwriteAction ShowOverwritePrompt(IWin32Window owner, string pathName)
  522. {
  523. FileOverwriteAction returnVal;
  524. string title = PdnResources.GetString("SaveAs.OverwriteConfirmation.Title");
  525. string textFormat = PdnResources.GetString("SaveAs.OverwriteConfirmation.Text.Format");
  526. string fileName;
  527. try
  528. {
  529. fileName = Path.GetFileName(pathName);
  530. }
  531. catch (Exception)
  532. {
  533. fileName = pathName;
  534. }
  535. string text = string.Format(textFormat, fileName);
  536. DialogResult result = MessageBox.Show(owner, text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
  537. switch (result)
  538. {
  539. case DialogResult.Yes:
  540. returnVal = FileOverwriteAction.Overwrite;
  541. break;
  542. case DialogResult.No:
  543. returnVal = FileOverwriteAction.Cancel;
  544. break;
  545. default:
  546. throw new InvalidEnumArgumentException();
  547. }
  548. return returnVal;
  549. }
  550. public bool ShowError(IWin32Window owner, string filePath, Exception ex)
  551. {
  552. if (ex is PathTooLongException)
  553. {
  554. string title = PdnInfo.GetBareProductName();
  555. string message = PdnResources.GetString("FileDialog.PathTooLongException.Message");
  556. MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
  557. return true;
  558. }
  559. else
  560. {
  561. return false;
  562. }
  563. }
  564. public IFileTransferProgressEvents CreateFileTransferProgressEvents()
  565. {
  566. return new OurProgressEvents();
  567. }
  568. }
  569. private sealed class OurProgressEvents : IFileTransferProgressEvents
  570. {
  571. private TransferProgressDialog progressDialog;
  572. private ICancelable cancelSink;
  573. private int itemCount = 0;
  574. private int itemOrdinal = 0;
  575. private string itemName = string.Empty;
  576. private long totalWork;
  577. private long totalProgress;
  578. private const int maxPBValue = 200; // granularity of progress bar. 100 means 1%, 200 means 0.5%, etc.
  579. private bool cancelRequested = false;
  580. public OurProgressEvents()
  581. {
  582. }
  583. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "cancelSink")]
  584. public void BeginOperation(IWin32Window owner, EventHandler callWhenUIShown, ICancelable cancelSink)
  585. {
  586. if (this.progressDialog != null)
  587. {
  588. throw new InvalidOperationException("Operation already in progress");
  589. }
  590. this.progressDialog = new TransferProgressDialog();
  591. this.progressDialog.Text = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.TransferProgress.Title");
  592. this.progressDialog.Icon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileOpenIcon.png").Reference);
  593. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  594. this.progressDialog.ProgressBar.Maximum = maxPBValue;
  595. this.progressDialog.CancelClicked +=
  596. delegate (object sender, EventArgs e)
  597. {
  598. this.cancelRequested = true;
  599. this.cancelSink.RequestCancel();
  600. UpdateUI();
  601. };
  602. EventHandler progressDialog_Shown =
  603. delegate (object sender, EventArgs e)
  604. {
  605. callWhenUIShown(this, EventArgs.Empty);
  606. };
  607. this.cancelSink = cancelSink;
  608. this.itemOrdinal = 0;
  609. this.cancelRequested = false;
  610. this.itemName = string.Empty;
  611. this.itemCount = 0;
  612. this.itemOrdinal = 0;
  613. this.totalProgress = 0;
  614. this.totalWork = 0;
  615. this.progressDialog.Shown += progressDialog_Shown;
  616. this.progressDialog.ShowDialog(owner);
  617. this.progressDialog.Shown -= progressDialog_Shown;
  618. this.progressDialog.Dispose();
  619. this.progressDialog = null;
  620. this.cancelSink = null;
  621. }
  622. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemCount")]
  623. public void SetItemCount(int itemCount)
  624. {
  625. if (this.progressDialog.InvokeRequired)
  626. {
  627. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemCount), new object[] { itemCount });
  628. }
  629. else
  630. {
  631. this.itemCount = itemCount;
  632. UpdateUI();
  633. }
  634. }
  635. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemOrdinal")]
  636. public void SetItemOrdinal(int itemOrdinal)
  637. {
  638. if (this.progressDialog.InvokeRequired)
  639. {
  640. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemOrdinal), new object[] { itemOrdinal });
  641. }
  642. else
  643. {
  644. this.itemOrdinal = itemOrdinal;
  645. this.totalWork = 0;
  646. this.totalProgress = 0;
  647. UpdateUI();
  648. }
  649. }
  650. public void SetItemInfo(string itemInfo)
  651. {
  652. if (this.progressDialog.InvokeRequired)
  653. {
  654. this.progressDialog.BeginInvoke(new Procedure<string>(SetItemInfo), new object[] { itemInfo });
  655. }
  656. else
  657. {
  658. this.itemName = itemInfo;
  659. UpdateUI();
  660. }
  661. }
  662. public void BeginItem()
  663. {
  664. if (this.progressDialog.InvokeRequired)
  665. {
  666. this.progressDialog.BeginInvoke(new Procedure(BeginItem), null);
  667. }
  668. else
  669. {
  670. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  671. }
  672. }
  673. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalWork")]
  674. public void SetItemWorkTotal(long totalWork)
  675. {
  676. if (this.progressDialog.InvokeRequired)
  677. {
  678. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkTotal), new object[] { totalWork });
  679. }
  680. else
  681. {
  682. this.totalWork = totalWork;
  683. UpdateUI();
  684. }
  685. }
  686. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalProgress")]
  687. public void SetItemWorkProgress(long totalProgress)
  688. {
  689. if (this.progressDialog.InvokeRequired)
  690. {
  691. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkProgress), new object[] { totalProgress });
  692. }
  693. else
  694. {
  695. this.totalProgress = totalProgress;
  696. UpdateUI();
  697. }
  698. }
  699. public void EndItem(WorkItemResult result)
  700. {
  701. if (this.progressDialog.InvokeRequired)
  702. {
  703. this.progressDialog.BeginInvoke(new Procedure<WorkItemResult>(EndItem), new object[] { result });
  704. }
  705. else
  706. {
  707. }
  708. }
  709. public void EndOperation(OperationResult result)
  710. {
  711. if (this.progressDialog.InvokeRequired)
  712. {
  713. this.progressDialog.BeginInvoke(new Procedure<OperationResult>(EndOperation), new object[] { result });
  714. }
  715. else
  716. {
  717. this.progressDialog.Close();
  718. }
  719. }
  720. public WorkItemFailureAction ReportItemFailure(Exception ex)
  721. {
  722. if (this.progressDialog.InvokeRequired)
  723. {
  724. object result = this.progressDialog.Invoke(
  725. new Function<WorkItemFailureAction, Exception>(ReportItemFailure),
  726. new object[] { ex });
  727. return (WorkItemFailureAction)result;
  728. }
  729. else
  730. {
  731. WorkItemFailureAction result;
  732. result = ShowFileTransferFailedDialog(ex);
  733. return result;
  734. }
  735. }
  736. private WorkItemFailureAction ShowFileTransferFailedDialog(Exception ex)
  737. {
  738. WorkItemFailureAction result;
  739. Icon formIcon = this.progressDialog.Icon;
  740. string formTitle = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.Title");
  741. Image taskImage = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference;
  742. string introTextFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.IntroText.Format");
  743. string introText = string.Format(introTextFormat, ex.Message);
  744. TaskButton retryTB = new TaskButton(
  745. PdnResources.GetImageResource("Icons.MenuImageRotate90CWIcon.png").Reference,
  746. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ActionText"),
  747. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ExplanationText"));
  748. TaskButton skipTB = new TaskButton(
  749. PdnResources.GetImageResource("Icons.HistoryFastForwardIcon.png").Reference,
  750. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ActionText"),
  751. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ExplanationText"));
  752. TaskButton cancelTB = new TaskButton(
  753. PdnResources.GetImageResource("Icons.CancelIcon.png").Reference,
  754. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ActionText"),
  755. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ExplanationText"));
  756. List<TaskButton> taskButtons = new List<TaskButton>();
  757. taskButtons.Add(retryTB);
  758. // Only have the Skip button if there is more than 1 item being transferred.
  759. // If only 1 item is begin transferred, Skip and Cancel are essentially synonymous.
  760. if (this.itemCount > 1)
  761. {
  762. taskButtons.Add(skipTB);
  763. }
  764. taskButtons.Add(cancelTB);
  765. int width96 = (TaskDialog.DefaultPixelWidth96Dpi * 4) / 3;
  766. TaskButton clickedTB = TaskDialog.Show(
  767. this.progressDialog,
  768. formIcon,
  769. formTitle,
  770. taskImage,
  771. true,
  772. introText,
  773. taskButtons.ToArray(),
  774. retryTB,
  775. cancelTB,
  776. width96,
  777. false,
  778. 0,
  779. out bool unuse);
  780. if (clickedTB == retryTB)
  781. {
  782. result = WorkItemFailureAction.RetryItem;
  783. }
  784. else if (clickedTB == skipTB)
  785. {
  786. result = WorkItemFailureAction.SkipItem;
  787. }
  788. else
  789. {
  790. result = WorkItemFailureAction.CancelOperation;
  791. }
  792. return result;
  793. }
  794. private void UpdateUI()
  795. {
  796. int itemCount2 = Math.Max(1, this.itemCount);
  797. double startValue = (double)this.itemOrdinal / (double)itemCount2;
  798. double endValue = (double)(this.itemOrdinal + 1) / (double)itemCount2;
  799. long totalWork2 = Math.Max(1, this.totalWork);
  800. double lerp = (double)this.totalProgress / (double)totalWork2;
  801. double newValue = Utility.Lerp(startValue, endValue, lerp);
  802. int newValueInt = (int)Math.Ceiling(maxPBValue * newValue);
  803. if (this.cancelRequested)
  804. {
  805. this.progressDialog.CancelEnabled = false;
  806. //this.progressDialog.ItemText = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling");
  807. //this.progressDialog.OperationProgress = string.Empty;
  808. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  809. }
  810. else
  811. {
  812. this.progressDialog.CancelEnabled = true;
  813. //this.progressDialog.ItemText = this.itemName;
  814. string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format");
  815. string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount);
  816. //this.progressDialog.OperationProgress = progressText;
  817. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  818. this.progressDialog.ProgressBar.Value = newValueInt;
  819. }
  820. }
  821. }
  822. public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect, string startingDir)
  823. {
  824. using (IFileOpenDialog ofd = new ClassicFileOpenDialog())
  825. {
  826. ofd.InitialDirectory = "";
  827. if (startingDir != null)
  828. {
  829. ofd.InitialDirectory = startingDir;
  830. }
  831. ofd.CheckFileExists = true;
  832. ofd.CheckPathExists = true;
  833. ofd.Multiselect = multiselect;
  834. ofd.Filter = PdnResources.GetString("NewRasterData") + "(*.tif,*.tiff,*.jpg,*.jpeg,*.png,*.bmp)|*.tif;*.tiff;*.jpg;*.jpeg;*.png;*.bmp";
  835. ofd.FilterIndex = 0;
  836. DialogResult result = ShowFileDialog(owner, ofd);
  837. if (result == DialogResult.OK)
  838. {
  839. fileNames = ofd.FileNames;
  840. }
  841. else
  842. {
  843. fileNames = new string[0];
  844. }
  845. return result;
  846. }
  847. }
  848. /// <summary>
  849. /// 图片保存,保存当前激活图片,用来替换原框架的保存
  850. /// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1)
  851. /// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果
  852. /// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为:
  853. /// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像
  854. /// </summary>
  855. /// <returns></returns>
  856. public bool DoSaveNew()
  857. {
  858. string newFileName;
  859. GetDocumentSaveOptions(out newFileName);
  860. // 如果没有指定文件名(不是从硬盘打开,是生成或从相机获得),则执行另存为
  861. if (newFileName == null)
  862. {
  863. return DoSaveAsNew();
  864. }
  865. else
  866. {
  867. try
  868. {
  869. //获取文件后缀名
  870. string extension = Path.GetExtension(newFileName);
  871. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像、不保存相
  872. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  873. {
  874. //保存图片
  875. if (!extension.Equals(".tga"))//不是压缩包
  876. {
  877. ImageCodecInfo icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg);
  878. if (extension.Equals(".jpg"))
  879. {
  880. icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg);
  881. }
  882. else if (extension.Equals(".bmp"))
  883. {
  884. icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Bmp);
  885. }
  886. else if (extension.Equals("TIFF"))
  887. {
  888. icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Tiff);
  889. }
  890. EncoderParameters parms = new EncoderParameters(1);
  891. EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
  892. parms.Param[0] = parm;
  893. bitmap.Save(newFileName, icf, parms);
  894. }
  895. }
  896. }
  897. catch (Exception)
  898. {
  899. MessageBox.Show(PdnResources.GetString("Menu.Imagesavefailed.text"));
  900. return false;
  901. }
  902. }
  903. return true;
  904. }
  905. /// <summary>
  906. /// 获取批量保存中设置的参数,按生成规律提取文件名称
  907. /// </summary>
  908. /// <param name="file_Name">文件名称</param>
  909. /// <returns></returns>
  910. public bool GetParameters(out string file_Name)
  911. {
  912. file_Name = string.Empty;
  913. batchSaveAutoModel = XmlSerializeHelper.DESerializer<BatchSaveAutoModel>(FileOperationHelper.ReadStringFromFile(Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml", FileMode.Open));
  914. if (batchSaveAutoModel.Whether)
  915. {
  916. file_Name = batchSaveAutoModel.prefix + batchSaveAutoModel.fileName + "_" + batchSaveAutoModel.startNum + batchSaveAutoModel.suffix;
  917. batchSaveAutoModel.startNum = batchSaveAutoModel.startNum + 1;
  918. //另存为XML
  919. string stageModelXml = XmlSerializeHelper.XmlSerialize<BatchSaveAutoModel>(batchSaveAutoModel);
  920. string filePath = Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml";
  921. FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create);
  922. }
  923. return batchSaveAutoModel.Whether;
  924. }
  925. /// <summary>
  926. /// 文件另存,用来替换原框架的保存
  927. /// 1)将图片另存到其他位置,即变化不保存在原图像上
  928. /// 2)点击另存为,打开保存路径窗口(图1)
  929. /// 3)并根据(图1)中对应的设置判断是否关闭打开的图像
  930. /// 4)若名称重复,则弹出对应提示,查看效果可点击图1中的【保存】按钮
  931. /// </summary>
  932. /// <returns></returns>
  933. public bool DoSaveAsNew()
  934. {
  935. //获取批量保存中设置的参数,提取文件名称
  936. string file_Name;
  937. //判断是否是压缩包文件
  938. bool isZipFile = false;
  939. if (zipHandleHelper != null)
  940. isZipFile = true;
  941. using (SaveFileDialog saveDialog = new SaveFileDialog())
  942. {
  943. ConfigModel configModel = Program.instance.configModel;//获取另存窗口几个选项的配置
  944. File.MySaveDialogControl saveDialogCtrl = new File.MySaveDialogControl(@"C:\Users\dlrj\Desktop\晶粒度-冷轧薄板晶粒度评级2 - 副本.JPG"/*lblFilePath.Text*/, this);
  945. //saveDialogCtrl.FileDlgInitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
  946. saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
  947. //生成配置文件选中状态
  948. if (configModel.WhetherGenerateConfig == 0)
  949. saveDialogCtrl.checkBox1.Checked = false;
  950. //关闭图像选中状态
  951. if (configModel.WhetherCloseAfterSave == 0)
  952. saveDialogCtrl.checkBox2.Checked = false;
  953. if (isZipFile)
  954. {
  955. saveDialog.Filter = "Tga(*.tga)|*.tga";
  956. saveDialog.DefaultExt = "tga";
  957. saveDialogCtrl.checkBox5.Visible = false;
  958. saveDialogCtrl.numericUpDown1.Visible = false;
  959. saveDialogCtrl.label1.Visible = false;
  960. }
  961. else
  962. {
  963. //压缩比例选中状态
  964. if (configModel.WhetherCompression == 1)
  965. saveDialogCtrl.checkBox5.Checked = true;
  966. saveDialogCtrl.numericUpDown1.Value = configModel.CompressionRatio;//压缩比例数值
  967. saveDialog.Filter = "Jpeg(*.jpg)|*.jpg|Tiff(*.tiff)|*.tiff|Bmp(*.bmp)|*.bmp";
  968. saveDialog.DefaultExt = "jpg";
  969. }
  970. saveDialog.FilterIndex = 1;
  971. saveDialog.CheckFileExists = false;// true;
  972. saveDialog.AddExtension = true;
  973. string friendName = AppWorkspace.ActiveDocumentWorkspace.GetFriendlyName();
  974. string m_FileName = Path.GetFileNameWithoutExtension(friendName);//friendName.Substring(friendName.LastIndexOf('\\') + 1, friendName.LastIndexOf('.') - friendName.LastIndexOf('\\') - 1);
  975. string suffixName = Path.GetExtension(friendName);//friendName.Substring(friendName.LastIndexOf(".") + 1, (friendName.Length - friendName.LastIndexOf(".") - 1)); ;
  976. //判断是否有保存参数,有则获取,无则使用原始文件名
  977. if (GetParameters(out file_Name))
  978. {
  979. saveDialog.FileName = file_Name;
  980. }
  981. else
  982. {
  983. saveDialog.FileName = m_FileName + " - " + PdnResources.GetString("Menu.Acopyofth.Text") + suffixName;
  984. }
  985. saveDialog.DereferenceLinks = true;
  986. //saveDialog.ShowHelp = true;
  987. if (Environment.OSVersion.Version.Major < 6)
  988. saveDialog.SetPlaces(new object[] { (int)Places.Desktop, (int)Places.Printers, (int)Places.Favorites, (int)Places.Programs, (int)Places.Fonts, });
  989. string path = "";
  990. if (saveDialog.ShowDialog(saveDialogCtrl, this) == DialogResult.OK)
  991. {
  992. //文件路径
  993. path = saveDialog.FileName;
  994. //是否生成配置文件
  995. bool createConfig = saveDialogCtrl.checkBox1.Checked;
  996. //保存后是否关闭图像
  997. bool afterSaveClost = saveDialogCtrl.checkBox2.Checked;
  998. //是否压缩
  999. bool compress = saveDialogCtrl.checkBox5.Checked;
  1000. //压缩比例
  1001. decimal compressRate = saveDialogCtrl.numericUpDown1.Value;
  1002. //重新保存选项到配置文件
  1003. if (createConfig)
  1004. configModel.WhetherGenerateConfig = 1;
  1005. else
  1006. configModel.WhetherGenerateConfig = 0;
  1007. if (afterSaveClost)
  1008. configModel.WhetherCloseAfterSave = 1;
  1009. else
  1010. configModel.WhetherCloseAfterSave = 0;
  1011. if (compress)
  1012. configModel.WhetherCompression = 1;
  1013. else
  1014. configModel.WhetherCompression = 0;
  1015. configModel.CompressionRatio = compressRate;
  1016. string configModelXml = XmlSerializeHelper.XmlSerialize<ConfigModel>(configModel);
  1017. FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" +
  1018. Program.instance.SettingPrefix + "\\Config.xml", FileMode.Create);
  1019. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
  1020. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  1021. {
  1022. //获取文件后缀名
  1023. string extension = Path.GetExtension(path);
  1024. if (!extension.Equals(".tga"))
  1025. {
  1026. using (Bitmap dstBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat))
  1027. {
  1028. Graphics graphics = Graphics.FromImage(dstBitmap);
  1029. //保存图片
  1030. ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1031. if (extension.Equals(".jpg"))
  1032. {
  1033. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1034. }
  1035. else if (extension.Equals(".bmp"))
  1036. {
  1037. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
  1038. }
  1039. else if (extension.Equals(".tiff"))
  1040. {
  1041. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff);
  1042. }
  1043. EncoderParameters parms = new EncoderParameters(1);
  1044. EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
  1045. parms.Param[0] = parm;
  1046. dstBitmap.Save(path, icf, parms);
  1047. }
  1048. }
  1049. else
  1050. {
  1051. //另存的路径与原zip路径不相同,则copy一份;相同不做处理
  1052. if (!path.Equals(zipHandleHelper.zipName))
  1053. {
  1054. System.IO.File.Copy(zipHandleHelper.zipName, path, true);
  1055. }
  1056. }
  1057. //保存配置文件
  1058. if (createConfig)
  1059. {
  1060. //组织配置文件的数据
  1061. PicConfigModel picConfigModel = new PicConfigModel();
  1062. //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
  1063. picConfigModel.hardware = new PicConfigModel.Hardware();
  1064. ////相机参数赋值
  1065. //GetCameraParameters(picConfigModel);
  1066. picConfigModel.meta = new PicConfigModel.Meta();
  1067. picConfigModel.rule = new PicConfigModel.Rule();
  1068. picConfigModel.meta.format = extension;
  1069. picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  1070. if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
  1071. {
  1072. picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1073. picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1074. picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1075. picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1076. picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1077. }
  1078. else
  1079. {
  1080. if (Program.instance.ruleDB != null)
  1081. {
  1082. picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name;
  1083. picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple;
  1084. picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length;
  1085. picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length;
  1086. picConfigModel.rule.ruler_units = Program.instance.ruleDB.ruler_units;
  1087. }
  1088. }
  1089. FileInfo fileInfo = new FileInfo(path);
  1090. long lengthOfDocument = fileInfo.Length;
  1091. picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument);
  1092. //获取图像所在的目录
  1093. string directoryPath = Path.GetDirectoryName(path);
  1094. //获取不带后缀的文件名
  1095. string noExtension = Path.GetFileNameWithoutExtension(path);
  1096. picConfigModel.meta.text = noExtension;
  1097. //按路径和名称保存xml文件
  1098. string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1099. //xml保存路径
  1100. string filePath = directoryPath + "\\" + noExtension + ".xml";
  1101. //保存xml
  1102. FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1103. if (extension.Equals(".tga"))
  1104. {
  1105. //copy了新的zip包,则修改新zip包内的xml
  1106. if (!path.Equals(zipHandleHelper.zipName))
  1107. {
  1108. ZipHandleHelper newZipFile = new ZipHandleHelper(path);
  1109. //if (newZipFile != null)
  1110. //{
  1111. // if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel))
  1112. // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1113. //}
  1114. }
  1115. //没有copy,修改旧zip包的xml
  1116. else
  1117. {
  1118. //if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
  1119. // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1120. }
  1121. }
  1122. //if (!extension.Equals(".tga"))//压缩包不清楚是否要保存基础和标尺等信息
  1123. //{
  1124. // picConfigModel.meta = new PicConfigModel.Meta();
  1125. // picConfigModel.rule = new PicConfigModel.Rule();
  1126. // picConfigModel.meta.format = extension;
  1127. // picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  1128. // if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0))
  1129. // {
  1130. // picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1131. // picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1132. // picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1133. // picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1134. // picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1135. // }
  1136. // else
  1137. // {
  1138. // if (Program.instance.ruleDB != null)
  1139. // {
  1140. // picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name;
  1141. // picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple;
  1142. // picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length;
  1143. // picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length;
  1144. // picConfigModel.rule.ruler_units = Program.instance.ruleDB.ruler_units;
  1145. // }
  1146. // }
  1147. // FileInfo fileInfo = new FileInfo(path);
  1148. // long lengthOfDocument = fileInfo.Length;
  1149. // picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument);
  1150. // //获取图像所在的目录
  1151. // string directoryPath = Path.GetDirectoryName(path);
  1152. // //获取不带后缀的文件名
  1153. // string noExtension = Path.GetFileNameWithoutExtension(path);
  1154. // picConfigModel.meta.text = noExtension;
  1155. // //按路径和名称保存xml文件
  1156. // string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1157. // //xml保存路径
  1158. // string filePath = directoryPath + "\\" + noExtension + ".xml";
  1159. // //保存xml
  1160. // FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1161. //}
  1162. //else
  1163. //{
  1164. // //copy了新的zip包,则修改新zip包内的xml
  1165. // if (!path.Equals(zipHandleHelper.zipName))
  1166. // {
  1167. // ZipHandleHelper newZipFile = new ZipHandleHelper(path);
  1168. // if (newZipFile != null)
  1169. // {
  1170. // if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel))
  1171. // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1172. // }
  1173. // }
  1174. // //没有copy,修改旧zip包的xml
  1175. // else
  1176. // {
  1177. // if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel))
  1178. // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text"));
  1179. // }
  1180. //}
  1181. }
  1182. if (this.Document != null)
  1183. {
  1184. this.Document.Dirty = false;
  1185. }
  1186. //保存后是否关闭图像
  1187. if (afterSaveClost)
  1188. {
  1189. this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
  1190. }
  1191. else
  1192. {
  1193. this.filePath = path;
  1194. this.fileText = this.GetFriendlyName();
  1195. this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
  1196. }
  1197. }
  1198. }
  1199. else
  1200. {
  1201. return false;
  1202. }
  1203. }
  1204. return true;
  1205. }
  1206. public static Document LoadDocument(Control owner, string fileName, ProgressEventHandler progressCallback)
  1207. {
  1208. Document document = null;
  1209. using (new WaitCursorChanger(owner))
  1210. {
  1211. //Utility.GCFullCollect();
  1212. //Stream stream = null;
  1213. using (OpenCvSharp.Mat tempMat = new Mat(fileName))
  1214. {
  1215. try
  1216. {
  1217. try
  1218. {
  1219. //stream = tempMat.ToMemoryStream(Path.GetExtension(fileName));
  1220. //long totalBytes = 0;
  1221. //SiphonStream siphonStream = new SiphonStream(stream);
  1222. /*IOEventHandler ioEventHandler = null;
  1223. ioEventHandler =
  1224. delegate (object sender, IOEventArgs e)
  1225. {
  1226. if (progressCallback != null)
  1227. {
  1228. totalBytes += (long)e.Count;
  1229. double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
  1230. progressCallback(null, new ProgressEventArgs(percent));
  1231. }
  1232. };*/
  1233. //siphonStream.IOFinished += ioEventHandler;
  1234. using (new WaitCursorChanger(owner))
  1235. {
  1236. document = Document.FromMat(tempMat);// fileType.Load(siphonStream);//
  1237. /*if (progressCallback != null)
  1238. {
  1239. progressCallback(null, new ProgressEventArgs(100.0));
  1240. }*/
  1241. }
  1242. //siphonStream.IOFinished -= ioEventHandler;
  1243. //siphonStream.Close();
  1244. GC.Collect();
  1245. }
  1246. catch (WorkerThreadException ex)
  1247. {
  1248. Type innerExType = ex.InnerException.GetType();
  1249. ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });
  1250. if (ci == null)
  1251. {
  1252. throw;
  1253. }
  1254. else
  1255. {
  1256. Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
  1257. throw ex2;
  1258. }
  1259. }
  1260. }
  1261. catch (ArgumentException)
  1262. {
  1263. if (fileName.Length == 0)
  1264. {
  1265. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
  1266. }
  1267. else
  1268. {
  1269. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
  1270. }
  1271. }
  1272. catch (UnauthorizedAccessException)
  1273. {
  1274. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
  1275. }
  1276. catch (SecurityException)
  1277. {
  1278. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
  1279. }
  1280. catch (FileNotFoundException)
  1281. {
  1282. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
  1283. }
  1284. catch (DirectoryNotFoundException)
  1285. {
  1286. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
  1287. }
  1288. catch (PathTooLongException)
  1289. {
  1290. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
  1291. }
  1292. catch (IOException)
  1293. {
  1294. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
  1295. }
  1296. catch (SerializationException)
  1297. {
  1298. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
  1299. }
  1300. catch (OutOfMemoryException)
  1301. {
  1302. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
  1303. }
  1304. catch (Exception)
  1305. {
  1306. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
  1307. }
  1308. finally
  1309. {
  1310. /*if (stream != null)
  1311. {
  1312. stream.Close();
  1313. stream = null;
  1314. }*/
  1315. /*if (tempMat != null)
  1316. {
  1317. tempMat.Dispose();
  1318. }*/
  1319. }
  1320. }
  1321. }
  1322. return document;
  1323. }
  1324. /// <summary>
  1325. /// 批量保存
  1326. /// </summary>
  1327. /// <param name="fileName">文件名</param>
  1328. /// <param name="createConfig">是否生成配置文件</param>
  1329. /// <param name="afterSaveClost">保存后是否关闭图像</param>
  1330. /// <param name="saveGridLine">保存时是否保存网格数据</param>
  1331. /// <param name="implantLabelAndMeasure">标注及测量信息是否嵌入图像</param>
  1332. /// <param name="compress">是否压缩</param>
  1333. /// <param name="compressRate">压缩比例</param>
  1334. /// <returns></returns>
  1335. public bool SaveForBatch(string fileName, bool createConfig, bool afterSaveClost, bool saveGridLine, bool implantLabelAndMeasure, bool compress, decimal compressRate, bool implantPhase)
  1336. {
  1337. //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像
  1338. using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap())
  1339. {
  1340. Graphics graphics = Graphics.FromImage(bitmap);
  1341. //获取文件后缀名
  1342. string extension = Path.GetExtension(fileName);
  1343. //保存图片
  1344. ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1345. if (extension.Equals(".jpg"))
  1346. {
  1347. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg);
  1348. }
  1349. else if (extension.Equals(".bmp"))
  1350. {
  1351. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp);
  1352. }
  1353. else if (extension.Equals(".tiff"))
  1354. {
  1355. icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff);
  1356. }
  1357. EncoderParameters parms = new EncoderParameters(1);
  1358. EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L);
  1359. parms.Param[0] = parm;
  1360. bitmap.Save(fileName, icf, parms);
  1361. //保存配置文件
  1362. if (createConfig)
  1363. {
  1364. //组织配置文件的数据
  1365. PicConfigModel picConfigModel = new PicConfigModel();
  1366. picConfigModel.hardware = new PicConfigModel.Hardware();
  1367. //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other);
  1368. picConfigModel.meta = new PicConfigModel.Meta();
  1369. picConfigModel.rule = new PicConfigModel.Rule();
  1370. if (this.xmlSaveModel != null)
  1371. {
  1372. picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name;
  1373. picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple;
  1374. picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length;
  1375. picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length;
  1376. picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units;
  1377. }
  1378. //GetCameraParameters(picConfigModel);
  1379. //获取图像所在的目录
  1380. string directoryPath = Path.GetDirectoryName(fileName);
  1381. //获取不带后缀的文件名
  1382. string noExtension = Path.GetFileNameWithoutExtension(fileName);
  1383. //按路径和名称保存xml文件
  1384. string userInfoXml = XmlSerializeHelper.XmlSerialize<PicConfigModel>(picConfigModel);
  1385. //xml保存路径
  1386. string filePath = directoryPath + "\\" + noExtension + ".xml";
  1387. //保存xml
  1388. FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create);
  1389. }
  1390. if (this.Document != null)
  1391. {
  1392. this.Document.Dirty = false;
  1393. }
  1394. //保存后是否关闭图像
  1395. if (afterSaveClost)
  1396. {
  1397. this.Document.Dirty = false;
  1398. this.AppWorkspace.toRemoveDocumentWorkspaceIndex = this.AppWorkspace.DocumentWorkspaces.Length - 1;
  1399. this.AppWorkspace.PerformAction(new CloseWorkspaceAction());
  1400. }
  1401. else
  1402. {
  1403. this.filePath = fileName;
  1404. this.fileText = this.GetFriendlyName();
  1405. this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this);
  1406. }
  1407. }
  1408. return true;
  1409. }
  1410. /// <summary>
  1411. /// 更新测量单位,刷新UI
  1412. /// </summary>
  1413. /// <param name="measurementUnit"></param>
  1414. public void UpdateMeasureUnit(MeasurementUnit measurementUnit)
  1415. {
  1416. //循环所有测量,更新单位
  1417. if (this.GraphicsList != null
  1418. && this.GraphicsList.Count > 0)
  1419. {
  1420. int count = this.GraphicsList.Count;
  1421. for (int i = 0; i < count; i++)
  1422. {
  1423. if (this.GraphicsList[i].objectType == DrawClass.Measure)
  1424. {
  1425. ((MeasureDrawObject)(this.GraphicsList[i])).MeasurementUnit = measurementUnit;
  1426. }
  1427. }
  1428. }
  1429. this.Refresh();
  1430. }
  1431. protected override string[] startUpRules(Dictionary<MeasurementUnit, double> rules)
  1432. {
  1433. string[] result = new string[5];
  1434. result[0] = Program.instance.measurementUnit.ToString();
  1435. result[1] = InvariantData.unitsDictionary[(int)Program.instance.measurementUnit];
  1436. result[2] = InvariantData.unitSymbolsDictionary[(int)Program.instance.measurementUnit];
  1437. if (rules != null)
  1438. {
  1439. result[3] = (rules[Program.instance.measurementUnit]).ToString();
  1440. result[4] = (rules[MeasurementUnit.Micron]).ToString();
  1441. }
  1442. else
  1443. {
  1444. result[3] = (Program.instance.rules[Program.instance.measurementUnit]).ToString();
  1445. result[4] = (Program.instance.rules[MeasurementUnit.Micron]).ToString();
  1446. }
  1447. return result;
  1448. }
  1449. public override void ToolStripMenuItem1_Click(object sender, EventArgs e)
  1450. {
  1451. using (MeasureSettingDialog af = new MeasureSettingDialog(AppWorkspace))
  1452. {
  1453. af.StartPosition = FormStartPosition.CenterScreen;
  1454. af.ShowDialog();
  1455. }
  1456. }
  1457. public override void ToolStripMenuItem3_Click(object sender, EventArgs e)
  1458. {
  1459. for (int i = 0; i < this.GraphicsList.Count; i++)
  1460. {
  1461. if (GraphicsList[i].Selected)
  1462. {
  1463. MeasurementPropertiesDialog measurementPropertiesDialog = new MeasurementPropertiesDialog(this.appWorkspace, this.GraphicsList[i]);
  1464. measurementPropertiesDialog.StartPosition = FormStartPosition.CenterScreen;
  1465. measurementPropertiesDialog.ShowDialog();
  1466. }
  1467. }
  1468. }
  1469. }
  1470. }