Annotation of modules/damieng/graphical_editor/loncapa_daxe/web/loncapa_daxe.dart, revision 1.5
1.1 damieng 1: /*
2: This file is part of LON-CAPA.
3:
4: LON-CAPA is free software: you can redistribute it and/or modify
5: it under the terms of the GNU General Public License as published by
6: the Free Software Foundation, either version 3 of the License, or
7: (at your option) any later version.
8:
9: LON-CAPA is distributed in the hope that it will be useful,
10: but WITHOUT ANY WARRANTY; without even the implied warranty of
11: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: GNU General Public License for more details.
13:
14: You should have received a copy of the GNU General Public License
15: along with LON-CAPA. If not, see <http://www.gnu.org/licenses/>.
16: */
17:
18: library loncapa_daxe;
19:
20: import 'dart:async';
21: import 'dart:collection';
22: import 'dart:html' as h;
23: import 'package:daxe/daxe.dart';
24: import 'package:daxe/src/xmldom/xmldom.dart' as x;
25: import 'package:daxe/src/strings.dart';
26: import 'package:daxe/src/nodes/nodes.dart' show DNCData, DNText, SimpleTypeControl, ParentUpdatingDNText;
27: import 'dart:js' as js;
28:
29: import 'lcd_strings.dart';
30: part 'nodes/lcd_block.dart';
31: part 'nodes/lcd_parameter.dart';
32: part 'nodes/tex_mathjax.dart';
33: part 'nodes/lm.dart';
1.2 damieng 34: part 'nodes/numerical_response.dart';
1.3 damieng 35: part 'nodes/formula_response.dart';
36: part 'nodes/string_response.dart';
1.1 damieng 37: part 'nodes/radio_response.dart';
38: part 'nodes/radio_foilgroup.dart';
39: part 'nodes/radio_foil.dart';
40: part 'nodes/option_response.dart';
41: part 'nodes/option_foilgroup.dart';
42: part 'nodes/option_foil.dart';
43: part 'nodes/rank_response.dart';
44: part 'nodes/rank_foilgroup.dart';
45: part 'nodes/rank_foil.dart';
1.5 ! damieng 46: part 'nodes/textline.dart';
1.1 damieng 47: part 'nodes/hintgroup.dart';
48: part 'nodes/simple_ui_text.dart';
49: part 'nodes/script_block.dart';
1.2 damieng 50: part 'nodes/simple_ui_exception.dart';
1.1 damieng 51: part 'lcd_button.dart';
52:
53:
54: void main() {
55: NodeFactory.addCoreDisplayTypes();
56:
57: addDisplayType('lcdblock',
58: (x.Element ref) => new LCDBlock.fromRef(ref),
59: (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
60: );
61:
62: addDisplayType('texmathjax',
63: (x.Element ref) => new TeXMathJax.fromRef(ref),
64: (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
65: );
66:
67: addDisplayType('lm',
68: (x.Element ref) => new Lm.fromRef(ref),
69: (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
70: );
71:
72: addDisplayType('script',
73: (x.Element ref) => new ScriptBlock.fromRef(ref),
74: (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
75: );
76:
77: addDisplayType('parameter',
78: (x.Element ref) => new LCDParameter.fromRef(ref),
79: (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
80: );
81:
1.2 damieng 82: addDisplayType('numericalresponse',
83: (x.Element ref) => new NumericalResponse.fromRef(ref),
84: (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
85: );
86:
1.3 damieng 87: addDisplayType('formularesponse',
88: (x.Element ref) => new FormulaResponse.fromRef(ref),
89: (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
90: );
91:
92: addDisplayType('stringresponse',
93: (x.Element ref) => new StringResponse.fromRef(ref),
94: (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
95: );
96:
1.1 damieng 97: addDisplayType('radioresponse',
98: (x.Element ref) => new RadioResponse.fromRef(ref),
99: (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
100: );
101:
102: addDisplayType('optionresponse',
103: (x.Element ref) => new OptionResponse.fromRef(ref),
104: (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
105: );
106:
107: addDisplayType('rankresponse',
108: (x.Element ref) => new RankResponse.fromRef(ref),
109: (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
110: );
111:
112: addDisplayType('foilgroup',
113: (x.Element ref) {
114: if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
115: return new RadioFoilgroup.fromRef(ref);
116: else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
117: return new OptionFoilgroup.fromRef(ref);
118: else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
119: return new RankFoilgroup.fromRef(ref);
120: return new LCDBlock.fromRef(ref);
121: },
122: (x.Node node, DaxeNode parent) {
123: if (parent is RadioResponse)
124: return new RadioFoilgroup.fromNode(node, parent);
125: else if (parent is OptionResponse)
126: return new OptionFoilgroup.fromNode(node, parent);
127: else if (parent is RankResponse)
128: return new RankFoilgroup.fromNode(node, parent);
129: return new LCDBlock.fromNode(node, parent);
130: }
131: );
132:
133: addDisplayType('foil',
134: (x.Element ref) {
135: if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
136: return new RadioFoil.fromRef(ref);
137: else if (ref.getAttribute('type') == 'optionresponse--foil')
138: return new OptionFoil.fromRef(ref);
139: else if (ref.getAttribute('type') == 'rankresponse--foil')
140: return new RankFoil.fromRef(ref);
141: return new LCDBlock.fromRef(ref);
142: },
143: (x.Node node, DaxeNode parent) {
144: if (parent is RadioFoilgroup)
145: return new RadioFoil.fromNode(node, parent);
146: else if (parent is OptionFoilgroup)
147: return new OptionFoil.fromNode(node, parent);
148: else if (parent is RankFoilgroup)
149: return new RankFoil.fromNode(node, parent);
150: return new LCDBlock.fromNode(node, parent);
151: }
152: );
153:
1.5 ! damieng 154: addDisplayType('textline',
! 155: (x.Element ref) => new Textline.fromRef(ref),
! 156: (x.Node node, DaxeNode parent) => new Textline.fromNode(node, parent)
! 157: );
! 158:
1.1 damieng 159: addDisplayType('hintgroup',
160: (x.Element ref) => new Hintgroup.fromRef(ref),
161: (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
162: );
163:
164: Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
165: _init_daxe().then((v) {
166: // add things to the toolbar
167: ToolbarMenu sectionMenu = _makeSectionMenu();
168: if (sectionMenu != null)
169: page.toolbar.add(sectionMenu);
170: x.Element texRef = doc.cfg.elementReference('m');
171: if (texRef != null) {
172: ToolbarBox insertBox = new ToolbarBox();
173: ToolbarButton texButton = new ToolbarButton(
174: LCDStrings.get('tex_equation'), 'images/tex.png',
175: () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate,
176: data:new ToolbarStyleInfo([texRef], null, null));
177: insertBox.add(texButton);
178: page.toolbar.add(insertBox);
179: }
180: h.Element tbh = h.querySelector('.toolbar');
181: tbh.replaceWith(page.toolbar.html());
182: page.adjustPositionsUnderToolbar();
183: page.updateAfterPathChange();
184: // add things to the menubar
185: if (responses[2] is x.Document) {
186: // at this point the menubar html is already in the document, so we have to fix the HTML
187: h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
1.4 damieng 188: if (doc.filePath != null && doc.filePath.indexOf('&url=') != -1) { // otherwise we are not on LON-CAPA
1.1 damieng 189: MenuItem item = new MenuItem(Strings.get('menu.save'), () => save(), shortcut: 'S');
190: Menu fileMenu = page.mbar.menus[0];
191: fileMenu.add(item);
192: menubarDiv.firstChild.replaceWith(page.mbar.createMenuDiv(fileMenu));
193: }
194: Menu m = _makeTemplatesMenu(responses[2]);
195: page.mbar.add(m);
196: menubarDiv.append(page.mbar.createMenuDiv(m));
197: page.updateAfterPathChange();
198: } else
199: print("Error reading templates file, could not build the menu.");
200: });
201: });
202: }
203:
204: Future _init_daxe() {
205: Completer completer = new Completer();
206: doc = new DaxeDocument();
207: page = new WebPage();
208:
209: // check parameters for a config and file to open
210: String file = null;
211: String config = null;
212: String saveURL = null;
213: h.Location location = h.window.location;
214: String search = location.search;
215: if (search.startsWith('?'))
216: search = search.substring(1);
217: List<String> parameters = search.split('&');
218: for (String param in parameters) {
219: List<String> lparam = param.split('=');
220: if (lparam.length != 2)
221: continue;
222: if (lparam[0] == 'config')
223: config = lparam[1];
224: else if (lparam[0] == 'file')
225: file = Uri.decodeComponent(lparam[1]);
226: else if (lparam[0] == 'save')
227: saveURL = lparam[1];
228: }
229: if (saveURL != null)
230: doc.saveURL = saveURL;
231: if (config != null && file != null)
232: page.openDocument(file, config).then((v) => completer.complete());
233: else if (config != null)
234: page.newDocument(config).then((v) => completer.complete());
235: else {
236: h.window.alert(Strings.get('daxe.missing_config'));
237: completer.completeError(Strings.get('daxe.missing_config'));
238: }
239: return(completer.future);
240: }
241:
242: void save() {
243: saveOnLONCAPA().then((_) {
244: h.window.alert(Strings.get('save.success'));
245: }, onError: (DaxeException ex) {
246: h.window.alert(Strings.get('save.error') + ': ' + ex.message);
247: });
248: }
249:
250: /**
251: * Send the document with a POST request to LON-CAPA.
252: */
253: Future saveOnLONCAPA() {
254: int ind = doc.filePath.indexOf('&url=');
255: if (ind == -1)
256: return(new Future.error(new DaxeException('bad URL')));
257: String path = doc.filePath.substring(ind+5);
258: path = Uri.decodeQueryComponent(path);
259: ind = path.lastIndexOf('/');
260: String filename;
261: if (ind == -1)
262: filename = path;
263: else {
264: filename = path.substring(ind+1);
265: path = path.substring(0, ind+1);
266: }
267: Completer completer = new Completer();
268: String bound = 'AaB03x';
269: h.HttpRequest request = new h.HttpRequest();
270: request.onLoad.listen((h.ProgressEvent event) {
271: completer.complete(); // TODO: check for something, status is sometimes wrongly OK
272: });
273: request.onError.listen((h.ProgressEvent event) {
274: completer.completeError(new DaxeException(request.status.toString()));
275: });
276: request.open('POST', '/upload_file');
277: request.setRequestHeader('Content-Type', "multipart/form-data; boundary=$bound");
278:
279: StringBuffer sb = new StringBuffer();
280: sb.write("--$bound\r\n");
281: sb.write('Content-Disposition: form-data; name="uploads_path"\r\n');
282: sb.write('Content-type: text/plain; charset=UTF-8\r\n');
283: sb.write('Content-transfer-encoding: 8bit\r\n\r\n');
284: sb.write(path);
285: sb.write("\r\n--$bound\r\n");
286: sb.write('Content-Disposition: form-data; name="uploads"; filename="$filename"\r\n');
287: sb.write('Content-Type: application/octet-stream\r\n\r\n');
288: doc.dndoc.xmlEncoding = 'UTF-8'; // the document is forced to use UTF-8
289: sb.write(doc.toString());
290: sb.write('\r\n--$bound--\r\n\r\n');
291: request.send(sb.toString());
292: return(completer.future);
293: }
294:
295: ToolbarMenu _makeSectionMenu() {
296: Menu menu = new Menu(LCDStrings.get('Section'));
297: List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
298: if (sectionRefs == null || sectionRefs.length == 0)
299: return(null);
300: x.Element h1Ref = doc.cfg.elementReference('h1');
301: for (String role in ['introduction', 'conclusion', 'prerequisites', 'objectives',
302: 'reminder', 'definition', 'demonstration', 'example', 'advise',
303: 'remark', 'warning', 'more_information', 'method',
304: 'activity', 'bibliography', 'citation']) {
305: MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
306: data:new ToolbarStyleInfo(sectionRefs, null, null));
307: menuItem.action = () {
308: ToolbarStyleInfo info = menuItem.data;
309: x.Element sectionRef = info.validRef;
310: LCDBlock section = NodeFactory.create(sectionRef);
311: section.state = 1;
312: section.setAttribute('class', 'role-' + role);
313: LCDBlock h1 = NodeFactory.create(h1Ref);
314: h1.state = 1;
315: if (doc.insert2(section, page.getSelectionStart())) {
316: doc.insertNode(h1, new Position(section, 0));
317: page.cursor.moveTo(new Position(h1, 0));
318: page.updateAfterPathChange();
319: }
320: };
321: menu.add(menuItem);
322: }
323: ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
324: return(tbmenu);
325: }
326:
327: Future<x.Document> _readTemplates(String templatesPath) {
328: x.DOMParser dp = new x.DOMParser();
329: return(dp.parseFromURL(templatesPath));
330: }
331:
332: Menu _makeTemplatesMenu(x.Document templatesDoc) {
333: Menu menu = new Menu(LCDStrings.get('Templates'));
334: x.Element templates = templatesDoc.documentElement;
335: for (x.Node child in templates.childNodes) {
336: if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
337: menu.add(_makeMenu(child));
338: }
339: }
340: return(menu);
341: }
342:
343: Menu _makeMenu(x.Element el) {
344: String locale = LCDStrings.systemLocale;
345: String defaultLocale = LCDStrings.defaultLocale;
346: String title;
347: for (x.Node child in el.childNodes) {
348: if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
349: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
350: if ((child as x.Element).getAttribute('lang') == locale) {
351: title = child.firstChild.nodeValue;
352: break;
353: } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
354: title = child.firstChild.nodeValue;
355: }
356: }
357: }
358: }
359: if (title == null)
360: title = '?';
361: Menu menu = new Menu(title);
362: for (x.Node child in el.childNodes) {
363: if (child.nodeType == x.Node.ELEMENT_NODE) {
364: if (child.nodeName == 'menu') {
365: menu.add(_makeMenu(child));
366: } else if (child.nodeName == 'item') {
367: menu.add(_makeItem(child));
368: }
369: }
370: }
371: return(menu);
372: }
373:
374: MenuItem _makeItem(x.Element item) {
375: String locale = LCDStrings.systemLocale;
376: String defaultLocale = LCDStrings.defaultLocale;
377: String path, type, title, help;
378: for (x.Node child in item.childNodes) {
379: if (child.nodeType == x.Node.ELEMENT_NODE) {
380: if (child.nodeName == 'title') {
381: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
382: if ((child as x.Element).getAttribute('lang') == locale) {
383: title = child.firstChild.nodeValue;
384: } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
385: title = child.firstChild.nodeValue;
386: }
387: }
388: } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
389: path = child.firstChild.nodeValue;
390: } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
391: type = child.firstChild.nodeValue;
392: } else if (child.nodeName == 'help') {
393: if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
394: if ((child as x.Element).getAttribute('lang') == locale) {
395: help = child.firstChild.nodeValue;
396: } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
397: help = child.firstChild.nodeValue;
398: }
399: }
400: }
401: }
402: }
403: if (type == null) {
404: print("Warning: missing type for template $title\n");
405: type = 'problem';
406: }
407: x.Element refElement = doc.cfg.elementReference(type);
408: MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
409: if (help != null)
410: menuItem.toolTipText = help;
411: return menuItem;
412: }
413:
414: void _insertTemplate(String filePath) {
415: try {
416: x.DOMParser dp = new x.DOMParser();
417: dp.parseFromURL(filePath).then((x.Document templateDoc) {
418: x.Element root = templateDoc.documentElement;
419: if (root == null)
420: return;
421: doc.removeWhitespace(root);
422: DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
423: UndoableEdit edit;
424: Position pos = page.getSelectionStart();
425: if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
426: edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
427: else
428: edit = new UndoableEdit.insertNode(pos, dnRoot);
429: doc.doNewEdit(edit);
430: page.updateAfterPathChange();
431: });
432: } on x.DOMException catch(ex) {
433: h.window.alert(ex.toString());
434: }
435: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>