Scheduler.js 20 KB

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