aboutsummaryrefslogtreecommitdiff
path: root/src/ImageViewer.cpp
blob: a30dd40acf35415da0f33b12942b327911769f6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#include "../include/ImageViewer.hpp"
#include "../include/Notification.hpp"
#include "../include/Storage.hpp"
#include "../include/SfmlFixes.hpp"
#include "../include/ResourceLoader.hpp"
#include "../include/Scale.hpp"
#include <cmath>
#include <malloc.h>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/RectangleShape.hpp>

namespace QuickMedia {
    static sf::Vector2<double> get_no_image_size_scaled(sf::Vector2<double> window_size, bool fit_image_to_window) {
        sf::Vector2<double> no_image_page_size(720.0, 1280.0);
        sf::Vector2f no_image_page_size_f(no_image_page_size.x, no_image_page_size.y);
        sf::Vector2f content_size(window_size.x, window_size.y);

        sf::Vector2f image_scale;
        if(fit_image_to_window)
            image_scale = get_ratio(no_image_page_size_f, wrap_to_size_x(no_image_page_size_f, content_size));
        else
            image_scale = get_ratio(no_image_page_size_f, clamp_to_size_x(no_image_page_size_f, content_size));

        no_image_page_size.x *= image_scale.x;
        no_image_page_size.y *= image_scale.y;
        return no_image_page_size;
    }

    ImageViewer::ImageViewer(sf::RenderWindow *window, int num_pages, const std::string &content_title, const std::string &chapter_title, int current_page, const Path &chapter_cache_dir, bool *fit_image_to_window) :
        window(window),
        current_page(current_page),
        num_pages(num_pages),
        content_title(content_title),
        chapter_title(chapter_title),
        chapter_cache_dir(chapter_cache_dir),
        focused_page(current_page),
        font(FontLoader::get_font(FontLoader::FontType::LATIN)),
        page_text("", *FontLoader::get_font(FontLoader::FontType::LATIN), 14),
        fit_image_to_window(fit_image_to_window)
    {
        current_page = std::min(current_page, num_pages);
        image_data.resize(num_pages);
        page_size.resize(num_pages);
        for(int i = 0; i < num_pages; ++i) {
            image_data[i] = nullptr;
            page_size[i].loaded = false;
        }
        page_text.setFillColor(sf::Color::White);

        has_default_cursor = default_cursor.loadFromSystem(sf::Cursor::Arrow);
        has_size_vertical_cursor = size_vertical_cursor.loadFromSystem(sf::Cursor::SizeVertical);
    }

    ImageViewer::~ImageViewer() {
        if(has_default_cursor)
            window->setMouseCursor(default_cursor);
        if(image_loader_thread.joinable())
            image_loader_thread.join();
    }

    void ImageViewer::load_image_async(const Path &path, std::shared_ptr<ImageData> image_data) {
        image_data->image_status = ImageStatus::LOADING;
        //image_data->texture.setSmooth(true);
        assert(!loading_image);
        loading_image = true;
        if(image_loader_thread.joinable())
            image_loader_thread.join();
        image_loader_thread = std::thread([this, image_data, path]() mutable {
            auto image = std::make_unique<sf::Image>();
            if(load_image_from_file(*image, path.data)) {
                image_data->image = std::move(image);
                image_data->image_status = ImageStatus::LOADED;
            } else {
                image_data->image_status = ImageStatus::FAILED_TO_LOAD;
            }
            loading_image = false;
        });
    }

    bool ImageViewer::render_page(sf::RenderWindow &window, int page, double offset_y) {
        if(page < 0 || page >= (int)image_data.size())
            return false;

        std::shared_ptr<ImageData> &page_image_data = image_data[page];
        const sf::Vector2<double> image_size = get_page_size(page);
        sf::Vector2<double> render_pos(std::floor(window_size.x * 0.5 - image_size.x * 0.5), - image_size.y * 0.5 + scroll + offset_y);
        if(render_pos.y + image_size.y <= 0.0 || render_pos.y >= window_size.y) {
            if(page_image_data)
                page_image_data->visible_on_screen = false;
            return true;
        }

        bool scrolling = (std::abs(scroll_speed) > 0.01f);
        if(!scrolling)
            render_pos.y = std::floor(render_pos.y);

        double center_dist = std::abs(window_size.y * 0.5 - (render_pos.y + image_size.y * 0.5));
        if(center_dist < min_page_center_dist) {
            min_page_center_dist = center_dist;
            page_closest_to_center = page;
        }

        if(page_image_data) {
            page_image_data->visible_on_screen = true;

            if(page_image_data->image_status == ImageStatus::APPLIED_TO_TEXTURE) {
                auto texture_size = page_image_data->sprite.getTexture()->getSize();
                sf::Vector2f texture_size_f(texture_size.x, texture_size.y);
                sf::Vector2f content_size(window_size.x, window_size.y);

                sf::Vector2f image_scale;
                if(*fit_image_to_window)
                    image_scale = get_ratio(texture_size_f, wrap_to_size_x(texture_size_f, content_size));
                else
                    image_scale = get_ratio(texture_size_f, clamp_to_size_x(texture_size_f, content_size));

                page_image_data->sprite.setScale(image_scale);
                page_image_data->sprite.setPosition(render_pos.x, render_pos.y);
                window.draw(page_image_data->sprite);
            } else {
                std::string page_str = std::to_string(1 + page);
                std::string msg;
                if(page_image_data->image_status == ImageStatus::WAITING) {
                    if(!loading_image) {
                        Path image_path = chapter_cache_dir;
                        image_path.join(page_str);
                        load_image_async(image_path, page_image_data);
                    }
                    msg = "Loading image for page " + page_str;
                } else if(page_image_data->image_status == ImageStatus::LOADING) {
                    msg = "Loading image for page " + page_str;
                } else if(page_image_data->image_status == ImageStatus::FAILED_TO_LOAD) {
                    msg = "Failed to load image for page " + page_str;
                }

                sf::Text error_message(std::move(msg), *font, 30);
                auto text_bounds = error_message.getLocalBounds();
                error_message.setFillColor(sf::Color::Black);
                sf::Vector2<double> render_pos_text(std::floor(window_size.x * 0.5 - text_bounds.width * 0.5), - text_bounds.height * 0.5 + scroll + offset_y);

                if(!scrolling)
                    render_pos_text.y = std::floor(render_pos_text.y);

                sf::RectangleShape background(sf::Vector2f(image_size.x, image_size.y));
                background.setFillColor(sf::Color::White);
                background.setPosition(render_pos.x, render_pos.y);
                window.draw(background);

                error_message.setPosition(render_pos_text.x, render_pos_text.y);
                window.draw(error_message);
            }
        } else {
            std::string page_str = std::to_string(1 + page);

            sf::Text error_message("Downloading page " + page_str, *font, 30);
            auto text_bounds = error_message.getLocalBounds();
            error_message.setFillColor(sf::Color::Black);
            sf::Vector2<double> render_pos_text(std::floor(window_size.x * 0.5 - text_bounds.width * 0.5), - text_bounds.height * 0.5 + scroll + offset_y);

            if(!scrolling)
                render_pos_text.y = std::floor(render_pos_text.y);

            sf::RectangleShape background(sf::Vector2f(image_size.x, image_size.y));
            background.setFillColor(sf::Color::White);
            background.setPosition(render_pos.x, render_pos.y);
            window.draw(background);

            error_message.setPosition(render_pos_text.x, render_pos_text.y);
            window.draw(error_message);

            Path image_path = chapter_cache_dir;
            image_path.join(page_str);

            // TODO: Add delay before checking again?
            if(get_file_type(image_path) == FileType::REGULAR) {
                //fprintf(stderr, "ImageViewer: Loaded page %d\n", 1 + page);

                page_image_data = std::make_shared<ImageData>();
                page_image_data->visible_on_screen = true;
                
                page_image_data->image_status = ImageStatus::WAITING;
                //page_image_data->texture.setSmooth(true);
            }
        }

        return true;
    }

    static double sign(double value) {
        return value >= 0.0 ? 1.0 : -1.0;
    }

    ImageViewerAction ImageViewer::draw() {
        const double frame_delta = frame_timer.restart().asSeconds();
        const double scroll_speed_key_input = 50.0;
        const double scroll_speed_mouse_wheel = 600.0;
        const double scroll_speed_autoscroll = 10.0;
        const double scroll_deaccel = 0.96;

        if(!window_size_set) {
            auto window_size_i = window->getSize();
            window_size.x = window_size_i.x;
            window_size.y = window_size_i.y;
            window_size_set = true;
        }

        // TODO: Only redraw when scrolling and when image has finished downloading
        sf::Event event;
        while(window->pollEvent(event)) {
            if(event.type == sf::Event::KeyPressed) {
                if(event.key.code == sf::Keyboard::Q && event.key.control)
                    window->close();
            }

            if(event.type == sf::Event::Resized) {
                window_size.x = event.size.width;
                window_size.y = event.size.height;
                sf::FloatRect visible_area(0, 0, window_size.x, window_size.y);
                window->setView(sf::View(visible_area));
                //redraw = true;
            } else if(event.type == sf::Event::GainedFocus) {
                //redraw = true;
            } else if(event.type == sf::Event::KeyPressed) {
                if(event.key.code == sf::Keyboard::Up || (event.key.control && event.key.code == sf::Keyboard::K))
                    up_pressed = true;
                if(event.key.code == sf::Keyboard::Down || (event.key.control && event.key.code == sf::Keyboard::J))
                    down_pressed = true;

                if(event.key.code == sf::Keyboard::Escape)
                    return ImageViewerAction::RETURN;
                
                if(event.key.code == sf::Keyboard::I)
                    return ImageViewerAction::SWITCH_TO_SINGLE_IMAGE_MODE;

                if(event.key.code == sf::Keyboard::F)
                    *fit_image_to_window = !*fit_image_to_window;
            } else if(event.type == sf::Event::KeyReleased) {
                if(event.key.code == sf::Keyboard::Up || (event.key.control && event.key.code == sf::Keyboard::K))
                    up_pressed = false;
                if(event.key.code == sf::Keyboard::Down || (event.key.control && event.key.code == sf::Keyboard::J))
                    down_pressed = false;
            } else if(event.type == sf::Event::MouseWheelScrolled && event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel) {
                scroll_speed += scroll_speed_mouse_wheel * event.mouseWheelScroll.delta * frame_delta;
            } else if(event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Button::Middle) {
                middle_mouse_scrolling = true;
                autoscroll_start_y = sf::Mouse::getPosition(*window).y;
                if(has_size_vertical_cursor)
                    window->setMouseCursor(size_vertical_cursor);

            } else if(event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Button::Middle) {
                middle_mouse_scrolling = false;
                scroll_speed = 0.0;
                if(has_default_cursor)
                    window->setMouseCursor(default_cursor);
            }
        }

        if(up_pressed)
            scroll_speed += scroll_speed_key_input * frame_delta;
        if(down_pressed)
            scroll_speed -= scroll_speed_key_input * frame_delta;

        if(middle_mouse_scrolling) {
            double distance_to_start_y = (double)sf::Mouse::getPosition(*window).y - autoscroll_start_y;
            double dist_abs = std::abs(distance_to_start_y);
            dist_abs -= 20.0;
            if(dist_abs < 0.0)
                dist_abs = 0.0;
            scroll_speed = -(dist_abs * sign(distance_to_start_y)) * scroll_speed_autoscroll * frame_delta;
            const double max_speed = 100.0;
            if(scroll_speed > max_speed)
                scroll_speed = max_speed;
            if(scroll_speed < -max_speed)
                scroll_speed = -max_speed;
            scroll += scroll_speed;
        } else {
            const double max_speed = 100.0;
            if(scroll_speed > max_speed)
                scroll_speed = max_speed;
            if(scroll_speed < -max_speed)
                scroll_speed = -max_speed;

            scroll_speed *= scroll_deaccel;
            if(std::abs(scroll_speed) < 0.01) {
                scroll_speed = 0.0;
                scroll = std::round(scroll); /* Better image quality! */
            } else {
                scroll += scroll_speed;
            }
        }

        min_page_center_dist = 9999999.0;
        page_closest_to_center = -1;

        bool loaded_textures_changed = false;
        int page_i = 0;
        for(auto &page_data : image_data) {
            if(page_data) {
                if(page_data->image_status == ImageStatus::LOADED && page_data->image->getSize().x > 0 && page_data->image->getSize().y > 0) {
                    if(page_data->texture.loadFromImage(*page_data->image)) {
                        page_data->texture.setSmooth(true);
                        //page_data->texture.generateMipmap();
                        double height_before = get_page_size(page_i).y;
                        page_data->image_status = ImageStatus::APPLIED_TO_TEXTURE;
                        page_data->sprite.setTexture(page_data->texture, true);
                        sf::Vector2u texture_size = image_data[page_i]->texture.getSize();
                        page_size[page_i].size = sf::Vector2<double>(texture_size.x, texture_size.y);
                        page_size[page_i].loaded = true;
                        double height_after = get_page_size(page_i).y;

                        double height_diff = height_before - height_after;
                        if(scroll_speed <= 0.0 && page_i < current_page) {
                            scroll -= height_diff;
                        }
                    } else {
                        page_data->image_status = ImageStatus::FAILED_TO_LOAD;
                    }
                    page_data->image.reset();
                    loaded_textures_changed = true;
                }
                page_data->visible_on_screen = false;
            }
            ++page_i;
        }

        const sf::Vector2<double> selected_page_size = get_page_size(current_page);
        render_page(*window, current_page, window_size.y*0.5);
        //if(!focused_page_rendered)
        //    return;

        // Render previous pages
        double page_offset = window_size.y*0.5 - selected_page_size.y*0.5;
        int page = current_page - 1;
        while(true) {
            const sf::Vector2<double> image_size = get_page_size(page);
            page_offset -= image_size.y*0.5;
            if(!render_page(*window, page, page_offset))
                break;
            --page;
            page_offset -= image_size.y*0.5;
        }

        // Render next pages
        page_offset = window_size.y*0.5 + selected_page_size.y*0.5;
        page = current_page + 1;
        while(true) {
            const sf::Vector2<double> image_size = get_page_size(page);
            page_offset += image_size.y*0.5;
            if(!render_page(*window, page, page_offset))
                break;
            ++page;
            page_offset += image_size.y*0.5;
        }

        if(page_closest_to_center != -1) {
            focused_page = page_closest_to_center;
        }

        if(focused_page != prev_focused_page) {
            prev_focused_page = focused_page;
            page_text.setString(content_title + " | " + chapter_title + " | Page " + std::to_string(1 + focused_page) + "/" + std::to_string(num_pages));
        }

        const float font_height = page_text.getCharacterSize() + 8.0f;
        const float background_height = font_height + 6.0f;

        sf::RectangleShape page_text_background(sf::Vector2f(window_size.x, background_height));
        page_text_background.setFillColor(sf::Color(0, 0, 0, 150));
        page_text_background.setPosition(0.0f, window_size.y - background_height);
        window->draw(page_text_background);

        auto page_text_bounds = page_text.getLocalBounds();
        page_text.setPosition(std::floor(window_size.x * 0.5f - page_text_bounds.width * 0.5f), std::floor(window_size.y - background_height * 0.5f - font_height * 0.5f));
        window->draw(page_text);

        // Free pages that are not visible on the screen
        int i = 0;
        for(auto &page_data : image_data) {
            if(page_data && !page_data->visible_on_screen) {
                //fprintf(stderr, "ImageViewer: Unloaded page %d\n", 1 + i);
                page_data.reset();
                loaded_textures_changed = true;
            }
            ++i;
        }

        if(loaded_textures_changed)
            malloc_trim(0);

        return ImageViewerAction::NONE;
    }

    int ImageViewer::get_focused_page() const {
        return 1 + focused_page;
    }

    sf::Vector2<double> ImageViewer::get_page_size(int page) {
        sf::Vector2<double> no_image_page_size = get_no_image_size_scaled(window_size, *fit_image_to_window);

        if(page < 0 || page >= (int)image_data.size())
            return no_image_page_size;

        if(page_size[page].loaded) {
            sf::Vector2f texture_size_f(page_size[page].size.x, page_size[page].size.y);
            sf::Vector2f content_size(window_size.x, window_size.y);

            sf::Vector2f image_scale;
            if(*fit_image_to_window)
                image_scale = get_ratio(texture_size_f, wrap_to_size_x(texture_size_f, content_size));
            else
                image_scale = get_ratio(texture_size_f, clamp_to_size_x(texture_size_f, content_size));

            return sf::Vector2<double>(page_size[page].size.x * image_scale.x, page_size[page].size.y * image_scale.y);
        }

        if(!image_data[page] || image_data[page]->image_status != ImageStatus::APPLIED_TO_TEXTURE)
            return no_image_page_size;

        // Do not scale here, because this will be used to set page_size[page].size
        sf::Vector2u texture_size = image_data[page]->texture.getSize();
        return sf::Vector2<double>(texture_size.x, texture_size.y);
    }
}