commit changes to pattern document before study check action
[idea/community.git] / python / educational-core / course-creator / src / com / jetbrains / edu / coursecreator / CCStudyCheckActionListener.java
1 package com.jetbrains.edu.coursecreator;
2
3 import com.intellij.openapi.actionSystem.AnActionEvent;
4 import com.intellij.openapi.actionSystem.CommonDataKeys;
5 import com.intellij.openapi.editor.Document;
6 import com.intellij.openapi.fileEditor.FileDocumentManager;
7 import com.intellij.openapi.project.Project;
8 import com.intellij.openapi.vfs.VirtualFile;
9 import com.intellij.util.DocumentUtil;
10 import com.jetbrains.edu.learning.StudyCheckActionListener;
11 import com.jetbrains.edu.learning.StudyUtils;
12 import com.jetbrains.edu.learning.courseFormat.Task;
13 import com.jetbrains.edu.learning.courseFormat.TaskFile;
14
15 import java.util.Map;
16
17 public class CCStudyCheckActionListener implements StudyCheckActionListener {
18   @Override
19   public void beforeCheck(AnActionEvent event) {
20     Project project = event.getProject();
21     if (project == null) {
22       return;
23     }
24     VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(event.getDataContext());
25     if (virtualFile == null) {
26       return;
27     }
28
29     TaskFile taskFile = StudyUtils.getTaskFile(project, virtualFile);
30     if (taskFile == null) {
31       return;
32     }
33
34     Task task = taskFile.getTask();
35     VirtualFile taskDir = StudyUtils.getTaskDir(virtualFile);
36     if (taskDir == null) {
37       return;
38     }
39     Map<String, TaskFile> files = task.getTaskFiles();
40     for (Map.Entry<String, TaskFile> entry : files.entrySet()) {
41       String name = entry.getKey();
42       VirtualFile child = taskDir.findChild(name);
43       if (child == null) {
44         continue;
45       }
46       Document patternDocument = StudyUtils.getPatternDocument(entry.getValue(), name);
47       Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
48       if (document == null || patternDocument == null) {
49         return;
50       }
51       DocumentUtil.writeInRunUndoTransparentAction(() -> {
52         patternDocument.replaceString(0, patternDocument.getTextLength(), document.getCharsSequence());
53         FileDocumentManager.getInstance().saveDocument(patternDocument);
54       });
55     }
56   }
57 }