PageRenderTime 34ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/src/DocumentWorkspace.cs

https://bitbucket.org/tcz001/openpdn
C# | 2944 lines | 2357 code | 451 blank | 136 comment | 287 complexity | 5edb570d764eb19ca36f67c71e1b848a MD5 | raw file
Possible License(s): Unlicense
  1. /////////////////////////////////////////////////////////////////////////////////
  2. // Paint.NET //
  3. // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
  4. // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
  5. // See src/Resources/Files/License.txt for full licensing and attribution //
  6. // details. //
  7. // . //
  8. /////////////////////////////////////////////////////////////////////////////////
  9. using PaintDotNet.Data;
  10. using PaintDotNet.Effects;
  11. using PaintDotNet.HistoryFunctions;
  12. using PaintDotNet.HistoryMementos;
  13. using PaintDotNet.SystemLayer;
  14. using PaintDotNet.Tools;
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.Drawing;
  20. using System.Drawing.Imaging;
  21. using System.Globalization;
  22. using System.IO;
  23. using System.Reflection;
  24. using System.Runtime.Serialization;
  25. using System.Security;
  26. using System.Text;
  27. using System.Threading;
  28. using System.Windows.Forms;
  29. namespace PaintDotNet
  30. {
  31. /// <summary>
  32. /// Builds on DocumentView by adding application-specific elements.
  33. /// </summary>
  34. internal class DocumentWorkspace
  35. : DocumentView,
  36. IHistoryWorkspace,
  37. IThumbnailProvider
  38. {
  39. public static readonly DateTime NeverSavedDateTime = DateTime.MinValue;
  40. private static Type[] tools; // TODO: move to Tool class?
  41. private static ToolInfo[] toolInfos;
  42. private ZoomBasis zoomBasis;
  43. private AppWorkspace appWorkspace;
  44. private string filePath = null;
  45. private FileType fileType = null;
  46. private SaveConfigToken saveConfigToken = null;
  47. private Selection selection = new Selection();
  48. private Surface scratchSurface = null;
  49. private SelectionRenderer selectionRenderer;
  50. private Hashtable staticToolData = Hashtable.Synchronized(new Hashtable());
  51. private Tool activeTool;
  52. private Type previousActiveToolType;
  53. private Type preNullTool = null;
  54. private int nullToolCount = 0;
  55. private int zoomChangesCount = 0;
  56. private HistoryStack history;
  57. private Layer activeLayer;
  58. private System.Windows.Forms.Timer toolPulseTimer;
  59. private DateTime lastSaveTime = NeverSavedDateTime;
  60. private int suspendToolCursorChanges = 0;
  61. private ImageResource statusIcon = null;
  62. private string statusText = null;
  63. private readonly string contextStatusBarWithAngleFormat = PdnResources.GetString("StatusBar.Context.SelectedArea.Text.WithAngle.Format");
  64. private readonly string contextStatusBarFormat = PdnResources.GetString("StatusBar.Context.SelectedArea.Text.Format");
  65. public void SuspendToolCursorChanges()
  66. {
  67. ++this.suspendToolCursorChanges;
  68. }
  69. public void ResumeToolCursorChanges()
  70. {
  71. --this.suspendToolCursorChanges;
  72. if (this.suspendToolCursorChanges <= 0 && this.activeTool != null)
  73. {
  74. Cursor = this.activeTool.Cursor;
  75. }
  76. }
  77. public ImageResource StatusIcon
  78. {
  79. get
  80. {
  81. return this.statusIcon;
  82. }
  83. }
  84. public string StatusText
  85. {
  86. get
  87. {
  88. return this.statusText;
  89. }
  90. }
  91. public void SetStatus(string newStatusText, ImageResource newStatusIcon)
  92. {
  93. this.statusText = newStatusText;
  94. this.statusIcon = newStatusIcon;
  95. OnStatusChanged();
  96. }
  97. public event EventHandler StatusChanged;
  98. protected virtual void OnStatusChanged()
  99. {
  100. if (StatusChanged != null)
  101. {
  102. StatusChanged(this, EventArgs.Empty);
  103. }
  104. }
  105. static DocumentWorkspace()
  106. {
  107. InitializeTools();
  108. InitializeToolInfos();
  109. }
  110. public DateTime LastSaveTime
  111. {
  112. get
  113. {
  114. return this.lastSaveTime;
  115. }
  116. }
  117. public bool IsZoomChanging
  118. {
  119. get
  120. {
  121. return (this.zoomChangesCount > 0);
  122. }
  123. }
  124. private void BeginZoomChanges()
  125. {
  126. ++this.zoomChangesCount;
  127. }
  128. private void EndZoomChanges()
  129. {
  130. --this.zoomChangesCount;
  131. }
  132. protected override void OnSizeChanged(EventArgs e)
  133. {
  134. PerformLayout();
  135. base.OnSizeChanged(e);
  136. }
  137. protected override void OnLayout(LayoutEventArgs e)
  138. {
  139. if (this.zoomBasis == ZoomBasis.FitToWindow)
  140. {
  141. ZoomToWindow();
  142. // This bizarre ordering of setting PanelAutoScroll prevents some very weird layout/scroll-without-scrollbars stuff.
  143. PanelAutoScroll = true;
  144. PanelAutoScroll = false;
  145. }
  146. base.OnLayout(e);
  147. }
  148. protected override void OnResize(EventArgs e)
  149. {
  150. if (this.zoomBasis == ZoomBasis.FitToWindow)
  151. {
  152. PerformLayout();
  153. }
  154. base.OnResize(e);
  155. }
  156. public DocumentWorkspace()
  157. {
  158. this.activeLayer = null;
  159. this.history = new HistoryStack(this);
  160. InitializeComponent();
  161. // hook the DocumentWorkspace with its selectedPath ...
  162. this.selectionRenderer = new SelectionRenderer(this.RendererList, this.Selection, this);
  163. this.RendererList.Add(this.selectionRenderer, true);
  164. this.selectionRenderer.EnableOutlineAnimation = true;
  165. this.selectionRenderer.EnableSelectionTinting = false;
  166. this.selectionRenderer.EnableSelectionOutline = true;
  167. this.selection.Changed += new EventHandler(Selection_Changed);
  168. this.zoomBasis = ZoomBasis.FitToWindow;
  169. }
  170. protected override void OnUnitsChanged()
  171. {
  172. if (!Selection.IsEmpty)
  173. {
  174. UpdateSelectionInfoInStatusBar();
  175. }
  176. base.OnUnitsChanged();
  177. }
  178. public void UpdateStatusBarToToolHelpText(Tool tool)
  179. {
  180. if (tool == null)
  181. {
  182. SetStatus(string.Empty, null);
  183. }
  184. else
  185. {
  186. string toolName = tool.Name;
  187. string helpText = tool.HelpText;
  188. string contextFormat = PdnResources.GetString("StatusBar.Context.Help.Text.Format");
  189. string contextText = string.Format(contextFormat, toolName, helpText);
  190. SetStatus(contextText, PdnResources.GetImageResource("Icons.MenuHelpHelpTopicsIcon.png"));
  191. }
  192. }
  193. public void UpdateStatusBarToToolHelpText()
  194. {
  195. UpdateStatusBarToToolHelpText(this.activeTool);
  196. }
  197. private void UpdateSelectionInfoInStatusBar()
  198. {
  199. if (Selection.IsEmpty)
  200. {
  201. UpdateStatusBarToToolHelpText();
  202. }
  203. else
  204. {
  205. string newStatusText;
  206. int area = 0;
  207. Rectangle bounds;
  208. using (PdnRegion tempSelection = Selection.CreateRegionRaw())
  209. {
  210. tempSelection.Intersect(Document.Bounds);
  211. bounds = Utility.GetRegionBounds(tempSelection);
  212. area = tempSelection.GetArea();
  213. }
  214. string unitsAbbreviationXY;
  215. string xString;
  216. string yString;
  217. string unitsAbbreviationWH;
  218. string widthString;
  219. string heightString;
  220. Document.CoordinatesToStrings(Units, bounds.X, bounds.Y, out xString, out yString, out unitsAbbreviationXY);
  221. Document.CoordinatesToStrings(Units, bounds.Width, bounds.Height, out widthString, out heightString, out unitsAbbreviationWH);
  222. NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
  223. string areaString;
  224. if (this.Units == MeasurementUnit.Pixel)
  225. {
  226. nfi.NumberDecimalDigits = 0;
  227. areaString = area.ToString("N", nfi);
  228. }
  229. else
  230. {
  231. nfi.NumberDecimalDigits = 2;
  232. double areaD = Document.PixelAreaToPhysicalArea(area, this.Units);
  233. areaString = areaD.ToString("N", nfi);
  234. }
  235. string pluralUnits = PdnResources.GetString("MeasurementUnit." + this.Units.ToString() + ".Plural");
  236. MoveToolBase moveTool = Tool as MoveToolBase;
  237. if (moveTool != null && moveTool.HostShouldShowAngle)
  238. {
  239. NumberFormatInfo nfi2 = (NumberFormatInfo)nfi.Clone();
  240. nfi2.NumberDecimalDigits = 2;
  241. float angle = moveTool.HostAngle;
  242. while (angle > 180.0f)
  243. {
  244. angle -= 360.0f;
  245. }
  246. while (angle < -180.0f)
  247. {
  248. angle += 360.0f;
  249. }
  250. newStatusText = string.Format(
  251. contextStatusBarWithAngleFormat,
  252. xString,
  253. unitsAbbreviationXY,
  254. yString,
  255. unitsAbbreviationXY,
  256. widthString,
  257. unitsAbbreviationWH,
  258. heightString,
  259. unitsAbbreviationWH,
  260. areaString,
  261. pluralUnits.ToLower(),
  262. moveTool.HostAngle.ToString("N", nfi2));
  263. }
  264. else
  265. {
  266. newStatusText = string.Format(
  267. contextStatusBarFormat,
  268. xString,
  269. unitsAbbreviationXY,
  270. yString,
  271. unitsAbbreviationXY,
  272. widthString,
  273. unitsAbbreviationWH,
  274. heightString,
  275. unitsAbbreviationWH,
  276. areaString,
  277. pluralUnits.ToLower());
  278. }
  279. SetStatus(newStatusText, PdnResources.GetImageResource("Icons.SelectionIcon.png"));
  280. }
  281. }
  282. private void Selection_Changed(object sender, EventArgs e)
  283. {
  284. UpdateRulerSelectionTinting();
  285. UpdateSelectionInfoInStatusBar();
  286. }
  287. private void InitializeComponent()
  288. {
  289. this.toolPulseTimer = new System.Windows.Forms.Timer();
  290. this.toolPulseTimer.Interval = 16;
  291. this.toolPulseTimer.Tick += new EventHandler(this.ToolPulseTimer_Tick);
  292. }
  293. protected override void Dispose(bool disposing)
  294. {
  295. if (disposing)
  296. {
  297. if (this.activeTool != null)
  298. {
  299. this.activeTool.Dispose();
  300. this.activeTool = null;
  301. }
  302. }
  303. base.Dispose(disposing);
  304. }
  305. public void PerformActionAsync(DocumentWorkspaceAction action)
  306. {
  307. BeginInvoke(new Procedure<DocumentWorkspaceAction>(PerformAction), new object[] { action });
  308. }
  309. public void PerformAction(DocumentWorkspaceAction action)
  310. {
  311. bool nullTool = false;
  312. if ((action.ActionFlags & ActionFlags.KeepToolActive) != ActionFlags.KeepToolActive)
  313. {
  314. PushNullTool();
  315. Update();
  316. nullTool = true;
  317. }
  318. try
  319. {
  320. using (new WaitCursorChanger(this))
  321. {
  322. HistoryMemento ha = action.PerformAction(this);
  323. if (ha != null)
  324. {
  325. History.PushNewMemento(ha);
  326. }
  327. }
  328. }
  329. finally
  330. {
  331. if (nullTool)
  332. {
  333. PopNullTool();
  334. }
  335. }
  336. }
  337. /// <summary>
  338. /// Executes a HistoryFunction in the context of this DocumentWorkspace.
  339. /// </summary>
  340. /// <param name="function">The HistoryFunction to execute.</param>
  341. /// <remarks>
  342. /// Depending on the HistoryFunction, the currently active tool may be refreshed.
  343. /// </remarks>
  344. public HistoryFunctionResult ExecuteFunction(HistoryFunction function)
  345. {
  346. HistoryFunctionResult result;
  347. bool nullTool = false;
  348. if ((function.ActionFlags & ActionFlags.KeepToolActive) != ActionFlags.KeepToolActive)
  349. {
  350. PushNullTool();
  351. Update();
  352. nullTool = true;
  353. }
  354. try
  355. {
  356. using (new WaitCursorChanger(this))
  357. {
  358. HistoryMemento hm = null;
  359. string errorText;
  360. try
  361. {
  362. bool cancelled = false;
  363. if ((function.ActionFlags & ActionFlags.ReportsProgress) != ActionFlags.ReportsProgress)
  364. {
  365. hm = function.Execute(this);
  366. }
  367. else
  368. {
  369. ProgressDialog pd = new ProgressDialog();
  370. bool pdLoaded = false;
  371. bool closeAtLoad = false;
  372. EventHandler loadCallback =
  373. delegate(object sender, EventArgs e)
  374. {
  375. pdLoaded = true;
  376. if (closeAtLoad)
  377. {
  378. pd.Close();
  379. }
  380. };
  381. ProgressEventHandler progressCallback =
  382. delegate(object sender, ProgressEventArgs e)
  383. {
  384. if (pdLoaded)
  385. {
  386. double newValue = Utility.Clamp(e.Percent, 0.0, 100.0);
  387. pd.Value = newValue;
  388. }
  389. };
  390. EventHandler<EventArgs<HistoryMemento>> finishedCallback =
  391. delegate(object sender, EventArgs<HistoryMemento> e)
  392. {
  393. hm = e.Data;
  394. if (pdLoaded)
  395. {
  396. // TODO: fix ProgressDialog's very weird interface
  397. pd.ExternalFinish();
  398. pd.Close();
  399. }
  400. else
  401. {
  402. closeAtLoad = true;
  403. }
  404. };
  405. EventHandler cancelClickCallback =
  406. delegate(object sender, EventArgs e)
  407. {
  408. cancelled = true;
  409. function.RequestCancel();
  410. //pd.Cancellable = false;
  411. };
  412. pd.Text = PdnInfo.GetBareProductName();
  413. pd.Description = PdnResources.GetString("ExecuteFunction.ProgressDialog.Description.Text");
  414. pd.Load += loadCallback;
  415. pd.Cancellable = false; //function.Cancellable;
  416. pd.CancelClick += cancelClickCallback;
  417. function.Progress += progressCallback;
  418. function.BeginExecute(this, this, finishedCallback);
  419. pd.ShowDialog(this);
  420. pd.Dispose();
  421. }
  422. if (hm == null && !cancelled)
  423. {
  424. result = HistoryFunctionResult.SuccessNoOp;
  425. }
  426. else if (hm == null && cancelled)
  427. {
  428. result = HistoryFunctionResult.Cancelled;
  429. }
  430. else
  431. {
  432. result = HistoryFunctionResult.Success;
  433. }
  434. errorText = null;
  435. }
  436. catch (HistoryFunctionNonFatalException hfnfex)
  437. {
  438. if (hfnfex.InnerException is OutOfMemoryException)
  439. {
  440. result = HistoryFunctionResult.OutOfMemory;
  441. }
  442. else
  443. {
  444. result = HistoryFunctionResult.NonFatalError;
  445. }
  446. if (hfnfex.LocalizedErrorText != null)
  447. {
  448. errorText = hfnfex.LocalizedErrorText;
  449. }
  450. else
  451. {
  452. if (hfnfex.InnerException is OutOfMemoryException)
  453. {
  454. errorText = PdnResources.GetString("ExecuteFunction.GenericOutOfMemory");
  455. }
  456. else
  457. {
  458. errorText = PdnResources.GetString("ExecuteFunction.GenericError");
  459. }
  460. }
  461. }
  462. if (errorText != null)
  463. {
  464. Utility.ErrorBox(this, errorText);
  465. }
  466. if (hm != null)
  467. {
  468. History.PushNewMemento(hm);
  469. }
  470. }
  471. }
  472. finally
  473. {
  474. if (nullTool)
  475. {
  476. PopNullTool();
  477. }
  478. }
  479. return result;
  480. }
  481. public override void ZoomIn()
  482. {
  483. this.ZoomBasis = ZoomBasis.ScaleFactor;
  484. base.ZoomIn();
  485. }
  486. public override void ZoomIn(double factor)
  487. {
  488. this.ZoomBasis = ZoomBasis.ScaleFactor;
  489. base.ZoomIn(factor);
  490. }
  491. public override void ZoomOut()
  492. {
  493. this.ZoomBasis = ZoomBasis.ScaleFactor;
  494. base.ZoomOut();
  495. }
  496. public override void ZoomOut(double factor)
  497. {
  498. this.ZoomBasis = ZoomBasis.ScaleFactor;
  499. base.ZoomOut(factor);
  500. }
  501. // TODO:
  502. /// <summary>
  503. /// Same as PerformAction(Type) except it lets you rename the HistoryMemento's name.
  504. /// </summary>
  505. /// <param name="actionType"></param>
  506. /// <param name="newName"></param>
  507. public void PerformAction(Type actionType, string newName, ImageResource icon)
  508. {
  509. using (new WaitCursorChanger(this))
  510. {
  511. ConstructorInfo ci = actionType.GetConstructor(new Type[] { typeof(DocumentWorkspace) });
  512. object actionAsObject = ci.Invoke(new object[] { this });
  513. DocumentWorkspaceAction action = actionAsObject as DocumentWorkspaceAction;
  514. if (action != null)
  515. {
  516. bool nullTool = false;
  517. if ((action.ActionFlags & ActionFlags.KeepToolActive) != ActionFlags.KeepToolActive)
  518. {
  519. PushNullTool();
  520. Update();
  521. nullTool = true;
  522. }
  523. try
  524. {
  525. HistoryMemento ha = action.PerformAction(this);
  526. if (ha != null)
  527. {
  528. ha.Name = newName;
  529. ha.Image = icon;
  530. History.PushNewMemento(ha);
  531. }
  532. }
  533. finally
  534. {
  535. if (nullTool)
  536. {
  537. PopNullTool();
  538. }
  539. }
  540. }
  541. }
  542. }
  543. public event EventHandler ZoomBasisChanging;
  544. protected virtual void OnZoomBasisChanging()
  545. {
  546. if (ZoomBasisChanging != null)
  547. {
  548. ZoomBasisChanging(this, EventArgs.Empty);
  549. }
  550. }
  551. public event EventHandler ZoomBasisChanged;
  552. protected virtual void OnZoomBasisChanged()
  553. {
  554. if (ZoomBasisChanged != null)
  555. {
  556. ZoomBasisChanged(this, EventArgs.Empty);
  557. }
  558. }
  559. public ZoomBasis ZoomBasis
  560. {
  561. get
  562. {
  563. return this.zoomBasis;
  564. }
  565. set
  566. {
  567. if (this.zoomBasis != value)
  568. {
  569. OnZoomBasisChanging();
  570. this.zoomBasis = value;
  571. switch (this.zoomBasis)
  572. {
  573. case ZoomBasis.FitToWindow:
  574. ZoomToWindow();
  575. // Enable PanelAutoScroll only long enough to recenter the view
  576. PanelAutoScroll = true;
  577. PanelAutoScroll = false;
  578. // this would be unset by the scalefactor changes in ZoomToWindow
  579. this.zoomBasis = ZoomBasis.FitToWindow;
  580. break;
  581. case ZoomBasis.ScaleFactor:
  582. PanelAutoScroll = true;
  583. break;
  584. default:
  585. throw new InvalidEnumArgumentException();
  586. }
  587. OnZoomBasisChanged();
  588. }
  589. }
  590. }
  591. public void ZoomToSelection()
  592. {
  593. if (Selection.IsEmpty)
  594. {
  595. ZoomToWindow();
  596. }
  597. else
  598. {
  599. using (PdnRegion region = Selection.CreateRegion())
  600. {
  601. ZoomToRectangle(region.GetBoundsInt());
  602. }
  603. }
  604. }
  605. public void ZoomToRectangle(Rectangle selectionBounds)
  606. {
  607. PointF selectionCenter = new PointF((selectionBounds.Left + selectionBounds.Right + 1) / 2,
  608. (selectionBounds.Top + selectionBounds.Bottom + 1) / 2);
  609. PointF cornerPosition;
  610. ScaleFactor zoom = ScaleFactor.Min(ClientRectangleMin.Width, selectionBounds.Width + 2,
  611. ClientRectangleMin.Height, selectionBounds.Height + 2,
  612. ScaleFactor.MinValue);
  613. // Zoom out to fit the image
  614. ZoomBasis = ZoomBasis.ScaleFactor;
  615. ScaleFactor = zoom;
  616. cornerPosition = new PointF(selectionCenter.X - (VisibleDocumentRectangleF.Width / 2),
  617. selectionCenter.Y - (VisibleDocumentRectangleF.Height / 2));
  618. DocumentScrollPositionF = cornerPosition;
  619. }
  620. protected override void HandleMouseWheel(Control sender, MouseEventArgs e)
  621. {
  622. if (Control.ModifierKeys == Keys.Control)
  623. {
  624. double mouseDelta = (double)e.Delta / 120.0f;
  625. Rectangle visibleDocBoundsStart = this.VisibleDocumentBounds;
  626. Point mouseDocPt = this.MouseToDocument(sender, new Point(e.X, e.Y));
  627. RectangleF visibleDocDocRect1 = this.VisibleDocumentRectangleF;
  628. PointF mouseNPt = new PointF(
  629. (mouseDocPt.X - visibleDocDocRect1.X) / visibleDocDocRect1.Width,
  630. (mouseDocPt.Y - visibleDocDocRect1.Y) / visibleDocDocRect1.Height);
  631. const double factor = 1.12;
  632. double mouseFactor = Math.Pow(factor, Math.Abs(mouseDelta));
  633. if (e.Delta > 0)
  634. {
  635. this.ZoomIn(mouseFactor);
  636. }
  637. else if (e.Delta < 0)
  638. {
  639. this.ZoomOut(mouseFactor);
  640. }
  641. RectangleF visibleDocDocRect2 = this.VisibleDocumentRectangleF;
  642. PointF scrollPt2 = new PointF(
  643. mouseDocPt.X - visibleDocDocRect2.Width * mouseNPt.X,
  644. mouseDocPt.Y - visibleDocDocRect2.Height * mouseNPt.Y);
  645. this.DocumentScrollPositionF = scrollPt2;
  646. Rectangle visibleDocBoundsEnd = this.VisibleDocumentBounds;
  647. if (visibleDocBoundsEnd != visibleDocBoundsStart)
  648. {
  649. // Make sure the screen updates, otherwise it can get a little funky looking
  650. this.Update();
  651. }
  652. }
  653. base.HandleMouseWheel(sender, e);
  654. }
  655. public void SelectClosestVisibleLayer(Layer layer)
  656. {
  657. int oldLayerIndex = this.Document.Layers.IndexOf(layer);
  658. int newLayerIndex = oldLayerIndex;
  659. // find the closest layer that is still visible
  660. for (int i = 0; i < this.Document.Layers.Count; ++i)
  661. {
  662. int lower = oldLayerIndex - i;
  663. int upper = oldLayerIndex + i;
  664. if (lower >= 0 && lower < this.Document.Layers.Count && ((Layer)this.Document.Layers[lower]).Visible)
  665. {
  666. newLayerIndex = lower;
  667. break;
  668. }
  669. if (upper >= 0 && upper < this.Document.Layers.Count && ((Layer)this.Document.Layers[upper]).Visible)
  670. {
  671. newLayerIndex = upper;
  672. break;
  673. }
  674. }
  675. if (newLayerIndex != oldLayerIndex)
  676. {
  677. this.ActiveLayer = (Layer)Document.Layers[newLayerIndex];
  678. }
  679. }
  680. public void UpdateRulerSelectionTinting()
  681. {
  682. if (this.RulersEnabled)
  683. {
  684. Rectangle bounds = this.Selection.GetBounds();
  685. this.SetHighlightRectangle(bounds);
  686. }
  687. }
  688. private void LayerRemovingHandler(object sender, IndexEventArgs e)
  689. {
  690. Layer layer = (Layer)this.Document.Layers[e.Index];
  691. layer.PropertyChanging -= LayerPropertyChangingHandler;
  692. layer.PropertyChanged -= LayerPropertyChangedHandler;
  693. // pick a new valid layer!
  694. int newLayerIndex;
  695. if (e.Index == this.Document.Layers.Count - 1)
  696. {
  697. newLayerIndex = e.Index - 1;
  698. }
  699. else
  700. {
  701. newLayerIndex = e.Index + 1;
  702. }
  703. if (newLayerIndex >= 0 && newLayerIndex < this.Document.Layers.Count)
  704. {
  705. this.ActiveLayer = (Layer)this.Document.Layers[newLayerIndex];
  706. }
  707. else
  708. {
  709. if (this.Document.Layers.Count == 0)
  710. {
  711. this.ActiveLayer = null;
  712. }
  713. else
  714. {
  715. this.ActiveLayer = (Layer)this.Document.Layers[0];
  716. }
  717. }
  718. }
  719. private void LayerRemovedHandler(object sender, IndexEventArgs e)
  720. {
  721. }
  722. private void LayerInsertedHandler(object sender, IndexEventArgs e)
  723. {
  724. Layer layer = (Layer)this.Document.Layers[e.Index];
  725. this.ActiveLayer = layer;
  726. layer.PropertyChanging += LayerPropertyChangingHandler;
  727. layer.PropertyChanged += LayerPropertyChangedHandler;
  728. }
  729. private void LayerPropertyChangingHandler(object sender, PropertyEventArgs e)
  730. {
  731. string nameFormat = PdnResources.GetString("LayerPropertyChanging.HistoryMementoNameFormat");
  732. string haName = string.Format(nameFormat, e.PropertyName);
  733. LayerPropertyHistoryMemento lpha = new LayerPropertyHistoryMemento(
  734. haName,
  735. PdnResources.GetImageResource("Icons.MenuLayersLayerPropertiesIcon.png"),
  736. this,
  737. this.Document.Layers.IndexOf(sender));
  738. this.History.PushNewMemento(lpha);
  739. }
  740. private void LayerPropertyChangedHandler(object sender, PropertyEventArgs e)
  741. {
  742. Layer layer = (Layer)sender;
  743. if (!layer.Visible &&
  744. layer == this.ActiveLayer &&
  745. this.Document.Layers.Count > 1 &&
  746. !History.IsExecutingMemento)
  747. {
  748. SelectClosestVisibleLayer(layer);
  749. }
  750. }
  751. private void ToolPulseTimer_Tick(object sender, EventArgs e)
  752. {
  753. if (FindForm() == null || FindForm().WindowState == FormWindowState.Minimized)
  754. {
  755. return;
  756. }
  757. if (this.Tool != null && this.Tool.Active)
  758. {
  759. this.Tool.PerformPulse();
  760. }
  761. }
  762. protected override void OnLoad(EventArgs e)
  763. {
  764. if (this.appWorkspace == null)
  765. {
  766. throw new InvalidOperationException("Must set the Workspace property");
  767. }
  768. base.OnLoad(e);
  769. }
  770. public event EventHandler ActiveLayerChanging;
  771. protected void OnLayerChanging()
  772. {
  773. if (ActiveLayerChanging != null)
  774. {
  775. ActiveLayerChanging(this, EventArgs.Empty);
  776. }
  777. }
  778. public event EventHandler ActiveLayerChanged;
  779. protected void OnLayerChanged()
  780. {
  781. this.Focus();
  782. if (ActiveLayerChanged != null)
  783. {
  784. ActiveLayerChanged(this, EventArgs.Empty);
  785. }
  786. }
  787. public Layer ActiveLayer
  788. {
  789. get
  790. {
  791. return this.activeLayer;
  792. }
  793. set
  794. {
  795. OnLayerChanging();
  796. bool deactivateTool;
  797. if (this.Tool != null)
  798. {
  799. deactivateTool = this.Tool.DeactivateOnLayerChange;
  800. }
  801. else
  802. {
  803. deactivateTool = false;
  804. }
  805. if (deactivateTool)
  806. {
  807. PushNullTool();
  808. this.EnableToolPulse = false;
  809. }
  810. try
  811. {
  812. // Verify that the layer is in the document (sanity checking)
  813. if (this.Document != null)
  814. {
  815. if (value != null && !this.Document.Layers.Contains(value))
  816. {
  817. throw new InvalidOperationException("ActiveLayer was changed to a layer that is not contained within the Document");
  818. }
  819. }
  820. else
  821. {
  822. // Document == null
  823. if (value != null)
  824. {
  825. throw new InvalidOperationException("ActiveLayer was set to non-null while Document was null");
  826. }
  827. }
  828. // Finally, set the field.
  829. this.activeLayer = value;
  830. }
  831. finally
  832. {
  833. if (deactivateTool)
  834. {
  835. PopNullTool();
  836. this.EnableToolPulse = true;
  837. }
  838. }
  839. OnLayerChanged();
  840. }
  841. }
  842. public int ActiveLayerIndex
  843. {
  844. get
  845. {
  846. return Document.Layers.IndexOf(ActiveLayer);
  847. }
  848. set
  849. {
  850. this.ActiveLayer = (Layer)Document.Layers[value];
  851. }
  852. }
  853. public bool EnableToolPulse
  854. {
  855. get
  856. {
  857. return this.toolPulseTimer.Enabled;
  858. }
  859. set
  860. {
  861. this.toolPulseTimer.Enabled = value;
  862. }
  863. }
  864. public HistoryStack History
  865. {
  866. get
  867. {
  868. return this.history;
  869. }
  870. }
  871. public Tool Tool
  872. {
  873. get
  874. {
  875. return this.activeTool;
  876. }
  877. }
  878. public Type GetToolType()
  879. {
  880. if (Tool != null)
  881. {
  882. return Tool.GetType();
  883. }
  884. else
  885. {
  886. return null;
  887. }
  888. }
  889. public void SetToolFromType(Type toolType)
  890. {
  891. if (toolType == GetToolType())
  892. {
  893. return;
  894. }
  895. else if (toolType == null)
  896. {
  897. SetTool(null);
  898. }
  899. else
  900. {
  901. Tool newTool = CreateTool(toolType);
  902. SetTool(newTool);
  903. }
  904. }
  905. public void PushNullTool()
  906. {
  907. if (this.nullToolCount == 0)
  908. {
  909. this.preNullTool = GetToolType();
  910. this.SetTool(null);
  911. this.nullToolCount = 1;
  912. }
  913. else
  914. {
  915. ++this.nullToolCount;
  916. }
  917. }
  918. public void PopNullTool()
  919. {
  920. --this.nullToolCount;
  921. if (this.nullToolCount == 0)
  922. {
  923. this.SetToolFromType(this.preNullTool);
  924. this.preNullTool = null;
  925. }
  926. else if (this.nullToolCount < 0)
  927. {
  928. throw new InvalidOperationException("PopNullTool() call was not matched with PushNullTool()");
  929. }
  930. }
  931. public Type PreviousActiveToolType
  932. {
  933. get
  934. {
  935. return this.previousActiveToolType;
  936. }
  937. }
  938. public void SetTool(Tool copyMe)
  939. {
  940. OnToolChanging();
  941. if (this.activeTool != null)
  942. {
  943. this.previousActiveToolType = this.activeTool.GetType();
  944. this.activeTool.CursorChanged -= ToolCursorChangedHandler;
  945. this.activeTool.PerformDeactivate();
  946. this.activeTool.Dispose();
  947. this.activeTool = null;
  948. }
  949. if (copyMe == null)
  950. {
  951. EnableToolPulse = false;
  952. }
  953. else
  954. {
  955. Tracing.LogFeature("SetTool(" + copyMe.GetType().FullName + ")");
  956. this.activeTool = CreateTool(copyMe.GetType());
  957. this.activeTool.PerformActivate();
  958. this.activeTool.CursorChanged += ToolCursorChangedHandler;
  959. if (this.suspendToolCursorChanges <= 0)
  960. {
  961. Cursor = this.activeTool.Cursor;
  962. }
  963. EnableToolPulse = true;
  964. }
  965. OnToolChanged();
  966. }
  967. public Tool CreateTool(Type toolType)
  968. {
  969. return DocumentWorkspace.CreateTool(toolType, this);
  970. }
  971. private static Tool CreateTool(Type toolType, DocumentWorkspace dc)
  972. {
  973. ConstructorInfo ci = toolType.GetConstructor(new Type[] { typeof(DocumentWorkspace) });
  974. Tool tool = (Tool)ci.Invoke(new object[] { dc });
  975. return tool;
  976. }
  977. private static void InitializeTools()
  978. {
  979. // add all the tools
  980. tools = new Type[]
  981. {
  982. typeof(RectangleSelectTool),
  983. typeof(MoveTool),
  984. typeof(LassoSelectTool),
  985. typeof(MoveSelectionTool),
  986. typeof(EllipseSelectTool),
  987. typeof(ZoomTool),
  988. typeof(MagicWandTool),
  989. typeof(PanTool),
  990. typeof(PaintBucketTool),
  991. typeof(GradientTool),
  992. typeof(PaintBrushTool),
  993. typeof(EraserTool),
  994. typeof(PencilTool),
  995. typeof(ColorPickerTool),
  996. typeof(CloneStampTool),
  997. typeof(RecolorTool),
  998. typeof(TextTool),
  999. typeof(LineTool),
  1000. typeof(RectangleTool),
  1001. typeof(RoundedRectangleTool),
  1002. typeof(EllipseTool),
  1003. typeof(FreeformShapeTool),
  1004. };
  1005. }
  1006. private static void InitializeToolInfos()
  1007. {
  1008. int i = 0;
  1009. toolInfos = new ToolInfo[tools.Length];
  1010. foreach (Type toolType in tools)
  1011. {
  1012. using (Tool tool = DocumentWorkspace.CreateTool(toolType, null))
  1013. {
  1014. toolInfos[i] = tool.Info;
  1015. ++i;
  1016. }
  1017. }
  1018. }
  1019. public static Type[] Tools
  1020. {
  1021. get
  1022. {
  1023. return (Type[])tools.Clone();
  1024. }
  1025. }
  1026. public static ToolInfo[] ToolInfos
  1027. {
  1028. get
  1029. {
  1030. return (ToolInfo[])toolInfos.Clone();
  1031. }
  1032. }
  1033. public event EventHandler ToolChanging;
  1034. protected void OnToolChanging()
  1035. {
  1036. if (ToolChanging != null)
  1037. {
  1038. ToolChanging(this, EventArgs.Empty);
  1039. }
  1040. }
  1041. public event EventHandler ToolChanged;
  1042. protected void OnToolChanged()
  1043. {
  1044. if (ToolChanged != null)
  1045. {
  1046. ToolChanged(this, EventArgs.Empty);
  1047. }
  1048. }
  1049. private void ToolCursorChangedHandler(object sender, EventArgs e)
  1050. {
  1051. if (this.suspendToolCursorChanges <= 0)
  1052. {
  1053. Cursor = this.activeTool.Cursor;
  1054. }
  1055. }
  1056. // Note: static tool data is removed whenever the Document changes
  1057. // TODO: shouldn't this be moved to the Tool class somehow?
  1058. public object GetStaticToolData(Type toolType)
  1059. {
  1060. return staticToolData[toolType];
  1061. }
  1062. public void SetStaticToolData(Type toolType, object data)
  1063. {
  1064. staticToolData[toolType] = data;
  1065. }
  1066. public AppWorkspace AppWorkspace
  1067. {
  1068. get
  1069. {
  1070. return this.appWorkspace;
  1071. }
  1072. set
  1073. {
  1074. this.appWorkspace = value;
  1075. }
  1076. }
  1077. public Selection Selection
  1078. {
  1079. get
  1080. {
  1081. return this.selection;
  1082. }
  1083. }
  1084. public bool EnableOutlineAnimation
  1085. {
  1086. get
  1087. {
  1088. return this.selectionRenderer.EnableOutlineAnimation;
  1089. }
  1090. set
  1091. {
  1092. this.selectionRenderer.EnableOutlineAnimation = value;
  1093. }
  1094. }
  1095. public bool EnableSelectionOutline
  1096. {
  1097. get
  1098. {
  1099. return this.selectionRenderer.EnableSelectionOutline;
  1100. }
  1101. set
  1102. {
  1103. this.selectionRenderer.EnableSelectionOutline = value;
  1104. }
  1105. }
  1106. public bool EnableSelectionTinting
  1107. {
  1108. get
  1109. {
  1110. return this.selectionRenderer.EnableSelectionTinting;
  1111. }
  1112. set
  1113. {
  1114. this.selectionRenderer.EnableSelectionTinting = value;
  1115. }
  1116. }
  1117. public void ResetOutlineWhiteOpacity()
  1118. {
  1119. this.selectionRenderer.ResetOutlineWhiteOpacity();
  1120. }
  1121. public event EventHandler FilePathChanged;
  1122. protected virtual void OnFilePathChanged()
  1123. {
  1124. if (FilePathChanged != null)
  1125. {
  1126. FilePathChanged(this, EventArgs.Empty);
  1127. }
  1128. }
  1129. public string FilePath
  1130. {
  1131. get
  1132. {
  1133. return this.filePath;
  1134. }
  1135. }
  1136. public string GetFriendlyName()
  1137. {
  1138. string friendlyName;
  1139. if (this.filePath != null)
  1140. {
  1141. friendlyName = Path.GetFileName(this.filePath);
  1142. }
  1143. else
  1144. {
  1145. friendlyName = PdnResources.GetString("Untitled.FriendlyName");
  1146. }
  1147. return friendlyName;
  1148. }
  1149. public FileType FileType
  1150. {
  1151. get
  1152. {
  1153. return this.fileType;
  1154. }
  1155. }
  1156. public SaveConfigToken SaveConfigToken
  1157. {
  1158. get
  1159. {
  1160. if (this.saveConfigToken == null)
  1161. {
  1162. return null;
  1163. }
  1164. else
  1165. {
  1166. return (SaveConfigToken)this.saveConfigToken.Clone();
  1167. }
  1168. }
  1169. }
  1170. public event EventHandler SaveOptionsChanged;
  1171. protected virtual void OnSaveOptionsChanged()
  1172. {
  1173. if (SaveOptionsChanged != null)
  1174. {
  1175. SaveOptionsChanged(this, EventArgs.Empty);
  1176. }
  1177. }
  1178. /// <summary>
  1179. /// Sets the FileType and SaveConfigToken parameters that are used if the
  1180. /// user chooses "Save" from the File menu. These are not used by the
  1181. /// DocumentControl class and should be used by whoever actually goes
  1182. /// to save the Document instance.
  1183. /// </summary>
  1184. /// <param name="fileType"></param>
  1185. /// <param name="saveParameters"></param>
  1186. public void SetDocumentSaveOptions(string newFilePath, FileType newFileType, SaveConfigToken newSaveConfigToken)
  1187. {
  1188. this.filePath = newFilePath;
  1189. OnFilePathChanged();
  1190. this.fileType = newFileType;
  1191. if (newSaveConfigToken == null)
  1192. {
  1193. this.saveConfigToken = null;
  1194. }
  1195. else
  1196. {
  1197. this.saveConfigToken = (SaveConfigToken)newSaveConfigToken.Clone();
  1198. }
  1199. OnSaveOptionsChanged();
  1200. }
  1201. public void GetDocumentSaveOptions(out string filePathResult, out FileType fileTypeResult, out SaveConfigToken saveConfigTokenResult)
  1202. {
  1203. filePathResult = this.filePath;
  1204. fileTypeResult = this.fileType;
  1205. if (this.saveConfigToken == null)
  1206. {
  1207. saveConfigTokenResult = null;
  1208. }
  1209. else
  1210. {
  1211. saveConfigTokenResult = (SaveConfigToken)this.saveConfigToken.Clone();
  1212. }
  1213. }
  1214. private bool isScratchSurfaceBorrowed = false;
  1215. private string borrowScratchSurfaceReason = string.Empty;
  1216. /// The scratch, stencil, accumulation, whatever buffer. This is used by many parts
  1217. /// of Paint.NET as a temporary area for which to store data.
  1218. /// This surface is 'owned' by any Tool that is active. If you want to use this you
  1219. /// must first deactivate the Tool using PushNullTool() and then reactivate it when
  1220. /// you are finished by calling PopNullTool().
  1221. /// Tools should use Tool.ScratchSurface instead of these API's.
  1222. public Surface BorrowScratchSurface(string reason)
  1223. {
  1224. if (this.isScratchSurfaceBorrowed)
  1225. {
  1226. throw new InvalidOperationException(
  1227. "ScratchSurface already borrowed: '" +
  1228. this.borrowScratchSurfaceReason +
  1229. "' (trying to borrow for: '" + reason + "')");
  1230. }
  1231. Tracing.Ping("Borrowing scratchSurface: " + reason);
  1232. this.isScratchSurfaceBorrowed = true;
  1233. this.borrowScratchSurfaceReason = reason;
  1234. return this.scratchSurface;
  1235. }
  1236. public void ReturnScratchSurface(Surface borrowedScratchSurface)
  1237. {
  1238. if (!this.isScratchSurfaceBorrowed)
  1239. {
  1240. throw new InvalidOperationException("ScratchSurface wasn't borrowed");
  1241. }
  1242. if (this.scratchSurface != borrowedScratchSurface)
  1243. {
  1244. throw new InvalidOperationException("returned ScratchSurface doesn't match the real one");
  1245. }
  1246. Tracing.Ping("Returning scratchSurface: " + this.borrowScratchSurfaceReason);
  1247. this.isScratchSurfaceBorrowed = false;
  1248. this.borrowScratchSurfaceReason = string.Empty;
  1249. }
  1250. /// <summary>
  1251. /// Updates any pertinent EXIF tags, such as "Creation Software", to be
  1252. /// relevant or up-to-date.
  1253. /// </summary>
  1254. /// <param name="document"></param>
  1255. private void UpdateExifTags(Document document)
  1256. {
  1257. // We want it to say "Creation Software: Paint.NET vX.Y"
  1258. // I have verified that other image editing software overwrites this tag,
  1259. // and does not just add it when it does not exist.
  1260. PropertyItem pi = Exif.CreateAscii(ExifTagID.Software, PdnInfo.GetProductName(false));
  1261. document.Metadata.ReplaceExifValues(ExifTagID.Software, new PropertyItem[1] { pi });
  1262. }
  1263. private ZoomBasis savedZb;
  1264. private ScaleFactor savedSf;
  1265. private int savedAli;
  1266. protected override void OnDocumentChanging(Document newDocument)
  1267. {
  1268. base.OnDocumentChanging(newDocument);
  1269. this.savedZb = this.ZoomBasis;
  1270. this.savedSf = ScaleFactor;
  1271. if (this.ActiveLayer != null)
  1272. {
  1273. this.savedAli = ActiveLayerIndex;
  1274. }
  1275. else
  1276. {
  1277. this.savedAli = -1;
  1278. }
  1279. if (newDocument != null)
  1280. {
  1281. UpdateExifTags(newDocument);
  1282. }
  1283. if (this.Document != null)
  1284. {
  1285. foreach (Layer layer in this.Document.Layers)
  1286. {
  1287. layer.PropertyChanging -= LayerPropertyChangingHandler;
  1288. layer.PropertyChanged -= LayerPropertyChangedHandler;
  1289. }
  1290. this.Document.Layers.RemovingAt -= LayerRemovingHandler;
  1291. this.Document.Layers.RemovedAt -= LayerRemovedHandler;
  1292. this.Document.Layers.Inserted -= LayerInsertedHandler;
  1293. }
  1294. this.staticToolData.Clear();
  1295. PushNullTool(); // matching Pop is in OnDocumetChanged()
  1296. ActiveLayer = null;
  1297. if (this.scratchSurface != null)
  1298. {
  1299. if (this.isScratchSurfaceBorrowed)
  1300. {
  1301. throw new InvalidOperationException("scratchSurface is currently borrowed: " + this.borrowScratchSurfaceReason);
  1302. }
  1303. if (newDocument == null || newDocument.Size != this.scratchSurface.Size)
  1304. {
  1305. this.scratchSurface.Dispose();
  1306. this.scratchSurface = null;
  1307. }
  1308. }
  1309. if (!Selection.IsEmpty)
  1310. {
  1311. Selection.Reset();
  1312. }
  1313. }
  1314. protected override void OnDocumentChanged()
  1315. {
  1316. // if the ActiveLayer is not in this new document, then
  1317. // we try to set ActiveLayer to the first layer in this
  1318. // new document. But if the document contains no layers,
  1319. // or is null, we just null the ActiveLayer.
  1320. if (this.Document == null)
  1321. {
  1322. this.ActiveLayer = null;
  1323. }
  1324. else
  1325. {
  1326. if (this.activeTool != null)
  1327. {
  1328. throw new InvalidOperationException("Tool was not deactivated while Document was being changed");
  1329. }
  1330. if (this.scratchSurface != null)
  1331. {
  1332. if (this.isScratchSurfaceBorrowed)
  1333. {
  1334. throw new InvalidOperationException("scratchSurface is currently borrowed: " + this.borrowScratchSurfaceReason);
  1335. }
  1336. if (Document == null || this.scratchSurface.Size != Document.Size)
  1337. {
  1338. this.scratchSurface.Dispose();
  1339. this.scratchSurface = null;
  1340. }
  1341. }
  1342. this.scratchSurface = new Surface(this.Document.Size);
  1343. this.Selection.ClipRectangle = this.Document.Bounds;
  1344. foreach (Layer layer in this.Document.Layers)
  1345. {
  1346. layer.PropertyChanging += LayerPropertyChangingHandler;
  1347. layer.PropertyChanged += LayerPropertyChangedHandler;
  1348. }
  1349. this.Document.Layers.RemovingAt += LayerRemovingHandler;
  1350. this.Document.Layers.RemovedAt += LayerRemovedHandler;
  1351. this.Document.Layers.Inserted += LayerInsertedHandler;
  1352. if (!this.Document.Layers.Contains(this.ActiveLayer))
  1353. {
  1354. if (this.Document.Layers.Count > 0)
  1355. {
  1356. if (savedAli >= 0 && savedAli < this.Document.Layers.Count)
  1357. {
  1358. this.ActiveLayer = (Layer)this.Document.Layers[savedAli];
  1359. }
  1360. else
  1361. {
  1362. this.ActiveLayer = (Layer)this.Document.Layers[0];
  1363. }
  1364. }
  1365. else
  1366. {
  1367. this.ActiveLayer = null;
  1368. }
  1369. }
  1370. // we invalidate each layer so that the layer previews refresh themselves
  1371. foreach (Layer layer in this.Document.Layers)
  1372. {
  1373. layer.Invalidate();
  1374. }
  1375. bool oldDirty = this.Document.Dirty;
  1376. this.Document.Invalidate();
  1377. this.Document.Dirty = oldDirty;
  1378. this.ZoomBasis = this.savedZb;
  1379. if (this.savedZb == ZoomBasis.ScaleFactor)
  1380. {
  1381. ScaleFactor = this.savedSf;
  1382. }
  1383. }
  1384. PopNullTool();
  1385. AutoScrollPosition = new Point(0, 0);
  1386. base.OnDocumentChanged();
  1387. }
  1388. /// <summary>
  1389. /// Takes the current Document from this DocumentWorkspace instance and adds it to the MRU list.
  1390. /// </summary>
  1391. /// <param name="fileName"></param>
  1392. public void AddToMruList()
  1393. {
  1394. using (new PushNullToolMode(this))
  1395. {
  1396. string fullFileName = Path.GetFullPath(this.FilePath);
  1397. int edgeLength = AppWorkspace.MostRecentFiles.IconSize;
  1398. Surface thumb1 = RenderThumbnail(edgeLength, true, true);
  1399. // Put it inside a square bitmap
  1400. Surface thumb = new Surface(4 + edgeLength, 4 + edgeLength);
  1401. thumb.Clear(ColorBgra.Transparent);
  1402. Rectangle dstRect = new Rectangle((thumb.Width - thumb1.Width) / 2,
  1403. (thumb.Height - thumb1.Height) / 2, thumb1.Width, thumb1.Height);
  1404. thumb.CopySurface(thumb1, dstRect.Location);
  1405. using (RenderArgs ra = new RenderArgs(thumb))
  1406. {
  1407. // Draw black border
  1408. Rectangle borderRect = new Rectangle(dstRect.Left - 1, dstRect.Top - 1, dstRect.Width + 2, dstRect.Height + 2);
  1409. --borderRect.Width;
  1410. --borderRect.Height;
  1411. ra.Graphics.DrawRectangle(Pens.Black, borderRect);
  1412. Rectangle shadowRect = Rectangle.Inflate(borderRect, 1, 1);
  1413. ++shadowRect.Width;
  1414. ++shadowRect.Height;
  1415. Utility.DrawDropShadow1px(ra.Graphics, shadowRect);
  1416. thumb1.Dispose();
  1417. thumb1 = null;
  1418. MostRecentFile mrf = new MostRecentFile(fullFileName, Utility.FullCloneBitmap(ra.Bitmap));
  1419. if (AppWorkspace.MostRecentFiles.Contains(fullFileName))
  1420. {
  1421. AppWorkspace.MostRecentFiles.Remove(fullFileName);
  1422. }
  1423. AppWorkspace.MostRecentFiles.Add(mrf);
  1424. AppWorkspace.MostRecentFiles.SaveMruList();
  1425. }
  1426. }
  1427. }
  1428. /// <summary>
  1429. /// Shows an OpenFileDialog or SaveFileDialog and populates the InitialDirectory from the global
  1430. /// settings repository if possible.
  1431. /// </summary>
  1432. /// <param name="fd">The FileDialog to show.</param>
  1433. /// <remarks>
  1434. /// The FileDialog should already have its InitialDirectory populated as a suggestion of where to start.
  1435. /// </remarks>
  1436. public static DialogResult ShowFileDialog(Control owner, IFileDialog fd)
  1437. {
  1438. string initialDirectory = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, fd.InitialDirectory);
  1439. // TODO: spawn this in a background thread, if it doesn't respond within ~500ms?, assume the dir doesn't exist
  1440. bool dirExists = false;
  1441. try
  1442. {
  1443. DirectoryInfo dirInfo = new DirectoryInfo(initialDirectory);
  1444. using (new WaitCursorChanger(owner))
  1445. {
  1446. dirExists = dirInfo.Exists;
  1447. if (!dirInfo.Exists)
  1448. {
  1449. initialDirectory = fd.InitialDirectory;
  1450. }
  1451. }
  1452. }
  1453. catch (Exception)
  1454. {
  1455. initialDirectory = fd.InitialDirectory;
  1456. }
  1457. fd.InitialDirectory = initialDirectory;
  1458. OurFileDialogUICallbacks ouc = new OurFileDialogUICallbacks();
  1459. DialogResult result = fd.ShowDialog(owner, ouc);
  1460. if (result == DialogResult.OK)
  1461. {
  1462. string fileName;
  1463. if (fd is IFileOpenDialog)
  1464. {
  1465. string[] fileNames = ((IFileOpenDialog)fd).FileNames;
  1466. if (fileNames.Length > 0)
  1467. {
  1468. fileName = fileNames[0];
  1469. }
  1470. else
  1471. {
  1472. fileName = null;
  1473. }
  1474. }
  1475. else if (fd is IFileSaveDialog)
  1476. {
  1477. fileName = ((IFileSaveDialog)fd).FileName;
  1478. }
  1479. else
  1480. {
  1481. throw new InvalidOperationException();
  1482. }
  1483. if (fileName != null)
  1484. {
  1485. string newDir = Path.GetDirectoryName(fileName);
  1486. Settings.CurrentUser.SetString(SettingNames.LastFileDialogDirectory, newDir);
  1487. }
  1488. else
  1489. {
  1490. throw new FileNotFoundException();
  1491. }
  1492. }
  1493. return result;
  1494. }
  1495. private sealed class OurFileDialogUICallbacks
  1496. : IFileDialogUICallbacks
  1497. {
  1498. public FileOverwriteAction ShowOverwritePrompt(IWin32Window owner, string pathName)
  1499. {
  1500. FileOverwriteAction returnVal;
  1501. string title = PdnResources.GetString("SaveAs.OverwriteConfirmation.Title");
  1502. string textFormat = PdnResources.GetString("SaveAs.OverwriteConfirmation.Text.Format");
  1503. string fileName;
  1504. try
  1505. {
  1506. fileName = Path.GetFileName(pathName);
  1507. }
  1508. catch (Exception)
  1509. {
  1510. fileName = pathName;
  1511. }
  1512. string text = string.Format(textFormat, fileName);
  1513. DialogResult result = MessageBox.Show(owner, text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2);
  1514. switch (result)
  1515. {
  1516. case DialogResult.Yes:
  1517. returnVal = FileOverwriteAction.Overwrite;
  1518. break;
  1519. case DialogResult.No:
  1520. returnVal = FileOverwriteAction.Cancel;
  1521. break;
  1522. default:
  1523. throw new InvalidEnumArgumentException();
  1524. }
  1525. return returnVal;
  1526. }
  1527. public bool ShowError(IWin32Window owner, string filePath, Exception ex)
  1528. {
  1529. if (ex is PathTooLongException)
  1530. {
  1531. string title = PdnInfo.GetBareProductName();
  1532. string message = PdnResources.GetString("FileDialog.PathTooLongException.Message");
  1533. MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
  1534. return true;
  1535. }
  1536. else
  1537. {
  1538. return false;
  1539. }
  1540. }
  1541. public IFileTransferProgressEvents CreateFileTransferProgressEvents()
  1542. {
  1543. return new OurProgressEvents();
  1544. }
  1545. }
  1546. private sealed class OurProgressEvents
  1547. : IFileTransferProgressEvents
  1548. {
  1549. private TransferProgressDialog progressDialog;
  1550. private ICancelable cancelSink;
  1551. private int itemCount = 0;
  1552. private int itemOrdinal = 0;
  1553. private string itemName = string.Empty;
  1554. private long totalWork;
  1555. private long totalProgress;
  1556. private const int maxPBValue = 200; // granularity of progress bar. 100 means 1%, 200 means 0.5%, etc.
  1557. private bool cancelRequested = false;
  1558. private ManualResetEvent operationEnded = new ManualResetEvent(false);
  1559. public OurProgressEvents()
  1560. {
  1561. }
  1562. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "cancelSink")]
  1563. public void BeginOperation(IWin32Window owner, EventHandler callWhenUIShown, ICancelable cancelSink)
  1564. {
  1565. if (this.progressDialog != null)
  1566. {
  1567. throw new InvalidOperationException("Operation already in progress");
  1568. }
  1569. this.progressDialog = new TransferProgressDialog();
  1570. this.progressDialog.Text = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.TransferProgress.Title");
  1571. this.progressDialog.Icon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileOpenIcon.png").Reference);
  1572. this.progressDialog.ItemText = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Initializing");
  1573. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  1574. this.progressDialog.ProgressBar.Maximum = maxPBValue;
  1575. this.progressDialog.CancelClicked +=
  1576. delegate(object sender, EventArgs e)
  1577. {
  1578. this.cancelRequested = true;
  1579. this.cancelSink.RequestCancel();
  1580. UpdateUI();
  1581. };
  1582. EventHandler progressDialog_Shown =
  1583. delegate(object sender, EventArgs e)
  1584. {
  1585. callWhenUIShown(this, EventArgs.Empty);
  1586. };
  1587. this.cancelSink = cancelSink;
  1588. this.itemOrdinal = 0;
  1589. this.cancelRequested = false;
  1590. this.itemName = string.Empty;
  1591. this.itemCount = 0;
  1592. this.itemOrdinal = 0;
  1593. this.totalProgress = 0;
  1594. this.totalWork = 0;
  1595. this.progressDialog.Shown += progressDialog_Shown;
  1596. this.progressDialog.ShowDialog(owner);
  1597. this.progressDialog.Shown -= progressDialog_Shown;
  1598. this.progressDialog.Dispose();
  1599. this.progressDialog = null;
  1600. this.cancelSink = null;
  1601. }
  1602. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemCount")]
  1603. public void SetItemCount(int itemCount)
  1604. {
  1605. if (this.progressDialog.InvokeRequired)
  1606. {
  1607. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemCount), new object[] { itemCount });
  1608. }
  1609. else
  1610. {
  1611. this.itemCount = itemCount;
  1612. UpdateUI();
  1613. }
  1614. }
  1615. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemOrdinal")]
  1616. public void SetItemOrdinal(int itemOrdinal)
  1617. {
  1618. if (this.progressDialog.InvokeRequired)
  1619. {
  1620. this.progressDialog.BeginInvoke(new Procedure<int>(SetItemOrdinal), new object[] { itemOrdinal });
  1621. }
  1622. else
  1623. {
  1624. this.itemOrdinal = itemOrdinal;
  1625. this.totalWork = 0;
  1626. this.totalProgress = 0;
  1627. UpdateUI();
  1628. }
  1629. }
  1630. public void SetItemInfo(string itemInfo)
  1631. {
  1632. if (this.progressDialog.InvokeRequired)
  1633. {
  1634. this.progressDialog.BeginInvoke(new Procedure<string>(SetItemInfo), new object[] { itemInfo });
  1635. }
  1636. else
  1637. {
  1638. this.itemName = itemInfo;
  1639. UpdateUI();
  1640. }
  1641. }
  1642. public void BeginItem()
  1643. {
  1644. if (this.progressDialog.InvokeRequired)
  1645. {
  1646. this.progressDialog.BeginInvoke(new Procedure(BeginItem), null);
  1647. }
  1648. else
  1649. {
  1650. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  1651. }
  1652. }
  1653. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalWork")]
  1654. public void SetItemWorkTotal(long totalWork)
  1655. {
  1656. if (this.progressDialog.InvokeRequired)
  1657. {
  1658. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkTotal), new object[] { totalWork });
  1659. }
  1660. else
  1661. {
  1662. this.totalWork = totalWork;
  1663. UpdateUI();
  1664. }
  1665. }
  1666. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalProgress")]
  1667. public void SetItemWorkProgress(long totalProgress)
  1668. {
  1669. if (this.progressDialog.InvokeRequired)
  1670. {
  1671. this.progressDialog.BeginInvoke(new Procedure<long>(SetItemWorkProgress), new object[] { totalProgress });
  1672. }
  1673. else
  1674. {
  1675. this.totalProgress = totalProgress;
  1676. UpdateUI();
  1677. }
  1678. }
  1679. public void EndItem(WorkItemResult result)
  1680. {
  1681. if (this.progressDialog.InvokeRequired)
  1682. {
  1683. this.progressDialog.BeginInvoke(new Procedure<WorkItemResult>(EndItem), new object[] { result });
  1684. }
  1685. else
  1686. {
  1687. }
  1688. }
  1689. public void EndOperation(OperationResult result)
  1690. {
  1691. if (this.progressDialog.InvokeRequired)
  1692. {
  1693. this.progressDialog.BeginInvoke(new Procedure<OperationResult>(EndOperation), new object[] { result });
  1694. }
  1695. else
  1696. {
  1697. this.progressDialog.Close();
  1698. }
  1699. }
  1700. public WorkItemFailureAction ReportItemFailure(Exception ex)
  1701. {
  1702. if (this.progressDialog.InvokeRequired)
  1703. {
  1704. object result = this.progressDialog.Invoke(
  1705. new Function<WorkItemFailureAction, Exception>(ReportItemFailure),
  1706. new object[] { ex });
  1707. return (WorkItemFailureAction)result;
  1708. }
  1709. else
  1710. {
  1711. WorkItemFailureAction result;
  1712. result = ShowFileTransferFailedDialog(ex);
  1713. return result;
  1714. }
  1715. }
  1716. private WorkItemFailureAction ShowFileTransferFailedDialog(Exception ex)
  1717. {
  1718. WorkItemFailureAction result;
  1719. Icon formIcon = this.progressDialog.Icon;
  1720. string formTitle = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.Title");
  1721. Image taskImage = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference;
  1722. string introTextFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.IntroText.Format");
  1723. string introText = string.Format(introTextFormat, ex.Message);
  1724. TaskButton retryTB = new TaskButton(
  1725. PdnResources.GetImageResource("Icons.MenuImageRotate90CWIcon.png").Reference,
  1726. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ActionText"),
  1727. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ExplanationText"));
  1728. TaskButton skipTB = new TaskButton(
  1729. PdnResources.GetImageResource("Icons.HistoryFastForwardIcon.png").Reference,
  1730. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ActionText"),
  1731. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ExplanationText"));
  1732. TaskButton cancelTB = new TaskButton(
  1733. PdnResources.GetImageResource("Icons.CancelIcon.png").Reference,
  1734. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ActionText"),
  1735. PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ExplanationText"));
  1736. List<TaskButton> taskButtons = new List<TaskButton>();
  1737. taskButtons.Add(retryTB);
  1738. // Only have the Skip button if there is more than 1 item being transferred.
  1739. // If only 1 item is begin transferred, Skip and Cancel are essentially synonymous.
  1740. if (this.itemCount > 1)
  1741. {
  1742. taskButtons.Add(skipTB);
  1743. }
  1744. taskButtons.Add(cancelTB);
  1745. int width96 = (TaskDialog.DefaultPixelWidth96Dpi * 4) / 3; // 33% wider
  1746. TaskButton clickedTB = TaskDialog.Show(
  1747. this.progressDialog,
  1748. formIcon,
  1749. formTitle,
  1750. taskImage,
  1751. true,
  1752. introText,
  1753. taskButtons.ToArray(),
  1754. retryTB,
  1755. cancelTB,
  1756. width96);
  1757. if (clickedTB == retryTB)
  1758. {
  1759. result = WorkItemFailureAction.RetryItem;
  1760. }
  1761. else if (clickedTB == skipTB)
  1762. {
  1763. result = WorkItemFailureAction.SkipItem;
  1764. }
  1765. else
  1766. {
  1767. result = WorkItemFailureAction.CancelOperation;
  1768. }
  1769. return result;
  1770. }
  1771. private void UpdateUI()
  1772. {
  1773. int itemCount2 = Math.Max(1, this.itemCount);
  1774. double startValue = (double)this.itemOrdinal / (double)itemCount2;
  1775. double endValue = (double)(this.itemOrdinal + 1) / (double)itemCount2;
  1776. long totalWork2 = Math.Max(1, this.totalWork);
  1777. double lerp = (double)this.totalProgress / (double)totalWork2;
  1778. double newValue = Utility.Lerp(startValue, endValue, lerp);
  1779. int newValueInt = (int)Math.Ceiling(maxPBValue * newValue);
  1780. if (this.cancelRequested)
  1781. {
  1782. this.progressDialog.CancelEnabled = false;
  1783. this.progressDialog.ItemText = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling");
  1784. this.progressDialog.OperationProgress = string.Empty;
  1785. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee;
  1786. }
  1787. else
  1788. {
  1789. this.progressDialog.CancelEnabled = true;
  1790. this.progressDialog.ItemText = this.itemName;
  1791. string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format");
  1792. string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount);
  1793. this.progressDialog.OperationProgress = progressText;
  1794. this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous;
  1795. this.progressDialog.ProgressBar.Value = newValueInt;
  1796. }
  1797. }
  1798. }
  1799. public static DialogResult ChooseFile(Control parent, out string fileName)
  1800. {
  1801. return ChooseFile(parent, out fileName, null);
  1802. }
  1803. public static DialogResult ChooseFile(Control parent, out string fileName, string startingDir)
  1804. {
  1805. string[] fileNames;
  1806. DialogResult result = ChooseFiles(parent, out fileNames, false, startingDir);
  1807. if (result == DialogResult.OK)
  1808. {
  1809. fileName = fileNames[0];
  1810. }
  1811. else
  1812. {
  1813. fileName = null;
  1814. }
  1815. return result;
  1816. }
  1817. public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect)
  1818. {
  1819. return ChooseFiles(owner, out fileNames, multiselect, null);
  1820. }
  1821. public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect, string startingDir)
  1822. {
  1823. FileTypeCollection fileTypes = FileTypes.GetFileTypes();
  1824. using (IFileOpenDialog ofd = SystemLayer.CommonDialogs.CreateFileOpenDialog())
  1825. {
  1826. if (startingDir != null)
  1827. {
  1828. ofd.InitialDirectory = startingDir;
  1829. }
  1830. else
  1831. {
  1832. ofd.InitialDirectory = GetDefaultSavePath();
  1833. }
  1834. ofd.CheckFileExists = true;
  1835. ofd.CheckPathExists = true;
  1836. ofd.Multiselect = multiselect;
  1837. ofd.Filter = fileTypes.ToString(true, PdnResources.GetString("FileDialog.Types.AllImages"), false, true);
  1838. ofd.FilterIndex = 0;
  1839. DialogResult result = ShowFileDialog(owner, ofd);
  1840. if (result == DialogResult.OK)
  1841. {
  1842. fileNames = ofd.FileNames;
  1843. }
  1844. else
  1845. {
  1846. fileNames = new string[0];
  1847. }
  1848. return result;
  1849. }
  1850. }
  1851. /// <summary>
  1852. /// Use this to get a save config token. You should already know the filename and file type.
  1853. /// An existing save config token is optional and will be used to pre-populate the config dialog.
  1854. /// </summary>
  1855. /// <param name="fileType"></param>
  1856. /// <param name="saveConfigToken"></param>
  1857. /// <param name="newSaveConfigToken"></param>
  1858. /// <returns>false if the user cancelled, otherwise true</returns>
  1859. private bool GetSaveConfigToken(
  1860. FileType currentFileType,
  1861. SaveConfigToken currentSaveConfigToken,
  1862. out SaveConfigToken newSaveConfigToken,
  1863. Surface saveScratchSurface)
  1864. {
  1865. if (currentFileType.SupportsConfiguration)
  1866. {
  1867. using (SaveConfigDialog scd = new SaveConfigDialog())
  1868. {
  1869. scd.ScratchSurface = saveScratchSurface;
  1870. ProgressEventHandler peh = delegate(object sender, ProgressEventArgs e)
  1871. {
  1872. if (e.Percent < 0 || e.Percent >= 100)
  1873. {
  1874. AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
  1875. AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBar();
  1876. }
  1877. else
  1878. {
  1879. AppWorkspace.Widgets.StatusBarProgress.SetProgressStatusBar(e.Percent);
  1880. }
  1881. };
  1882. //if (currentFileType.SavesWithProgress)
  1883. {
  1884. scd.Progress += peh;
  1885. }
  1886. scd.Document = Document;
  1887. scd.FileType = currentFileType;
  1888. SaveConfigToken token = currentFileType.GetLastSaveConfigToken();
  1889. if (currentSaveConfigToken != null &&
  1890. token.GetType() == currentSaveConfigToken.GetType())
  1891. {
  1892. scd.SaveConfigToken = currentSaveConfigToken;
  1893. }
  1894. scd.EnableInstanceOpacity = false;
  1895. // show configuration/preview dialog
  1896. DialogResult dr = scd.ShowDialog(this);
  1897. //if (currentFileType.SavesWithProgress)
  1898. {
  1899. scd.Progress -= peh;
  1900. AppWorkspace.Widgets.StatusBarProgress.ResetProgressStatusBar();
  1901. AppWorkspace.Widgets.StatusBarProgress.EraseProgressStatusBar();
  1902. }
  1903. if (dr == DialogResult.OK)
  1904. {
  1905. newSaveConfigToken = scd.SaveConfigToken;
  1906. return true;
  1907. }
  1908. else
  1909. {
  1910. newSaveConfigToken = null;
  1911. return false;
  1912. }
  1913. }
  1914. }
  1915. else
  1916. {
  1917. newSaveConfigToken = currentFileType.GetLastSaveConfigToken();
  1918. return true;
  1919. }
  1920. }
  1921. /// <summary>
  1922. /// Used to set the file name, file type, and save config token
  1923. /// </summary>
  1924. /// <param name="newFileName"></param>
  1925. /// <param name="newFileType"></param>
  1926. /// <param name="newSaveConfigToken"></param>
  1927. /// <returns>true if the user clicked through and accepted, or false if they cancelled at any point</returns>
  1928. private bool DoSaveAsDialog(
  1929. out string newFileName,
  1930. out FileType newFileType,
  1931. out SaveConfigToken newSaveConfigToken,
  1932. Surface saveScratchSurface)
  1933. {
  1934. FileTypeCollection fileTypes = FileTypes.GetFileTypes();
  1935. using (IFileSaveDialog sfd = SystemLayer.CommonDialogs.CreateFileSaveDialog())
  1936. {
  1937. sfd.AddExtension = true;
  1938. sfd.CheckPathExists = true;
  1939. sfd.OverwritePrompt = true;
  1940. string filter = fileTypes.ToString(false, null, true, false);
  1941. sfd.Filter = filter;
  1942. string localFileName;
  1943. FileType localFileType;
  1944. SaveConfigToken localSaveConfigToken;
  1945. GetDocumentSaveOptions(out localFileName, out localFileType, out localSaveConfigToken);
  1946. if (Document.Layers.Count > 1 &&
  1947. localFileType != null &&
  1948. !localFileType.SupportsLayers)
  1949. {
  1950. localFileType = null;
  1951. }
  1952. if (localFileType == null)
  1953. {
  1954. if (Document.Layers.Count == 1)
  1955. {
  1956. localFileType = PdnFileTypes.Png;
  1957. }
  1958. else
  1959. {
  1960. localFileType = PdnFileTypes.Pdn;
  1961. }
  1962. localFileName = Path.ChangeExtension(localFileName, localFileType.DefaultExtension);
  1963. }
  1964. if (localFileName == null)
  1965. {
  1966. string name = GetDefaultSaveName();
  1967. string newName = Path.ChangeExtension(name, localFileType.DefaultExtension);
  1968. localFileName = Path.Combine(GetDefaultSavePath(), newName);
  1969. }
  1970. // If the filename is only an extension (i.e. ".lmnop") then we must treat it specially
  1971. string fileNameOnly = Path.GetFileName(localFileName);
  1972. if (fileNameOnly.Length >= 1 && fileNameOnly[0] == '.')
  1973. {
  1974. sfd.FileName = localFileName;
  1975. }
  1976. else
  1977. {
  1978. sfd.FileName = Path.ChangeExtension(localFileName, null);
  1979. }
  1980. sfd.FilterIndex = 1 + fileTypes.IndexOfFileType(localFileType);
  1981. sfd.InitialDirectory = Path.GetDirectoryName(localFileName);
  1982. sfd.Title = PdnResources.GetString("SaveAsDialog.Title");
  1983. DialogResult dr1 = ShowFileDialog(this, sfd);
  1984. bool result;
  1985. if (dr1 != DialogResult.OK)
  1986. {
  1987. result = false;
  1988. }
  1989. else
  1990. {
  1991. localFileName = sfd.FileName;
  1992. FileType fileType2 = fileTypes[sfd.FilterIndex - 1];
  1993. result = GetSaveConfigToken(fileType2, localSaveConfigToken, out localSaveConfigToken, saveScratchSurface);
  1994. localFileType = fileType2;
  1995. }
  1996. if (result)
  1997. {
  1998. newFileName = localFileName;
  1999. newFileType = localFileType;
  2000. newSaveConfigToken = localSaveConfigToken;
  2001. }
  2002. else
  2003. {
  2004. newFileName = null;
  2005. newFileType = null;
  2006. newSaveConfigToken = null;
  2007. }
  2008. return result;
  2009. }
  2010. }
  2011. /// <summary>
  2012. /// Warns the user that we need to flatten the image.
  2013. /// </summary>
  2014. /// <returns>Returns DialogResult.Yes if they want to proceed or DialogResult.No if they don't.</returns>
  2015. private DialogResult WarnAboutFlattening()
  2016. {
  2017. Icon formIcon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileSaveIcon.png").Reference);
  2018. string formTitle = PdnResources.GetString("WarnAboutFlattening.Title");
  2019. string introText = PdnResources.GetString("WarnAboutFlattening.IntroText");
  2020. Image taskImage = null;
  2021. TaskButton flattenTB = new TaskButton(
  2022. PdnResources.GetImageResource("Icons.MenuImageFlattenIcon.png").Reference,
  2023. PdnResources.GetString("WarnAboutFlattening.FlattenTB.ActionText"),
  2024. PdnResources.GetString("WarnAboutFlattening.FlattenTB.ExplanationText"));
  2025. TaskButton cancelTB = new TaskButton(
  2026. TaskButton.Cancel.Image,
  2027. PdnResources.GetString("WarnAboutFlattening.CancelTB.ActionText"),
  2028. PdnResources.GetString("WarnAboutFlattening.CancelTB.ExplanationText"));
  2029. TaskButton clickedTB = TaskDialog.Show(
  2030. AppWorkspace,
  2031. formIcon,
  2032. formTitle,
  2033. taskImage,
  2034. true,
  2035. introText,
  2036. new TaskButton[] { flattenTB, cancelTB },
  2037. flattenTB,
  2038. cancelTB,
  2039. (TaskDialog.DefaultPixelWidth96Dpi * 5) / 4);
  2040. if (clickedTB == flattenTB)
  2041. {
  2042. return DialogResult.Yes;
  2043. }
  2044. else
  2045. {
  2046. return DialogResult.No;
  2047. }
  2048. }
  2049. private static string GetDefaultSaveName()
  2050. {
  2051. return PdnResources.GetString("Untitled.FriendlyName");
  2052. }
  2053. private static string GetDefaultSavePath()
  2054. {
  2055. string myPics;
  2056. try
  2057. {
  2058. myPics = Shell.GetVirtualPath(VirtualFolderName.UserPictures, false);
  2059. DirectoryInfo dirInfo = new DirectoryInfo(myPics); // validate
  2060. }
  2061. catch (Exception)
  2062. {
  2063. myPics = "";
  2064. }
  2065. string dir = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, null);
  2066. if (dir == null)
  2067. {
  2068. dir = myPics;
  2069. }
  2070. else
  2071. {
  2072. try
  2073. {
  2074. DirectoryInfo dirInfo = new DirectoryInfo(dir);
  2075. if (!dirInfo.Exists)
  2076. {
  2077. dir = myPics;
  2078. }
  2079. }
  2080. catch (Exception)
  2081. {
  2082. dir = myPics;
  2083. }
  2084. }
  2085. return dir;
  2086. }
  2087. public bool DoSave()
  2088. {
  2089. return DoSave(false);
  2090. }
  2091. /// <summary>
  2092. /// Does the dirty work for a File->Save operation. If any of the "Save Options" in the
  2093. /// DocumentWorkspace are null, this will call DoSaveAs(). If the image has more than 1
  2094. /// layer but the file type they want to save with does not support layers, then it will
  2095. /// ask the user about flattening the image.
  2096. /// </summary>
  2097. /// <param name="tryToFlatten">
  2098. /// If true, will ask the user about flattening if the workspace's saveFileType does not
  2099. /// support layers and the image has more than 1 layer.
  2100. /// If false, then DoSaveAs will be called and the fileType will be prepopulated with
  2101. /// the .PDN type.
  2102. /// </param>
  2103. /// <returns><b>true</b> if the file was saved, <b>false</b> if the user cancelled</returns>
  2104. protected bool DoSave(bool tryToFlatten)
  2105. {
  2106. using (new PushNullToolMode(this))
  2107. {
  2108. string newFileName;
  2109. FileType newFileType;
  2110. SaveConfigToken newSaveConfigToken;
  2111. GetDocumentSaveOptions(out newFileName, out newFileType, out newSaveConfigToken);
  2112. // if they haven't specified a filename, then revert to "Save As" behavior
  2113. if (newFileName == null)
  2114. {
  2115. return DoSaveAs();
  2116. }
  2117. // if we have a filename but no file type, try to infer the file type
  2118. if (newFileType == null)
  2119. {
  2120. FileTypeCollection fileTypes = FileTypes.GetFileTypes();
  2121. string ext = Path.GetExtension(newFileName);
  2122. int index = fileTypes.IndexOfExtension(ext);
  2123. FileType inferredFileType = fileTypes[index];
  2124. newFileType = inferredFileType;
  2125. }
  2126. // if the image has more than 1 layer but is saving with a file type that
  2127. // does not support layers, then we must ask them if we may flatten the
  2128. // image first
  2129. if (Document.Layers.Count > 1 && !newFileType.SupportsLayers)
  2130. {
  2131. if (!tryToFlatten)
  2132. {
  2133. return DoSaveAs();
  2134. }
  2135. else
  2136. {
  2137. DialogResult dr = WarnAboutFlattening();
  2138. if (dr == DialogResult.Yes)
  2139. {
  2140. ExecuteFunction(new FlattenFunction());
  2141. }
  2142. else
  2143. {
  2144. return false;
  2145. }
  2146. }
  2147. }
  2148. // get the configuration!
  2149. if (newSaveConfigToken == null)
  2150. {
  2151. Surface scratch = BorrowScratchSurface(this.GetType().Name + ".DoSave() calling GetSaveConfigToken()");
  2152. bool result;
  2153. try
  2154. {
  2155. result = GetSaveConfigToken(newFileType, newSaveConfigToken, out newSaveConfigToken, scratch);
  2156. }
  2157. finally
  2158. {
  2159. ReturnScratchSurface(scratch);
  2160. }
  2161. if (!result)
  2162. {
  2163. return false;
  2164. }
  2165. }
  2166. // At this point fileName, fileType, and saveConfigToken must all be non-null
  2167. // if the document supports custom headers, embed a thumbnail in there
  2168. if (newFileType.SupportsCustomHeaders)
  2169. {
  2170. using (new WaitCursorChanger(this))
  2171. {
  2172. Utility.GCFullCollect();
  2173. const int maxDim = 256;
  2174. Surface thumb;
  2175. Surface flattened = BorrowScratchSurface(this.GetType().Name + ".DoSave() preparing embedded thumbnail");
  2176. try
  2177. {
  2178. Document.Flatten(flattened);
  2179. if (Document.Width > maxDim || Document.Height > maxDim)
  2180. {
  2181. int width;
  2182. int height;
  2183. if (Document.Width > Document.Height)
  2184. {
  2185. width = maxDim;
  2186. height = (Document.Height * maxDim) / Document.Width;
  2187. }
  2188. else
  2189. {
  2190. height = maxDim;
  2191. width = (Document.Width * maxDim) / Document.Height;
  2192. }
  2193. int thumbWidth = Math.Max(1, width);
  2194. int thumbHeight = Math.Max(1, height);
  2195. thumb = new Surface(thumbWidth, thumbHeight);
  2196. thumb.SuperSamplingFitSurface(flattened);
  2197. }
  2198. else
  2199. {
  2200. thumb = new Surface(flattened.Size);
  2201. thumb.CopySurface(flattened);
  2202. }
  2203. }
  2204. finally
  2205. {
  2206. ReturnScratchSurface(flattened);
  2207. }
  2208. Document thumbDoc = new Document(thumb.Width, thumb.Height);
  2209. BitmapLayer thumbLayer = new BitmapLayer(thumb);
  2210. BitmapLayer backLayer = new BitmapLayer(thumb.Width, thumb.Height);
  2211. backLayer.Surface.Clear(ColorBgra.Transparent);
  2212. thumb.Dispose();
  2213. thumbDoc.Layers.Add(backLayer);
  2214. thumbDoc.Layers.Add(thumbLayer);
  2215. MemoryStream thumbPng = new MemoryStream();
  2216. PropertyBasedSaveConfigToken pngToken = PdnFileTypes.Png.CreateDefaultSaveConfigToken();
  2217. PdnFileTypes.Png.Save(thumbDoc, thumbPng, pngToken, null, null, false);
  2218. byte[] thumbBytes = thumbPng.ToArray();
  2219. string thumbString = Convert.ToBase64String(thumbBytes, Base64FormattingOptions.None);
  2220. thumbDoc.Dispose();
  2221. string thumbXml = "<thumb png=\"" + thumbString + "\" />";
  2222. Document.CustomHeaders = thumbXml;
  2223. }
  2224. }
  2225. // save!
  2226. bool success = false;
  2227. Stream stream = null;
  2228. try
  2229. {
  2230. stream = (Stream)new FileStream(newFileName, FileMode.Create, FileAccess.Write);
  2231. using (new WaitCursorChanger(this))
  2232. {
  2233. Utility.GCFullCollect();
  2234. SaveProgressDialog sd = new SaveProgressDialog(this);
  2235. Surface scratch = BorrowScratchSurface(this.GetType().Name + ".DoSave() handing off scratch surface to SaveProgressDialog.Save()");
  2236. try
  2237. {
  2238. sd.Save(stream, Document, newFileType, newSaveConfigToken, scratch);
  2239. }
  2240. finally
  2241. {
  2242. ReturnScratchSurface(scratch);
  2243. }
  2244. success = true;
  2245. this.lastSaveTime = DateTime.Now;
  2246. stream.Close();
  2247. stream = null;
  2248. }
  2249. }
  2250. catch (UnauthorizedAccessException)
  2251. {
  2252. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.UnauthorizedAccessException"));
  2253. }
  2254. catch (SecurityException)
  2255. {
  2256. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.SecurityException"));
  2257. }
  2258. catch (DirectoryNotFoundException)
  2259. {
  2260. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.DirectoryNotFoundException"));
  2261. }
  2262. catch (IOException)
  2263. {
  2264. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.IOException"));
  2265. }
  2266. catch (OutOfMemoryException)
  2267. {
  2268. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.OutOfMemoryException"));
  2269. }
  2270. #if !DEBUG
  2271. catch (Exception)
  2272. {
  2273. Utility.ErrorBox(this, PdnResources.GetString("SaveImage.Error.Exception"));
  2274. }
  2275. #endif
  2276. finally
  2277. {
  2278. if (stream != null)
  2279. {
  2280. stream.Close();
  2281. stream = null;
  2282. }
  2283. }
  2284. if (success)
  2285. {
  2286. Shell.AddToRecentDocumentsList(newFileName);
  2287. }
  2288. else
  2289. {
  2290. return false;
  2291. }
  2292. // reset the dirty bit so they won't be asked to save on quitting
  2293. Document.Dirty = false;
  2294. // some misc. book keeping ...
  2295. AddToMruList();
  2296. // and finally, shout happiness by way of ...
  2297. return true;
  2298. }
  2299. }
  2300. /// <summary>
  2301. /// Does the grunt work to do a File->Save As operation.
  2302. /// </summary>
  2303. /// <returns><b>true</b> if the file was saved correctly, <b>false</b> if the user cancelled</returns>
  2304. public bool DoSaveAs()
  2305. {
  2306. using (new PushNullToolMode(this))
  2307. {
  2308. string newFileName;
  2309. FileType newFileType;
  2310. SaveConfigToken newSaveConfigToken;
  2311. Surface scratch = BorrowScratchSurface(this.GetType() + ".DoSaveAs() handing off scratch surface to DoSaveAsDialog()");
  2312. bool result;
  2313. try
  2314. {
  2315. result = DoSaveAsDialog(out newFileName, out newFileType, out newSaveConfigToken, scratch);
  2316. }
  2317. finally
  2318. {
  2319. ReturnScratchSurface(scratch);
  2320. }
  2321. if (result)
  2322. {
  2323. string oldFileName;
  2324. FileType oldFileType;
  2325. SaveConfigToken oldSaveConfigToken;
  2326. GetDocumentSaveOptions(out oldFileName, out oldFileType, out oldSaveConfigToken);
  2327. SetDocumentSaveOptions(newFileName, newFileType, newSaveConfigToken);
  2328. bool result2 = DoSave(true);
  2329. if (!result2)
  2330. {
  2331. SetDocumentSaveOptions(oldFileName, oldFileType, oldSaveConfigToken);
  2332. }
  2333. return result2;
  2334. }
  2335. else
  2336. {
  2337. return false;
  2338. }
  2339. }
  2340. }
  2341. public static Document LoadDocument(Control owner, string fileName, out FileType fileTypeResult, ProgressEventHandler progressCallback)
  2342. {
  2343. FileTypeCollection fileTypes;
  2344. int ftIndex;
  2345. FileType fileType;
  2346. fileTypeResult = null;
  2347. try
  2348. {
  2349. fileTypes = FileTypes.GetFileTypes();
  2350. ftIndex = fileTypes.IndexOfExtension(Path.GetExtension(fileName));
  2351. if (ftIndex == -1)
  2352. {
  2353. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ImageTypeNotRecognized"));
  2354. return null;
  2355. }
  2356. fileType = fileTypes[ftIndex];
  2357. fileTypeResult = fileType;
  2358. }
  2359. catch (ArgumentException)
  2360. {
  2361. string format = PdnResources.GetString("LoadImage.Error.InvalidFileName.Format");
  2362. string error = string.Format(format, fileName);
  2363. Utility.ErrorBox(owner, error);
  2364. return null;
  2365. }
  2366. Document document = null;
  2367. using (new WaitCursorChanger(owner))
  2368. {
  2369. Utility.GCFullCollect();
  2370. Stream stream = null;
  2371. try
  2372. {
  2373. try
  2374. {
  2375. stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  2376. long totalBytes = 0;
  2377. SiphonStream siphonStream = new SiphonStream(stream);
  2378. IOEventHandler ioEventHandler = null;
  2379. ioEventHandler =
  2380. delegate(object sender, IOEventArgs e)
  2381. {
  2382. if (progressCallback != null)
  2383. {
  2384. totalBytes += (long)e.Count;
  2385. double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100);
  2386. progressCallback(null, new ProgressEventArgs(percent));
  2387. }
  2388. };
  2389. siphonStream.IOFinished += ioEventHandler;
  2390. using (new WaitCursorChanger(owner))
  2391. {
  2392. document = fileType.Load(siphonStream);
  2393. if (progressCallback != null)
  2394. {
  2395. progressCallback(null, new ProgressEventArgs(100.0));
  2396. }
  2397. }
  2398. siphonStream.IOFinished -= ioEventHandler;
  2399. siphonStream.Close();
  2400. }
  2401. catch (WorkerThreadException ex)
  2402. {
  2403. Type innerExType = ex.InnerException.GetType();
  2404. ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) });
  2405. if (ci == null)
  2406. {
  2407. throw;
  2408. }
  2409. else
  2410. {
  2411. Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException });
  2412. throw ex2;
  2413. }
  2414. }
  2415. }
  2416. catch (ArgumentException)
  2417. {
  2418. if (fileName.Length == 0)
  2419. {
  2420. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName"));
  2421. }
  2422. else
  2423. {
  2424. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException"));
  2425. }
  2426. }
  2427. catch (UnauthorizedAccessException)
  2428. {
  2429. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException"));
  2430. }
  2431. catch (SecurityException)
  2432. {
  2433. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException"));
  2434. }
  2435. catch (FileNotFoundException)
  2436. {
  2437. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException"));
  2438. }
  2439. catch (DirectoryNotFoundException)
  2440. {
  2441. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException"));
  2442. }
  2443. catch (PathTooLongException)
  2444. {
  2445. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException"));
  2446. }
  2447. catch (IOException)
  2448. {
  2449. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException"));
  2450. }
  2451. catch (SerializationException)
  2452. {
  2453. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException"));
  2454. }
  2455. catch (OutOfMemoryException)
  2456. {
  2457. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException"));
  2458. }
  2459. catch (Exception)
  2460. {
  2461. Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception"));
  2462. }
  2463. finally
  2464. {
  2465. if (stream != null)
  2466. {
  2467. stream.Close();
  2468. stream = null;
  2469. }
  2470. }
  2471. }
  2472. return document;
  2473. }
  2474. public Surface RenderThumbnail(int maxEdgeLength, bool highQuality, bool forceUpToDate)
  2475. {
  2476. if (Document == null)
  2477. {
  2478. Surface ret = new Surface(maxEdgeLength, maxEdgeLength);
  2479. ret.Clear(ColorBgra.Transparent);
  2480. return ret;
  2481. }
  2482. Size thumbSize = Utility.ComputeThumbnailSize(Document.Size, maxEdgeLength);
  2483. Surface thumb = new Surface(thumbSize);
  2484. thumb.Clear(ColorBgra.Transparent);
  2485. RenderCompositionTo(thumb, highQuality, forceUpToDate);
  2486. return thumb;
  2487. }
  2488. Surface IThumbnailProvider.RenderThumbnail(int maxEdgeLength)
  2489. {
  2490. return RenderThumbnail(maxEdgeLength, true, false);
  2491. }
  2492. }
  2493. }