session.py
10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: invesalius@cti.gov.br
# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt)
#--------------------------------------------------------------------------
# Este programa e software livre; voce pode redistribui-lo e/ou
# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme
# publicada pela Free Software Foundation; de acordo com a versao 2
# da Licenca.
#
# Este programa eh distribuido na expectativa de ser util, mas SEM
# QUALQUER GARANTIA; sem mesmo a garantia implicita de
# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
# detalhes.
#--------------------------------------------------------------------------
try:
import configparser as ConfigParser
except(ImportError):
import ConfigParser
import os
import shutil
import sys
from threading import Thread
import time
import codecs
import collections
import json
from pubsub import pub as Publisher
import wx
from invesalius.utils import Singleton, debug, decode
from random import randint
from invesalius import inv_paths
FS_ENCODE = sys.getfilesystemencoding()
USER_INV_CFG_PATH = os.path.join(inv_paths.USER_INV_DIR, 'config.json')
OLD_USER_INV_CFG_PATH = os.path.join(inv_paths.USER_INV_DIR, 'config.cfg')
SESSION_ENCODING = 'utf8'
# Only one session will be initialized per time. Therefore, we use
# Singleton design pattern for implementing it
class Session(metaclass=Singleton):
def __init__(self):
self.project_path = ()
self.temp_item = False
self._values = collections.defaultdict(dict, {
'session': {
'status': 3,
'language': '',
},
'project': {
},
'paths': {
}
})
self._map_attrs = {
'mode': ('session', 'mode'),
'project_status': ('session', 'status'),
'debug': ('session', 'debug'),
'language': ('session', 'language'),
'random_id': ('session', 'random_id'),
'surface_interpolation': ('session', 'surface_interpolation'),
'rendering': ('session', 'rendering'),
'slice_interpolation': ('session', 'slice_interpolation'),
'recent_projects': ('project', 'recent_projects'),
'homedir': ('paths', 'homedir'),
'tempdir': ('paths', 'homedir'),
'last_dicom_folder': ('paths', 'last_dicom_folder'),
}
def CreateItens(self):
import invesalius.constants as const
self._values = collections.defaultdict(dict, {
'session': {
'mode': const.MODE_RP,
'status': const.PROJ_CLOSE,
'debug': False,
'language': "",
'random_id': randint(0, pow(10,16)),
'surface_interpolation': 1,
'rendering': 0,
'slice_interpolation': 0,
},
'project': {
'recent_projects': [(str(inv_paths.SAMPLE_DIR), u"Cranium.inv3"), ],
},
'paths': {
'homedir': str(inv_paths.USER_DIR),
'tempdir': str(inv_paths.TEMP_DIR),
'last_dicom_folder': '',
},
})
def __contains__(self, key):
return key in self._values
def __getitem__(self, key):
return self._values[key]
def __setitem__(self, key, value):
self._values[key] = value
def __getattr__(self, name):
map_attrs = object.__getattribute__(self, '_map_attrs')
if name not in map_attrs:
raise AttributeError(name)
session, key = map_attrs[name]
return object.__getattribute__(self, '_values')[session][key]
def __setattr__(self, name, value):
if name in ("temp_item", "_map_attrs", "_values", "project_path"):
return object.__setattr__(self, name, value)
else:
session, key = self._map_attrs[name]
self._values[session][key] = value
def __str__(self):
return self._values.__str__()
def get(self, session, key, default_value):
try:
return self._values[session][key]
except KeyError:
return default_value
def IsOpen(self):
import invesalius.constants as const
return self.project_status != const.PROJ_CLOSE
def SaveConfigFileBackup(self):
path = os.path.join(self.homedir ,
u'.invesalius', u'config.cfg')
path_dst = os.path.join(self.homedir ,
u'.invesalius', u'config.backup')
shutil.copy(path, path_dst)
def RecoveryConfigFile(self):
homedir = self.homedir = os.path.expanduser('~')
try:
path = os.path.join(self.homedir ,
u'.invesalius', u'config.backup')
path_dst = os.path.join(self.homedir ,
u'.invesalius', u'config.cfg')
shutil.copy(path, path_dst)
return True
except(IOError):
return False
def CloseProject(self):
import invesalius.constants as const
debug("Session.CloseProject")
self.project_path = ()
self.project_status = const.PROJ_CLOSE
#self.mode = const.MODE_RP
self.temp_item = False
self.WriteSessionFile()
def SaveProject(self, path=()):
import invesalius.constants as const
debug("Session.SaveProject")
self.project_status = const.PROJ_OPEN
if path:
self.project_path = path
self.__add_to_list(path)
if self.temp_item:
self.temp_item = False
self.WriteSessionFile()
def ChangeProject(self):
import invesalius.constants as const
debug("Session.ChangeProject")
self.project_status = const.PROJ_CHANGE
def CreateProject(self, filename):
import invesalius.constants as const
debug("Session.CreateProject")
Publisher.sendMessage('Begin busy cursor')
# Set session info
self.project_path = (self.tempdir, filename)
self.project_status = const.PROJ_NEW
self.temp_item = True
self.WriteSessionFile()
return self.tempdir
def OpenProject(self, filepath):
import invesalius.constants as const
debug("Session.OpenProject")
# Add item to recent projects list
item = (path, file) = os.path.split(filepath)
self.__add_to_list(item)
# Set session info
self.project_path = item
self.project_status = const.PROJ_OPEN
self.WriteSessionFile()
def RemoveTemp(self):
if self.temp_item:
(dirpath, file) = self.project_path
path = os.path.join(dirpath, file)
os.remove(path)
self.temp_item = False
def WriteSessionFile(self):
self._write_to_json(self._values, USER_INV_CFG_PATH)
def _write_to_json(self, cfg_dict, cfg_filename):
with open(cfg_filename, 'w') as cfg_file:
json.dump(cfg_dict, cfg_file, sort_keys=True, indent=4)
def __add_to_list(self, item):
import invesalius.constants as const
# Last projects list
l = self.recent_projects
item = list(item)
# If item exists, remove it from list
if l.count(item):
l.remove(item)
# Add new item
l.insert(0, item)
self.recent_projects = l[:const.PROJ_MAX]
def GetLanguage(self):
return self.language
def SetLanguage(self, language):
self.language = language
def GetRandomId(self):
return self.random_id
def SetRandomId(self, random_id):
self.random_id = random_id
def GetLastDicomFolder(self):
return self.last_dicom_folder
def SetLastDicomFolder(self, folder):
self.last_dicom_folder = decode(folder, FS_ENCODE)
self.WriteSessionFile()
def _update_cfg_from_dict(self, config, cfg_dict):
for session in cfg_dict:
if cfg_dict[session] and isinstance(cfg_dict[session], dict):
config.add_section(session)
for key in cfg_dict[session]:
config.set(session, key, cfg_dict[session][key])
def _read_cfg_from_json(self, json_filename):
with open(json_filename, 'r') as cfg_file:
cfg_dict = json.load(cfg_file)
self._values.update(cfg_dict)
# Do not reading project status from the config file, since there
# isn't a recover session tool in InVesalius yet.
self.project_status = 3
def _read_cfg_from_ini(self, cfg_filename):
f = codecs.open(cfg_filename, 'rb', SESSION_ENCODING)
config = ConfigParser.ConfigParser()
config.readfp(f)
f.close()
self.mode = config.getint('session', 'mode')
# Do not reading project status from the config file, since there
# isn't a recover sessession tool in InVesalius
#self.project_status = int(config.get('session', 'status'))
self.debug = config.getboolean('session','debug')
self.language = config.get('session','language')
recent_projects = eval(config.get('project','recent_projects'))
self.recent_projects = [list(rp) for rp in recent_projects]
self.homedir = config.get('paths','homedir')
self.tempdir = config.get('paths','tempdir')
self.last_dicom_folder = config.get('paths','last_dicom_folder')
# if not(sys.platform == 'win32'):
# self.last_dicom_folder = self.last_dicom_folder.decode('utf-8')
self.surface_interpolation = config.getint('session', 'surface_interpolation')
self.slice_interpolation = config.getint('session', 'slice_interpolation')
self.rendering = config.getint('session', 'rendering')
self.random_id = config.getint('session','random_id')
def ReadSession(self):
try:
self._read_cfg_from_json(USER_INV_CFG_PATH)
except Exception as e1:
debug(e1)
try:
self._read_cfg_from_ini(OLD_USER_INV_CFG_PATH)
except Exception as e2:
debug(e2)
return False
self.WriteSessionFile()
return True