// Regression test for LP:#1340669
// Test is not deterministic since we are testing a race, but failure can be
// reproduced easily with repeated runs.
TEST_F(ClientWithCustomDisplayConfiguration,
       does_not_deadlock_server_with_existing_client_when_disconnecting)
{
    auto second_connection = mir_connect_sync(new_connection().c_str(), __PRETTY_FUNCTION__);

    auto second_surface = mtf::make_any_surface(connection);
    ASSERT_TRUE(mir_surface_is_valid(second_surface));

    auto configuration = mir_connection_create_display_config(connection);
    mir_wait_for(mir_connection_apply_display_config(connection, configuration));
    EXPECT_STREQ("", mir_connection_get_error_message(connection));
    mir_display_config_destroy(configuration);

    mir_connection_release(second_connection);

    // Server (and therefore the test) will deadlock and won't be able to
    // shut down without the fix. It's not ideal to deadlock on test failure,
    // but it's the best check we have at the moment.
}
SDL_Surface* Mir_SetVideoMode(_THIS, SDL_Surface* current,
                              int width, int height, int bpp, Uint32 flags)
{
    if (this->hidden->surface && mir_surface_is_valid(this->hidden->surface))
    {
         mir_surface_release_sync(this->hidden->surface);
         this->hidden->surface = NULL;
    }

    Uint32 output_id = mir_display_output_id_invalid;

    if (flags & SDL_FULLSCREEN)
    {
        MirDisplayConfiguration* display_config =
                mir_connection_create_display_config(this->hidden->connection);

        Uint32 fallback_output_id = mir_display_output_id_invalid;
        Uint32 d;
        Uint32 m;

        this->hidden->mode_changed = SDL_FALSE;

        for (d = 0; d < display_config->num_outputs; ++d)
        {
            MirDisplayOutput const* out = display_config->outputs + d;
            if (out->used && out->connected)
            {
                if (out->modes[out->current_mode].horizontal_resolution == width &&
                    out->modes[out->current_mode].vertical_resolution == height)
                {
                    output_id = out->output_id;
                    break;
                }

                if (fallback_output_id == mir_display_output_id_invalid &&
                    out->modes[out->current_mode].horizontal_resolution >= width &&
                    out->modes[out->current_mode].vertical_resolution >= height)
                {
                    fallback_output_id = out->output_id;
                }
            }
        }

        if (output_id == mir_display_output_id_invalid)
        {
            for (d = 0; d < display_config->num_outputs; ++d)
            {
                MirDisplayOutput* out = display_config->outputs + d;
                if (out->used && out->connected)
                {
                    for (m = 0; m < out->num_modes; ++m)
                    {
                        if (out->modes[m].horizontal_resolution == width &&
                            out->modes[m].vertical_resolution == height)
                        {
                            this->hidden->mode_changed = SDL_TRUE;
                            output_id = out->output_id;
                            out->current_mode = m;

                            mir_wait_for(
                                mir_connection_apply_display_config(this->hidden->connection,
                                                                    display_config)
                            );
                            break;
                        }
                    }
                }
            }
        }

        if (fallback_output_id == mir_display_output_id_invalid)
        {
            /* There's no native resolution for the requested format, so let's
             * just ensure we've an output large enough to show it */

            for (d = 0; d < display_config->num_outputs; ++d)
            {
                MirDisplayOutput* out = display_config->outputs + d;
                if (out->used && out->connected)
                {
                    for (m = 0; m < out->num_modes; ++m)
                    {
                        if (out->modes[m].horizontal_resolution >= width &&
                            out->modes[m].vertical_resolution >= height)
                        {
                            this->hidden->mode_changed = SDL_TRUE;
                            fallback_output_id = out->output_id;
                            out->current_mode = m;

                            mir_wait_for(
                                mir_connection_apply_display_config(this->hidden->connection,
                                                                    display_config)
                            );
                            break;
                        }
                    }
                }
            }

            /* Setting output_id = fallback_output_id here seems to cause
             * troubles to mir in creating a new surface */
        }

        mir_display_config_destroy(display_config);

        if (output_id == mir_display_output_id_invalid &&
            fallback_output_id == mir_display_output_id_invalid)
        {
            SDL_SetError("Impossible to find a valid output for mode %dx%d",
                         width, height);
            return NULL;
        }
    }
    else if (this->hidden->mode_changed)
    {
        Uint32 d;
        SDL_bool any_changed = SDL_FALSE;

        MirDisplayConfiguration* display_config =
                mir_connection_create_display_config(this->hidden->connection);

        for (d = 0; d < display_config->num_outputs; ++d)
        {
            MirDisplayOutput* out = display_config->outputs + d;
            if (out->used && out->connected)
            {
                if (out->current_mode != out->preferred_mode)
                {
                    out->current_mode = out->preferred_mode;
                    any_changed = SDL_TRUE;
                }
            }
        }

        if (any_changed)
        {
            mir_wait_for(
                mir_connection_apply_display_config(this->hidden->connection,
                                                    display_config)
            );
        }

        this->hidden->mode_changed = SDL_FALSE;
        mir_display_config_destroy(display_config);
    }

    MirSurfaceParameters surfaceparm =
    {
        .name   = "MirSurface",
        .width  = width,
        .height = height,
        .pixel_format = this->hidden->pixel_format,
        .output_id = output_id,
        .buffer_usage = (flags & SDL_OPENGL) ? mir_buffer_usage_hardware :
                                               mir_buffer_usage_software,
    };

    this->hidden->surface =
        mir_connection_create_surface_sync(this->hidden->connection, &surfaceparm);

    if (!mir_surface_is_valid(this->hidden->surface))
    {
        const char* error = mir_surface_get_error_message(this->hidden->surface);
        SDL_SetError("Failed to created a mir surface: %s", error);
        mir_surface_release_sync(this->hidden->surface);
        return NULL;
    }

    MirEventDelegate delegate = {
        Mir_HandleSurfaceEvent,
        NULL
    };

    mir_surface_set_event_handler(this->hidden->surface, &delegate);

    if (flags & SDL_OPENGL)
    {
        current->flags |= SDL_OPENGL;

        if (Mir_GL_CreateESurface(this) < 0)
        {
            SDL_SetError("Could not Create EGL Surface");
            return NULL;
        }

        if (Mir_GL_CreateContext(this) < 0)
        {
            SDL_SetError("Could not Create GL Context");
            return NULL;
        }
    }
    else
    {
        if ((current->w != width || current->h != height))
        {
            current->pixels = NULL;
            current->w      = width;
            current->h      = height;
            current->pitch  = SDL_CalculatePitch(current);

            current->pixels = SDL_calloc(1, current->h * current->pitch);
            if (!current->pixels)
            {
                  SDL_OutOfMemory();
                  return NULL;
            }
            this->UpdateRects = Mir_UpdateRects;
        }
    }

    return current;
}

static void Mir_ModeListFree(_THIS)
{
    if (this->hidden->modelist)
    {
        int i = 0;
        while (this->hidden->modelist[i] != NULL)
        {
          SDL_free(this->hidden->modelist[i]);
          ++i;
        }

        SDL_free(this->hidden->modelist);
        this->hidden->modelist = NULL;
    }
}

static void Mir_ModeListUpdate(_THIS)
{
    Uint32 d, m;
    Uint32 valid_outputs = 0;

    Mir_ModeListFree(this);

    MirDisplayConfiguration* display_config =
            mir_connection_create_display_config(this->hidden->connection);

    for (d = 0; d < display_config->num_outputs; d++)
    {
        MirDisplayOutput const* out = display_config->outputs + d;
        if (out->used && out->connected)
            valid_outputs += out->num_modes;
    }

    this->hidden->modelist = SDL_calloc(valid_outputs + 1, sizeof(SDL_Rect*));

    valid_outputs = 0;

    for (d = 0; d < display_config->num_outputs; ++d)
    {
        MirDisplayOutput const* out = display_config->outputs + d;
        if (out->used && out->connected)
        {
            for (m = 0; m < out->num_modes; ++m)
            {
                SDL_Rect* sdl_output = SDL_calloc(1, sizeof(SDL_Rect));
                sdl_output->x = out->position_x;
                sdl_output->y = out->position_y;
                sdl_output->w = out->modes[m].horizontal_resolution;
                sdl_output->h = out->modes[m].vertical_resolution;
                this->hidden->modelist[valid_outputs] = sdl_output;

                ++valid_outputs;
            }
        }
    }

    this->hidden->modelist[valid_outputs] = NULL;

    mir_display_config_destroy(display_config);
}