Annotation of modules/damieng/graphical_editor/loncapa_daxe/web/loncapa_daxe.dart, revision 1.2

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>