Scheduler.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. var _util = require("zrender/lib/core/util");
  20. var each = _util.each;
  21. var map = _util.map;
  22. var isFunction = _util.isFunction;
  23. var createHashMap = _util.createHashMap;
  24. var noop = _util.noop;
  25. var _task = require("./task");
  26. var createTask = _task.createTask;
  27. var _component = require("../util/component");
  28. var getUID = _component.getUID;
  29. var GlobalModel = require("../model/Global");
  30. var ExtensionAPI = require("../ExtensionAPI");
  31. var _model = require("../util/model");
  32. var normalizeToArray = _model.normalizeToArray;
  33. /*
  34. * Licensed to the Apache Software Foundation (ASF) under one
  35. * or more contributor license agreements. See the NOTICE file
  36. * distributed with this work for additional information
  37. * regarding copyright ownership. The ASF licenses this file
  38. * to you under the Apache License, Version 2.0 (the
  39. * "License"); you may not use this file except in compliance
  40. * with the License. You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing,
  45. * software distributed under the License is distributed on an
  46. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47. * KIND, either express or implied. See the License for the
  48. * specific language governing permissions and limitations
  49. * under the License.
  50. */
  51. /**
  52. * @module echarts/stream/Scheduler
  53. */
  54. /**
  55. * @constructor
  56. */
  57. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  58. this.ecInstance = ecInstance;
  59. this.api = api;
  60. this.unfinished; // Fix current processors in case that in some rear cases that
  61. // processors might be registered after echarts instance created.
  62. // Register processors incrementally for a echarts instance is
  63. // not supported by this stream architecture.
  64. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  65. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  66. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  67. /**
  68. * @private
  69. * @type {
  70. * [handlerUID: string]: {
  71. * seriesTaskMap?: {
  72. * [seriesUID: string]: Task
  73. * },
  74. * overallTask?: Task
  75. * }
  76. * }
  77. */
  78. this._stageTaskMap = createHashMap();
  79. }
  80. var proto = Scheduler.prototype;
  81. /**
  82. * @param {module:echarts/model/Global} ecModel
  83. * @param {Object} payload
  84. */
  85. proto.restoreData = function (ecModel, payload) {
  86. // TODO: Only restore needed series and components, but not all components.
  87. // Currently `restoreData` of all of the series and component will be called.
  88. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  89. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  90. // and some components like coordinate system, axes, dataZoom, visualMap only
  91. // need their target series refresh.
  92. // (1) If we are implementing this feature some day, we should consider these cases:
  93. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  94. // on the settings of `dataZoom`), it should be re-performed if the component
  95. // is modified by `setOption`.
  96. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  97. // it should be re-performed when the result array of `getTargetSeries` changed.
  98. // We use `dependencies` to cover these issues.
  99. // (3) How to update target series when coordinate system related components modified.
  100. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  101. // and this case all of the tasks will be set as dirty.
  102. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  103. // depends on all of the series.
  104. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  105. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  106. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  107. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  108. // probably cause state chaos (consider `dataZoomProcessor`).
  109. this._stageTaskMap.each(function (taskRecord) {
  110. var overallTask = taskRecord.overallTask;
  111. overallTask && overallTask.dirty();
  112. });
  113. }; // If seriesModel provided, incremental threshold is check by series data.
  114. proto.getPerformArgs = function (task, isBlock) {
  115. // For overall task
  116. if (!task.__pipeline) {
  117. return;
  118. }
  119. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  120. var pCtx = pipeline.context;
  121. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  122. var step = incremental ? pipeline.step : null;
  123. var modDataCount = pCtx && pCtx.modDataCount;
  124. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  125. return {
  126. step: step,
  127. modBy: modBy,
  128. modDataCount: modDataCount
  129. };
  130. };
  131. proto.getPipeline = function (pipelineId) {
  132. return this._pipelineMap.get(pipelineId);
  133. };
  134. /**
  135. * Current, progressive rendering starts from visual and layout.
  136. * Always detect render mode in the same stage, avoiding that incorrect
  137. * detection caused by data filtering.
  138. * Caution:
  139. * `updateStreamModes` use `seriesModel.getData()`.
  140. */
  141. proto.updateStreamModes = function (seriesModel, view) {
  142. var pipeline = this._pipelineMap.get(seriesModel.uid);
  143. var data = seriesModel.getData();
  144. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  145. // animation frame. Note that some types of series do not provide
  146. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  147. // use the term `incremental` but not `progressive` to describe the
  148. // case that `chart.appendData`.
  149. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  150. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  151. // see `test/candlestick-large3.html`
  152. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  153. seriesModel.pipelineContext = pipeline.context = {
  154. progressiveRender: progressiveRender,
  155. modDataCount: modDataCount,
  156. large: large
  157. };
  158. };
  159. proto.restorePipelines = function (ecModel) {
  160. var scheduler = this;
  161. var pipelineMap = scheduler._pipelineMap = createHashMap();
  162. ecModel.eachSeries(function (seriesModel) {
  163. var progressive = seriesModel.getProgressive();
  164. var pipelineId = seriesModel.uid;
  165. pipelineMap.set(pipelineId, {
  166. id: pipelineId,
  167. head: null,
  168. tail: null,
  169. threshold: seriesModel.getProgressiveThreshold(),
  170. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  171. blockIndex: -1,
  172. step: Math.round(progressive || 700),
  173. count: 0
  174. });
  175. pipe(scheduler, seriesModel, seriesModel.dataTask);
  176. });
  177. };
  178. proto.prepareStageTasks = function () {
  179. var stageTaskMap = this._stageTaskMap;
  180. var ecModel = this.ecInstance.getModel();
  181. var api = this.api;
  182. each(this._allHandlers, function (handler) {
  183. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  184. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  185. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  186. }, this);
  187. };
  188. proto.prepareView = function (view, model, ecModel, api) {
  189. var renderTask = view.renderTask;
  190. var context = renderTask.context;
  191. context.model = model;
  192. context.ecModel = ecModel;
  193. context.api = api;
  194. renderTask.__block = !view.incrementalPrepareRender;
  195. pipe(this, model, renderTask);
  196. };
  197. proto.performDataProcessorTasks = function (ecModel, payload) {
  198. // If we do not use `block` here, it should be considered when to update modes.
  199. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {
  200. block: true
  201. });
  202. }; // opt
  203. // opt.visualType: 'visual' or 'layout'
  204. // opt.setDirty
  205. proto.performVisualTasks = function (ecModel, payload, opt) {
  206. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  207. };
  208. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  209. opt = opt || {};
  210. var unfinished;
  211. each(stageHandlers, function (stageHandler, idx) {
  212. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  213. return;
  214. }
  215. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  216. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  217. var overallTask = stageHandlerRecord.overallTask;
  218. if (overallTask) {
  219. var overallNeedDirty;
  220. var agentStubMap = overallTask.agentStubMap;
  221. agentStubMap.each(function (stub) {
  222. if (needSetDirty(opt, stub)) {
  223. stub.dirty();
  224. overallNeedDirty = true;
  225. }
  226. });
  227. overallNeedDirty && overallTask.dirty();
  228. updatePayload(overallTask, payload);
  229. var performArgs = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  230. // then execute the overall task. And stub will call seriesModel.setData,
  231. // which ensures that in the overallTask seriesModel.getData() will not
  232. // return incorrect data.
  233. agentStubMap.each(function (stub) {
  234. stub.perform(performArgs);
  235. });
  236. unfinished |= overallTask.perform(performArgs);
  237. } else if (seriesTaskMap) {
  238. seriesTaskMap.each(function (task, pipelineId) {
  239. if (needSetDirty(opt, task)) {
  240. task.dirty();
  241. }
  242. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  243. // if intending to decalare `performRawSeries` in handlers, only
  244. // stream-independent (specifically, data item independent) operations can be
  245. // performed. Because is a series is filtered, most of the tasks will not
  246. // be performed. A stream-dependent operation probably cause wrong biz logic.
  247. // Perhaps we should not provide a separate callback for this case instead
  248. // of providing the config `performRawSeries`. The stream-dependent operaions
  249. // and stream-independent operations should better not be mixed.
  250. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  251. updatePayload(task, payload);
  252. unfinished |= task.perform(performArgs);
  253. });
  254. }
  255. });
  256. function needSetDirty(opt, task) {
  257. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  258. }
  259. scheduler.unfinished |= unfinished;
  260. }
  261. proto.performSeriesTasks = function (ecModel) {
  262. var unfinished;
  263. ecModel.eachSeries(function (seriesModel) {
  264. // Progress to the end for dataInit and dataRestore.
  265. unfinished |= seriesModel.dataTask.perform();
  266. });
  267. this.unfinished |= unfinished;
  268. };
  269. proto.plan = function () {
  270. // Travel pipelines, check block.
  271. this._pipelineMap.each(function (pipeline) {
  272. var task = pipeline.tail;
  273. do {
  274. if (task.__block) {
  275. pipeline.blockIndex = task.__idxInPipeline;
  276. break;
  277. }
  278. task = task.getUpstream();
  279. } while (task);
  280. });
  281. };
  282. var updatePayload = proto.updatePayload = function (task, payload) {
  283. payload !== 'remain' && (task.context.payload = payload);
  284. };
  285. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  286. var seriesTaskMap = stageHandlerRecord.seriesTaskMap || (stageHandlerRecord.seriesTaskMap = createHashMap());
  287. var seriesType = stageHandler.seriesType;
  288. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  289. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  290. // it works but it may cause other irrelevant charts blocked.
  291. if (stageHandler.createOnAllSeries) {
  292. ecModel.eachRawSeries(create);
  293. } else if (seriesType) {
  294. ecModel.eachRawSeriesByType(seriesType, create);
  295. } else if (getTargetSeries) {
  296. getTargetSeries(ecModel, api).each(create);
  297. }
  298. function create(seriesModel) {
  299. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  300. // Reuse original task instance.
  301. var task = seriesTaskMap.get(pipelineId) || seriesTaskMap.set(pipelineId, createTask({
  302. plan: seriesTaskPlan,
  303. reset: seriesTaskReset,
  304. count: seriesTaskCount
  305. }));
  306. task.context = {
  307. model: seriesModel,
  308. ecModel: ecModel,
  309. api: api,
  310. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  311. plan: stageHandler.plan,
  312. reset: stageHandler.reset,
  313. scheduler: scheduler
  314. };
  315. pipe(scheduler, seriesModel, task);
  316. } // Clear unused series tasks.
  317. var pipelineMap = scheduler._pipelineMap;
  318. seriesTaskMap.each(function (task, pipelineId) {
  319. if (!pipelineMap.get(pipelineId)) {
  320. task.dispose();
  321. seriesTaskMap.removeKey(pipelineId);
  322. }
  323. });
  324. }
  325. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  326. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  327. || createTask({
  328. reset: overallTaskReset
  329. });
  330. overallTask.context = {
  331. ecModel: ecModel,
  332. api: api,
  333. overallReset: stageHandler.overallReset,
  334. scheduler: scheduler
  335. }; // Reuse orignal stubs.
  336. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  337. var seriesType = stageHandler.seriesType;
  338. var getTargetSeries = stageHandler.getTargetSeries;
  339. var overallProgress = true;
  340. var modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add
  341. // stub in each pipelines, it will set the overall task dirty when the pipeline
  342. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  343. // we set the pipeline block.
  344. if (seriesType) {
  345. ecModel.eachRawSeriesByType(seriesType, createStub);
  346. } else if (getTargetSeries) {
  347. getTargetSeries(ecModel, api).each(createStub);
  348. } // Otherwise, (usually it is legancy case), the overall task will only be
  349. // executed when upstream dirty. Otherwise the progressive rendering of all
  350. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  351. // dirty info from upsteam.
  352. else {
  353. overallProgress = false;
  354. each(ecModel.getSeries(), createStub);
  355. }
  356. function createStub(seriesModel) {
  357. var pipelineId = seriesModel.uid;
  358. var stub = agentStubMap.get(pipelineId);
  359. if (!stub) {
  360. stub = agentStubMap.set(pipelineId, createTask({
  361. reset: stubReset,
  362. onDirty: stubOnDirty
  363. })); // When the result of `getTargetSeries` changed, the overallTask
  364. // should be set as dirty and re-performed.
  365. overallTask.dirty();
  366. }
  367. stub.context = {
  368. model: seriesModel,
  369. overallProgress: overallProgress,
  370. modifyOutputEnd: modifyOutputEnd
  371. };
  372. stub.agent = overallTask;
  373. stub.__block = overallProgress;
  374. pipe(scheduler, seriesModel, stub);
  375. } // Clear unused stubs.
  376. var pipelineMap = scheduler._pipelineMap;
  377. agentStubMap.each(function (stub, pipelineId) {
  378. if (!pipelineMap.get(pipelineId)) {
  379. stub.dispose(); // When the result of `getTargetSeries` changed, the overallTask
  380. // should be set as dirty and re-performed.
  381. overallTask.dirty();
  382. agentStubMap.removeKey(pipelineId);
  383. }
  384. });
  385. }
  386. function overallTaskReset(context) {
  387. context.overallReset(context.ecModel, context.api, context.payload);
  388. }
  389. function stubReset(context, upstreamContext) {
  390. return context.overallProgress && stubProgress;
  391. }
  392. function stubProgress() {
  393. this.agent.dirty();
  394. this.getDownstream().dirty();
  395. }
  396. function stubOnDirty() {
  397. this.agent && this.agent.dirty();
  398. }
  399. function seriesTaskPlan(context) {
  400. return context.plan && context.plan(context.model, context.ecModel, context.api, context.payload);
  401. }
  402. function seriesTaskReset(context) {
  403. if (context.useClearVisual) {
  404. context.data.clearAllVisual();
  405. }
  406. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  407. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  408. return makeSeriesTaskProgress(idx);
  409. }) : singleSeriesTaskProgress;
  410. }
  411. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  412. function makeSeriesTaskProgress(resetDefineIdx) {
  413. return function (params, context) {
  414. var data = context.data;
  415. var resetDefine = context.resetDefines[resetDefineIdx];
  416. if (resetDefine && resetDefine.dataEach) {
  417. for (var i = params.start; i < params.end; i++) {
  418. resetDefine.dataEach(data, i);
  419. }
  420. } else if (resetDefine && resetDefine.progress) {
  421. resetDefine.progress(params, data);
  422. }
  423. };
  424. }
  425. function seriesTaskCount(context) {
  426. return context.data.count();
  427. }
  428. function pipe(scheduler, seriesModel, task) {
  429. var pipelineId = seriesModel.uid;
  430. var pipeline = scheduler._pipelineMap.get(pipelineId);
  431. !pipeline.head && (pipeline.head = task);
  432. pipeline.tail && pipeline.tail.pipe(task);
  433. pipeline.tail = task;
  434. task.__idxInPipeline = pipeline.count++;
  435. task.__pipeline = pipeline;
  436. }
  437. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  438. if (isFunction(stageHandler)) {
  439. stageHandler = {
  440. overallReset: stageHandler,
  441. seriesType: detectSeriseType(stageHandler)
  442. };
  443. }
  444. stageHandler.uid = getUID('stageHandler');
  445. visualType && (stageHandler.visualType = visualType);
  446. return stageHandler;
  447. };
  448. /**
  449. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  450. * To ensure that they can work normally, they should work in block mode, that is,
  451. * they should not be started util the previous tasks finished. So they cause the
  452. * progressive rendering disabled. We try to detect the series type, to narrow down
  453. * the block range to only the series type they concern, but not all series.
  454. */
  455. function detectSeriseType(legacyFunc) {
  456. seriesType = null;
  457. try {
  458. // Assume there is no async when calling `eachSeriesByType`.
  459. legacyFunc(ecModelMock, apiMock);
  460. } catch (e) {}
  461. return seriesType;
  462. }
  463. var ecModelMock = {};
  464. var apiMock = {};
  465. var seriesType;
  466. mockMethods(ecModelMock, GlobalModel);
  467. mockMethods(apiMock, ExtensionAPI);
  468. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  469. seriesType = type;
  470. };
  471. ecModelMock.eachComponent = function (cond) {
  472. if (cond.mainType === 'series' && cond.subType) {
  473. seriesType = cond.subType;
  474. }
  475. };
  476. function mockMethods(target, Clz) {
  477. /* eslint-disable */
  478. for (var name in Clz.prototype) {
  479. // Do not use hasOwnProperty
  480. target[name] = noop;
  481. }
  482. /* eslint-enable */
  483. }
  484. var _default = Scheduler;
  485. module.exports = _default;