921f976971155fe1abec46020a990b5504ed0660
[idea/community.git] / python / educational-core / course-creator / src / com / jetbrains / edu / coursecreator / CCStudyActionListener.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.StudyActionListener;
11 import com.jetbrains.edu.learning.StudyUtils;
12 import com.jetbrains.edu.learning.core.EduUtils;
13 import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder;
14 import com.jetbrains.edu.learning.courseFormat.Task;
15 import com.jetbrains.edu.learning.courseFormat.TaskFile;
16
17 import java.util.Map;
18
19 public class CCStudyActionListener implements StudyActionListener {
20   @Override
21   public void beforeCheck(AnActionEvent event) {
22     Project project = event.getProject();
23     if (project == null) {
24       return;
25     }
26     VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(event.getDataContext());
27     if (virtualFile == null) {
28       return;
29     }
30
31     TaskFile taskFile = StudyUtils.getTaskFile(project, virtualFile);
32     if (taskFile == null) {
33       return;
34     }
35
36     Task task = taskFile.getTask();
37     VirtualFile taskDir = StudyUtils.getTaskDir(virtualFile);
38     if (taskDir == null) {
39       return;
40     }
41     Map<String, TaskFile> files = task.getTaskFiles();
42     for (Map.Entry<String, TaskFile> entry : files.entrySet()) {
43       String name = entry.getKey();
44       VirtualFile child = taskDir.findChild(name);
45       if (child == null) {
46         continue;
47       }
48       Document patternDocument = StudyUtils.getPatternDocument(entry.getValue(), name);
49       Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
50       if (document == null || patternDocument == null) {
51         return;
52       }
53       DocumentUtil.writeInRunUndoTransparentAction(() -> {
54         patternDocument.replaceString(0, patternDocument.getTextLength(), document.getCharsSequence());
55         FileDocumentManager.getInstance().saveDocument(patternDocument);
56       });
57       TaskFile target = new TaskFile();
58       TaskFile.copy(taskFile, target);
59       for (AnswerPlaceholder placeholder : target.getAnswerPlaceholders()) {
60         placeholder.setUseLength(false);
61       }
62       EduUtils.createStudentDocument(project, target, child, patternDocument);
63     }
64   }
65 }