1 // Copyright (C) 2014-2018 Manuel Schneider 2 3 #pragma once 4 #include <QAbstractListModel> 5 #include <QFuture> 6 #include <QFutureWatcher> 7 #include <QTimer> 8 #include <chrono> 9 #include <map> 10 #include <memory> 11 #include <set> 12 #include <utility> 13 #include <vector> 14 #include "albert/query.h" 15 16 namespace Core { 17 18 class QueryHandler; 19 class FallbackProvider; 20 class Extension; 21 class Item; 22 23 struct QueryStatistics { 24 QString input; 25 std::chrono::system_clock::time_point start; 26 std::chrono::system_clock::time_point end; 27 std::map<QString, uint> runtimes; 28 bool cancelled = false; 29 QString activatedItem; 30 }; 31 32 33 /** 34 * @brief The QueryExecution class 35 * Represents the execution of a query 36 */ 37 class QueryExecution : public QAbstractListModel 38 { 39 Q_OBJECT 40 41 public: 42 43 enum class State { Idle, Running, Finished }; 44 45 QueryExecution(const std::set<QueryHandler*> &, 46 const std::set<FallbackProvider*> &, 47 const QString &queryString, 48 std::map<QString,uint> scores, 49 bool fetchIncrementally); 50 ~QueryExecution() override; 51 52 const State &state() const; 53 54 const Query *query(); 55 56 void run(); 57 void cancel(); 58 59 // Model interface 60 int rowCount(const QModelIndex &) const override; 61 QHash<int,QByteArray> roleNames() const override; 62 QVariant data(const QModelIndex &index, int role) const override; 63 bool setData(const QModelIndex &index, const QVariant &value, int role) override; 64 bool canFetchMore(const QModelIndex &) const override; 65 void fetchMore(const QModelIndex &) override; 66 67 QueryStatistics stats; 68 69 private: 70 71 void setState(State state); 72 73 void runBatchHandlers(); 74 void onBatchHandlersFinished(); 75 void runRealtimeHandlers(); 76 void onRealtimeHandlersFinsished(); 77 void insertPendingResults(); 78 79 bool isValid_ = true; 80 81 Query query_; 82 State state_; 83 84 std::set<QueryHandler*> batchHandlers_; 85 std::set<QueryHandler*> realtimeHandlers_; 86 87 mutable std::vector<std::pair<std::shared_ptr<Item>, uint>> results_; 88 mutable std::vector<std::pair<std::shared_ptr<Item>, uint>> fallbacks_; 89 mutable int sortedItems_ = 0; 90 bool fetchIncrementally_ = false; 91 92 QTimer fiftyMsTimer_; 93 94 QFuture<std::pair<QueryHandler*,uint>> future_; 95 QFutureWatcher<std::pair<QueryHandler*,uint>> futureWatcher_; 96 97 signals: 98 99 void resultsReady(QAbstractItemModel*); 100 void stateChanged(State state); 101 102 }; 103 104 } 105 106 107