Salome HOME
Code improvements, review and simplifications (4)
[modules/adao.git] / src / daComposant / daCore / Reporting.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2022 EDF R&D
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 """
24     Gestion simple de rapports structurés créés par l'utilisateur.
25 """
26 __author__ = "Jean-Philippe ARGAUD"
27 __all__ = []
28
29 import os.path
30
31 # ==============================================================================
32 # Classes de services non utilisateur
33
34 class _ReportPartM__(object):
35     """
36     Store and retrieve the data for C: internal class
37     """
38     def __init__(self, part="default"):
39         self.__part    = str(part)
40         self.__styles  = []
41         self.__content = []
42
43     def append(self, content, style="p", position=-1):
44         if position == -1:
45             self.__styles.append(style)
46             self.__content.append(content)
47         else:
48             self.__styles.insert(position, style)
49             self.__content.insert(position, content)
50         return 0
51
52     def get_styles(self):
53         return self.__styles
54
55     def get_content(self):
56         return self.__content
57
58 class _ReportM__(object):
59     """
60     Store and retrieve the data for C: internal class
61     """
62     def __init__(self, part='default'):
63         self.__document = {}
64         self.__document[part] = _ReportPartM__(part)
65
66     def append(self,  content, style="p", position=-1, part='default'):
67         if part not in self.__document:
68             self.__document[part] = _ReportPartM__(part)
69         self.__document[part].append(content, style, position)
70         return 0
71
72     def get_styles(self):
73         op = list(self.__document.keys()) ; op.sort()
74         return [self.__document[k].get_styles() for k in op]
75
76     def get_content(self):
77         op = list(self.__document.keys()) ; op.sort()
78         return [self.__document[k].get_content() for k in op]
79
80     def clear(self):
81         self.__init__()
82
83 class __ReportC__(object):
84     """
85     Get user commands, update M and V: user intertace to create the report
86     """
87     m = _ReportM__()
88
89     def append(self, content="", style="p", position=-1, part="default"):
90         return self.m.append(content, style, position, part)
91
92     def retrieve(self):
93         st = self.m.get_styles()
94         ct = self.m.get_content()
95         return st, ct
96
97     def clear(self):
98         self.m.clear()
99
100 class __ReportV__(object):
101     """
102     Interact with user and C: template for reports
103     """
104
105     default_filename="report.txt"
106
107     def __init__(self, c):
108         self.c = c
109
110     def save(self, filename=None):
111         if filename is None:
112             filename = self.default_filename
113         _filename = os.path.abspath(filename)
114         #
115         h = self.get()
116         fid = open(_filename, 'w')
117         fid.write(h)
118         fid.close()
119         return filename, _filename
120
121     def retrieve(self):
122         return self.c.retrieve()
123
124     def __str__(self):
125         return self.get()
126
127     def close(self):
128         del self.c
129         return 0
130
131 # ==============================================================================
132 # Classes d'interface utilisateur : ReportViewIn*, ReportStorage
133 # Tags de structure : (title, h1, h2, h3, p, uli, oli, <b></b>, <i></i>)
134
135 class ReportViewInHtml(__ReportV__):
136     """
137     Report in HTML
138     """
139
140     default_filename="report.html"
141     tags = {
142         "oli":"li",
143         "uli":"li",
144         }
145
146     def get(self):
147         st, ct = self.retrieve()
148         inuLi, inoLi = False, False
149         pg = "<html>\n<head>"
150         pg += "\n<title>Report in HTML</title>"
151         pg += "\n</head>\n<body>"
152         for k,ps in enumerate(st):
153             pc = ct[k]
154             try:
155                 ii = ps.index("title")
156                 title = pc[ii]
157                 pg += "%s\n%s\n%s"%('<hr noshade><h1 align="center">',title,'</h1><hr noshade>')
158             except Exception:
159                 pass
160             for i,s in enumerate(ps):
161                 c = pc[i]
162                 if s == "uli" and not inuLi:
163                     pg += "\n<ul>"
164                     inuLi = True
165                 elif s == "oli" and not inoLi:
166                     pg += "\n<ol>"
167                     inoLi = True
168                 elif s != "uli" and inuLi:
169                     pg += "\n</ul>"
170                     inuLi = False
171                 elif s != "oli" and inoLi:
172                     pg += "\n</ol>"
173                     inoLi = False
174                 elif s == "title":
175                     continue
176                 for t in self.tags:
177                     if s == t: s = self.tags[t]
178                 pg += "\n<%s>%s</%s>"%(s,c,s)
179         pg += "\n</body>\n</html>"
180         return pg
181
182 class ReportViewInRst(__ReportV__):
183     """
184     Report in RST
185     """
186
187     default_filename="report.rst"
188     tags = {
189         "p":["\n\n",""],
190         "uli":["\n  - ",""],
191         "oli":["\n  #. ",""],
192         }
193     titles = {
194         # "title":["=","="],
195         "h1":["","-"],
196         "h2":["","+"],
197         "h3":["","*"],
198         }
199     translation = {
200         "<b>":"**",
201         "<i>":"*",
202         "</b>":"**",
203         "</i>":"*",
204         }
205
206     def get(self):
207         st, ct = self.retrieve()
208         inuLi, inoLi = False, False
209         pg = ""
210         for k,ps in enumerate(st):
211             pc = ct[k]
212             try:
213                 ii = ps.index("title")
214                 title = pc[ii]
215                 pg += "%s\n%s\n%s"%("="*80,title,"="*80)
216             except Exception:
217                 pass
218             for i,s in enumerate(ps):
219                 c = pc[i]
220                 if s == "uli" and not inuLi:
221                     pg += "\n"
222                     inuLi = True
223                 elif s == "oli" and not inoLi:
224                     pg += "\n"
225                     inoLi = True
226                 elif s != "uli" and inuLi:
227                     pg += "\n"
228                     inuLi = False
229                 elif s != "oli" and inoLi:
230                     pg += "\n"
231                     inoLi = False
232                 for t in self.translation:
233                     c = c.replace(t,self.translation[t])
234                 if s in self.titles.keys():
235                     pg += "\n%s\n%s\n%s"%(self.titles[s][0]*len(c),c,self.titles[s][1]*len(c))
236                 elif s in self.tags.keys():
237                     pg += "%s%s%s"%(self.tags[s][0],c,self.tags[s][1])
238             pg += "\n"
239         return pg
240
241 class ReportViewInPlainTxt(__ReportV__):
242     """
243     Report in plain TXT
244     """
245
246     default_filename="report.txt"
247     tags = {
248         "p":["\n",""],
249         "uli":["\n  - ",""],
250         "oli":["\n  - ",""],
251         }
252     titles = {
253         # "title":["=","="],
254         "h1":["",""],
255         "h2":["",""],
256         "h3":["",""],
257         }
258     translation = {
259         "<b>":"",
260         "<i>":"",
261         "</b>":"",
262         "</i>":"",
263         }
264
265     def get(self):
266         st, ct = self.retrieve()
267         inuLi, inoLi = False, False
268         pg = ""
269         for k,ps in enumerate(st):
270             pc = ct[k]
271             try:
272                 ii = ps.index("title")
273                 title = pc[ii]
274                 pg += "%s\n%s\n%s"%("="*80,title,"="*80)
275             except Exception:
276                 pass
277             for i,s in enumerate(ps):
278                 c = pc[i]
279                 if s == "uli" and not inuLi:
280                     inuLi = True
281                 elif s == "oli" and not inoLi:
282                     inoLi = True
283                 elif s != "uli" and inuLi:
284                     inuLi = False
285                 elif s != "oli" and inoLi:
286                     inoLi = False
287                 for t in self.translation:
288                     c = c.replace(t,self.translation[t])
289                 if s in self.titles.keys():
290                     pg += "\n%s\n%s\n%s"%(self.titles[s][0]*len(c),c,self.titles[s][1]*len(c))
291                 elif s in self.tags.keys():
292                     pg += "\n%s%s%s"%(self.tags[s][0],c,self.tags[s][1])
293             pg += "\n"
294         return pg
295
296
297 # Interface utilisateur de stockage des informations
298 ReportStorage = __ReportC__
299
300 # ==============================================================================
301 if __name__ == "__main__":
302     print('\n AUTODIAGNOSTIC\n')