src/eric7/Sessions/SessionFile.py

branch
eric7
changeset 9221
bf71ee032bb4
parent 9209
b99e7fd55fd3
child 9278
36448ca469c2
equal deleted inserted replaced
9220:e9e7eca7efee 9221:bf71ee032bb4
22 22
23 class SessionFile(QObject): 23 class SessionFile(QObject):
24 """ 24 """
25 Class representing the session JSON file. 25 Class representing the session JSON file.
26 """ 26 """
27
27 def __init__(self, isGlobal: bool, parent: QObject = None): 28 def __init__(self, isGlobal: bool, parent: QObject = None):
28 """ 29 """
29 Constructor 30 Constructor
30 31
31 @param isGlobal flag indicating a file for a global session 32 @param isGlobal flag indicating a file for a global session
32 @type bool 33 @type bool
33 @param parent reference to the parent object (defaults to None) 34 @param parent reference to the parent object (defaults to None)
34 @type QObject (optional) 35 @type QObject (optional)
35 """ 36 """
36 super().__init__(parent) 37 super().__init__(parent)
37 38
38 self.__isGlobal = isGlobal 39 self.__isGlobal = isGlobal
39 40
40 def writeFile(self, filename: str) -> bool: 41 def writeFile(self, filename: str) -> bool:
41 """ 42 """
42 Public method to write the session data to a session JSON file. 43 Public method to write the session data to a session JSON file.
43 44
44 @param filename name of the session file 45 @param filename name of the session file
45 @type str 46 @type str
46 @return flag indicating a successful write 47 @return flag indicating a successful write
47 @rtype bool 48 @rtype bool
48 """ 49 """
51 projectBrowser = ericApp().getObject("ProjectBrowser") 52 projectBrowser = ericApp().getObject("ProjectBrowser")
52 multiProject = ericApp().getObject("MultiProject") 53 multiProject = ericApp().getObject("MultiProject")
53 vm = ericApp().getObject("ViewManager") 54 vm = ericApp().getObject("ViewManager")
54 dbg = ericApp().getObject("DebugUI") 55 dbg = ericApp().getObject("DebugUI")
55 dbs = ericApp().getObject("DebugServer") 56 dbs = ericApp().getObject("DebugServer")
56 57
57 # prepare the session data dictionary 58 # prepare the session data dictionary
58 # step 0: header 59 # step 0: header
59 sessionDict = {} 60 sessionDict = {}
60 sessionDict["header"] = {} 61 sessionDict["header"] = {}
61 if not self.__isGlobal: 62 if not self.__isGlobal:
62 sessionDict["header"]["comment"] = ( 63 sessionDict["header"][
63 "eric session file for project {0}" 64 "comment"
64 .format(project.getProjectName()) 65 ] = "eric session file for project {0}".format(project.getProjectName())
65 ) 66 sessionDict["header"][
66 sessionDict["header"]["warning"] = ( 67 "warning"
67 "This file was generated automatically, do not edit." 68 ] = "This file was generated automatically, do not edit."
68 ) 69
69
70 if Preferences.getProject("TimestampFile") or self.__isGlobal: 70 if Preferences.getProject("TimestampFile") or self.__isGlobal:
71 sessionDict["header"]["saved"] = ( 71 sessionDict["header"]["saved"] = time.strftime("%Y-%m-%d, %H:%M:%S")
72 time.strftime('%Y-%m-%d, %H:%M:%S') 72
73 )
74
75 # step 1: open multi project and project for global session 73 # step 1: open multi project and project for global session
76 sessionDict["MultiProject"] = "" 74 sessionDict["MultiProject"] = ""
77 sessionDict["Project"] = "" 75 sessionDict["Project"] = ""
78 if self.__isGlobal: 76 if self.__isGlobal:
79 if multiProject.isOpen(): 77 if multiProject.isOpen():
80 sessionDict["MultiProject"] = ( 78 sessionDict["MultiProject"] = multiProject.getMultiProjectFile()
81 multiProject.getMultiProjectFile()
82 )
83 if project.isOpen(): 79 if project.isOpen():
84 sessionDict["Project"] = project.getProjectFile() 80 sessionDict["Project"] = project.getProjectFile()
85 81
86 # step 2: all open (project) filenames and the active editor 82 # step 2: all open (project) filenames and the active editor
87 if vm.canSplit(): 83 if vm.canSplit():
88 sessionDict["ViewManagerSplits"] = { 84 sessionDict["ViewManagerSplits"] = {
89 "Count": vm.splitCount(), 85 "Count": vm.splitCount(),
90 "Orientation": vm.getSplitOrientation().value, 86 "Orientation": vm.getSplitOrientation().value,
92 else: 88 else:
93 sessionDict["ViewManagerSplits"] = { 89 sessionDict["ViewManagerSplits"] = {
94 "Count": 0, 90 "Count": 0,
95 "Orientation": 1, 91 "Orientation": 1,
96 } 92 }
97 93
98 editorsDict = {} # remember editors by file name to detect clones 94 editorsDict = {} # remember editors by file name to detect clones
99 sessionDict["Editors"] = [] 95 sessionDict["Editors"] = []
100 allOpenEditorLists = vm.getOpenEditorsForSession() 96 allOpenEditorLists = vm.getOpenEditorsForSession()
101 for splitIndex, openEditorList in enumerate(allOpenEditorLists): 97 for splitIndex, openEditorList in enumerate(allOpenEditorLists):
102 for editorIndex, editor in enumerate(openEditorList): 98 for editorIndex, editor in enumerate(openEditorList):
103 fileName = editor.getFileName() 99 fileName = editor.getFileName()
115 "Clone": isClone, 111 "Clone": isClone,
116 "Splitindex": splitIndex, 112 "Splitindex": splitIndex,
117 "Editorindex": editorIndex, 113 "Editorindex": editorIndex,
118 } 114 }
119 sessionDict["Editors"].append(editorDict) 115 sessionDict["Editors"].append(editorDict)
120 116
121 aw = vm.getActiveName() 117 aw = vm.getActiveName()
122 sessionDict["ActiveWindow"] = {} 118 sessionDict["ActiveWindow"] = {}
123 if aw and (self.__isGlobal or project.isProjectFile(aw)): 119 if aw and (self.__isGlobal or project.isProjectFile(aw)):
124 ed = vm.getOpenEditor(aw) 120 ed = vm.getOpenEditor(aw)
125 sessionDict["ActiveWindow"] = { 121 sessionDict["ActiveWindow"] = {
126 "Filename": aw, 122 "Filename": aw,
127 "Cursor": ed.getCursorPosition(), 123 "Cursor": ed.getCursorPosition(),
128 } 124 }
129 125
130 # step 3: breakpoints 126 # step 3: breakpoints
131 allBreaks = Preferences.getProject("SessionAllBreakpoints") 127 allBreaks = Preferences.getProject("SessionAllBreakpoints")
132 projectFiles = project.getSources(True) 128 projectFiles = project.getSources(True)
133 bpModel = dbs.getBreakPointModel() 129 bpModel = dbs.getBreakPointModel()
134 if self.__isGlobal or allBreaks: 130 if self.__isGlobal or allBreaks:
135 sessionDict["Breakpoints"] = bpModel.getAllBreakpoints() 131 sessionDict["Breakpoints"] = bpModel.getAllBreakpoints()
136 else: 132 else:
137 sessionDict["Breakpoints"] = [ 133 sessionDict["Breakpoints"] = [
138 bp 134 bp for bp in bpModel.getAllBreakpoints() if bp[0] in projectFiles
139 for bp in bpModel.getAllBreakpoints()
140 if bp[0] in projectFiles
141 ] 135 ]
142 136
143 # step 4: watch expressions 137 # step 4: watch expressions
144 wpModel = dbs.getWatchPointModel() 138 wpModel = dbs.getWatchPointModel()
145 sessionDict["Watchpoints"] = wpModel.getAllWatchpoints() 139 sessionDict["Watchpoints"] = wpModel.getAllWatchpoints()
146 140
147 # step 5: debug info 141 # step 5: debug info
148 if self.__isGlobal: 142 if self.__isGlobal:
149 if len(dbg.scriptsHistory): 143 if len(dbg.scriptsHistory):
150 dbgScriptName = dbg.scriptsHistory[0] 144 dbgScriptName = dbg.scriptsHistory[0]
151 else: 145 else:
161 if len(dbg.envHistory): 155 if len(dbg.envHistory):
162 dbgEnv = dbg.envHistory[0] 156 dbgEnv = dbg.envHistory[0]
163 else: 157 else:
164 dbgEnv = "" 158 dbgEnv = ""
165 if len(dbg.multiprocessNoDebugHistory): 159 if len(dbg.multiprocessNoDebugHistory):
166 dbgMultiprocessNoDebug = ( 160 dbgMultiprocessNoDebug = dbg.multiprocessNoDebugHistory[0]
167 dbg.multiprocessNoDebugHistory[0]
168 )
169 else: 161 else:
170 dbgMultiprocessNoDebug = "" 162 dbgMultiprocessNoDebug = ""
171 sessionDict["DebugInfo"] = { 163 sessionDict["DebugInfo"] = {
172 "VirtualEnv": dbg.lastUsedVenvName, 164 "VirtualEnv": dbg.lastUsedVenvName,
173 "ScriptName": dbgScriptName, 165 "ScriptName": dbgScriptName,
199 "AutoContinue": project.dbgAutoContinue, 191 "AutoContinue": project.dbgAutoContinue,
200 "EnableMultiprocess": project.dbgEnableMultiprocess, 192 "EnableMultiprocess": project.dbgEnableMultiprocess,
201 "MultiprocessNoDebug": project.dbgMultiprocessNoDebug, 193 "MultiprocessNoDebug": project.dbgMultiprocessNoDebug,
202 "GlobalConfigOverride": project.dbgGlobalConfigOverride, 194 "GlobalConfigOverride": project.dbgGlobalConfigOverride,
203 } 195 }
204 196
205 # step 6: bookmarks 197 # step 6: bookmarks
206 bookmarksList = [] 198 bookmarksList = []
207 for fileName in editorsDict: 199 for fileName in editorsDict:
208 if self.__isGlobal or project.isProjectFile(fileName): 200 if self.__isGlobal or project.isProjectFile(fileName):
209 editor = editorsDict[fileName] 201 editor = editorsDict[fileName]
210 bookmarks = editor.getBookmarks() 202 bookmarks = editor.getBookmarks()
211 if bookmarks: 203 if bookmarks:
212 bookmarksList.append({ 204 bookmarksList.append(
213 "Filename": fileName, 205 {
214 "Lines": bookmarks, 206 "Filename": fileName,
215 }) 207 "Lines": bookmarks,
208 }
209 )
216 sessionDict["Bookmarks"] = bookmarksList 210 sessionDict["Bookmarks"] = bookmarksList
217 211
218 # step 7: state of the various project browsers 212 # step 7: state of the various project browsers
219 browsersList = [] 213 browsersList = []
220 for browserName in projectBrowser.getProjectBrowserNames(): 214 for browserName in projectBrowser.getProjectBrowserNames():
221 expandedItems = ( 215 expandedItems = projectBrowser.getProjectBrowser(
222 projectBrowser.getProjectBrowser(browserName) 216 browserName
223 .getExpandedItemNames() 217 ).getExpandedItemNames()
224 )
225 if expandedItems: 218 if expandedItems:
226 browsersList.append({ 219 browsersList.append(
227 "Name": browserName, 220 {
228 "ExpandedItems": expandedItems, 221 "Name": browserName,
229 }) 222 "ExpandedItems": expandedItems,
223 }
224 )
230 sessionDict["ProjectBrowserStates"] = browsersList 225 sessionDict["ProjectBrowserStates"] = browsersList
231 226
232 try: 227 try:
233 jsonString = json.dumps(sessionDict, indent=2) 228 jsonString = json.dumps(sessionDict, indent=2)
234 with open(filename, "w") as f: 229 with open(filename, "w") as f:
235 f.write(jsonString) 230 f.write(jsonString)
236 except (TypeError, OSError) as err: 231 except (TypeError, OSError) as err:
239 None, 234 None,
240 self.tr("Save Session"), 235 self.tr("Save Session"),
241 self.tr( 236 self.tr(
242 "<p>The session file <b>{0}</b> could not be" 237 "<p>The session file <b>{0}</b> could not be"
243 " written.</p><p>Reason: {1}</p>" 238 " written.</p><p>Reason: {1}</p>"
244 ).format(filename, str(err)) 239 ).format(filename, str(err)),
245 ) 240 )
246 return False 241 return False
247 242
248 return True 243 return True
249 244
250 def readFile(self, filename: str) -> bool: 245 def readFile(self, filename: str) -> bool:
251 """ 246 """
252 Public method to read the session data from a session JSON file. 247 Public method to read the session data from a session JSON file.
253 248
254 @param filename name of the project file 249 @param filename name of the project file
255 @type str 250 @type str
256 @return flag indicating a successful read 251 @return flag indicating a successful read
257 @rtype bool 252 @rtype bool
258 """ 253 """
265 None, 260 None,
266 self.tr("Read Session"), 261 self.tr("Read Session"),
267 self.tr( 262 self.tr(
268 "<p>The session file <b>{0}</b> could not be read.</p>" 263 "<p>The session file <b>{0}</b> could not be read.</p>"
269 "<p>Reason: {1}</p>" 264 "<p>Reason: {1}</p>"
270 ).format(filename, str(err)) 265 ).format(filename, str(err)),
271 ) 266 )
272 return False 267 return False
273 268
274 # get references to objects we need 269 # get references to objects we need
275 project = ericApp().getObject("Project") 270 project = ericApp().getObject("Project")
276 projectBrowser = ericApp().getObject("ProjectBrowser") 271 projectBrowser = ericApp().getObject("ProjectBrowser")
277 multiProject = ericApp().getObject("MultiProject") 272 multiProject = ericApp().getObject("MultiProject")
278 vm = ericApp().getObject("ViewManager") 273 vm = ericApp().getObject("ViewManager")
279 dbg = ericApp().getObject("DebugUI") 274 dbg = ericApp().getObject("DebugUI")
280 dbs = ericApp().getObject("DebugServer") 275 dbs = ericApp().getObject("DebugServer")
281 276
282 # step 1: multi project and project 277 # step 1: multi project and project
283 # ================================= 278 # =================================
284 if sessionDict["MultiProject"]: 279 if sessionDict["MultiProject"]:
285 multiProject.openMultiProject(sessionDict["MultiProject"], False) 280 multiProject.openMultiProject(sessionDict["MultiProject"], False)
286 if sessionDict["Project"]: 281 if sessionDict["Project"]:
287 project.openProject(sessionDict["Project"], False) 282 project.openProject(sessionDict["Project"], False)
288 283
289 # step 2: (project) filenames and the active editor 284 # step 2: (project) filenames and the active editor
290 # ================================================= 285 # =================================================
291 vm.setSplitOrientation( 286 vm.setSplitOrientation(
292 Qt.Orientation(sessionDict["ViewManagerSplits"]["Orientation"]) 287 Qt.Orientation(sessionDict["ViewManagerSplits"]["Orientation"])
293 ) 288 )
294 vm.setSplitCount(sessionDict["ViewManagerSplits"]["Count"]) 289 vm.setSplitCount(sessionDict["ViewManagerSplits"]["Count"])
295 290
296 editorsDict = {} 291 editorsDict = {}
297 for editorDict in sessionDict["Editors"]: 292 for editorDict in sessionDict["Editors"]:
298 if editorDict["Clone"] and editorDict["Filename"] in editorsDict: 293 if editorDict["Clone"] and editorDict["Filename"] in editorsDict:
299 editor = editorsDict[editorDict["Filename"]] 294 editor = editorsDict[editorDict["Filename"]]
300 ed = vm.newEditorView( 295 ed = vm.newEditorView(
301 editorDict["Filename"], editor, editor.getFileType(), 296 editorDict["Filename"],
302 indexes=(editorDict["Splitindex"], 297 editor,
303 editorDict["Editorindex"]) 298 editor.getFileType(),
299 indexes=(editorDict["Splitindex"], editorDict["Editorindex"]),
304 ) 300 )
305 else: 301 else:
306 ed = vm.openSourceFile( 302 ed = vm.openSourceFile(
307 editorDict["Filename"], 303 editorDict["Filename"],
308 indexes=(editorDict["Splitindex"], 304 indexes=(editorDict["Splitindex"], editorDict["Editorindex"]),
309 editorDict["Editorindex"])
310 ) 305 )
311 editorsDict[editorDict["Filename"]] = ed 306 editorsDict[editorDict["Filename"]] = ed
312 if ed is not None: 307 if ed is not None:
313 ed.zoomTo(editorDict["Zoom"]) 308 ed.zoomTo(editorDict["Zoom"])
314 if editorDict["Folds"]: 309 if editorDict["Folds"]:
315 ed.recolor() 310 ed.recolor()
316 ed.setContractedFolds(editorDict["Folds"]) 311 ed.setContractedFolds(editorDict["Folds"])
317 ed.setCursorPosition(*editorDict["Cursor"]) 312 ed.setCursorPosition(*editorDict["Cursor"])
318 313
319 # step 3: breakpoints 314 # step 3: breakpoints
320 # =================== 315 # ===================
321 bpModel = dbs.getBreakPointModel() 316 bpModel = dbs.getBreakPointModel()
322 bpModel.addBreakPoints(sessionDict["Breakpoints"]) 317 bpModel.addBreakPoints(sessionDict["Breakpoints"])
323 318
324 # step 4: watch expressions 319 # step 4: watch expressions
325 # ========================= 320 # =========================
326 wpModel = dbs.getWatchPointModel() 321 wpModel = dbs.getWatchPointModel()
327 wpModel.addWatchPoints(sessionDict["Watchpoints"]) 322 wpModel.addWatchPoints(sessionDict["Watchpoints"])
328 323
329 # step 5: debug info 324 # step 5: debug info
330 # ================== 325 # ==================
331 debugInfoDict = sessionDict["DebugInfo"] 326 debugInfoDict = sessionDict["DebugInfo"]
332 327
333 # adjust for newer session types 328 # adjust for newer session types
334 if "GlobalConfigOverride" not in debugInfoDict: 329 if "GlobalConfigOverride" not in debugInfoDict:
335 debugInfoDict["GlobalConfigOverride"] = { 330 debugInfoDict["GlobalConfigOverride"] = {
336 "enable": False, 331 "enable": False,
337 "redirect": True, 332 "redirect": True,
338 } 333 }
339 334
340 dbg.lastUsedVenvName = debugInfoDict["VirtualEnv"] 335 dbg.lastUsedVenvName = debugInfoDict["VirtualEnv"]
341 with contextlib.suppress(KeyError): 336 with contextlib.suppress(KeyError):
342 dbg.setScriptsHistory(debugInfoDict["ScriptName"]) 337 dbg.setScriptsHistory(debugInfoDict["ScriptName"])
343 dbg.setArgvHistory(debugInfoDict["CommandLine"]) 338 dbg.setArgvHistory(debugInfoDict["CommandLine"])
344 dbg.setWdHistory(debugInfoDict["WorkingDirectory"]) 339 dbg.setWdHistory(debugInfoDict["WorkingDirectory"])
349 dbg.setAutoClearShell(debugInfoDict["AutoClearShell"]) 344 dbg.setAutoClearShell(debugInfoDict["AutoClearShell"])
350 dbg.setTracePython(debugInfoDict["TracePython"]) 345 dbg.setTracePython(debugInfoDict["TracePython"])
351 dbg.setAutoContinue(debugInfoDict["AutoContinue"]) 346 dbg.setAutoContinue(debugInfoDict["AutoContinue"])
352 dbg.setEnableMultiprocess(debugInfoDict["EnableMultiprocess"]) 347 dbg.setEnableMultiprocess(debugInfoDict["EnableMultiprocess"])
353 dbg.setMultiprocessNoDebugHistory(debugInfoDict["MultiprocessNoDebug"]) 348 dbg.setMultiprocessNoDebugHistory(debugInfoDict["MultiprocessNoDebug"])
354 dbg.setEnableGlobalConfigOverride( 349 dbg.setEnableGlobalConfigOverride(debugInfoDict["GlobalConfigOverride"])
355 debugInfoDict["GlobalConfigOverride"])
356 if not self.__isGlobal: 350 if not self.__isGlobal:
357 project.setDbgInfo( 351 project.setDbgInfo(
358 debugInfoDict["VirtualEnv"], 352 debugInfoDict["VirtualEnv"],
359 debugInfoDict["CommandLine"], 353 debugInfoDict["CommandLine"],
360 debugInfoDict["WorkingDirectory"], 354 debugInfoDict["WorkingDirectory"],
367 debugInfoDict["AutoContinue"], 361 debugInfoDict["AutoContinue"],
368 debugInfoDict["EnableMultiprocess"], 362 debugInfoDict["EnableMultiprocess"],
369 debugInfoDict["MultiprocessNoDebug"], 363 debugInfoDict["MultiprocessNoDebug"],
370 debugInfoDict["GlobalConfigOverride"], 364 debugInfoDict["GlobalConfigOverride"],
371 ) 365 )
372 366
373 # step 6: bookmarks 367 # step 6: bookmarks
374 # ================= 368 # =================
375 for bookmark in sessionDict["Bookmarks"]: 369 for bookmark in sessionDict["Bookmarks"]:
376 editor = vm.getOpenEditor(bookmark["Filename"]) 370 editor = vm.getOpenEditor(bookmark["Filename"])
377 if editor is not None: 371 if editor is not None:
378 for lineno in bookmark["Lines"]: 372 for lineno in bookmark["Lines"]:
379 editor.toggleBookmark(lineno) 373 editor.toggleBookmark(lineno)
380 374
381 # step 7: state of the various project browsers 375 # step 7: state of the various project browsers
382 # ============================================= 376 # =============================================
383 for browserState in sessionDict["ProjectBrowserStates"]: 377 for browserState in sessionDict["ProjectBrowserStates"]:
384 browser = projectBrowser.getProjectBrowser(browserState["Name"]) 378 browser = projectBrowser.getProjectBrowser(browserState["Name"])
385 if browser is not None: 379 if browser is not None:
386 browser.expandItemsByName(browserState["ExpandedItems"]) 380 browser.expandItemsByName(browserState["ExpandedItems"])
387 381
388 # step 8: active window 382 # step 8: active window
389 # ===================== 383 # =====================
390 if sessionDict["ActiveWindow"]: 384 if sessionDict["ActiveWindow"]:
391 vm.openFiles(sessionDict["ActiveWindow"]["Filename"]) 385 vm.openFiles(sessionDict["ActiveWindow"]["Filename"])
392 ed = vm.getOpenEditor(sessionDict["ActiveWindow"]["Filename"]) 386 ed = vm.getOpenEditor(sessionDict["ActiveWindow"]["Filename"])
393 if ed is not None: 387 if ed is not None:
394 ed.setCursorPosition(*sessionDict["ActiveWindow"]["Cursor"]) 388 ed.setCursorPosition(*sessionDict["ActiveWindow"]["Cursor"])
395 ed.ensureCursorVisible() 389 ed.ensureCursorVisible()
396 390
397 return True 391 return True

eric ide

mercurial