Minsky
saver.cc
Go to the documentation of this file.
1 /*
2  @copyright Steve Keen 2021
3  @author Russell Standish
4  This file is part of Minsky.
5 
6  Minsky is free software: you can redistribute it and/or modify it
7  under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  Minsky is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with Minsky. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 #include "saver.h"
21 #include "schema3.h"
22 #include "minsky_epilogue.h"
23 
24 namespace minsky
25 {
26  const char* schemaURL="http://minsky.sf.net/minsky";
27 
28  Saver::Saver(const string& fileName): fileName(fileName), packer(os, schemaURL) {}
29 
30  namespace
31  {
32  struct OnExit
33  {
34  std::function<void()> f;
35  OnExit(const std::function<void()>& f): f(f) {}
36  ~OnExit() {f();}
37  };
38  }
39 
41  {
42  os.open(fileName);
43  const OnExit closeOnExit([&](){os.close();});
44 
45  try
46  {
47  packer.abort=false; // reset abort flag
48  xml_pack(packer, "Minsky", m);
49  }
50  catch (const xml_pack_t::PackAborted&) {}
51  catch (...) {
52  // if exception is due to file error, provide a more useful message
53  if (!os)
54  throw runtime_error("cannot save to "+fileName);
55  throw;
56  }
57  }
58 
60  {
61  if (thread.joinable())
62  {
63  packer.abort=true;
64  thread.join();
65  }
66  }
67 
69  {
70  killThread();
71  if (!lastError.empty())
72  {
73  lastError.clear();
74  throw std::runtime_error(lastError);
75  }
76  thread=std::thread([this,m](){
77  try
78  {
79  Saver::save(m);
80  }
81  catch (const std::exception& ex) {lastError=ex.what();}
82  catch (...) {} // we don't want any error to propagate
83  });
84  }
85 
86 
87 }
function f
Definition: canvas.m:1
std::ofstream os
Definition: saver.h:39
OnExit(const std::function< void()> &f)
Definition: saver.cc:35
std::thread thread
Definition: saver.h:47
void save(const schema3::Minsky &)
Definition: saver.cc:40
Creation and access to the minskyTCL_obj object, which has code to record whenever Minsky&#39;s state cha...
Definition: constMap.h:22
std::string fileName
Definition: saver.h:38
const char * schemaURL
Definition: saver.cc:26
void xml_pack(xml_pack_t &t, const string &d, minsky::Optional< T > &a)
Definition: optional.h:84
Saver(const std::string &fileName)
Definition: saver.cc:28
std::string lastError
Definition: saver.h:48
classdesc::xml_pack_t packer
Definition: saver.h:40
void save(const schema3::Minsky &)
Definition: saver.cc:68