/[ascend]/branches/python3/pygtk/moduleview.py
ViewVC logotype

Contents of /branches/python3/pygtk/moduleview.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3506 - (show annotations) (download) (as text)
Wed Mar 8 23:02:10 2023 UTC (6 months, 2 weeks ago) by jpye
File MIME type: text/x-python
File size: 8550 byte(s)
solving ascxx compile issues in MSYS2 (maybe breaks other things)

1 import gi
2 gi.require_version('GtkSource','3.0')
3 from gi.repository import Gtk, GtkSource, GObject
4 from gi.repository import Pango
5 import ascpy
6 #import gtksourceview2 as gtksourceview
7 import os
8
9 class ModuleView:
10 def __init__(self,browser,builder, library):
11 """Set up the 'modules' tab, set up column types."""
12
13 self.browser = browser
14 self.builder = builder
15 self.library = library
16 self.moduleview = builder.get_object('moduleview')
17
18 modulestorecoltypes = [str, str, int] # bool=can-be-instantiated
19 self.modulestore = Gtk.TreeStore(*modulestorecoltypes)
20 moduleviewtitles = ["Module name", "Filename"]
21 self.moduleview.set_model(self.modulestore)
22 self.modcols = [ Gtk.TreeViewColumn() for _type in modulestorecoltypes]
23 i = 0
24 for modcol in self.modcols[:len(moduleviewtitles)]:
25 modcol.set_title(moduleviewtitles[i])
26 self.moduleview.append_column(modcol)
27 _renderer = Gtk.CellRendererText()
28 modcol.pack_start(_renderer, True)
29 modcol.add_attribute(_renderer, 'text', i)
30 modcol.add_attribute(_renderer,'weight',2)
31 i = i + 1
32 self.moduleview.connect("row-activated", self.module_activated )
33 self.moduleview.connect("button-press-event", self.on_treeview_event)
34 self.modtank = {}
35
36 self.browser.builder.add_objects_from_file(self.browser.glade_file, ["modulemenu"])
37 self.modulemenu = self.browser.builder.get_object("modulemenu")
38 self.viewmenuitem = self.browser.builder.get_object("view")
39 self.viewmenuitem.connect("activate",self.view_activate)
40 self.modelname = None
41 self.modulename = None
42 self.moduleview.get_selection().set_mode(Gtk.SelectionMode.SINGLE)
43
44 def refresh(self, library):
45 """Repopulate the 'modules' tab with the current (new) contents of the 'library'."""
46
47 self.modtank = {}
48 self.modulestore.clear()
49 self.library = library
50 modules = library.getModules()
51 try:
52 _lll=len(modules)
53 except:
54 _msg = "UNABLE TO ACCESS MODULES LIST. This is bad.\n"+\
55 "Check your SWIG configuration (check for warnings during build)."
56
57 self.browser.reporter.reportError(_msg)
58 raise RuntimeError(_msg)
59
60 firstpath = None
61 for m in reversed(modules):
62 _n = str( m.getName() )
63 _f = str( m.getFilename() )
64 #print "ADDING ROW name %s, file = %s" % (_n, _f)
65 _r = self.modulestore.append(None, [ _n, _f, Pango.Weight.NORMAL ])
66
67 if firstpath is None:
68 firstpath = self.modulestore.get_path(_r)
69
70 for t in library.getModuleTypes(m):
71 _n = str(t.getName())
72 if t.isModel() and not t.hasParameters():
73 _w = Pango.Weight.BOLD
74 else:
75 _w = Pango.Weight.NORMAL
76
77 #print "ADDING TYPE %s" % _n
78 _piter = self.modulestore.append(_r , [ _n, "", _w ])
79 _path = self.modulestore.get_path(_piter)
80 self.modtank[_path.to_string()]=t
81
82 # open up the top-level module (ie the one we just openened)
83 if firstpath is not None:
84 #print "EXPANDING PATH",firstpath
85 self.moduleview.expand_row(firstpath,False)
86
87 #print "DONE ADDING MODULES"
88
89 def module_activated(self, treeview, path, column, *args):
90 """You can't currently double-click a module to open it, but that is
91 something we might allow in the future."""
92
93 modules = self.library.getModules()
94 if len(path.to_string())==1:
95 if self.moduleview.row_expanded(path):
96 self.moduleview.collapse_row(path)
97 else:
98 self.moduleview.expand_row(path,False)
99 #self.browser.reporter.reportNote("Launching of external editor not yet implemented")
100 elif len(path.to_string())>=3:
101 if path.to_string() in self.modtank:
102 _type = self.modtank[path.to_string()];
103 if not _type.isModel():
104 self.browser.reporter.reportError("Can't create simulation for type '%s': not a MODEL type" % str(_type.getName()))
105 return
106 if _type.hasParameters():
107 self.browser.reporter.reportError("Can't create simulation for MODEL '%s': requires parameters" % str(_type.getName()))
108 return
109 self.browser.reporter.reportNote("Creating simulation for type '%s'" % str(_type.getName()) )
110 self.browser.do_sim(_type)
111 else:
112 self.browser.reporter.reportError("Didn't find type corresponding to row")
113
114 def on_treeview_event(self,widget,event):
115 _x = int(event.x)
116 _y = int(event.y)
117 _button = event.button
118 _pthinfo = self.moduleview.get_path_at_pos(_x, _y)
119 if _pthinfo is not None:
120 _path, _col, _cellx, _celly = _pthinfo
121 else:
122 return
123 #self.moduleview.grab_focus()
124 self.moduleview.set_cursor(_path,_col,0)
125 if event.button == 3:
126 x = widget.get_selection()
127 y = x.get_selected()
128 if len(y[0].get_path(y[1]).to_string())==1:
129 self.modulename=y[0].get_value(y[1],0)
130 self.modelname=None
131 elif len(y[0].get_path(y[1]).to_string())==3:
132 self.modelname = y[0].get_value(y[1],0)
133 self.modulename = None
134 self.viewmenuitem.set_sensitive(True)
135 self.modulemenu.popup(None,None,None,None,3,event.time)
136
137 def view_activate(self,widget,*args):
138 filename=''
139 if self.modulename:
140 x = ascpy.Library()
141 # TODO is this the fastest way??
142 for module in x.getModules():
143 if module.getName()==self.modulename:
144 fn=module.getFilename()
145 break
146 # FIXME what if module not found??
147 ViewModel(filename=fn,title="Module '%s'" % (self.modulename))
148 elif self.modelname:
149 x = ascpy.Library()
150 for module in x.getModules():
151 for model in x.getModuleTypes(module):
152 if str(model)==self.modelname:
153 filename=module.getFilename()
154 if not filename:
155 return
156 displaytext=[]
157 typelist = ['MODEL','DEFINITION','ATOM']
158 proceed = False
159 flagvariable = False
160 module = open(filename,"r")
161 if module:
162 lines = module.readlines()
163 for line in lines:
164 words = line.split()
165 for i in range(len(words)):
166 if words[i] in typelist:
167 if i!= len(words)-1:
168 if words[i+1].split(';')[0]==self.modelname or words[i+1].split('(')[0]==self.modelname:
169 proceed = True
170 elif words[i]=='END':
171 if words[i+1].split(';')[0]==self.modelname or words[i+1].split('(')[0]==self.modelname:
172 flagvariable = True
173 if proceed == True:
174 displaytext.append(line)
175 proceed = False
176 break
177 if proceed == True:
178 displaytext.append(line)
179 break
180 if flagvariable==True:
181 break
182 ViewModel(text=''.join(displaytext),title="Model '%s'" % (self.modelname))
183
184 def clear(self):
185 self.modulestore.clear()
186
187 class ViewModel:
188 """
189 A window to display the content of an ASCEND model in syntax-highlighted text
190 NOTE: syntax highlighting as implemented here requires the gtksourceview-3.0
191 syntax file to be installed in /usr/share/gtksourceview-3.0/language-specs,
192 which requires install-time configuration.
193 """
194 #TODO Enable Model Editing (REALLY? That would be complicated -- JP)
195
196 def __init__(self, filename=None, text=None, title="View"):
197 # Defining the main window
198 window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
199 window.set_resizable(True)
200 window.connect("destroy", self.close_window, window)
201 window.set_title(title)
202 window.set_border_width(0)
203 window.set_position(Gtk.WindowPosition.CENTER)
204 window.set_size_request(600,400)
205
206 #Creating a vertical box
207 box = Gtk.VBox(False, 10)
208 box.set_border_width(10)
209 window.add(box)
210 box.show()
211
212 #Get the ASCEND language
213 GObject.type_register(GtkSource.View)
214 mgr = GtkSource.LanguageManager.get_default()
215 op = mgr.get_search_path()
216 if os.path.join('..','tools','gtksourceview-3.0') not in op:
217 op.append(os.path.join('..','tools','gtksourceview-3.0'))
218 mgr.set_search_path(op)
219 lang = mgr.get_language('ascend')
220
221 # TODO add status bar where this message can be reported?
222 if lang is None:
223 print("UNABLE TO LOCATE ASCEND LANGUAGE DESCRIPTION for gtksourceview")
224
225 #Creating a ScrolledWindow for the textview widget
226 scroll = Gtk.ScrolledWindow()
227 scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
228 view = GtkSource.View()
229 view.set_editable(False)
230 buff = GtkSource.Buffer()
231 buff.set_language(lang)
232 buff.set_highlight_syntax(True)
233 view.set_buffer(buff)
234 scroll.add(view)
235
236 scroll.show()
237 view.show()
238 box.pack_start(scroll, True, True, 0)
239
240 if filename is not None:
241 #Get the content of the file
242 model = open(filename, "r")
243 if model:
244 string = model.read()
245 model.close()
246 buff.set_text(string)
247 else:
248 self.reporter.reportError( "Error opening the file" )
249 elif text is not None:
250 buff.set_text(text)
251 else:
252 buff.set_text("Nothing was selected")
253
254 window.show()
255
256 def close_window(self, widget, *data):
257 data[0].hide()
258
259 # vim: ts=4:sw=4:noet

john.pye@anu.edu.au
ViewVC Help
Powered by ViewVC 1.1.22