Scheduler.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 restroe 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);
  243. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  244. updatePayload(task, payload);
  245. unfinished |= task.perform(performArgs);
  246. });
  247. }
  248. });
  249. function needSetDirty(opt, task) {
  250. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  251. }
  252. scheduler.unfinished |= unfinished;
  253. }
  254. proto.performSeriesTasks = function (ecModel) {
  255. var unfinished;
  256. ecModel.eachSeries(function (seriesModel) {
  257. // Progress to the end for dataInit and dataRestore.
  258. unfinished |= seriesModel.dataTask.perform();
  259. });
  260. this.unfinished |= unfinished;
  261. };
  262. proto.plan = function () {
  263. // Travel pipelines, check block.
  264. this._pipelineMap.each(function (pipeline) {
  265. var task = pipeline.tail;
  266. do {
  267. if (task.__block) {
  268. pipeline.blockIndex = task.__idxInPipeline;
  269. break;
  270. }
  271. task = task.getUpstream();
  272. } while (task);
  273. });
  274. };
  275. var updatePayload = proto.updatePayload = function (task, payload) {
  276. payload !== 'remain' && (task.context.payload = payload);
  277. };
  278. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  279. var seriesTaskMap = stageHandlerRecord.seriesTaskMap || (stageHandlerRecord.seriesTaskMap = createHashMap());
  280. var seriesType = stageHandler.seriesType;
  281. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  282. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  283. // it works but it may cause other irrelevant charts blocked.
  284. if (stageHandler.createOnAllSeries) {
  285. ecModel.eachRawSeries(create);
  286. } else if (seriesType) {
  287. ecModel.eachRawSeriesByType(seriesType, create);
  288. } else if (getTargetSeries) {
  289. getTargetSeries(ecModel, api).each(create);
  290. }
  291. function create(seriesModel) {
  292. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  293. // Reuse original task instance.
  294. var task = seriesTaskMap.get(pipelineId) || seriesTaskMap.set(pipelineId, createTask({
  295. plan: seriesTaskPlan,
  296. reset: seriesTaskReset,
  297. count: seriesTaskCount
  298. }));
  299. task.context = {
  300. model: seriesModel,
  301. ecModel: ecModel,
  302. api: api,
  303. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  304. plan: stageHandler.plan,
  305. reset: stageHandler.reset,
  306. scheduler: scheduler
  307. };
  308. pipe(scheduler, seriesModel, task);
  309. } // Clear unused series tasks.
  310. var pipelineMap = scheduler._pipelineMap;
  311. seriesTaskMap.each(function (task, pipelineId) {
  312. if (!pipelineMap.get(pipelineId)) {
  313. task.dispose();
  314. seriesTaskMap.removeKey(pipelineId);
  315. }
  316. });
  317. }
  318. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  319. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  320. || createTask({
  321. reset: overallTaskReset
  322. });
  323. overallTask.context = {
  324. ecModel: ecModel,
  325. api: api,
  326. overallReset: stageHandler.overallReset,
  327. scheduler: scheduler
  328. }; // Reuse orignal stubs.
  329. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  330. var seriesType = stageHandler.seriesType;
  331. var getTargetSeries = stageHandler.getTargetSeries;
  332. var overallProgress = true;
  333. var modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add
  334. // stub in each pipelines, it will set the overall task dirty when the pipeline
  335. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  336. // we set the pipeline block.
  337. if (seriesType) {
  338. ecModel.eachRawSeriesByType(seriesType, createStub);
  339. } else if (getTargetSeries) {
  340. getTargetSeries(ecModel, api).each(createStub);
  341. } // Otherwise, (usually it is legancy case), the overall task will only be
  342. // executed when upstream dirty. Otherwise the progressive rendering of all
  343. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  344. // dirty info from upsteam.
  345. else {
  346. overallProgress = false;
  347. each(ecModel.getSeries(), createStub);
  348. }
  349. function createStub(seriesModel) {
  350. var pipelineId = seriesModel.uid;
  351. var stub = agentStubMap.get(pipelineId);
  352. if (!stub) {
  353. stub = agentStubMap.set(pipelineId, createTask({
  354. reset: stubReset,
  355. onDirty: stubOnDirty
  356. })); // When the result of `getTargetSeries` changed, the overallTask
  357. // should be set as dirty and re-performed.
  358. overallTask.dirty();
  359. }
  360. stub.context = {
  361. model: seriesModel,
  362. overallProgress: overallProgress,
  363. modifyOutputEnd: modifyOutputEnd
  364. };
  365. stub.agent = overallTask;
  366. stub.__block = overallProgress;
  367. pipe(scheduler, seriesModel, stub);
  368. } // Clear unused stubs.
  369. var pipelineMap = scheduler._pipelineMap;
  370. agentStubMap.each(function (stub, pipelineId) {
  371. if (!pipelineMap.get(pipelineId)) {
  372. stub.dispose(); // When the result of `getTargetSeries` changed, the overallTask
  373. // should be set as dirty and re-performed.
  374. overallTask.dirty();
  375. agentStubMap.removeKey(pipelineId);
  376. }
  377. });
  378. }
  379. function overallTaskReset(context) {
  380. context.overallReset(context.ecModel, context.api, context.payload);
  381. }
  382. function stubReset(context, upstreamContext) {
  383. return context.overallProgress && stubProgress;
  384. }
  385. function stubProgress() {
  386. this.agent.dirty();
  387. this.getDownstream().dirty();
  388. }
  389. function stubOnDirty() {
  390. this.agent && this.agent.dirty();
  391. }
  392. function seriesTaskPlan(context) {
  393. return context.plan && context.plan(context.model, context.ecModel, context.api, context.payload);
  394. }
  395. function seriesTaskReset(context) {
  396. if (context.useClearVisual) {
  397. context.data.clearAllVisual();
  398. }
  399. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  400. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  401. return makeSeriesTaskProgress(idx);
  402. }) : singleSeriesTaskProgress;
  403. }
  404. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  405. function makeSeriesTaskProgress(resetDefineIdx) {
  406. return function (params, context) {
  407. var data = context.data;
  408. var resetDefine = context.resetDefines[resetDefineIdx];
  409. if (resetDefine && resetDefine.dataEach) {
  410. for (var i = params.start; i < params.end; i++) {
  411. resetDefine.dataEach(data, i);
  412. }
  413. } else if (resetDefine && resetDefine.progress) {
  414. resetDefine.progress(params, data);
  415. }
  416. };
  417. }
  418. function seriesTaskCount(context) {
  419. return context.data.count();
  420. }
  421. function pipe(scheduler, seriesModel, task) {
  422. var pipelineId = seriesModel.uid;
  423. var pipeline = scheduler._pipelineMap.get(pipelineId);
  424. !pipeline.head && (pipeline.head = task);
  425. pipeline.tail && pipeline.tail.pipe(task);
  426. pipeline.tail = task;
  427. task.__idxInPipeline = pipeline.count++;
  428. task.__pipeline = pipeline;
  429. }
  430. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  431. if (isFunction(stageHandler)) {
  432. stageHandler = {
  433. overallReset: stageHandler,
  434. seriesType: detectSeriseType(stageHandler)
  435. };
  436. }
  437. stageHandler.uid = getUID('stageHandler');
  438. visualType && (stageHandler.visualType = visualType);
  439. return stageHandler;
  440. };
  441. /**
  442. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  443. * To ensure that they can work normally, they should work in block mode, that is,
  444. * they should not be started util the previous tasks finished. So they cause the
  445. * progressive rendering disabled. We try to detect the series type, to narrow down
  446. * the block range to only the series type they concern, but not all series.
  447. */
  448. function detectSeriseType(legacyFunc) {
  449. seriesType = null;
  450. try {
  451. // Assume there is no async when calling `eachSeriesByType`.
  452. legacyFunc(ecModelMock, apiMock);
  453. } catch (e) {}
  454. return seriesType;
  455. }
  456. var ecModelMock = {};
  457. var apiMock = {};
  458. var seriesType;
  459. mockMethods(ecModelMock, GlobalModel);
  460. mockMethods(apiMock, ExtensionAPI);
  461. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  462. seriesType = type;
  463. };
  464. ecModelMock.eachComponent = function (cond) {
  465. if (cond.mainType === 'series' && cond.subType) {
  466. seriesType = cond.subType;
  467. }
  468. };
  469. function mockMethods(target, Clz) {
  470. /* eslint-disable */
  471. for (var name in Clz.prototype) {
  472. // Do not use hasOwnProperty
  473. target[name] = noop;
  474. }
  475. /* eslint-enable */
  476. }
  477. var _default = Scheduler;
  478. module.exports = _default;