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

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';
1.14      damieng    26: import 'package:daxe/src/nodes/nodes.dart' show DNCData, DNText, SimpleTypeControl, ParentUpdatingDNText, DNHiddenP, DNString;
1.1       damieng    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.14      damieng    34: part 'nodes/chem.dart';
1.2       damieng    35: part 'nodes/numerical_response.dart';
1.3       damieng    36: part 'nodes/formula_response.dart';
                     37: part 'nodes/string_response.dart';
1.11      damieng    38: part 'nodes/essay_response.dart';
                     39: part 'nodes/textfield.dart';
1.1       damieng    40: part 'nodes/radio_response.dart';
                     41: part 'nodes/radio_foilgroup.dart';
                     42: part 'nodes/radio_foil.dart';
                     43: part 'nodes/option_response.dart';
                     44: part 'nodes/option_foilgroup.dart';
                     45: part 'nodes/option_foil.dart';
1.6       damieng    46: part 'nodes/match_response.dart';
                     47: part 'nodes/match_foilgroup.dart';
                     48: part 'nodes/match_foil.dart';
                     49: part 'nodes/itemgroup.dart';
                     50: part 'nodes/match_item.dart';
1.1       damieng    51: part 'nodes/rank_response.dart';
                     52: part 'nodes/rank_foilgroup.dart';
                     53: part 'nodes/rank_foil.dart';
1.10      damieng    54: part 'nodes/math_response.dart';
                     55: part 'nodes/math_answer.dart';
1.13      damieng    56: part 'nodes/organic_response.dart';
                     57: part 'nodes/jsme_dialog.dart';
                     58: part 'nodes/reaction_response.dart';
1.5       damieng    59: part 'nodes/textline.dart';
1.1       damieng    60: part 'nodes/hintgroup.dart';
                     61: part 'nodes/simple_ui_text.dart';
                     62: part 'nodes/script_block.dart';
1.2       damieng    63: part 'nodes/simple_ui_exception.dart';
1.7       damieng    64: part 'nodes/gnuplot.dart';
                     65: part 'nodes/fake_attribute_element.dart';
                     66: part 'nodes/plot_axis.dart';
                     67: part 'nodes/plot_curve.dart';
1.1       damieng    68: part 'lcd_button.dart';
                     69: 
                     70: 
                     71: void main() {
                     72:   NodeFactory.addCoreDisplayTypes();
                     73:   
                     74:   addDisplayType('lcdblock',
                     75:         (x.Element ref) => new LCDBlock.fromRef(ref),
                     76:         (x.Node node, DaxeNode parent) => new LCDBlock.fromNode(node, parent)
                     77:     );
                     78:   
                     79:   addDisplayType('texmathjax',
                     80:         (x.Element ref) => new TeXMathJax.fromRef(ref),
                     81:         (x.Node node, DaxeNode parent) => new TeXMathJax.fromNode(node, parent)
                     82:     );
                     83:   
                     84:   addDisplayType('lm',
                     85:         (x.Element ref) => new Lm.fromRef(ref),
                     86:         (x.Node node, DaxeNode parent) => new Lm.fromNode(node, parent)
                     87:     );
                     88:   
1.14      damieng    89:   addDisplayType('chem',
                     90:         (x.Element ref) => new Chem.fromRef(ref),
                     91:         (x.Node node, DaxeNode parent) => new Chem.fromNode(node, parent)
                     92:     );
                     93:   
1.1       damieng    94:   addDisplayType('script',
                     95:         (x.Element ref) => new ScriptBlock.fromRef(ref),
                     96:         (x.Node node, DaxeNode parent) => new ScriptBlock.fromNode(node, parent)
                     97:     );
                     98:   
                     99:   addDisplayType('parameter',
                    100:         (x.Element ref) => new LCDParameter.fromRef(ref),
                    101:         (x.Node node, DaxeNode parent) => new LCDParameter.fromNode(node, parent)
                    102:     );
                    103:   
1.2       damieng   104:   addDisplayType('numericalresponse',
                    105:         (x.Element ref) => new NumericalResponse.fromRef(ref),
                    106:         (x.Node node, DaxeNode parent) => new NumericalResponse.fromNode(node, parent)
                    107:     );
                    108:   
1.3       damieng   109:   addDisplayType('formularesponse',
                    110:         (x.Element ref) => new FormulaResponse.fromRef(ref),
                    111:         (x.Node node, DaxeNode parent) => new FormulaResponse.fromNode(node, parent)
                    112:     );
                    113:   
                    114:   addDisplayType('stringresponse',
                    115:         (x.Element ref) => new StringResponse.fromRef(ref),
                    116:         (x.Node node, DaxeNode parent) => new StringResponse.fromNode(node, parent)
                    117:     );
                    118:   
1.11      damieng   119:   addDisplayType('essayresponse',
                    120:         (x.Element ref) => new EssayResponse.fromRef(ref),
                    121:         (x.Node node, DaxeNode parent) => new EssayResponse.fromNode(node, parent)
                    122:     );
                    123:   
1.1       damieng   124:   addDisplayType('radioresponse',
                    125:         (x.Element ref) => new RadioResponse.fromRef(ref),
                    126:         (x.Node node, DaxeNode parent) => new RadioResponse.fromNode(node, parent)
                    127:     );
                    128:   
                    129:   addDisplayType('optionresponse',
                    130:         (x.Element ref) => new OptionResponse.fromRef(ref),
                    131:         (x.Node node, DaxeNode parent) => new OptionResponse.fromNode(node, parent)
                    132:     );
                    133:   
1.6       damieng   134:   addDisplayType('matchresponse',
                    135:         (x.Element ref) => new MatchResponse.fromRef(ref),
                    136:         (x.Node node, DaxeNode parent) => new MatchResponse.fromNode(node, parent)
                    137:     );
                    138:   
1.1       damieng   139:   addDisplayType('rankresponse',
                    140:         (x.Element ref) => new RankResponse.fromRef(ref),
                    141:         (x.Node node, DaxeNode parent) => new RankResponse.fromNode(node, parent)
                    142:     );
                    143:   
1.10      damieng   144:   addDisplayType('mathresponse',
                    145:         (x.Element ref) => new MathResponse.fromRef(ref),
                    146:         (x.Node node, DaxeNode parent) => new MathResponse.fromNode(node, parent)
                    147:     );
                    148:   
1.13      damieng   149:   addDisplayType('organicresponse',
                    150:         (x.Element ref) => new OrganicResponse.fromRef(ref),
                    151:         (x.Node node, DaxeNode parent) => new OrganicResponse.fromNode(node, parent)
                    152:     );
                    153:   
                    154:   addDisplayType('reactionresponse',
                    155:         (x.Element ref) => new ReactionResponse.fromRef(ref),
                    156:         (x.Node node, DaxeNode parent) => new ReactionResponse.fromNode(node, parent)
                    157:     );
                    158:   
1.1       damieng   159:   addDisplayType('foilgroup',
                    160:         (x.Element ref) {
                    161:           if (ref.getAttribute('type') == 'radiobuttonresponse--foilgroup')
                    162:             return new RadioFoilgroup.fromRef(ref);
                    163:           else if (ref.getAttribute('type') == 'optionresponse--foilgroup')
                    164:             return new OptionFoilgroup.fromRef(ref);
1.6       damieng   165:           else if (ref.getAttribute('type') == 'matchresponse--foilgroup')
                    166:             return new MatchFoilgroup.fromRef(ref);
1.1       damieng   167:           else if (ref.getAttribute('type') == 'rankresponse--foilgroup')
                    168:             return new RankFoilgroup.fromRef(ref);
                    169:           return new LCDBlock.fromRef(ref);
                    170:         },
                    171:         (x.Node node, DaxeNode parent) {
                    172:           if (parent is RadioResponse)
                    173:             return new RadioFoilgroup.fromNode(node, parent);
                    174:           else if (parent is OptionResponse)
                    175:             return new OptionFoilgroup.fromNode(node, parent);
1.6       damieng   176:           else if (parent is MatchResponse)
                    177:             return new MatchFoilgroup.fromNode(node, parent);
1.1       damieng   178:           else if (parent is RankResponse)
                    179:             return new RankFoilgroup.fromNode(node, parent);
                    180:           return new LCDBlock.fromNode(node, parent);
                    181:         }
                    182:     );
                    183:   
                    184:   addDisplayType('foil',
                    185:         (x.Element ref) {
                    186:           if (ref.getAttribute('type') == 'radiobuttonresponse--foil')
                    187:             return new RadioFoil.fromRef(ref);
                    188:           else if (ref.getAttribute('type') == 'optionresponse--foil')
                    189:             return new OptionFoil.fromRef(ref);
1.6       damieng   190:           else if (ref.getAttribute('type') == 'matchresponse--foil')
                    191:             return new MatchFoil.fromRef(ref);
1.1       damieng   192:           else if (ref.getAttribute('type') == 'rankresponse--foil')
                    193:             return new RankFoil.fromRef(ref);
                    194:           return new LCDBlock.fromRef(ref);
                    195:         },
                    196:         (x.Node node, DaxeNode parent) {
                    197:           if (parent is RadioFoilgroup)
                    198:             return new RadioFoil.fromNode(node, parent);
                    199:           else if (parent is OptionFoilgroup)
                    200:             return new OptionFoil.fromNode(node, parent);
1.6       damieng   201:           else if (parent is MatchFoilgroup)
                    202:             return new MatchFoil.fromNode(node, parent);
1.1       damieng   203:           else if (parent is RankFoilgroup)
                    204:             return new RankFoil.fromNode(node, parent);
                    205:           return new LCDBlock.fromNode(node, parent);
                    206:         }
                    207:     );
                    208:   
1.6       damieng   209:   addDisplayType('itemgroup',
                    210:         (x.Element ref) => new Itemgroup.fromRef(ref),
                    211:         (x.Node node, DaxeNode parent) => new Itemgroup.fromNode(node, parent)
                    212:     );
                    213:   
                    214:   addDisplayType('matchitem',
                    215:         (x.Element ref) => new MatchItem.fromRef(ref),
                    216:         (x.Node node, DaxeNode parent) => new MatchItem.fromNode(node, parent)
                    217:     );
                    218:   
1.5       damieng   219:   addDisplayType('textline',
                    220:         (x.Element ref) => new Textline.fromRef(ref),
                    221:         (x.Node node, DaxeNode parent) => new Textline.fromNode(node, parent)
                    222:     );
                    223:   
1.11      damieng   224:   addDisplayType('textfield',
                    225:         (x.Element ref) => new Textfield.fromRef(ref),
                    226:         (x.Node node, DaxeNode parent) => new Textfield.fromNode(node, parent)
                    227:     );
                    228:   
1.1       damieng   229:   addDisplayType('hintgroup',
                    230:         (x.Element ref) => new Hintgroup.fromRef(ref),
                    231:         (x.Node node, DaxeNode parent) => new Hintgroup.fromNode(node, parent)
                    232:     );
                    233:   
1.10      damieng   234:   addDisplayType('answer',
                    235:         (x.Element ref) {
                    236:           if (ref.getAttribute('type') == 'mathresponse--answer')
                    237:             return new MathAnswer.fromRef(ref);
                    238:           return new LCDBlock.fromRef(ref);
                    239:         },
                    240:         (x.Node node, DaxeNode parent) {
                    241:           if (parent is MathResponse)
                    242:             return new MathAnswer.fromNode(node, parent);
                    243:           return new LCDBlock.fromNode(node, parent);
                    244:         }
                    245:     );
                    246:   
1.7       damieng   247:   addDisplayType('gnuplot',
                    248:         (x.Element ref) => new Gnuplot.fromRef(ref),
                    249:         (x.Node node, DaxeNode parent) => new Gnuplot.fromNode(node, parent)
                    250:     );
                    251:   
                    252:   addDisplayType('fakeattribute',
                    253:         (x.Element ref) {
                    254:           if (doc.cfg.elementName(ref) != 'title' || ref.getAttribute('type') == 'lonplot--title')
                    255:             return new FakeAttributeElement.fromRef(ref);
                    256:           return new LCDBlock.fromRef(ref);
                    257:         },
                    258:         (x.Node node, DaxeNode parent) {
                    259:           if (parent is Gnuplot || parent is PlotCurve)
                    260:             return new FakeAttributeElement.fromNode(node, parent);
                    261:           return new LCDBlock.fromNode(node, parent);
                    262:         }
                    263:     );
                    264:   
                    265:   addDisplayType('plotaxis',
                    266:         (x.Element ref) => new PlotAxis.fromRef(ref),
                    267:         (x.Node node, DaxeNode parent) => new PlotAxis.fromNode(node, parent)
                    268:     );
                    269:   
                    270:   addDisplayType('plotcurve',
                    271:         (x.Element ref) => new PlotCurve.fromRef(ref),
                    272:         (x.Node node, DaxeNode parent) => new PlotCurve.fromNode(node, parent)
                    273:     );
                    274:   
1.1       damieng   275:   Future.wait([Strings.load(), LCDStrings.load(), _readTemplates('templates.xml')]).then((List responses) {
                    276:     _init_daxe().then((v) {
                    277:       // add things to the toolbar
                    278:       ToolbarMenu sectionMenu = _makeSectionMenu();
                    279:       if (sectionMenu != null)
                    280:         page.toolbar.add(sectionMenu);
                    281:       x.Element texRef = doc.cfg.elementReference('m');
                    282:       if (texRef != null) {
                    283:         ToolbarBox insertBox = new ToolbarBox();
                    284:         ToolbarButton texButton = new ToolbarButton(
                    285:             LCDStrings.get('tex_equation'), 'images/tex.png',
                    286:             () => doc.insertNewNode(texRef, 'element'), Toolbar.insertButtonUpdate, 
                    287:             data:new ToolbarStyleInfo([texRef], null, null));
                    288:         insertBox.add(texButton);
                    289:         page.toolbar.add(insertBox);
                    290:       }
                    291:       h.Element tbh = h.querySelector('.toolbar');
                    292:       tbh.replaceWith(page.toolbar.html());
                    293:       page.adjustPositionsUnderToolbar();
                    294:       page.updateAfterPathChange();
                    295:       // add things to the menubar
                    296:       if (responses[2] is x.Document) {
                    297:         // at this point the menubar html is already in the document, so we have to fix the HTML
                    298:         h.Element menubarDiv = h.document.getElementsByClassName('menubar')[0];
1.4       damieng   299:         if (doc.filePath != null && doc.filePath.indexOf('&url=') != -1) { // otherwise we are not on LON-CAPA
1.1       damieng   300:           MenuItem item = new MenuItem(Strings.get('menu.save'), () => save(), shortcut: 'S');
                    301:           Menu fileMenu = page.mbar.menus[0];
                    302:           fileMenu.add(item);
                    303:           menubarDiv.firstChild.replaceWith(page.mbar.createMenuDiv(fileMenu));
                    304:         }
                    305:         Menu m = _makeTemplatesMenu(responses[2]);
                    306:         page.mbar.add(m);
                    307:         menubarDiv.append(page.mbar.createMenuDiv(m));
                    308:         page.updateAfterPathChange();
                    309:       } else
                    310:         print("Error reading templates file, could not build the menu.");
1.15    ! damieng   311:     }).catchError((e) {
        !           312:       h.document.body.appendText('Initialization error: ' + e);
1.1       damieng   313:     });
1.15    ! damieng   314:   }).catchError((e) {
        !           315:     h.document.body.appendText('Initialization error: ' + e);
1.1       damieng   316:   });
                    317: }
                    318: 
                    319: Future _init_daxe() {
                    320:   Completer completer = new Completer();
                    321:   doc = new DaxeDocument();
                    322:   page = new WebPage();
                    323:   
                    324:   // check parameters for a config and file to open
                    325:   String file = null;
                    326:   String config = null;
                    327:   String saveURL = null;
                    328:   h.Location location = h.window.location;
                    329:   String search = location.search;
                    330:   if (search.startsWith('?'))
                    331:     search = search.substring(1);
                    332:   List<String> parameters = search.split('&');
                    333:   for (String param in parameters) {
                    334:     List<String> lparam = param.split('=');
                    335:     if (lparam.length != 2)
                    336:       continue;
                    337:     if (lparam[0] == 'config')
                    338:       config = lparam[1];
                    339:     else if (lparam[0] == 'file')
                    340:       file = Uri.decodeComponent(lparam[1]);
                    341:     else if (lparam[0] == 'save')
                    342:       saveURL = lparam[1];
                    343:   }
                    344:   if (saveURL != null)
                    345:     doc.saveURL = saveURL;
                    346:   if (config != null && file != null)
                    347:     page.openDocument(file, config).then((v) => completer.complete());
                    348:   else if (config != null)
                    349:     page.newDocument(config).then((v) => completer.complete());
                    350:   else {
                    351:     h.window.alert(Strings.get('daxe.missing_config'));
                    352:     completer.completeError(Strings.get('daxe.missing_config'));
                    353:   }
                    354:   return(completer.future);
                    355: }
                    356: 
                    357: void save() {
                    358:   saveOnLONCAPA().then((_) {
                    359:     h.window.alert(Strings.get('save.success'));
                    360:   }, onError: (DaxeException ex) {
                    361:     h.window.alert(Strings.get('save.error') + ': ' + ex.message);
                    362:   });
                    363: }
                    364: 
                    365: /**
                    366:  * Send the document with a POST request to LON-CAPA.
                    367:  */
                    368: Future saveOnLONCAPA() {
                    369:   int ind = doc.filePath.indexOf('&url=');
                    370:   if (ind == -1)
                    371:     return(new Future.error(new DaxeException('bad URL')));
                    372:   String path = doc.filePath.substring(ind+5);
                    373:   path = Uri.decodeQueryComponent(path);
                    374:   ind = path.lastIndexOf('/');
                    375:   String filename;
                    376:   if (ind == -1)
                    377:     filename = path;
                    378:   else {
                    379:     filename = path.substring(ind+1);
                    380:     path = path.substring(0, ind+1);
                    381:   }
                    382:   Completer completer = new Completer();
                    383:   String bound = 'AaB03x';
                    384:   h.HttpRequest request = new h.HttpRequest();
                    385:   request.onLoad.listen((h.ProgressEvent event) {
                    386:     completer.complete(); // TODO: check for something, status is sometimes wrongly OK
                    387:   });
                    388:   request.onError.listen((h.ProgressEvent event) {
                    389:     completer.completeError(new DaxeException(request.status.toString()));
                    390:   });
                    391:   request.open('POST', '/upload_file');
                    392:   request.setRequestHeader('Content-Type', "multipart/form-data; boundary=$bound");
                    393:   
                    394:   StringBuffer sb = new StringBuffer();
                    395:   sb.write("--$bound\r\n");
                    396:   sb.write('Content-Disposition: form-data; name="uploads_path"\r\n');
                    397:   sb.write('Content-type: text/plain; charset=UTF-8\r\n');
                    398:   sb.write('Content-transfer-encoding: 8bit\r\n\r\n');
                    399:   sb.write(path);
                    400:   sb.write("\r\n--$bound\r\n");
                    401:   sb.write('Content-Disposition: form-data; name="uploads"; filename="$filename"\r\n');
                    402:   sb.write('Content-Type: application/octet-stream\r\n\r\n');
                    403:   doc.dndoc.xmlEncoding = 'UTF-8'; // the document is forced to use UTF-8
                    404:   sb.write(doc.toString());
                    405:   sb.write('\r\n--$bound--\r\n\r\n');
                    406:   request.send(sb.toString());
                    407:   return(completer.future);
                    408: }
                    409: 
                    410: ToolbarMenu _makeSectionMenu() {
                    411:   Menu menu = new Menu(LCDStrings.get('Section'));
                    412:   List<x.Element> sectionRefs = doc.cfg.elementReferences('section');
                    413:   if (sectionRefs == null || sectionRefs.length == 0)
                    414:     return(null);
                    415:   x.Element h1Ref = doc.cfg.elementReference('h1');
                    416:   for (String role in ['introduction', 'conclusion', 'prerequisites', 'objectives',
                    417:                        'reminder', 'definition', 'demonstration', 'example', 'advise',
                    418:                        'remark', 'warning', 'more_information', 'method',
                    419:                        'activity', 'bibliography', 'citation']) {
                    420:     MenuItem menuItem = new MenuItem(LCDStrings.get(role), null,
                    421:         data:new ToolbarStyleInfo(sectionRefs, null, null));
                    422:     menuItem.action = () {
                    423:       ToolbarStyleInfo info = menuItem.data;
                    424:       x.Element sectionRef = info.validRef;
                    425:       LCDBlock section = NodeFactory.create(sectionRef);
                    426:       section.state = 1;
                    427:       section.setAttribute('class', 'role-' + role);
                    428:       LCDBlock h1 = NodeFactory.create(h1Ref);
                    429:       h1.state = 1;
1.9       damieng   430:       section.appendChild(h1);
                    431:       x.Element hiddenp = doc.cfg.findSubElement(sectionRef, doc.hiddenParaRefs);
                    432:       DNHiddenP p = NodeFactory.create(hiddenp);
                    433:       section.appendChild(p);
1.1       damieng   434:       if (doc.insert2(section, page.getSelectionStart())) {
                    435:         page.cursor.moveTo(new Position(h1, 0));
                    436:         page.updateAfterPathChange();
                    437:       }
                    438:     };
                    439:     menu.add(menuItem);
                    440:   }
                    441:   ToolbarMenu tbmenu = new ToolbarMenu(menu, Toolbar.insertMenuUpdate, page.toolbar);
                    442:   return(tbmenu);
                    443: }
                    444: 
                    445: Future<x.Document> _readTemplates(String templatesPath) {
                    446:   x.DOMParser dp = new x.DOMParser();
                    447:   return(dp.parseFromURL(templatesPath));
                    448: }
                    449: 
                    450: Menu _makeTemplatesMenu(x.Document templatesDoc) {
                    451:   Menu menu = new Menu(LCDStrings.get('Templates'));
                    452:   x.Element templates = templatesDoc.documentElement;
                    453:   for (x.Node child in templates.childNodes) {
                    454:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'menu') {
                    455:       menu.add(_makeMenu(child));
                    456:     }
                    457:   }
                    458:   return(menu);
                    459: }
                    460: 
                    461: Menu _makeMenu(x.Element el) {
                    462:   String locale = LCDStrings.systemLocale;
                    463:   String defaultLocale = LCDStrings.defaultLocale;
                    464:   String title;
                    465:   for (x.Node child in el.childNodes) {
                    466:     if (child.nodeType == x.Node.ELEMENT_NODE && child.nodeName == 'title') {
                    467:       if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    468:         if ((child as x.Element).getAttribute('lang') == locale) {
                    469:           title = child.firstChild.nodeValue;
                    470:           break;
                    471:         } else if ((child as x.Element).getAttribute('lang') == defaultLocale) {
                    472:           title = child.firstChild.nodeValue;
                    473:         }
                    474:       }
                    475:     }
                    476:   }
                    477:   if (title == null)
                    478:     title = '?';
                    479:   Menu menu = new Menu(title);
                    480:   for (x.Node child in el.childNodes) {
                    481:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    482:       if (child.nodeName == 'menu') {
                    483:         menu.add(_makeMenu(child));
                    484:       } else if (child.nodeName == 'item') {
                    485:         menu.add(_makeItem(child));
                    486:       }
                    487:     }
                    488:   }
                    489:   return(menu);
                    490: }
                    491: 
                    492: MenuItem _makeItem(x.Element item) {
                    493:   String locale = LCDStrings.systemLocale;
                    494:   String defaultLocale = LCDStrings.defaultLocale;
                    495:   String path, type, title, help;
                    496:   for (x.Node child in item.childNodes) {
                    497:     if (child.nodeType == x.Node.ELEMENT_NODE) {
                    498:       if (child.nodeName == 'title') {
                    499:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    500:           if ((child as x.Element).getAttribute('lang') == locale) {
                    501:             title = child.firstChild.nodeValue;
                    502:           } else if (title == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    503:             title = child.firstChild.nodeValue;
                    504:           }
                    505:         }
                    506:       } else if (child.nodeName == 'path' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    507:         path = child.firstChild.nodeValue;
                    508:       } else if (child.nodeName == 'type' && child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    509:         type = child.firstChild.nodeValue;
                    510:       } else if (child.nodeName == 'help') {
                    511:         if (child.firstChild != null && child.firstChild.nodeType == x.Node.TEXT_NODE) {
                    512:           if ((child as x.Element).getAttribute('lang') == locale) {
                    513:             help = child.firstChild.nodeValue;
                    514:           } else if (help == null && (child as x.Element).getAttribute('lang') == defaultLocale) {
                    515:             help = child.firstChild.nodeValue;
                    516:           }
                    517:         }
                    518:       }
                    519:     }
                    520:   }
                    521:   if (type == null) {
                    522:     print("Warning: missing type for template $title\n");
                    523:     type = 'problem';
                    524:   }
                    525:   x.Element refElement = doc.cfg.elementReference(type);
                    526:   MenuItem menuItem = new MenuItem(title, () => _insertTemplate(path), data: refElement);
                    527:   if (help != null)
                    528:     menuItem.toolTipText = help;
                    529:   return menuItem;
                    530: }
                    531: 
                    532: void _insertTemplate(String filePath) {
                    533:   try {
                    534:     x.DOMParser dp = new x.DOMParser();
                    535:     dp.parseFromURL(filePath).then((x.Document templateDoc) {
                    536:       x.Element root = templateDoc.documentElement;
                    537:       if (root == null)
                    538:         return;
                    539:       doc.removeWhitespace(root);
                    540:       DaxeNode dnRoot = NodeFactory.createFromNode(root, null);
                    541:       UndoableEdit edit;
                    542:       Position pos = page.getSelectionStart();
                    543:       if (dnRoot.nodeName == 'loncapa' && doc.getRootElement() != null)
                    544:         edit = doc.insertChildrenEdit(dnRoot, pos, checkValidity:true);
1.12      damieng   545:       else {
                    546:         DaxeNode parent = pos.dn;
                    547:         if (parent is DNText)
                    548:           parent = parent.parent;
                    549:         if (parent is DNHiddenP && !doc.cfg.isSubElement(parent.ref, dnRoot.ref)) {
                    550:           // The node must be inserted outside of the paragraph.
                    551:           // If there is something in the paragraph to the right of the cursor, it must be
                    552:           // moved into a new paragraph after the inserted node.
                    553:           // (as in DaxeDocument.insert2)
                    554:           DNHiddenP p = parent;
                    555:           edit = new UndoableEdit.compound(Strings.get('undo.insert_element'));
                    556:           Position pend = new Position(p, p.offsetLength);
                    557:           pend.moveInsideTextNodeIfPossible();
                    558:           if (pos < pend) {
                    559:             DaxeNode clone = doc.cloneBetween(pos, pend);
                    560:             edit.addSubEdit(doc.removeBetweenEdit(pos, pend));
                    561:             DNHiddenP newp = NodeFactory.create(p.ref);
                    562:             edit.addSubEdit(new UndoableEdit.insertNode(
                    563:                 new Position(p.parent, p.parent.offsetOf(p) + 1), newp));
                    564:             edit.addSubEdit(doc.insertChildrenEdit(clone, new Position(newp, 0)));
                    565:           }
                    566:           edit.addSubEdit(new UndoableEdit.insertNode(
                    567:               new Position(p.parent, p.parent.offsetOf(p)+1), dnRoot));
                    568:         } else
                    569:           edit = new UndoableEdit.insertNode(pos, dnRoot);
                    570:       }
1.1       damieng   571:       doc.doNewEdit(edit);
                    572:       page.updateAfterPathChange();
1.8       damieng   573:       if (dnRoot.nodeName != 'loncapa')
                    574:         page.scrollToNode(dnRoot);
1.1       damieng   575:     });
                    576:   } on x.DOMException catch(ex) {
                    577:     h.window.alert(ex.toString());
                    578:   }
                    579: }

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