Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3095 was 2961, checked in by swagner, 14 years ago

Refactored enabling and disabling of save buttons and menu items to prevent saving of running algorithms (#685)

File size: 8.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
26using System.Threading;
27using System.Windows.Forms;
28using HeuristicLab.Core.Views;
29using HeuristicLab.MainForm;
30using HeuristicLab.Persistence.Default.Xml;
31
32namespace HeuristicLab.Optimizer {
33  internal static class FileManager {
34
35    #region Private Class FileInfo
36    private class FileInfo {
37      public string Filename { get; set; }
38      public bool Compressed { get; set; }
39
40      public FileInfo(string filename, bool compressed) {
41        Filename = filename;
42        Compressed = compressed;
43      }
44      public FileInfo(string filename)
45        : this(filename, true) {
46      }
47      public FileInfo()
48        : this(string.Empty, true) {
49      }
50    }
51    #endregion
52
53    private static Dictionary<IContentView, FileInfo> files;
54    private static NewItemDialog newItemDialog;
55    private static OpenFileDialog openFileDialog;
56    private static SaveFileDialog saveFileDialog;
57    private static int waitingCursors;
58    private static int newDocumentsCounter;
59
60    static FileManager() {
61      files = new Dictionary<IContentView, FileInfo>();
62      newItemDialog = null;
63      openFileDialog = null;
64      saveFileDialog = null;
65      waitingCursors = 0;
66      newDocumentsCounter = 1;
67      // NOTE: Events fired by the main form are registered in HeuristicLabOptimizerApplication.
68    }
69
70    public static void New() {
71      if (newItemDialog == null) newItemDialog = new NewItemDialog();
72      if (newItemDialog.ShowDialog() == DialogResult.OK) {
73        IView view = MainFormManager.CreateDefaultView(newItemDialog.Item);
74        if (view == null) {
75          MessageBox.Show("There is no view for the new item. It cannot be displayed. ", "No View Available", MessageBoxButtons.OK, MessageBoxIcon.Error);
76        } else {
77          if (view is IContentView) {
78            view.Caption = "Item" + newDocumentsCounter.ToString() + ".hl";
79            newDocumentsCounter++;
80          }
81          view.Show();
82        }
83      }
84    }
85
86    public static void Open() {
87      if (openFileDialog == null) {
88        openFileDialog = new OpenFileDialog();
89        openFileDialog.Title = "Open Item";
90        openFileDialog.FileName = "Item";
91        openFileDialog.Multiselect = true;
92        openFileDialog.DefaultExt = "hl";
93        openFileDialog.Filter = "HeuristicLab Files|*.hl|All Files|*.*";
94      }
95
96      if (openFileDialog.ShowDialog() == DialogResult.OK) {
97        foreach (string filename in openFileDialog.FileNames)
98          LoadItemAsync(filename);
99      }
100    }
101
102    public static void Save() {
103      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
104      if (activeView != null) {
105        Save(activeView);
106      }
107    }
108    private static void Save(IContentView view) {
109      if (view.SaveEnabled) {
110        if ((!files.ContainsKey(view)) || (!File.Exists(files[view].Filename))) {
111          SaveAs(view);
112        } else {
113          if (files[view].Compressed)
114            SaveItemAsync(view, files[view].Filename, 9);
115          else
116            SaveItemAsync(view, files[view].Filename, 0);
117        }
118      }
119    }
120
121    public static void SaveAs() {
122      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
123      if (activeView != null) {
124        SaveAs(activeView);
125      }
126    }
127    public static void SaveAs(IContentView view) {
128      if (view.SaveEnabled) {
129        if (saveFileDialog == null) {
130          saveFileDialog = new SaveFileDialog();
131          saveFileDialog.Title = "Save Item";
132          saveFileDialog.DefaultExt = "hl";
133          saveFileDialog.Filter = "Uncompressed HeuristicLab Files|*.hl|HeuristicLab Files|*.hl|All Files|*.*";
134          saveFileDialog.FilterIndex = 2;
135        }
136
137        if (!files.ContainsKey(view)) {
138          files.Add(view, new FileInfo());
139          saveFileDialog.FileName = view.Caption;
140        } else {
141          saveFileDialog.FileName = files[view].Filename;
142        }
143        if (!files[view].Compressed)
144          saveFileDialog.FilterIndex = 1;
145        else
146          saveFileDialog.FilterIndex = 2;
147
148        if (saveFileDialog.ShowDialog() == DialogResult.OK) {
149          if (saveFileDialog.FilterIndex == 1) {
150            SaveItemAsync(view, saveFileDialog.FileName, 0);
151          } else {
152            SaveItemAsync(view, saveFileDialog.FileName, 9);
153          }
154        }
155      }
156    }
157
158    public static void SaveAll() {
159      foreach (IContentView view in MainFormManager.MainForm.Views.OfType<IContentView>())
160        Save(view);
161    }
162
163    // NOTE: This event is fired by the main form. It is registered in HeuristicLabOptimizerApplication.
164    internal static void ViewClosed(object sender, ViewEventArgs e) {
165      IContentView view = e.View as IContentView;
166      if (view != null) files.Remove(view);
167    }
168
169    #region Asynchronous Save/Load Operations
170    private static void Invoke(Action a) {
171      Form form = MainFormManager.MainForm as Form;
172      if (form.InvokeRequired)
173        form.Invoke(a);
174      else
175        a.Invoke();
176    }
177
178    private static void SaveItemAsync(IContentView view, string filename, int compression) {
179      ThreadPool.QueueUserWorkItem(
180        new WaitCallback(
181          delegate(object arg) {
182            try {
183              DisableView(view);
184              SetWaitingCursor();
185              XmlGenerator.Serialize(view.Content, filename, compression);
186              Invoke(delegate() {
187                view.Caption = Path.GetFileName(filename);
188                files[view].Filename = filename;
189                files[view].Compressed = compression > 0;
190              });
191            }
192            catch (Exception ex) {
193              Auxiliary.ShowErrorMessageBox(ex);
194            } finally {
195              ResetWaitingCursor();
196              EnableView(view);
197            }
198          }
199        )
200      );
201    }
202    private static void LoadItemAsync(string filename) {
203      ThreadPool.QueueUserWorkItem(
204        new WaitCallback(
205          delegate(object arg) {
206            try {
207              SetWaitingCursor();
208              object content = XmlParser.Deserialize(filename);
209              Invoke(delegate() {
210                IContentView view = MainFormManager.CreateDefaultView(content) as IContentView;
211                if (view == null) {
212                  MessageBox.Show("There is no view for the loaded item. It cannot be displayed. ", "No View Available", MessageBoxButtons.OK, MessageBoxIcon.Error);
213                } else {
214                  view.Caption = Path.GetFileName(filename);
215                  files.Add(view, new FileInfo(filename));
216                  view.Show();
217                }
218              });
219            } catch (Exception ex) {
220              Auxiliary.ShowErrorMessageBox(ex);
221            } finally {
222              ResetWaitingCursor();
223            }
224          }
225        )
226      );
227    }
228
229    private static void SetWaitingCursor() {
230      Invoke(delegate() {
231        waitingCursors++;
232        ((Form)MainFormManager.MainForm).Cursor = Cursors.AppStarting;
233      });
234    }
235    private static void ResetWaitingCursor() {
236      Invoke(delegate() {
237        waitingCursors--;
238        if (waitingCursors == 0) ((Form)MainFormManager.MainForm).Cursor = Cursors.Default;
239      });
240    }
241    private static void DisableView(IView view) {
242      Invoke(delegate() {
243        ((UserControl)view).Enabled = false;
244      });
245    }
246    private static void EnableView(IView view) {
247      Invoke(delegate() {
248        ((UserControl)view).Enabled = true;
249      });
250    }
251    #endregion
252  }
253}
Note: See TracBrowser for help on using the repository browser.