Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimizer/3.3/FileManager.cs @ 2614

Last change on this file since 2614 was 2557, checked in by swagner, 15 years ago

Fixed exception when trying to save a file whose location is no longer available (#499)

File size: 7.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading;
6using System.IO;
7using System.Windows.Forms;
8using HeuristicLab.MainForm;
9using HeuristicLab.Core;
10using HeuristicLab.Persistence.Default.Xml;
11using HeuristicLab.Core.Views;
12
13namespace HeuristicLab.Optimizer {
14  internal static class FileManager {
15
16    #region Private Class FileInfo
17    private class FileInfo {
18      public string Filename { get; set; }
19      public bool Compressed { get; set; }
20
21      public FileInfo(string filename, bool compressed) {
22        Filename = filename;
23        Compressed = compressed;
24      }
25      public FileInfo(string filename)
26        : this(filename, true) {
27      }
28      public FileInfo()
29        : this(string.Empty, true) {
30      }
31    }
32    #endregion
33
34    private static Dictionary<IItemView, FileInfo> files;
35    private static NewItemDialog newItemDialog;
36    private static OpenFileDialog openFileDialog;
37    private static SaveFileDialog saveFileDialog;
38    private static int waitingCursors;
39    private static int newDocumentsCounter;
40
41    static FileManager() {
42      files = new Dictionary<IItemView, FileInfo>();
43      newItemDialog = null;
44      openFileDialog = null;
45      saveFileDialog = null;
46      waitingCursors = 0;
47      newDocumentsCounter = 1;
48      // NOTE: Events fired by the main form are registered in HeuristicLabOptimizerApplication.
49    }
50
51    public static void New() {
52      if (newItemDialog == null) newItemDialog = new NewItemDialog();
53      if (newItemDialog.ShowDialog() == DialogResult.OK) {
54        IView view = MainFormManager.CreateDefaultView(newItemDialog.Item);
55        if (view is IItemView) {
56          view.Caption = "Item" + newDocumentsCounter.ToString() + ".hl";
57          newDocumentsCounter++;
58        }
59        MainFormManager.MainForm.ShowView(view);
60      }
61    }
62
63    public static void Open() {
64      if (openFileDialog == null) {
65        openFileDialog = new OpenFileDialog();
66        openFileDialog.Title = "Open Item";
67        openFileDialog.FileName = "Item";
68        openFileDialog.Multiselect = true;
69        openFileDialog.DefaultExt = "hl";
70        openFileDialog.Filter = "HeuristicLab Files|*.hl|All Files|*.*";
71      }
72
73      if (openFileDialog.ShowDialog() == DialogResult.OK) {
74        foreach (string filename in openFileDialog.FileNames)
75          LoadItemAsync(filename);
76      }
77    }
78
79    public static void Save() {
80      IItemView activeView = MainFormManager.MainForm.ActiveView as IItemView;
81      if ((activeView != null) && (CreatableAttribute.IsCreatable(activeView.Item.GetType()))) {
82        Save(activeView);
83      }
84    }
85    private static void Save(IItemView view) {
86      if ((!files.ContainsKey(view)) || (!File.Exists(files[view].Filename))) {
87        SaveAs(view);
88      } else {
89        if (files[view].Compressed)
90          SaveItemAsync(view, files[view].Filename, 9);
91        else
92          SaveItemAsync(view, files[view].Filename, 0);
93      }
94    }
95
96    public static void SaveAs() {
97      IItemView activeView = MainFormManager.MainForm.ActiveView as IItemView;
98      if ((activeView != null) && (CreatableAttribute.IsCreatable(activeView.Item.GetType()))) {
99        SaveAs(activeView);
100      }
101    }
102    public static void SaveAs(IItemView view) {
103      if (saveFileDialog == null) {
104        saveFileDialog = new SaveFileDialog();
105        saveFileDialog.Title = "Save Item";
106        saveFileDialog.DefaultExt = "hl";
107        saveFileDialog.Filter = "Uncompressed HeuristicLab Files|*.hl|HeuristicLab Files|*.hl|All Files|*.*";
108        saveFileDialog.FilterIndex = 2;
109      }
110
111      if (!files.ContainsKey(view)) {
112        files.Add(view, new FileInfo());
113        saveFileDialog.FileName = view.Caption;
114      } else {
115        saveFileDialog.FileName = files[view].Filename;
116      }
117      if (! files[view].Compressed)
118        saveFileDialog.FilterIndex = 1;
119      else
120        saveFileDialog.FilterIndex = 2;
121
122      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
123        if (saveFileDialog.FilterIndex == 1) {
124          SaveItemAsync(view, saveFileDialog.FileName, 0);
125        } else {
126          SaveItemAsync(view, saveFileDialog.FileName, 9);
127        }
128      }
129    }
130
131    public static void SaveAll() {
132      var views = from v in MainFormManager.MainForm.Views
133                  where v is IItemView
134                  where CreatableAttribute.IsCreatable(((IItemView)v).Item.GetType())
135                  select v as IItemView;
136
137      foreach (IItemView view in views) {
138        Save(view);
139      }
140    }
141
142    // NOTE: This event is fired by the main form. It is registered in HeuristicLabOptimizerApplication.
143    internal static void ViewClosed(object sender, ViewEventArgs e) {
144      IItemView view = e.View as IItemView;
145      files.Remove(view);
146    }
147
148    #region Asynchronous Save/Load Operations
149    private static void Invoke(Action a) {
150      Form form = MainFormManager.MainForm as Form;
151      if (form.InvokeRequired)
152        form.Invoke(a);
153      else
154        a.Invoke();
155    }
156
157    private static void SaveItemAsync(IItemView view, string filename, int compression) {
158      ThreadPool.QueueUserWorkItem(
159        new WaitCallback(
160          delegate(object arg) {
161            try {
162              DisableView(view);
163              SetWaitingCursor();
164              XmlGenerator.Serialize(view.Item, filename, compression);
165              Invoke(delegate() {
166                view.Caption = Path.GetFileName(filename);
167                files[view].Filename = filename;
168                files[view].Compressed = compression > 0;
169              });
170            }
171            catch (Exception ex) {
172              Auxiliary.ShowErrorMessageBox(ex);
173            } finally {
174              ResetWaitingCursor();
175              EnableView(view);
176            }
177          }
178        )
179      );
180    }
181    private static void LoadItemAsync(string filename) {
182      ThreadPool.QueueUserWorkItem(
183        new WaitCallback(
184          delegate(object arg) {
185            try {
186              SetWaitingCursor();
187              IItem item = (IItem)XmlParser.Deserialize(filename);
188              Invoke(delegate() {
189                IItemView view = MainFormManager.CreateDefaultView(item) as IItemView;
190                if (view != null) {
191                  view.Caption = Path.GetFileName(filename);
192                  files.Add(view, new FileInfo(filename));
193                  MainFormManager.MainForm.ShowView(view);
194                }
195              });
196            } catch (Exception ex) {
197              Auxiliary.ShowErrorMessageBox(ex);
198            } finally {
199              ResetWaitingCursor();
200            }
201          }
202        )
203      );
204    }
205
206    private static void SetWaitingCursor() {
207      Invoke(delegate() {
208        waitingCursors++;
209        ((Form)MainFormManager.MainForm).Cursor = Cursors.AppStarting;
210      });
211    }
212    private static void ResetWaitingCursor() {
213      Invoke(delegate() {
214        waitingCursors--;
215        if (waitingCursors == 0) ((Form)MainFormManager.MainForm).Cursor = Cursors.Default;
216      });
217    }
218    private static void DisableView(IView view) {
219      Invoke(delegate() {
220        ((UserControl)view).Enabled = false;
221      });
222    }
223    private static void EnableView(IView view) {
224      Invoke(delegate() {
225        ((UserControl)view).Enabled = true;
226      });
227    }
228    #endregion
229  }
230}
Note: See TracBrowser for help on using the repository browser.