do not show task description for subtasks in project view
[idea/community.git] / python / educational-core / student / src / com / jetbrains / edu / learning / StudyUtils.java
1 package com.jetbrains.edu.learning;
2
3 import com.intellij.execution.RunContentExecutor;
4 import com.intellij.execution.configurations.GeneralCommandLine;
5 import com.intellij.execution.process.ProcessHandler;
6 import com.intellij.lang.Language;
7 import com.intellij.openapi.actionSystem.AnActionEvent;
8 import com.intellij.openapi.actionSystem.CommonDataKeys;
9 import com.intellij.openapi.actionSystem.DataContext;
10 import com.intellij.openapi.actionSystem.Presentation;
11 import com.intellij.openapi.application.ApplicationManager;
12 import com.intellij.openapi.diagnostic.Logger;
13 import com.intellij.openapi.editor.Document;
14 import com.intellij.openapi.editor.Editor;
15 import com.intellij.openapi.editor.RangeMarker;
16 import com.intellij.openapi.editor.actionSystem.EditorActionManager;
17 import com.intellij.openapi.editor.colors.EditorColors;
18 import com.intellij.openapi.editor.colors.EditorColorsManager;
19 import com.intellij.openapi.editor.impl.DocumentImpl;
20 import com.intellij.openapi.fileEditor.FileDocumentManager;
21 import com.intellij.openapi.fileEditor.FileEditor;
22 import com.intellij.openapi.fileEditor.FileEditorManager;
23 import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
24 import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
25 import com.intellij.openapi.progress.ProgressManager;
26 import com.intellij.openapi.project.Project;
27 import com.intellij.openapi.project.ProjectManager;
28 import com.intellij.openapi.projectRoots.Sdk;
29 import com.intellij.openapi.ui.MessageType;
30 import com.intellij.openapi.ui.popup.Balloon;
31 import com.intellij.openapi.ui.popup.JBPopupFactory;
32 import com.intellij.openapi.util.Disposer;
33 import com.intellij.openapi.util.io.FileUtil;
34 import com.intellij.openapi.util.io.FileUtilRt;
35 import com.intellij.openapi.util.text.StringUtil;
36 import com.intellij.openapi.vfs.LocalFileSystem;
37 import com.intellij.openapi.vfs.VfsUtil;
38 import com.intellij.openapi.vfs.VirtualFile;
39 import com.intellij.openapi.wm.IdeFocusManager;
40 import com.intellij.openapi.wm.ToolWindow;
41 import com.intellij.openapi.wm.ToolWindowAnchor;
42 import com.intellij.openapi.wm.ToolWindowManager;
43 import com.intellij.psi.PsiDirectory;
44 import com.intellij.psi.PsiElement;
45 import com.intellij.psi.PsiFile;
46 import com.intellij.ui.JBColor;
47 import com.intellij.ui.awt.RelativePoint;
48 import com.intellij.ui.content.Content;
49 import com.intellij.util.ObjectUtils;
50 import com.intellij.util.TimeoutUtil;
51 import com.intellij.util.containers.ContainerUtil;
52 import com.intellij.util.text.MarkdownUtil;
53 import com.intellij.util.ui.UIUtil;
54 import com.jetbrains.edu.learning.checker.StudyExecutor;
55 import com.jetbrains.edu.learning.checker.StudyTestRunner;
56 import com.jetbrains.edu.learning.core.EduAnswerPlaceholderDeleteHandler;
57 import com.jetbrains.edu.learning.core.EduAnswerPlaceholderPainter;
58 import com.jetbrains.edu.learning.core.EduNames;
59 import com.jetbrains.edu.learning.core.EduUtils;
60 import com.jetbrains.edu.learning.courseFormat.*;
61 import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator;
62 import com.jetbrains.edu.learning.editor.StudyEditor;
63 import com.jetbrains.edu.learning.ui.StudyToolWindow;
64 import com.jetbrains.edu.learning.ui.StudyToolWindowFactory;
65 import com.petebevin.markdown.MarkdownProcessor;
66 import org.jetbrains.annotations.NotNull;
67 import org.jetbrains.annotations.Nullable;
68
69 import javax.swing.*;
70 import java.awt.*;
71 import java.io.*;
72 import java.util.ArrayList;
73 import java.util.Collection;
74 import java.util.Iterator;
75 import java.util.List;
76 import java.util.concurrent.Callable;
77 import java.util.concurrent.ExecutionException;
78 import java.util.concurrent.Future;
79
80 public class StudyUtils {
81   private StudyUtils() {
82   }
83
84   private static final Logger LOG = Logger.getInstance(StudyUtils.class.getName());
85   private static final String EMPTY_TASK_TEXT = "Please, open any task to see task description";
86   private static final String ourPrefix = "<html><head><script type=\"text/x-mathjax-config\">\n" +
87                                           "            MathJax.Hub.Config({\n" +
88                                           "                tex2jax: {\n" +
89                                           "                    inlineMath: [ ['$','$'], [\"\\\\(\",\"\\\\)\"] ],\n" +
90                                           "                    displayMath: [ ['$$','$$'], [\"\\\\[\",\"\\\\]\"] ],\n" +
91                                           "                    processEscapes: true,\n" +
92                                           "                    processEnvironments: true\n" +
93                                           "                },\n" +
94                                           "                displayAlign: 'center',\n" +
95                                           "                \"HTML-CSS\": {\n" +
96                                           "                    styles: {'#mydiv': {\"font-size\": %s}},\n" +
97                                           "                    preferredFont: null,\n" +
98                                           "                    linebreaks: { automatic: true }\n" +
99                                           "                }\n" +
100                                           "            });\n" +
101                                           "</script><script type=\"text/javascript\"\n" +
102                                           " src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full\">\n" +
103                                           " </script></head><body><div id=\"mydiv\">";
104
105   private static final String ourPostfix = "</div></body></html>";
106
107   public static void closeSilently(@Nullable final Closeable stream) {
108     if (stream != null) {
109       try {
110         stream.close();
111       }
112       catch (IOException e) {
113         // close silently
114       }
115     }
116   }
117
118   public static boolean isZip(String fileName) {
119     return fileName.contains(".zip");
120   }
121
122   @Nullable
123   public static <T> T getFirst(@NotNull final Iterable<T> container) {
124     Iterator<T> iterator = container.iterator();
125     if (!iterator.hasNext()) {
126       return null;
127     }
128     return iterator.next();
129   }
130
131   public static boolean indexIsValid(int index, @NotNull final Collection collection) {
132     int size = collection.size();
133     return index >= 0 && index < size;
134   }
135
136   @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
137   @Nullable
138   public static String getFileText(@Nullable final String parentDir, @NotNull final String fileName, boolean wrapHTML,
139                                    @NotNull final String encoding) {
140     final File inputFile = parentDir != null ? new File(parentDir, fileName) : new File(fileName);
141     if (!inputFile.exists()) return null;
142     final StringBuilder taskText = new StringBuilder();
143     BufferedReader reader = null;
144     try {
145       reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), encoding));
146       String line;
147       while ((line = reader.readLine()) != null) {
148         taskText.append(line).append("\n");
149         if (wrapHTML) {
150           taskText.append("<br>");
151         }
152       }
153       return wrapHTML ? UIUtil.toHtml(taskText.toString()) : taskText.toString();
154     }
155     catch (IOException e) {
156       LOG.info("Failed to get file text from file " + fileName, e);
157     }
158     finally {
159       closeSilently(reader);
160     }
161     return null;
162   }
163
164   public static void updateAction(@NotNull final AnActionEvent e) {
165     final Presentation presentation = e.getPresentation();
166     presentation.setEnabled(false);
167     final Project project = e.getProject();
168     if (project != null) {
169       final StudyEditor studyEditor = getSelectedStudyEditor(project);
170       if (studyEditor != null) {
171         presentation.setEnabledAndVisible(true);
172       }
173     }
174   }
175
176   public static void updateToolWindows(@NotNull final Project project) {
177     final StudyToolWindow studyToolWindow = getStudyToolWindow(project);
178     if (studyToolWindow != null) {
179       String taskText = getTaskText(project);
180       if (taskText != null) {
181         studyToolWindow.setTaskText(taskText, null, project);
182       }
183       else {
184         LOG.warn("Task text is null");
185       }
186       studyToolWindow.updateCourseProgress(project);
187     }
188   }
189
190   public static void initToolWindows(@NotNull final Project project) {
191     final ToolWindowManager windowManager = ToolWindowManager.getInstance(project);
192     windowManager.getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW).getContentManager().removeAllContents(false);
193     StudyToolWindowFactory factory = new StudyToolWindowFactory();
194     factory.createToolWindowContent(project, windowManager.getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW));
195
196   }
197
198   @Nullable
199   public static StudyToolWindow getStudyToolWindow(@NotNull final Project project) {
200     if (project.isDisposed()) return null;
201     
202     ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW);
203     if (toolWindow != null) {
204       Content[] contents = toolWindow.getContentManager().getContents();
205       for (Content content: contents) {
206         JComponent component = content.getComponent();
207         if (component != null && component instanceof StudyToolWindow) {
208           return (StudyToolWindow)component;
209         }
210       }
211     }
212     return null;
213   }
214
215   public static void deleteFile(@NotNull final VirtualFile file) {
216     try {
217       file.delete(StudyUtils.class);
218     }
219     catch (IOException e) {
220       LOG.error(e);
221     }
222   }
223
224   public static File copyResourceFile(@NotNull final String sourceName, @NotNull final String copyName, @NotNull final Project project,
225                                       @NotNull final Task task)
226     throws IOException {
227     final StudyTaskManager taskManager = StudyTaskManager.getInstance(project);
228     final Course course = taskManager.getCourse();
229     int taskNum = task.getIndex();
230     int lessonNum = task.getLesson().getIndex();
231     assert course != null;
232     final String pathToResource = FileUtil.join(course.getCourseDirectory(), EduNames.LESSON + lessonNum, EduNames.TASK + taskNum);
233     final File resourceFile = new File(pathToResource, copyName);
234     FileUtil.copy(new File(pathToResource, sourceName), resourceFile);
235     return resourceFile;
236   }
237
238   @Nullable
239   public static Sdk findSdk(@NotNull final Task task, @NotNull final Project project) {
240     final Language language = task.getLesson().getCourse().getLanguageById();
241     return StudyExecutor.INSTANCE.forLanguage(language).findSdk(project);
242   }
243
244   @NotNull
245   public static StudyTestRunner getTestRunner(@NotNull final Task task, @NotNull final VirtualFile taskDir) {
246     final Language language = task.getLesson().getCourse().getLanguageById();
247     return StudyExecutor.INSTANCE.forLanguage(language).getTestRunner(task, taskDir);
248   }
249
250   public static RunContentExecutor getExecutor(@NotNull final Project project, @NotNull final Task currentTask,
251                                                @NotNull final ProcessHandler handler) {
252     final Language language = currentTask.getLesson().getCourse().getLanguageById();
253     return StudyExecutor.INSTANCE.forLanguage(language).getExecutor(project, handler);
254   }
255
256   public static void setCommandLineParameters(@NotNull final GeneralCommandLine cmd,
257                                               @NotNull final Project project,
258                                               @NotNull final String filePath,
259                                               @NotNull final String sdkPath,
260                                               @NotNull final Task currentTask) {
261     final Language language = currentTask.getLesson().getCourse().getLanguageById();
262     StudyExecutor.INSTANCE.forLanguage(language).setCommandLineParameters(cmd, project, filePath, sdkPath, currentTask);
263   }
264
265   public static void showNoSdkNotification(@NotNull final Task currentTask, @NotNull final Project project) {
266     final Language language = currentTask.getLesson().getCourse().getLanguageById();
267     StudyExecutor.INSTANCE.forLanguage(language).showNoSdkNotification(project);
268   }
269
270
271   /**
272    * shows pop up in the center of "check task" button in study editor
273    */
274   public static void showCheckPopUp(@NotNull final Project project, @NotNull final Balloon balloon) {
275     final StudyEditor studyEditor = getSelectedStudyEditor(project);
276     assert studyEditor != null;
277
278     balloon.show(computeLocation(studyEditor.getEditor()), Balloon.Position.above);
279     Disposer.register(project, balloon);
280   }
281
282   public static RelativePoint computeLocation(Editor editor){
283
284     final Rectangle visibleRect = editor.getComponent().getVisibleRect();
285     Point point = new Point(visibleRect.x + visibleRect.width + 10,
286                             visibleRect.y + 10);
287     return new RelativePoint(editor.getComponent(), point);
288   }
289
290
291   /**
292    * returns language manager which contains all the information about language specific file names
293    */
294   @Nullable
295   public static StudyLanguageManager getLanguageManager(@NotNull final Course course) {
296     Language language = course.getLanguageById();
297     return language == null ? null : StudyLanguageManager.INSTANCE.forLanguage(language);
298   }
299
300   public static boolean isTestsFile(@NotNull Project project, @NotNull final String name) {
301     Course course = StudyTaskManager.getInstance(project).getCourse();
302     if (course == null) {
303       return false;
304     }
305     StudyLanguageManager manager = getLanguageManager(course);
306     if (manager == null) {
307       return false;
308     }
309     return manager.getTestFileName().equals(name);
310   }
311
312   @Nullable
313   public static TaskFile getTaskFile(@NotNull final Project project, @NotNull final VirtualFile file) {
314     final Course course = StudyTaskManager.getInstance(project).getCourse();
315     if (course == null) {
316       return null;
317     }
318     VirtualFile taskDir = file.getParent();
319     if (taskDir == null) {
320       return null;
321     }
322     //need this because of multi-module generation
323     if (EduNames.SRC.equals(taskDir.getName())) {
324       taskDir = taskDir.getParent();
325       if (taskDir == null) {
326         return null;
327       }
328     }
329     final String taskDirName = taskDir.getName();
330     if (taskDirName.contains(EduNames.TASK)) {
331       final VirtualFile lessonDir = taskDir.getParent();
332       if (lessonDir != null) {
333         int lessonIndex = EduUtils.getIndex(lessonDir.getName(), EduNames.LESSON);
334         List<Lesson> lessons = course.getLessons();
335         if (!indexIsValid(lessonIndex, lessons)) {
336           return null;
337         }
338         final Lesson lesson = lessons.get(lessonIndex);
339         int taskIndex = EduUtils.getIndex(taskDirName, EduNames.TASK);
340         final List<Task> tasks = lesson.getTaskList();
341         if (!indexIsValid(taskIndex, tasks)) {
342           return null;
343         }
344         final Task task = tasks.get(taskIndex);
345         return task.getFile(file.getName());
346       }
347     }
348     return null;
349   }
350
351   public static void drawAllWindows(Editor editor, TaskFile taskFile) {
352     editor.getMarkupModel().removeAllHighlighters();
353     final Project project = editor.getProject();
354     if (project == null) return;
355     final StudyTaskManager taskManager = StudyTaskManager.getInstance(project);
356     for (AnswerPlaceholder answerPlaceholder : taskFile.getActivePlaceholders()) {
357       final JBColor color = taskManager.getColor(answerPlaceholder);
358       EduAnswerPlaceholderPainter.drawAnswerPlaceholder(editor, answerPlaceholder, color);
359     }
360     final Document document = editor.getDocument();
361     EditorActionManager.getInstance()
362       .setReadonlyFragmentModificationHandler(document, new EduAnswerPlaceholderDeleteHandler(editor));
363     EduAnswerPlaceholderPainter.createGuardedBlocks(editor, taskFile);
364     editor.getColorsScheme().setColor(EditorColors.READONLY_FRAGMENT_BACKGROUND_COLOR, null);
365   }
366
367   @Nullable
368   public static StudyEditor getSelectedStudyEditor(@NotNull final Project project) {
369     try {
370       final FileEditor fileEditor = FileEditorManagerEx.getInstanceEx(project).getSplitters().getCurrentWindow().
371         getSelectedEditor().getSelectedEditorWithProvider().getFirst();
372       if (fileEditor instanceof StudyEditor) {
373         return (StudyEditor)fileEditor;
374       }
375     }
376     catch (Exception e) {
377       return null;
378     }
379     return null;
380   }
381
382   @Nullable
383   public static Editor getSelectedEditor(@NotNull final Project project) {
384     final StudyEditor studyEditor = getSelectedStudyEditor(project);
385     if (studyEditor != null) {
386       return studyEditor.getEditor();
387     }
388     return null;
389   }
390
391   public static void deleteGuardedBlocks(@NotNull final Document document) {
392     if (document instanceof DocumentImpl) {
393       final DocumentImpl documentImpl = (DocumentImpl)document;
394       List<RangeMarker> blocks = documentImpl.getGuardedBlocks();
395       for (final RangeMarker block : blocks) {
396         ApplicationManager.getApplication().invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> document.removeGuardedBlock(block)));
397       }
398     }
399   }
400
401
402   @Nullable
403   public static VirtualFile getPatternFile(@NotNull TaskFile taskFile, String name) {
404     Task task = taskFile.getTask();
405     String lessonDir = EduNames.LESSON + String.valueOf(task.getLesson().getIndex());
406     String taskDir = EduNames.TASK + String.valueOf(task.getIndex());
407     Course course = task.getLesson().getCourse();
408     File resourceFile = new File(course.getCourseDirectory());
409     if (!resourceFile.exists()) {
410       return null;
411     }
412     String patternPath = FileUtil.join(resourceFile.getPath(), lessonDir, taskDir, name);
413     VirtualFile patternFile = VfsUtil.findFileByIoFile(new File(patternPath), true);
414     if (patternFile == null) {
415       return null;
416     }
417     return patternFile;
418   }
419
420   @Nullable
421   public static Document getPatternDocument(@NotNull final TaskFile taskFile, String name) {
422     VirtualFile patternFile = getPatternFile(taskFile, name);
423     if (patternFile == null) {
424       return null;
425     }
426     return FileDocumentManager.getInstance().getDocument(patternFile);
427   }
428
429   public static boolean isRenameableOrMoveable(@NotNull final Project project, @NotNull final Course course, @NotNull final PsiElement element) {
430     if (element instanceof PsiFile) {
431       VirtualFile virtualFile = ((PsiFile)element).getVirtualFile();
432       if (project.getBaseDir().equals(virtualFile.getParent())) {
433         return false;
434       }
435       TaskFile file = getTaskFile(project, virtualFile);
436       if (file != null) {
437         return false;
438       }
439       String name = virtualFile.getName();
440       return !isTestsFile(project, name) && !isTaskDescriptionFile(name);
441     }
442     if (element instanceof PsiDirectory) {
443       VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile();
444       VirtualFile parent = virtualFile.getParent();
445       if (parent == null) {
446         return true;
447       }
448       if (project.getBaseDir().equals(parent)) {
449         return false;
450       }
451       Lesson lesson = course.getLesson(parent.getName());
452       if (lesson != null) {
453         Task task = lesson.getTask(virtualFile.getName());
454         if (task != null) {
455           return false;
456         }
457       }
458     }
459     return true;
460   }
461
462   public static boolean canRenameOrMove(DataContext dataContext) {
463     Project project = CommonDataKeys.PROJECT.getData(dataContext);
464     PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
465     if (element == null || project == null) {
466       return false;
467     }
468     Course course = StudyTaskManager.getInstance(project).getCourse();
469     if (course == null || !EduNames.STUDY.equals(course.getCourseMode())) {
470       return false;
471     }
472
473     if (!isRenameableOrMoveable(project, course, element)) {
474       return true;
475     }
476     return false;
477   }
478
479   @Nullable
480   public static String getTaskTextFromTask(@Nullable final VirtualFile taskDirectory, @Nullable final Task task) {
481     if (task == null || task.getLesson() == null || task.getLesson().getCourse() == null) {
482       return null;
483     }
484     final Course course = task.getLesson().getCourse();
485     String text = task.getText() != null ? task.getText() : getTaskTextFromTaskName(taskDirectory, EduNames.TASK_MD);
486     
487     if (text == null) return null;
488     if (course.isAdaptive()) text = wrapAdaptiveCourseText(text);
489
490     return wrapTextToDisplayLatex(text);
491   }
492
493   private static String wrapAdaptiveCourseText(@NotNull String text) {
494     return text + "\n\n<b>Note</b>: Use standard input to obtain input for the task.";
495   }
496
497   public static String wrapTextToDisplayLatex(String taskTextFileHtml) {
498     final String prefix = String.format(ourPrefix, EditorColorsManager.getInstance().getGlobalScheme().getEditorFontSize());
499     return prefix + taskTextFileHtml + ourPostfix;
500   }
501
502   @Nullable
503   private static String getTaskTextFromTaskName(@Nullable VirtualFile taskDirectory, @NotNull String taskTextFilename) {
504     if (taskDirectory == null) return null;
505     taskDirectory.refresh(false, true);
506     VirtualFile taskTextFile = ObjectUtils.chooseNotNull(taskDirectory.findChild(EduNames.TASK_HTML), 
507                                                          taskDirectory.findChild(EduNames.TASK_MD));
508     if (taskTextFile == null) {
509       VirtualFile srcDir = taskDirectory.findChild(EduNames.SRC);
510       if (srcDir != null) {
511          taskTextFile = srcDir.findChild(taskTextFilename);
512       }
513     }
514     if (taskTextFile != null) {
515       return String.valueOf(LoadTextUtil.loadText(taskTextFile));
516     }
517     return null;
518   }
519
520   @Nullable
521   public static StudyPluginConfigurator getConfigurator(@NotNull final Project project) {
522     StudyPluginConfigurator[] extensions = StudyPluginConfigurator.EP_NAME.getExtensions();
523     for (StudyPluginConfigurator extension: extensions) {
524       if (extension.accept(project)) {
525         return extension;
526       }
527     }
528     return null;
529   }
530
531   @Nullable
532   public static StudyTwitterPluginConfigurator getTwitterConfigurator(@NotNull final Project project) {
533     StudyTwitterPluginConfigurator[] extensions = StudyTwitterPluginConfigurator.EP_NAME.getExtensions();
534     for (StudyTwitterPluginConfigurator extension: extensions) {
535       if (extension.accept(project)) {
536         return extension;
537       }
538     }
539     return null;
540   }
541
542   @Nullable
543   public static String getTaskText(@NotNull final Project project) {
544     TaskFile taskFile = getSelectedTaskFile(project);
545     if (taskFile == null) {
546       return EMPTY_TASK_TEXT;
547     }
548     final Task task = taskFile.getTask();
549     if (task != null) {
550       return getTaskTextFromTask(task.getTaskDir(project), task);
551     }
552     return null;
553   }
554   @Nullable
555   public static TaskFile getSelectedTaskFile(@NotNull Project project) {
556     VirtualFile[] files = FileEditorManager.getInstance(project).getSelectedFiles();
557     TaskFile taskFile = null;
558     for (VirtualFile file : files) {
559       taskFile = getTaskFile(project, file);
560       if (taskFile != null) {
561         break;
562       }
563     }
564     return taskFile;
565   }
566   
567   @Nullable
568   public static Task getCurrentTask(@NotNull final Project project) {
569     final TaskFile taskFile = getSelectedTaskFile(project);
570     return taskFile != null ? taskFile.getTask() : null;
571   }
572
573   public static boolean isStudyProject(@NotNull Project project) {
574     return StudyTaskManager.getInstance(project).getCourse() != null;
575   }
576
577   @Nullable
578   public static Project getStudyProject() {
579     Project studyProject = null;
580     Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
581     for (Project project : openProjects) {
582       if (StudyTaskManager.getInstance(project).getCourse() != null) {
583          studyProject = project;
584       }
585     }
586     return studyProject;
587   }
588
589   @NotNull
590   public static File getCourseDirectory(@NotNull Project project, Course course) {
591     final File courseDirectory;
592     if (course.isAdaptive()) {
593       courseDirectory = new File(StudyProjectGenerator.OUR_COURSES_DIR,
594                                  StudyProjectGenerator.ADAPTIVE_COURSE_PREFIX + course.getName()
595                                  + "_" + StudyTaskManager.getInstance(project).getUser().getEmail());
596     }
597     else {
598       courseDirectory = new File(StudyProjectGenerator.OUR_COURSES_DIR, course.getName());
599     }
600     return courseDirectory;
601   }
602
603   public static boolean hasJavaFx() {
604     try {
605       Class.forName("javafx.application.Platform");
606       return true;
607     }
608     catch (ClassNotFoundException e) {
609       return false;
610     }
611   }
612
613   @Nullable
614   public static Task getTask(@NotNull Project project, @NotNull VirtualFile taskVF) {
615     Course course = StudyTaskManager.getInstance(project).getCourse();
616     if (course == null) {
617       return null;
618     }
619     VirtualFile lessonVF = taskVF.getParent();
620     if (lessonVF == null) {
621       return null;
622     }
623     Lesson lesson = course.getLesson(lessonVF.getName());
624     if (lesson == null) {
625       return null;
626     }
627     return lesson.getTask(taskVF.getName());
628   }
629
630   @Nullable
631   public static VirtualFile getTaskDir(@NotNull VirtualFile taskFile) {
632     VirtualFile parent = taskFile.getParent();
633     if (parent == null) {
634       return null;
635     }
636     String name = parent.getName();
637     if (name.contains(EduNames.TASK)) {
638       return parent;
639     }
640     if (EduNames.SRC.equals(name)) {
641       return parent.getParent();
642     }
643     return null;
644   }
645
646   @Nullable
647   public static Task getTaskForFile(@NotNull Project project, @NotNull VirtualFile taskFile) {
648     VirtualFile taskDir = getTaskDir(taskFile);
649     if (taskDir == null) {
650       return null;
651     }
652     return getTask(project, taskDir);
653   }
654
655   // supposed to be called under progress
656   @Nullable
657   public static <T> T execCancelable(@NotNull final Callable<T> callable) {
658     final Future<T> future = ApplicationManager.getApplication().executeOnPooledThread(callable);
659
660     while (!future.isCancelled() && !future.isDone()) {
661       ProgressManager.checkCanceled();
662       TimeoutUtil.sleep(500);
663     }
664     T result = null;
665     try {
666       result = future.get();
667     }
668     catch (InterruptedException | ExecutionException e) {
669       LOG.warn(e.getMessage());
670     }
671     return result;
672   }
673
674   @Nullable
675   public static Task getTaskFromSelectedEditor(Project project) {
676     final StudyEditor editor = getSelectedStudyEditor(project);
677     Task task = null;
678     if (editor != null) {
679       final TaskFile file = editor.getTaskFile();
680       task = file.getTask();
681     }
682     return task;
683   }
684
685   private static String convertToHtml(@NotNull final String content) {
686     ArrayList<String> lines = ContainerUtil.newArrayList(content.split("\n|\r|\r\n"));
687     MarkdownUtil.replaceHeaders(lines);
688     MarkdownUtil.replaceCodeBlock(lines);
689     
690     return new MarkdownProcessor().markdown(StringUtil.join(lines, "\n"));
691   }
692   
693   public static boolean isTaskDescriptionFile(@NotNull final String fileName) {
694     if (EduNames.TASK_HTML.equals(fileName) || EduNames.TASK_MD.equals(fileName)) {
695       return true;
696     }
697     String extension = FileUtilRt.getExtension(fileName);
698     if (!extension.equals(FileUtilRt.getExtension(EduNames.TASK_HTML)) && !extension.equals(FileUtilRt.getExtension(EduNames.TASK_MD))) {
699       return false;
700     }
701     return fileName.contains(EduNames.TASK) && fileName.contains(EduNames.SUBTASK_MARKER);
702   }
703   
704   @Nullable
705   public static VirtualFile findTaskDescriptionVirtualFile(@NotNull VirtualFile taskDir) {
706     return ObjectUtils.chooseNotNull(taskDir.findChild(EduNames.TASK_HTML), taskDir.findChild(EduNames.TASK_MD));
707   }
708   
709   @NotNull
710   public static String getTaskDescriptionFileName(final boolean useHtml) {
711     return useHtml ? EduNames.TASK_HTML : EduNames.TASK_MD;    
712   }
713
714   @Nullable
715   public static Document getDocument(String basePath, int lessonIndex, int taskIndex, String fileName) {
716     String taskPath = FileUtil.join(basePath, EduNames.LESSON + lessonIndex, EduNames.TASK + taskIndex);
717     VirtualFile taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, fileName));
718     if (taskFile == null) {
719       taskFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.join(taskPath, EduNames.SRC, fileName));
720     }
721     if (taskFile == null) {
722       return null;
723     }
724     return FileDocumentManager.getInstance().getDocument(taskFile);
725   }
726
727   public static void showErrorPopupOnToolbar(@NotNull Project project) {
728     final Balloon balloon =
729       JBPopupFactory.getInstance().createHtmlTextBalloonBuilder("Couldn't post your reaction", MessageType.ERROR, null).createBalloon();
730     showCheckPopUp(project, balloon);
731   }
732
733   public static void selectFirstAnswerPlaceholder(@Nullable final StudyEditor studyEditor, @NotNull final Project project) {
734     if (studyEditor == null) return;
735     final Editor editor = studyEditor.getEditor();
736     IdeFocusManager.getInstance(project).requestFocus(editor.getContentComponent(), true);
737     final List<AnswerPlaceholder> placeholders = studyEditor.getTaskFile().getActivePlaceholders();
738     if (placeholders.isEmpty()) return;
739     final AnswerPlaceholder placeholder = placeholders.get(0);
740     int startOffset = placeholder.getOffset();
741     editor.getSelectionModel().setSelection(startOffset, startOffset + placeholder.getRealLength());
742   }
743
744   public static void registerStudyToolWindow(@Nullable final Course course, Project project) {
745     if (course != null && "PyCharm".equals(course.getCourseType())) {
746       final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
747       registerToolWindows(toolWindowManager, project);
748       final ToolWindow studyToolWindow = toolWindowManager.getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW);
749       if (studyToolWindow != null) {
750         studyToolWindow.show(null);
751         initToolWindows(project);
752       }
753     }
754   }
755
756   private static void registerToolWindows(@NotNull final ToolWindowManager toolWindowManager, Project project) {
757     final ToolWindow toolWindow = toolWindowManager.getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW);
758     if (toolWindow == null) {
759       toolWindowManager.registerToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW, true, ToolWindowAnchor.RIGHT, project, true);
760     }
761   }
762 }