1 /*
2  * SessionPythonEnvironments.cpp
3  *
4  * Copyright (C) 2021 by RStudio, PBC
5  *
6  * Unless you have received this program directly from RStudio pursuant
7  * to the terms of a commercial license agreement with RStudio, then
8  * this program is licensed to you under the terms of version 3 of the
9  * GNU Affero General Public License. This program is distributed WITHOUT
10  * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
11  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
12  * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
13  *
14  */
15 
16 #include "SessionPythonEnvironments.hpp"
17 
18 #include <core/Exec.hpp>
19 
20 #include <r/RExec.hpp>
21 
22 #include <session/prefs/UserPrefs.hpp>
23 #include <session/prefs/UserPrefValues.hpp>
24 #include <session/projects/SessionProjects.hpp>
25 
26 #include <session/SessionModuleContext.hpp>
27 
28 using namespace rstudio::core;
29 
30 namespace rstudio {
31 namespace session {
32 namespace modules {
33 namespace python_environments {
34 
35 namespace {
36 
onPrefsChanged(const std::string &,const std::string & prefName)37 void onPrefsChanged(const std::string& /* layerName */,
38                     const std::string& prefName)
39 {
40    if (prefName == kPythonPath)
41    {
42       std::string pythonPath = prefs::userPrefs().pythonPath();
43 
44       if (!pythonPath.empty())
45       {
46          Error error = r::exec::RFunction(".rs.reticulate.usePython")
47                .addParam(pythonPath)
48                .call();
49 
50          if (error)
51             LOG_ERROR(error);
52       }
53    }
54 }
55 
onInitComplete()56 void onInitComplete()
57 {
58    if (!projects::projectContext().hasProject())
59       return;
60 
61    Error error = r::exec::RFunction(".rs.python.initialize")
62          .addUtf8Param(projects::projectContext().directory())
63          .call();
64 
65    if (error)
66       LOG_ERROR(error);
67 }
68 
69 } // end anonymous namespace
70 
initialize()71 Error initialize()
72 {
73    using namespace module_context;
74 
75    events().onInitComplete.connect(onInitComplete);
76 
77    prefs::userPrefs().onChanged.connect(onPrefsChanged);
78 
79    ExecBlock initBlock;
80    initBlock.addFunctions()
81       (bind(sourceModuleRFile, "SessionPythonEnvironments.R"));
82 
83    return initBlock.execute();
84 }
85 
86 } // end namespace python_environments
87 } // end namespace modules
88 } // end namespace session
89 } // end namespace rstudio
90