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

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

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