Compare commits

..
420 Commits
Author SHA1 Message Date
Paris Kasidiaris 2221f70ff0 Bump version to 2.6.0
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-05-04 15:38:52 +00:00
Daniel Imms daad8d9c04 Merge pull request #652 from Tyriar/651_fix_travis_fail
Force failing mocha tests to return a exit code of 1
2017-05-04 08:35:37 -07:00
Daniel Imms 03d26e39c7 Force failing mocha tests to return a exit code of 1
Fixes #651
2017-05-03 10:06:53 -07:00
Paris Kasidiaris 64d3c089a2 Merge pull request #647 from Martin1994/orion_use
Add "Eclipse Orion" to "Real-World Uses".
2017-05-02 00:37:38 +03:00
Martin Chloride 938c011e63 Added "Eclipse Orion" to "Real-World Uses". 2017-05-01 17:12:07 -04:00
Paris Kasidiaris 66f6b88333 Merge pull request #645 from sourcelair/issue-#640-do-not-focus-on-open
Add `focus` argument in `Terminal.prototype.open`
2017-05-01 01:07:00 +03:00
Paris Kasidiaris 35f746c925 Add focus argument in Terminal.prototype.open
Fix #640
2017-04-26 10:37:07 +00:00
Paris Kasidiaris 944da28089 Merge pull request #643 from jsmecham/patch-1
Add "Terminal for Atom" to Real-World Uses
2017-04-24 17:43:20 +03:00
Justin Mecham 8f3e2b645a Added "Terminal for Atom" to Real-World Uses. 2017-04-23 14:36:01 -04:00
Daniel Imms 82b2a5305f Merge pull request #639 from Tyriar/638_retain_cursor_blink_interface
Keep cursor blink interval after a reset
2017-04-21 17:59:51 -07:00
Daniel Imms 6a2852ee26 Merge branch 'master' into 638_retain_cursor_blink_interface 2017-04-21 17:53:49 -07:00
Daniel Imms 526d6c4da9 Merge pull request #641 from Tyriar/support_demo_cursorStyle
Support cursorStyle selection in demo
2017-04-20 10:33:30 -07:00
Daniel Imms 46d62f4972 Support cursorStyle selection in demo 2017-04-19 18:16:48 -07:00
Daniel Imms 5cafcdb695 Keep cursor blink interval after a reset
Fixes #638
2017-04-19 11:22:18 -07:00
Paris Kasidiaris 2674258ead Merge pull request #635 from rstudio/master
Update README with RStudio under real-world uses.
2017-04-15 01:15:27 +03:00
Gary Ritchie b38be3a1d0 Update README with RStudio under real-world uses. 2017-04-14 10:50:15 -07:00
Daniel Imms 18a9f05626 Merge pull request #628 from saulcosta18/patch-1
Added Codevolve.com to README
2017-04-06 13:01:16 -07:00
Saul Costa bf34980c43 Added Codevolve.com to README
We use xterm.js for our courses at Codevolve.
2017-04-06 12:50:41 -07:00
Paris Kasidiaris d2f8f9dc1a Bump version to 2.5.0
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-04-05 18:48:57 +00:00
Daniel Imms df13469b6e Merge pull request #627 from Tyriar/591_element_on_validation
Give API access to valid link elements
2017-04-05 11:34:34 -07:00
Daniel Imms 584ec681af Merge remote-tracking branch 'ups/master' into 591_element_on_validation 2017-04-04 09:50:04 -07:00
Daniel Imms 0c5b5cca4a Merge pull request #623 from Tyriar/612_multiple_links_in_row
Support multiple link matches in a single row
2017-04-04 09:41:19 -07:00
Daniel Imms 64663bf4a8 Fix tests 2017-04-04 09:35:52 -07:00
Daniel Imms fe8334a873 Merge remote-tracking branch 'ups/master' into 612_multiple_links_in_row 2017-04-04 09:33:53 -07:00
Daniel Imms c74fd40e2a Merge pull request #619 from Tyriar/618_register_link_before_dom
Allow links to be registered before terminal is attached to DOM
2017-04-04 09:13:09 -07:00
Daniel Imms 0f8ff67451 Merge branch 'master' into 618_register_link_before_dom 2017-04-04 09:02:37 -07:00
Daniel Imms 8b0032c210 Merge branch 'master' into 612_multiple_links_in_row 2017-04-04 09:02:35 -07:00
Daniel Imms d9254ef2d9 Merge pull request #626 from Tyriar/625_cursor_blink_perf
Use setInterval over animation for cursor blink
2017-04-04 09:02:27 -07:00
Daniel Imms 66be05a962 Merge branch 'master' into 612_multiple_links_in_row 2017-04-04 09:00:47 -07:00
Daniel Imms 0e85a09dd3 Merge branch 'master' into 618_register_link_before_dom 2017-04-04 08:58:43 -07:00
Daniel Imms 0c4ba9fd67 Clear cursor blink interval on blur 2017-04-03 15:09:38 -07:00
Daniel Imms aca81c764a Use setInterval over animation for cursor blink
Fixes #625
2017-04-03 14:49:21 -07:00
Daniel Imms 6b3ddb97d1 Merge pull request #624 from InDieTasten/patch-1
Fix typos in comment
2017-03-31 13:27:29 -07:00
InDieTasten 26ccf2a316 Fix typos in comment 2017-03-31 22:16:11 +02:00
Daniel Imms 361894194a Merge branch 'master' into 612_multiple_links_in_row 2017-03-31 03:06:23 -07:00
Daniel Imms 8c2db8ddb8 More tests 2017-03-31 02:10:07 -07:00
Daniel Imms 5546baa927 Fix edge case 2017-03-31 01:54:21 -07:00
Daniel Imms d814009721 Add tests 2017-03-31 01:48:51 -07:00
Daniel Imms 08fd050c3f Support multiple link matches in a single row
Fixes #612
2017-03-31 01:48:35 -07:00
Daniel Imms 0b096d7d55 Merge pull request #621 from coderaiser/patch-1
Added Cloud Commander to real world uses
2017-03-30 11:31:11 -07:00
coderaiser 44cfb2dc87 Added Cloud Commander to real world uses 2017-03-30 14:26:56 +03:00
Daniel Imms b0624cadb7 Allow links to be registered before terminal is attached to DOM
Fixes #618
2017-03-24 11:04:04 -07:00
Paris Kasidiaris 045f361b0d Merge pull request #616 from LucianBuzzo/crop-lines
Prevent line data from being discarded on resize.
2017-03-20 09:52:22 +00:00
Lucian Buzzo cb77b9dc1a Prevent line data from being discarded on resize. 2017-03-19 08:26:37 +00:00
Paris Kasidiaris 0723dac596 Merge pull request #615 from andfoy/patch-1
Added Spyder IDE Terminal as a xterm case-use application
2017-03-19 00:26:41 +00:00
Edgar Andrés Margffoy Tuay 365f9b4c1b Added Spyder IDE as a xterm case-use application 2017-03-18 18:05:05 -05:00
Daniel Imms 2cf90d90f7 Merge pull request #610 from Tyriar/non_draggable_links
Ensure terminal links are not draggable
2017-03-17 09:22:05 -07:00
Daniel Imms da14f64d1b Merge branch 'master' into non_draggable_links 2017-03-17 02:27:07 -07:00
Paris Kasidiaris ef1b1c8ffc Merge pull request #608 from sourcelair/add-logo
Add xterm.js logo
2017-03-17 08:18:08 +00:00
Daniel Imms adde8ab2c3 Ensure terminal links are not draggable 2017-03-16 12:07:25 -07:00
Paris Kasidiaris 22cc8079dc Add xterm.js logo 2017-03-16 08:54:07 +00:00
Daniel Imms 6d25706300 Merge pull request #606 from Tyriar/vscode22640_tilde_path
Allow ~ char in linkify path and query fragments
2017-03-15 18:01:47 -07:00
Paris Kasidiaris 81419c980b Merge pull request #603 from sourcelair/fix-blurred-terminal-cursor
Fix cursor style on blurred terminals
2017-03-15 22:09:18 +00:00
Paris Kasidiaris 097e21f641 Merge pull request #604 from sourcelair/rebuild-on-css
Rebuild xterm.js even when CSS changes
2017-03-15 22:09:03 +00:00
Daniel Imms b68180b97b Allow ~ char in linkify path and query fragments 2017-03-15 13:55:57 -07:00
Daniel Imms d9059d18c0 Merge pull request #600 from sourcelair/Tyriar-patch-1
Polish development and contribution section
2017-03-15 10:53:03 -07:00
Paris Kasidiaris 5225a6e27a Rebuild xterm.js even when CSS changes
Otherwise you had to run `npm build` manually every time you changed a CSS file to see the updated result in the demo.
2017-03-15 18:36:06 +02:00
Paris Kasidiaris 9055bace96 Fix cursor style on blurred terminals 2017-03-15 18:28:17 +02:00
Paris Kasidiaris eb25e88754 Merge pull request #598 from mikesir87/fix-fit-calculation
Fixed characterHeight calculation, which could cause overflowing
2017-03-15 14:34:13 +00:00
Michael Irwin 0cb8ecc6f7 Use boundingClientRect instead of style to get actual height
PR #598
2017-03-15 09:06:56 -04:00
Daniel Imms 8cf76cc6e9 Polish development and contribution section 2017-03-14 15:15:36 -07:00
Michael Irwin 3c3a646d42 Fixed characterHeight calculation, which could cause overflowing
The previous calculation was simply using the height of the letter
W, but wasn't taking into account that each row has a lineHeight,
which might be greater. If the lineHeight is .4px off, after many
rows, it will cause the proposedGeometry to have an extra row,
potentially causing hidden rows (based on layout).
2017-03-14 17:02:53 -04:00
Paris Kasidiaris ff29fd69a3 Merge pull request #572 from AndrienkoAleksandr/gulpImprove
Use tsconfig.json data in gulpfile.js instead of hardcoded values.
2017-03-11 13:21:47 +00:00
Daniel Imms 91994a399c Merge pull request #582 from tmyt/propose/row-height
Support checking height in checkBoldBroken
2017-03-10 12:53:12 -08:00
Daniel Imms bef7137c92 Fix bug 2017-03-09 10:47:09 -08:00
Daniel Imms 11f62bab34 Expose setHypertextValidationCallback 2017-03-09 10:39:08 -08:00
Daniel Imms b66776a047 Include element in validationCallback
Fixes #591
2017-03-09 10:23:59 -08:00
Daniel Imms 2c151f444c Merge pull request #589 from warpdesign/patch-1
FIXED: typo
2017-03-08 15:52:55 -08:00
Nicolas Ramz d8f8b060cb FIXED: typo
`<div id="terminal"></div>` wasn't used, instead, a new one was created and used since getElementById('#terminal') returned null.
2017-03-09 00:47:29 +01:00
Daniel Imms ea9376019c Merge pull request #586 from AndrienkoAleksandr/cleanUpTsConfig
Clean up tsconfig.json.
2017-03-08 12:02:09 -08:00
Daniel Imms 008d1df106 Merge remote-tracking branch 'up/master' into cleanUpTsConfig 2017-03-08 11:47:56 -08:00
Daniel Imms ec91a6c7f4 Merge pull request #588 from Tyriar/587_csi_3_J
Implement CSI 3 J - Erase saved lines
2017-03-08 11:08:46 -08:00
yutaka 4b2ae6a79f Use rendered height for detect broken bold font. 2017-03-08 11:30:23 +00:00
yutaka 2ec756fd6b Use offsetWidth instead of scrollWidth
scrollWidth does not work on Chrome with `display: inline` element.
2017-03-08 05:11:26 +00:00
yutaka f0d5b40121 Detect bold font was broken correctly. 2017-03-08 04:54:18 +00:00
yutaka 31a0996b2f Revert "Set charMeasure.height values to each row height"
This reverts commit 43cb4f471f.
2017-03-08 00:27:22 +00:00
Daniel Imms 0bbd8f0a16 Implement CSI 3 J - Erase saved lines
Fixes #587
2017-03-07 14:01:42 -08:00
Paris Kasidiaris b1619e42fd Bump version to 2.4.0
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-03-07 09:38:48 +00:00
Daniel Imms 4cfec2fc09 Merge pull request #579 from Tyriar/578_ctrl_click_links
Require ctrl for link clicks
2017-03-06 07:21:58 -08:00
Aleksandr Andrienko 3d721a95bb Clean up tsconfig.json.
'include' field in the tsconfig.json defines source scope (top level of this scope is "src" folder), so we do not need 'exclude' folders in the root of the project, because this folders had already excluded by 'include' scope.

Signed-off-by: Aleksandr Andrienko <aandrienko@codenvy.com>
2017-03-06 13:17:01 +02:00
Aleksandr Andrienko dc3a136704 Use tsconfig.json data in gulpfile.js instead of hardcoded values.
Use tsconfig.json data in gulpfile.js instead of hardcoded values. Little code clean up

Signed-off-by: Aleksandr Andrienko <aandrienko@codenvy.com>
2017-03-06 12:25:22 +02:00
Daniel Imms 235ae2fbb9 Fix http link handler logic 2017-03-04 15:02:08 -08:00
Daniel Imms 1f518b0b45 Allow http link handler to fallback to standard handler 2017-03-04 14:44:11 -08:00
Daniel Imms ab34d53d6b Remove unused import 2017-03-04 14:09:13 -08:00
Daniel Imms aafb5333b9 Give event to handler 2017-03-04 14:08:05 -08:00
Daniel Imms 5e2791f981 Revert "Add fail handler"
This reverts commit 1ecc5674ac.
2017-03-04 14:01:40 -08:00
Daniel Imms 1ecc5674ac Add fail handler 2017-03-04 14:01:34 -08:00
Daniel Imms c9ad3a595a Merge pull request #584 from coderaiser/patch-1
Fix demo: wrong pid on windows #567
2017-03-03 14:38:55 -08:00
coderaiser 43558fa1dc Fix demo: wrong pid on windows #567 2017-03-03 23:40:36 +02:00
Daniel Imms 15a867d2b7 Support cmd+click on mac 2017-03-03 12:37:34 -08:00
yutaka 43cb4f471f Set charMeasure.height values to each row height 2017-03-03 07:57:05 +00:00
Daniel Imms 012051c1db Fix matchIndex on http 2017-03-02 17:35:10 -08:00
Daniel Imms b5483898da Merge remote-tracking branch 'upstream/master' into 578_ctrl_click_links 2017-03-02 17:34:30 -08:00
Daniel Imms c7b4c2beaf Require ctrl for link clicks
Fixes #578
2017-03-02 17:33:58 -08:00
Daniel Imms 8693d067e3 Merge pull request #577 from Tyriar/549_link_priority
Implement link matcher priorities
2017-03-02 15:24:09 -08:00
Daniel Imms 78d5fc9506 Fix bug with priority 2017-03-02 12:05:34 -08:00
Daniel Imms 7ac4f1a9be Implement link matcher priorities
Fixes #549
2017-03-02 11:25:27 -08:00
Daniel Imms 670fb01fbf Merge pull request #566 from Tyriar/linkify_issues
Linkify issues
2017-03-02 09:02:24 -08:00
Daniel Imms ec9608d54b Merge pull request #574 from Tyriar/link_validation_fixes
Link validation fixes
2017-03-02 00:42:01 -08:00
Daniel Imms dcffaf1c8c Ensure linkElement exists before firing validation callback 2017-03-01 09:38:59 -08:00
Daniel Imms efac5293c0 Use text cursor for invalid links
Part of #570
2017-03-01 09:37:30 -08:00
Daniel Imms c7563346a2 Merge pull request #571 from Tyriar/570_link_validation
Implement link validation
2017-03-01 09:12:53 -08:00
Daniel Imms 69906532b1 Remove test harness 2017-02-27 15:44:10 -08:00
Daniel Imms 9404fae725 Merge remote-tracking branch 'upstream/master' into linkify_issues 2017-02-27 12:59:59 -08:00
Daniel Imms 3542f15575 Don't expose CharMeasure/Linkifier for tests 2017-02-27 12:57:18 -08:00
Daniel Imms 15d79143e2 Get rid of exposed test method (phantom is gone) 2017-02-27 12:56:54 -08:00
Daniel Imms f6dafee748 Remove dead code 2017-02-27 12:52:54 -08:00
Daniel Imms 356d86ae74 Merge remote-tracking branch 'upstream/master' into 570_link_validation 2017-02-27 12:47:53 -08:00
Daniel Imms e673c6ec97 Upgrade to TypeScript 2.2 2017-02-27 11:54:55 -08:00
Daniel Imms 3e5fcf7004 Merge pull request #569 from wavebeem/issue/562
Fixes #562 adds Windows demo setup help
2017-02-27 11:52:47 -08:00
Daniel Imms 96d2a2bc68 Pin TypeScript at v2.1 to fix PhantomJS error 2017-02-27 11:47:57 -08:00
Daniel Imms b401992178 Add jsdom types 2017-02-27 11:22:59 -08:00
Daniel Imms 4c34351383 Remove PhantomJS completely 2017-02-27 11:22:50 -08:00
Daniel Imms 202b54afbb Convert CharMeasure phantom test to jsdom 2017-02-27 11:18:00 -08:00
Daniel Imms 26ebc3d944 Use jsdom instead of phantomjs for linkifier test 2017-02-27 11:00:12 -08:00
Daniel Imms d0f36e9939 Pin typescript 2.1 to prevent exports error 2017-02-27 10:02:12 -08:00
Daniel Imms 4c99c032ca Add tests 2017-02-27 09:47:36 -08:00
Daniel Imms 6198556e50 Implement link validation
Fixes #570
2017-02-27 08:35:59 -08:00
Brian Mock 514eba0e4e Fixes #562 adds Windows demo setup help 2017-02-25 12:16:18 -08:00
Daniel Imms 7279ee0f5f Support % in URLs 2017-02-24 08:56:42 -08:00
Daniel Imms ccadf3fcca Support percent and numbers in query/hash fragments 2017-02-23 10:02:18 -08:00
Daniel Imms cb80ce0d2c Link . and - in hash fragments and query strings 2017-02-23 09:55:05 -08:00
Daniel Imms 9aae43961f Support linking hash fragments 2017-02-23 09:53:20 -08:00
Daniel Imms b810687163 Support linking = in query strings 2017-02-23 09:42:59 -08:00
Daniel Imms 28d4ec779d Fix localhost links 2017-02-23 09:37:35 -08:00
Paris Kasidiaris cf4da6c748 Merge pull request #565 from sourcelair/issue-#531-coveralls
Fix #531: Submit code coverage to coveralls.io
2017-02-22 19:15:04 +02:00
Paris Kasidiaris e569b5669a Add coveralls badge 2017-02-22 16:22:50 +02:00
Paris Kasidiaris 695a9523fe Fix #531: Submit code coverage to coveralls.io 2017-02-22 16:17:22 +02:00
Daniel Imms 01b8e28a7d Merge pull request #556 from Tyriar/555_fix_mouse_coords
Use CharMeasure to determine mouse coordinates
2017-02-20 03:17:50 -08:00
Daniel Imms e221030a2b Merge pull request #559 from Tyriar/558_linkify_bad_trim
Remove bad trim optimization from Linkifier
2017-02-20 03:17:42 -08:00
Daniel Imms 88dc697392 Merge pull request #557 from Tyriar/CharMeasure_aria_hidden
Hide CharMeasure element from assistive technologies
2017-02-20 03:17:34 -08:00
Daniel Imms 99a270216c Remove bad trim optimization from Linkifier
This prevents whitespace from going missing after links are applied.

Fixes #558
2017-02-19 15:17:03 -08:00
Daniel Imms d06c920a2d Hide CharMeasure element from assistive technologies 2017-02-19 13:20:36 -08:00
Daniel Imms 5452986ce3 Use CharMeasure to determine mouse coordinates
Fixes #555
2017-02-19 12:34:36 -08:00
Daniel Imms ae69841174 Merge pull request #538 from Tyriar/455_linkify
Implement web links and custom link matcher registration
2017-02-17 11:40:59 -08:00
Daniel Imms e6fc80c13b Fix link matcher iteration direction 2017-02-17 10:22:55 -08:00
Daniel Imms a10ee8f58c Revert priority change, http handler needs to be top 2017-02-17 10:18:46 -08:00
Daniel Imms 3f69da2455 Support query string in linkifier 2017-02-17 10:06:35 -08:00
Daniel Imms a14a0834e9 Merge remote-tracking branch 'upstream/master' into 455_linkify 2017-02-17 10:05:22 -08:00
Daniel Imms c4f431849b Add a null check on linkifyRow 2017-02-16 22:41:08 -08:00
Daniel Imms ade3389cea Merge pull request #535 from Tyriar/534_phantomjs
Add PhantomJS test support and CharMeasure tests
2017-02-15 13:29:50 -08:00
Paris Kasidiaris 6873ba0909 Merge pull request #541 from AndrienkoAleksandr/FixSoftReset
Fix 'Autowrap Mode' after 'Soft Terminal reset' command.
2017-02-15 11:24:42 +02:00
Daniel Imms c3f31b5f65 Apply link matchers in reverse
This enables consumers to have full control.
2017-02-14 20:06:15 -08:00
Daniel Imms 3b62aa444b Improve jsdoc 2017-02-14 19:45:22 -08:00
Daniel Imms fb2b10b565 Merge pull request #545 from Martin1994/blink_cursor_color
Let blink animation support style inheritance
2017-02-14 19:23:22 -08:00
Martin Wang 345553012f Let blink animation support style inheritance
With this change, blinking cursor will use the same font and background
color that set before.
2017-02-14 12:35:39 -05:00
Daniel Imms fddc13d98e Merge pull request #544 from LucianBuzzo/master
Make fit plugin guard against non-existent parent element.
2017-02-13 13:26:14 -08:00
Lucian Buzzo aeb9f798c9 Make fit plugin guard against non-existent parent element. 2017-02-13 21:01:28 +00:00
Paris Kasidiaris 8fd44266a2 Bump version to 2.3.2
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-02-13 18:05:47 +00:00
Paris Kasidiaris ef4155fbf6 Merge pull request #542 from Tyriar/539_fix_initial_viewport_sync
Perform initial viewport sync after CharMeasure is ready
2017-02-13 20:05:03 +02:00
Daniel Imms 92f27d3144 Fix tests 2017-02-13 09:48:22 -08:00
Daniel Imms 5183332f6e Next link matcher ID must be non-static 2017-02-10 12:29:36 -08:00
Daniel Imms ee1de0980f Perform initial viewport sync after CharMeasure is ready
Fixes #539
2017-02-10 09:55:35 -08:00
Aleksandr Andrienko c53183d94b Fix default 'wraparoundMode' value for 'Soft reset'() XTERM terminal. 2017-02-10 16:52:19 +02:00
Daniel Imms 1ee774d01d Remove linkify test 2017-02-09 22:03:31 -08:00
Daniel Imms 1c030f57ef Force a refresh after register/deregister link matcher 2017-02-09 21:12:28 -08:00
Daniel Imms c8bb321654 Get custom link matcher working 2017-02-09 21:08:50 -08:00
Daniel Imms a1d71c9198 Properly queue linkify after refresh 2017-02-09 20:35:06 -08:00
Daniel Imms 55cb43d70b Add license 2017-02-09 20:12:35 -08:00
Daniel Imms 551159e0c3 Remove linkify addon 2017-02-09 20:10:01 -08:00
Daniel Imms 3bf31aa478 Polish 2017-02-09 20:09:47 -08:00
Daniel Imms 1316682343 Merge pull request #532 from AndrienkoAleksandr/cleanUpDependency
Remove excess library.
2017-02-09 20:01:46 -08:00
Daniel Imms 7167b06bf8 Add custom link handlers, use generic way for http handler 2017-02-08 20:44:22 -08:00
Daniel Imms 34582f9f65 Remove logs 2017-02-08 20:21:18 -08:00
Daniel Imms 8dc9ec5733 Only show underline on hover 2017-02-08 20:20:18 -08:00
Daniel Imms e8adf8ad2b Use gulp-mocha and attach run both test type in npm test 2017-02-08 20:06:14 -08:00
Daniel Imms 1306431e7c Add PhantomJS test support and CharMeasure tests
Fixes #534
2017-02-08 19:53:32 -08:00
Daniel Imms f7bc0fba4d Remove unnecessary variables 2017-02-08 18:57:45 -08:00
Paris Kasidiaris 639a2fd509 Bump version to 2.3.1
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-02-08 23:51:47 +00:00
Paris Kasidiaris b00083e0e5 Merge pull request #533 from vincentwoo/patch-2
Fix missing Number.isNaN in IE
2017-02-09 01:46:00 +02:00
Vincent Woo c3256556aa Fix missing Number.isNaN in IE
See https://github.com/sourcelair/xterm.js/pull/525#issuecomment-278497452
2017-02-08 15:33:20 -08:00
Paris Kasidiaris 8dd11f5587 Bump version to 2.3.0
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2017-02-08 22:24:56 +00:00
Daniel Imms 0f3ee21d9d Enable custom http link handlers 2017-02-08 14:13:30 -08:00
Daniel Imms a489037ec4 Improve node insertion, support custom link handlers 2017-02-08 13:50:36 -08:00
Aleksandr Andrienko c48388af14 Remove excess library.
Tsify lib used for browserify typescript sources. But folder /lib consist of js files has already compiled from TypeScript sources (by gulp task tsc). So Tsify library does nothing in this case.

Signed-off-by: Aleksandr Andrienko <aandrienko@codenvy.com>
2017-02-08 23:15:54 +02:00
Daniel Imms 2207d356f2 Initial linkify implementation
Part of 455
2017-02-08 11:11:52 -08:00
Daniel Imms 795cdb52dc Merge pull request #530 from Tyriar/fix_tests_on_windows
Disable escape sequence tests on windows
2017-02-08 10:41:06 -08:00
Daniel Imms e79e67c3ce Disable escape sequence tests on windows 2017-02-07 21:17:47 -08:00
Daniel Imms e0639e1b62 Merge pull request #526 from sourcelair/Tyriar-patch-1
Add description to package.json
2017-02-06 16:40:29 -08:00
Daniel Imms 56b541b44f Add description to package.json
This should fix the ugly broken markdown at the top of npm
2017-02-06 13:56:52 -08:00
Paris Kasidiaris 03e46fbdee Merge pull request #525 from LucianBuzzo/resize
Fix issue when resizing hidden terminals
2017-02-05 17:59:54 +02:00
Lucian Buzzo ee0d6b4533 Fixed issue where terminal would become unusable if NaN values are sent
to resize method.
2017-02-05 12:45:55 +00:00
Daniel Imms 937a9bf433 Merge pull request #523 from sourcelair/Tyriar-patch-1
Add null check on Terminal.element
2017-02-02 08:53:40 -08:00
Paris Kasidiaris 3bcdc4a354 Merge pull request #524 from billchurch/master
Adding WebSSH2 to real-world uses
2017-02-01 23:51:23 +02:00
Bill Church 382cd0bbf4 Merge pull request #1 from billchurch/billchurch-patch-1
Update README.md
2017-02-01 16:42:39 -05:00
Bill Church e58a6975da Update README.md
Adding WebSSH2 to real-word uses
2017-02-01 16:41:47 -05:00
Daniel Imms 833eb5216b Add null check on Terminal.element
Since the Terminal can be used now before being attached, we should check element on destroy.

Related to #266
2017-02-01 11:50:52 -08:00
Daniel Imms 742d28fcc3 Merge pull request #522 from Tyriar/266_pull_renderer_out
Pull renderer out of xterm.js
2017-02-01 11:33:52 -08:00
Daniel Imms cc78fdd63c Hold on to renderer if a reset occurs 2017-02-01 11:19:54 -08:00
Daniel Imms 20f22fb658 Convert flags to enum 2017-02-01 11:18:44 -08:00
Daniel Imms 3c635f3ce5 Remove Terminal.queueRefresh, call refresh directly 2017-02-01 11:13:00 -08:00
Daniel Imms 9d8f6c9ae7 Polish 2017-02-01 10:30:58 -08:00
Daniel Imms cc6893d0f2 Merge remote-tracking branch 'upstream/master' into 266_pull_renderer_out 2017-02-01 10:29:11 -08:00
Daniel Imms ca4e99e810 Add license 2017-02-01 10:21:43 -08:00
Daniel Imms 8d7df670b4 Merge pull request #521 from Tyriar/517_dont_loop_animation_frame
Don't requeue animation frame if not needed
2017-01-31 23:51:51 -08:00
Daniel Imms 4de7ed46bf Merge pull request #520 from Tyriar/519_erase_null_check
Add null checks in eraseRight and eraseLeft
2017-01-31 23:51:40 -08:00
Daniel Imms f9aac1bcc6 Fix tests 2017-01-31 23:46:58 -08:00
Daniel Imms 92068f36f2 Pull renderer out of xterm.js 2017-01-31 22:45:28 -08:00
Daniel Imms 047729ee9e Don't requeue animation frame if not needed
Fixes #517
2017-01-31 21:53:29 -08:00
Daniel Imms 637a5bd9cc Don't requeue animation frame if not needed
Fixes #517
2017-01-31 21:23:21 -08:00
Daniel Imms 6cd5c2b846 Add null checks in eraseRight and eraseLeft
Fixes #519
2017-01-31 21:03:13 -08:00
Daniel Imms 365a9f949c Merge pull request #513 from Tyriar/511_useFlowControl_option
Add useFlowControl option
2017-01-27 08:23:13 -08:00
Paris Kasidiaris d6de156cd8 Merge pull request #514 from LucianBuzzo/master
[issue #164] Fix bug that can occur when setting a scroll region
2017-01-27 12:58:57 +00:00
Lucian Buzzo 23c9fca088 [issue #164] Fix bug that can occur when setting a scroll region 2017-01-27 11:25:12 +00:00
Daniel Imms c2a69721f3 Add useFlowControl option
Fixes #511
2017-01-26 21:14:07 -08:00
Daniel Imms d1ad8a7831 Merge pull request #500 from Tyriar/fix_vt_tests
Fix many vt tests
2017-01-26 08:55:42 -08:00
Daniel Imms cee2285818 Merge pull request #509 from Tyriar/vscode_debugger_support
Support debugging mocha tests in vscode
2017-01-26 08:55:22 -08:00
Daniel Imms ca19da16e0 Merge pull request #499 from Tyriar/481_character_sets
Add support for rest of VT100 character sets
2017-01-25 13:00:49 -08:00
Daniel Imms 5850cbcd05 Add comments explaining actions preventing x from wrapping 2017-01-25 10:34:43 -08:00
Daniel Imms b789a7e85b Fix failing test given new auto wraparound behavior 2017-01-25 10:32:20 -08:00
Daniel Imms 9f0dbdd5c7 Support debugging mocha tests from vscode 2017-01-25 10:25:28 -08:00
Daniel Imms 98614f26ef Merge pull request #508 from Tyriar/507_fix_lint_in_src_root
Run lint on src/*.ts and fix errors
2017-01-25 07:30:09 -08:00
Daniel Imms 3b16696672 Run lint on src/*.ts and fix errors
Fixes #507
2017-01-24 13:34:47 -08:00
Paris Kasidiaris 0219ad2ed8 Merge pull request #505 from vincentwoo/patch-1
Add CoderPad to real world use cases
2017-01-24 07:48:37 +00:00
Vincent Woo e771483041 Add CoderPad to real world use cases
Hi everyone,

I'm very pleased to say I have cut CoderPad.io over to using xterm.js (replacing term.js). I've very pleased with the work you've done on it. You've implemented the many terrible hacks on top of term.js I had to write, except you've actually implemented stuff the right way.

I look forward to your continued progress on the project!

Cheers,
Vincent
2017-01-23 21:32:14 -08:00
Daniel Imms 4a7c3320fb Merge pull request #504 from Tyriar/fix_mode_recursive_call
Use InputHandler.setMode/resetMode, not Terminal
2017-01-23 12:41:19 -08:00
Daniel Imms 9359dca0f3 Use InputHandler.setMode/resetMode, not Terminal 2017-01-23 11:35:33 -08:00
Paris Kasidiaris c8ccc411d4 Merge pull request #502 from vincentwoo/master
Bundle top-level .js and .json files in NPM
2017-01-23 12:38:35 +02:00
Vincent Woo 537c8bad10 Bundle top-level JSON with npm 2017-01-22 22:28:46 -08:00
Vincent Woo 1a55367fc9 Bundle top-level JS with npm 2017-01-22 22:26:40 -08:00
Daniel Imms 4f7ee7dab0 Skip broken tests 2017-01-20 23:38:56 -08:00
Daniel Imms da16dd7cae Mock viewport.syncScrollArea 2017-01-20 23:22:04 -08:00
Daniel Imms 2aa7608ac0 Fix VPR behavior
Don't wrap cursor to column 0 after a VPR, fixes 1 test
2017-01-20 23:14:08 -08:00
Daniel Imms 74c3a4a6f7 Fix CUD behavior
Don't wrap cursor to column 0 after a CUD, fixes 1 test
2017-01-20 23:12:54 -08:00
Daniel Imms d30fb89fde Fix CUB behavior
Don't wrap cursor to column 0 after a CUB, fixes 3 tests
2017-01-20 23:11:22 -08:00
Daniel Imms 1b344ce789 Implement CAN (Cancel, ^X)
This helps partially pass t0014-CAN.in, it won't work 100% however
due to the very complex parsing logic of vanilla xterm that
gnome-terminal doesn't even seem to match. xterm's source seems to
have multiple ignore cases for a set of characters such that an
escape sequence like \e!!!!!! prints nothing as the ! continually
gets ignored. Our current logic is we ignore the escape sequence
immediately in this case and print the !.
2017-01-20 23:03:38 -08:00
Daniel Imms 99fbcd3d65 Fix LF/VT/FF behavior
Don't wrap cursor to column 0 after an index, fixes 2 tests
2017-01-20 22:14:18 -08:00
Daniel Imms 72063329fe Fix index behavior
Don't wrap cursor to column 0 after an index, fixes 2 tests
2017-01-20 21:49:39 -08:00
Daniel Imms adaf604ce0 Right trim expected output, we don't care for now
This fixes 2 tests
2017-01-20 21:39:27 -08:00
Daniel Imms d5f0fff523 Enable other tests and fix viewport check 2017-01-20 21:22:16 -08:00
Daniel Imms 43c3349494 Prevent wraparound mode from overriding last character 2017-01-20 21:20:11 -08:00
Daniel Imms b5d16ed7d7 Use block comment for SCLD 2017-01-20 20:14:17 -08:00
Daniel Imms aab67c2ed9 Reference CHARSETS using codes 2017-01-20 20:12:47 -08:00
Daniel Imms 0461a822c2 Add character sets for most languages
Part of #481
2017-01-20 19:05:13 -08:00
Paris Kasidiaris 7b87e78ed3 Merge pull request #497 from sourcelair/issue-#488-tabstopwidth
Implement configurable tab stop width
2017-01-21 01:08:23 +02:00
Paris Kasidiaris 6e1628bc3b Fixes on demo based on configurable tabStopWidth 2017-01-21 00:32:39 +02:00
Daniel Imms 370c5a971d Merge pull request #498 from Tyriar/259_fix_setupStops_in_resize
Fix setupStops call in resize
2017-01-20 14:29:13 -08:00
Daniel Imms 9a86e4e109 Fix setupStops call in resize
Fixes #259
2017-01-20 14:23:45 -08:00
Paris Kasidiaris 8cb46f2726 Move tabStopWidth option callback into setOption 2017-01-20 16:19:19 +00:00
Paris Kasidiaris f4293a6dfa Fix #488: Implement configurable tab width 2017-01-20 16:18:19 +00:00
Daniel Imms 1c759f1d6f Merge pull request #495 from Tyriar/494_display_none_resize_fix
Only keep > 0 geometry in CharMeasure
2017-01-20 07:26:46 -08:00
Daniel Imms 6918e83787 Merge pull request #492 from Tyriar/480_cursor_style
Implement CSI Ps SP q Set cursor style
2017-01-20 07:26:36 -08:00
Daniel Imms 9626b1e39d Only keep > 0 geometry in CharMeasure
Fixes #494
2017-01-19 18:02:09 -08:00
Daniel Imms 9227aed906 Add InputHandler.setCursorStyle test 2017-01-18 10:30:35 -08:00
Daniel Imms 0bd469f505 Implement CSI Ps SP q Set cursor style
Fixes #480
2017-01-18 10:06:57 -08:00
Daniel Imms 5bd803382a Merge pull request #462 from Tyriar/459_parser__on_460
Parser refactor and optimization
2017-01-18 10:02:03 -08:00
Daniel Imms ef60e50e1d Add documentation 2017-01-18 09:35:27 -08:00
Daniel Imms ed1ba14c6b Merge pull request #490 from Tyriar/489_namespace_cursor_blink
Namespace cursor-blink CSS animations
2017-01-18 08:18:23 -08:00
Daniel Imms a4080d3706 Namespace cursor-blink CSS animations
Fixes #489
2017-01-18 08:06:41 -08:00
Daniel Imms e2b2f98011 Merge remote-tracking branch 'upstream/master' into 459_parser__on_460 2017-01-16 15:17:35 -08:00
Daniel Imms ed13218f90 Merge pull request #485 from Tyriar/remove_comments_in_build
Remove comments in build
2017-01-16 15:14:42 -08:00
Daniel Imms 1cdd2e00ab Remove parser states from xterm.js 2017-01-16 14:11:00 -08:00
Daniel Imms 94eb08fb73 Remove comments in build 2017-01-16 14:02:55 -08:00
Daniel Imms 5e1ccb358b Merge remote-tracking branch 'upstream/master' into 459_parser__on_460 2017-01-16 13:53:19 -08:00
Daniel Imms 259338b8c2 Merge pull request #482 from Tyriar/348_keep_selection_on_mod_key
Don't drop selection on modifier keyup
2017-01-16 03:49:19 -08:00
Daniel Imms a05bb50230 Don't drop selection on modifier keyup
Fixes #348
2017-01-15 21:41:42 -08:00
Daniel Imms 8a07b8c798 Merge pull request #442 from Tyriar/441_windows_support
Use node-pty for Windows support
2017-01-15 02:38:16 -08:00
Daniel Imms 4d5046b5e7 Merge pull request #479 from Tyriar/478_cursorBlink_refresh
Apply cursorBlink via setOption
2017-01-15 02:35:30 -08:00
Daniel Imms 12160a50cb Fake xterm.element in tests 2017-01-15 02:31:54 -08:00
Daniel Imms 375ccbd9e2 Merge remote-tracking branch 'upstream/master' into 478_cursorBlink_refresh 2017-01-15 02:22:45 -08:00
Daniel Imms cc0f0d94f6 Merge remote-tracking branch 'upstream/master' into 441_windows_support 2017-01-15 02:12:17 -08:00
Paris Kasidiaris 6309752208 Merge pull request #435 from sourcelair/issue-#359-gulp
Introduce build system based on Gulp
2017-01-15 11:49:32 +02:00
Daniel Imms 4448ebe391 Use charsets to map 2017-01-14 22:06:30 -08:00
Daniel Imms d1dac57f7a Move cursor blink style to class on .terminal 2017-01-14 21:26:49 -08:00
Daniel Imms 3422f84e00 Merge pull request #477 from Tyriar/476_scrollback_update
Apply scrollback via setOption
2017-01-14 10:46:54 -08:00
Paris Kasidiaris ac6faf3dd8 Stick gulp-sourcemaps to 1.9.1
Paths became absolute by default at https://github.com/floridoo/gulp-sourcemaps/commit/fb4027a496898b8b7992ea5af9b3d707f1d82d38
2017-01-14 19:52:07 +02:00
Daniel Imms 7679475bfe Apply cursorBlink via setOption
Fixes #478
2017-01-13 21:31:31 -08:00
Daniel Imms 5a932b2a20 Apply scrollback via setOption
Fixes #476
2017-01-13 21:27:19 -08:00
Daniel Imms b1ef934aea Merge pull request #474 from Tyriar/473_refresh_null_checks
Add null checks to refresh line and character fetches
2017-01-13 07:09:12 -08:00
Daniel Imms a2ab0ffc46 Merge pull request #471 from Tyriar/470_CharMeasure_in_helper
Move CharMeasure element to the helper container
2017-01-13 07:08:45 -08:00
Daniel Imms ecd7e69f1a Start adding ESC state handler 2017-01-12 22:36:48 -08:00
Daniel Imms fa3484cd14 Pull character add char code to input handler 2017-01-12 22:17:36 -08:00
Daniel Imms f4846aa154 Finish CSI codes 2017-01-12 21:58:50 -08:00
Daniel Imms 9b66208029 Add more CSI codes 2017-01-12 21:33:28 -08:00
Daniel Imms c43c3b411a Add more CSI codes 2017-01-12 20:51:15 -08:00
Daniel Imms f9a286a851 Convert more CSI codes 2017-01-12 20:32:15 -08:00
Daniel Imms 3de3912b96 Add another null check on children[y] 2017-01-12 11:23:17 -08:00
Daniel Imms 23169e89c8 Add null checks to refresh line and character fetches
Fixes #473
2017-01-12 11:14:14 -08:00
Daniel Imms 0f5f34e8f5 Move CharMeasure element to the helper container
Fixes #470
2017-01-12 10:47:57 -08:00
Daniel Imms 342e862d69 Merge remote-tracking branch 'upstream/master' into 459_parser__on_460 2017-01-11 13:43:33 -08:00
Paris Kasidiaris 081fe3f301 Fix #359 - Introduce build system based on Gulp
- Add Gulp and new dependencies to `package.json`
- Add `gulpfile.js` with four tasks:
    - `tsc`: For building TypeScript sources
    - `bundle`: For bundling JavaScript modules in a monolith
    - `sorcery`: For resolving the source map chains back to the original TypeScript files
    - `build` (`default`): Runs the whole `tsc` → `bundle` → `sorcery` chain
- Clean up `Dockerfile`, since `cpio` is not needed any more
- Clean up not needed dependencies from `package.json`
- Remove `bin/build`
- Update `bin/release` to use `npm run build` instead of `./bin/build`
2017-01-11 08:11:45 +00:00
Daniel Imms fc528f6c0c Merge pull request #447 from Tyriar/425_xon_xoff_on_280
Sync with pty process using XOFF and XON
2017-01-10 21:20:58 -08:00
Daniel Imms 411c974960 Merge pull request #446 from Tyriar/335_viewport_var
Remove var usage from Viewport
2017-01-10 20:24:22 -08:00
Daniel Imms 0ec125557a Merge remote-tracking branch 'upstream/master' into 425_xon_xoff_on_280 2017-01-10 20:24:07 -08:00
Daniel Imms 0b977fc35f Merge pull request #461 from Tyriar/460_escape_sequence_c0
Pull C0 escape sequences into its own file
2017-01-10 20:06:36 -08:00
Daniel Imms 0739a4be06 Merge remote-tracking branch 'upstream/master' into 425_xon_xoff_on_280 2017-01-10 20:04:26 -08:00
Daniel Imms c4de07135f Merge pull request #466 from Tyriar/465_async_CharMeasure_measure
Perform CharMeasure.measure async
2017-01-10 20:03:59 -08:00
Daniel Imms d52b53889e Merge remote-tracking branch 'upstream/master' into 335_viewport_var 2017-01-10 20:03:19 -08:00
Daniel Imms d9682bd6d6 Perform CharMeasure.measure async
This fixes the edge case where getBoundingClientRect was returning a width and
height of 0,0.

Fixes #465
2017-01-10 11:36:22 -08:00
Daniel Imms 411b80cdc0 Add CSI @, E, F, G 2017-01-09 23:06:36 -08:00
Daniel Imms db81c28bd7 Support more CSI codes, remove unused CSI helper functions 2017-01-09 22:57:38 -08:00
Daniel Imms c7fa2d55b4 Handle remaining CSI_PARAM cases and introduce the state 2017-01-09 16:07:27 -08:00
Daniel Imms 7572dd5fa6 Remove IInputHandler from CSI_PARAM lambdas 2017-01-09 15:39:56 -08:00
Daniel Imms 9942477bff Start converting CSI codes 2017-01-09 15:38:54 -08:00
Daniel Imms 635a4d7682 Handle CSI postfix 2017-01-09 15:19:29 -08:00
Daniel Imms 672dc1a251 Start pulling CSI handlers out 2017-01-09 15:17:15 -08:00
Daniel Imms 6deaaa8ef8 Move all parser state handling into the parser 2017-01-09 15:00:37 -08:00
Daniel Imms f4267c4f74 Merge remote-tracking branch 'upstream/master' into 459_parser__on_460 2017-01-09 14:50:28 -08:00
Daniel Imms 1848fff4c9 Pull charsets out of xterm.js 2017-01-09 14:21:59 -08:00
Daniel Imms 991b2843d3 Fix references to Terminaal and fix TS lint warnings 2017-01-09 13:57:58 -08:00
Daniel Imms 940bd2699e Fix wcwidth TS errors 2017-01-09 13:48:52 -08:00
Daniel Imms 4a27b9a53f Move wcwidth into Parser.ts 2017-01-09 13:46:08 -08:00
Daniel Imms a31921ae73 Move parsing logic into Parser.ts 2017-01-09 13:45:55 -08:00
Daniel Imms 27a7f1504c Merge pull request #453 from Tyriar/452_disable_stdin_option
Add disableStdin option
2017-01-09 09:53:22 -08:00
Paris Kasidiaris aee8ddeafb Merge pull request #464 from TylerJewell/patch-1
Add Codenvy to the list of xTerm supporters
2017-01-09 19:17:50 +02:00
Tyler Jewell 6c29ccfbd1 Add Codenvy to the list of xTerm supporters 2017-01-08 17:41:02 -08:00
Daniel Imms da7ea104de Merge remote-tracking branch 'upstream/master' into 460_escape_sequence_c0 2017-01-08 17:13:28 -08:00
Daniel Imms 665a11acc0 Add C0.BS handler back 2017-01-08 17:12:35 -08:00
Daniel Imms dddc91fbcc Merge remote-tracking branch 'upstream/master' into 425_xon_xoff_on_280 2017-01-08 17:05:19 -08:00
Daniel Imms ecb892d995 Merge remote-tracking branch 'upstream/master' into 425_xon_xoff_on_280 2017-01-08 17:05:10 -08:00
Daniel Imms ada96a8373 Merge remote-tracking branch 'upstream/master' into 335_viewport_var 2017-01-08 17:04:18 -08:00
Daniel Imms cabe23b782 Merge pull request #436 from Tyriar/434_tmux_scroll_fix
Fix scroll in tmux with max scrollback
2017-01-08 17:02:44 -08:00
Daniel Imms b25bf9562e Merge pull request #457 from Tyriar/451_fix_events_after_reset
Keep previous terminal events after a reset
2017-01-08 17:00:55 -08:00
Daniel Imms e9da2a6330 Merge pull request #440 from Tyriar/439_wide_char_class
Style wide characters at charWidth*2 in DOM
2017-01-08 17:00:30 -08:00
Daniel Imms 9385b9309d Merge remote-tracking branch 'upstream/master' into 439_wide_char_class 2017-01-08 16:56:47 -08:00
Daniel Imms facc2659e7 Merge pull request #463 from sourcelair/revert-445-444_rate_limit_viewport_refresh
Revert "Rate limit Viewport.refresh"
2017-01-08 16:51:27 -08:00
Daniel Imms 06852cd904 Revert "Rate limit Viewport.refresh" 2017-01-08 16:46:23 -08:00
Daniel Imms a1ee8aefbb Merge remote-tracking branch 'upstream/master' into 439_wide_char_class 2017-01-08 16:32:51 -08:00
Daniel Imms eb3b3fa107 Merge pull request #437 from Tyriar/335_TS_Generic_Browser
Convert browser and generic to TS
2017-01-08 16:25:30 -08:00
Daniel Imms 3457b73ac8 Merge pull request #445 from Tyriar/444_rate_limit_viewport_refresh
Rate limit Viewport.refresh
2017-01-08 16:24:27 -08:00
Daniel Imms 28b38dc76d Merge pull request #438 from Tyriar/280_improve_refresh_queue
Improve refresh queue
2017-01-08 16:24:16 -08:00
Daniel Imms 659fb90c1c Handle C0 codes via handler map in Parser 2017-01-08 16:21:51 -08:00
Daniel Imms 04b1ebf1a7 Create InputHandler which performs C0 actions
Part of #459
2017-01-08 16:11:35 -08:00
Daniel Imms 1685cf2d8f Use namespace and const for C0 constants 2017-01-08 16:02:47 -08:00
Paris Kasidiaris 43d4d4f2bb Merge pull request #458 from TylerJewell/patch-1
Add additional products that use xTerm
2017-01-08 23:49:46 +00:00
Daniel Imms 3de3c0c6b6 Pull C0 escape sequences into its own file
Part of #460
2017-01-08 15:49:19 -08:00
Daniel Imms bebe43e5e1 Use node-pty as it's been published 2017-01-08 13:33:51 -08:00
Tyler Jewell 520f2bc9d6 Add additional products that use xTerm
Hi xTerm team. Over the past 6 months, we have been studying xTerm as a replacement for Eclipse Che's term.js. It's taken us a bit of an effort, but the work is now done!  You can expect that Eclipse Che engineers (abot 60 contributors) will make direct contributions back to xTerm ongoing now that we are fully integrated in. We integrate xTerm alongside GWT.  As we more natively integrate the solution, we'll make additional PRs directly back to the project.

As background on the research and integration work that we did, these are the postings from our engineering team's research from the past six months. Some of these issues have already been resolved, or in the process of being resolved.

We also plan a couple of blog posts to our forums (~250K followers) about xTerm integration later in Q1 after we make our 5.0.0 announcements. I could also add Codenvy to this PR as well since it has been released with the version based upon xTerm, but with Sourcelair being the initiators we didn't want to make it seem like we were trying to be competitive. This PR is about the promotion and success of xTerm, for which we are fully committed to.

## Xtermjs 
This document is result of investigation using xtemjs ui terminal instead of current term.js. It contains analyze pluses and minuses using xtermjs (release version 2.2.3) and technical problems.  Investigation issue: https://github.com/eclipse/che/issues/3210

## Description
For now we are using our own fork of the https://github.com/chjj/term.js for user interface websocket-terminal. But actually this project is no longer maintained. So we can not get new releases from this project and we need support this script on our own. Original project contains link for a maintained fork https://github.com/sourcelair/xterm.js. This fork uses MIT license and community intensive develops this project. It has such users like: Microsoft Visual Studio Code, SourceLair, ttyd. xterm.js had already done 46 releases https://github.com/sourcelair/xterm.js/releases.

## Technical Advantages of xTerm:
* xterm.js has js tests. We have not any test for old term.js.
* We can periodically update xtem.js by new release.
* Added parameter to cancel browser events.
* Default 256 colours moved from js to css.
* Added ability to set terminal theme.
* Improved resize mehanizm (added resize event).
* Added fit.ts script to fits terminal size to original height and width of parent div.
* Fixed lost text selection from current active line(when blink is enabled).
* Improved copy/paster mehanizm.
* Linkify URL feature.
* Implement moving back and forward across words with "Alt + ←" and "Alt + →" respectively.
* Improved special key handling.
* Added addons to exdens xterm.js
* Improved mehanizm copy/paster from clipboard.
* Fixed cross platform input problems(For IPad, Iphone, MacIntel, MacPPC and so on).
* Did some work to support UTF-8 symbols.
* Implemented scrollbar.
* Fixed incorrect mouse position for application with  pseudo-graphic user interface (for example Midnight Commander).
* Fix to prevent terminal scrolling when user is looking into scrollback(similar to gnome-terminal, if the user is scrolling up to look at past output and the currently running program adds output to the terminal, the viewport of xterm.js should not scroll and interrupt what they are looking at.)
* Make right-click work on all browsers.

##  Broken Changes: 
We can move on our changes to realize copy/paste by hotkeys Ctrl + C/Ctrl +V. But xterm.js support hotkeys more common for terminal: Ctrl + Insert and Shift + Insert and maybe that's enough.

Drop support for old mouse wheel APIs: all browsers have supported the WheelEvent (onwheel) for sometime now, since Firefox does not support onmousewheel which is also non-standard but works with the standard interface, it makes sense to drop support now.

## Browser Support
Since xterm.js is typically implemented as a developer tool, only modern browsers are supported officially. Here is a list of the versions to support:
Chrome 48+
Edge 13+
Firefox 44+
Internet Explorer 11+
Opera 35+
Safari 8+

Xterm.js works seamlessly in Electron apps and may even work on earlier versions of the browsers but these are the browsers xterm.js developers strive to keep working.

## Known major bugs:
https://github.com/sourcelair/xterm.js/issues/307
https://github.com/sourcelair/xterm.js/issues/362
https://github.com/sourcelair/xterm.js/issues/348
https://github.com/sourcelair/xterm.js/issues/325 Data loss when resizing terminal (but this bug is exist in the current terminal ui in the CHE too). Community has pull request to fix this issue for xtermjs https://github.com/sourcelair/xterm.js/pull/404 .
 
Additional information: 

Code base xterm.js consist of files written on native javascript and typescript. For manage js dependency and configuration used npm, typings, bower and node. Development tendency: rewrite xtemr.js completely on the Typescript(information about this included to the release notes 2.2.3).
2017-01-08 09:44:14 -08:00
Daniel Imms 996c25a364 Keep previous terminal events after a reset
This broke in the EventEmitter ts conversion, just reverts this line to what
it used to be.

Fixes #451
2017-01-07 16:04:49 -08:00
Daniel Imms d9d60063d7 Add disableStdin option
Fixes #452
2017-01-04 12:43:21 -08:00
Daniel Imms ff523bfc79 Fix tests 2017-01-04 10:30:04 -08:00
Daniel Imms 94c01ec378 Fix tests 2017-01-04 08:08:59 -08:00
Daniel Imms 2b8820fdac Further tweaks, add write batching 2017-01-03 15:52:45 -08:00
Daniel Imms 0ec7b661f2 Tweak config values 2017-01-03 15:38:14 -08:00
Daniel Imms dc5efa886a Make innerWrite iterative 2017-01-03 15:29:23 -08:00
Daniel Imms e66b1c5704 Add write buffer pause and refresh frame skip 2017-01-03 15:26:41 -08:00
Daniel Imms 6b8c43ed7f Send \x13 when a write buffer threadhold is reached 2017-01-03 14:57:13 -08:00
Daniel Imms b9d374affa Add XON/XOFF and eparate write from processing
Part of #425
2017-01-03 14:57:04 -08:00
Daniel Imms d2ef19dffe Remove var usage from Viewport
Part of #335
2017-01-03 11:26:59 -08:00
Daniel Imms efdf37b887 jsdoc 2017-01-03 11:23:36 -08:00
Daniel Imms 6ffb8f545b Rate limit Viewport.refresh
This prevents 1000 scroll events from firing when the buffer is not full

Fixes #444
2017-01-03 11:18:38 -08:00
Daniel Imms 2e4147b4fa Use Tyriar/pty.js for Windows support
Fixes #441
2017-01-01 16:24:55 -08:00
Daniel Imms 07a8b8f4f7 Fix tests 2016-12-31 18:06:49 -08:00
Daniel Imms 74483fb294 Use CharMeasure in Viewport and to style wide chars
Fixes #439
2016-12-31 15:56:57 -08:00
Daniel Imms 4f18d842f9 Add CharMeasure util class 2016-12-31 15:46:17 -08:00
Daniel Imms 188e197e20 Wrap wide chars in a span/class
Part of #439
2016-12-31 15:19:54 -08:00
Daniel Imms 7234bfb6eb Move row evaluation into refreshLoop
This allows the refresh public API to still function
2016-12-31 14:58:17 -08:00
Daniel Imms 97feb3321c Improve refresh queue
Use requestAnimationFrame in addition to a queue to refresh every animation
frame but only when a refresh is needed.

Fixes #280
Fixes #290
2016-12-31 14:14:02 -08:00
Daniel Imms 3e1a607179 Convert browser and generic to TS
Part of #335
2016-12-31 07:36:56 -08:00
Daniel Imms c3f46e4a6b Fix scroll in tmux with max scrollback
I believe this is related to when scrollBottom is not the last row in the viewport

Fixes #434
2016-12-31 07:18:50 -08:00
Daniel Imms 1fbd3c8f65 Merge pull request #432 from Tyriar/335_TS_EventEmitter
Convert EventEmitter to TypeScript and add tests
2016-12-31 07:14:47 -08:00
Daniel Imms 965ebde22f Remove remaining removeListener ref 2016-12-31 07:11:47 -08:00
Daniel Imms 0d9d3aca1a Remove addListener/removeListener 2016-12-31 07:10:45 -08:00
Daniel Imms 937cf43e09 Remove redundant assignment in constructor 2016-12-31 07:07:45 -08:00
Daniel Imms 23472e6fb4 Merge pull request #431 from Tyriar/427_refresh_scroll_on_buffer_change
Sync scroll bar when alt/normal buffer is switched in
2016-12-30 04:42:36 -08:00
Antonis Kalipetis 445728b2a2 Merge pull request #403 from akalipetis/docker-enhancement
Improve the Docker image
2016-12-30 11:24:22 +02:00
Antonis Kalipetis 61c213f9e3 Ignore all the build directories in Docker
This allows for reproducible builds.
Also, fix Dockerfile to first build and then run tests and a typo in the entrypoint.

Thanks @BenHall for reporting the issue with the Docker build!
2016-12-29 16:13:58 +02:00
Daniel Imms dba432d1b6 Add tests 2016-12-29 05:09:47 -08:00
Daniel Imms 2f416371bd Convert EventEmitter to TS
Pat of #335
2016-12-29 04:53:57 -08:00
Daniel Imms 2bfbdb1c06 Sync scroll bar when alt/normal buffer is switched in
Fixes #427
2016-12-29 03:55:36 -08:00
Antonis Kalipetis a4c958c54f Fix EOL character in .editorconfig and update docker-compose 2016-12-28 18:49:36 +02:00
Antonis Kalipetis b2e257bf37 Remove entrypoint
Signed-off-by: Antonis Kalipetis <akalipetis@gmail.com>
2016-12-28 18:45:21 +02:00
Antonis Kalipetis 6b6314227e Improve the Docker image
1. Bump Node version to 6.9 - the latest LTS
2. Include the `cpio` binary, used during building
3. Ignore node_modules and .git directories for faster builds
4. Run the tests and build during the image build, to make sure the image is not built if these break
5. Make npm run dev the default command
6. Add an entrypoint to automatically install Node modules if they do nott exist

Signed-off-by: Antonis Kalipetis <akalipetis@gmail.com>
2016-12-28 18:45:18 +02:00
Antonis Kalipetis 1e0eb3784e Merge pull request #402 from akalipetis/hotfix-npm-scripts
Improve the package.json scripts
2016-12-28 18:44:20 +02:00
Antonis Kalipetis f00ea4bfac Add a Procfile with the npm start command
Also, update the Procfile.dev with the updated `npm run dev` command.

Signed-off-by: Antonis Kalipetis <akalipetis@gmail.com>
2016-12-28 18:12:23 +02:00
Antonis Kalipetis 0da4c9d90d Improve the package.json scripts
1. Include a `prestart` script, which runs the build
2. Make the `start` script just start the demo server
3. Add a new `dev` script, which contains the nodemon logic
4. nodemon now watches for changes in `*.ts` files and runs the start command

Signed-off-by: Antonis Kalipetis <akalipetis@gmail.com>
2016-12-28 18:12:20 +02:00
Daniel Imms df83298c54 Merge pull request #429 from Tyriar/428_scrollback_exception
Ensure ydisp does not drop below 0 in refresh
2016-12-28 05:59:43 -08:00
Daniel Imms 5d29d4ea22 Remove log 2016-12-28 03:41:48 -08:00
Daniel Imms a9e1ed5a72 Ensure ydisp does not drop below 0 in refresh
Fixes #428
Related to #385
2016-12-28 03:41:12 -08:00
Daniel Imms e6ad8d8b50 Merge pull request #422 from Tyriar/361_circular_list_scrollback
Use a circular list to manage buffer
2016-12-28 03:10:31 -08:00
Daniel Imms 50cfe2b21a Improve header comment 2016-12-27 13:40:52 -08:00
Daniel Imms d7f2ec89d7 Polish 2016-12-24 03:17:30 -08:00
Daniel Imms cc5ae8193b Fix insertLines as max buffer size 2016-12-24 00:26:43 -08:00
Daniel Imms 30a1f1ccb5 Fix issue with max buffer size after vim fix 2016-12-24 00:14:30 -08:00
Daniel Imms 6f7cb990ca Fix issue with vim scrolling 2016-12-24 00:04:31 -08:00
Paris Kasidiaris 06f5746c86 Merge pull request #423 from katacoda/katacoda-integration
Katacoda xterm.js integration is live
2016-12-22 23:30:00 +02:00
Ben Hall cd44fe7bcd Katacoda xterm.js integration is live 2016-12-22 20:10:33 +00:00
Ben Hall bb3d6ee72c Katacoda xterm.js integration is live 2016-12-22 12:01:44 +00:00
Daniel Imms bf16fdc01d Have reverseIndex use CircularList.shiftElements 🎉 2016-12-21 03:26:40 -08:00
Daniel Imms 969a2e953c Implement CircularList.shiftElements 2016-12-21 03:18:30 -08:00
Daniel Imms bfaf9cd6eb Doc and testing 2016-12-21 02:39:21 -08:00
Daniel Imms be2e4b5d85 Add missing return type 2016-12-21 02:11:14 -08:00
Daniel Imms cc0fc953cf Remove logs 2016-12-22 02:04:31 -08:00
Daniel Imms 3b35d12e60 Fix issue with the git log
The old code was assuming that the buffer was not going to change, this is not
true with the current impl though where the list is shifted and ybase and ydisp
need to be compensated for that.
2016-12-22 02:02:05 -08:00
Daniel Imms 4bc679b0b3 Merge remote-tracking branch 'upstream/master' into 361_circular_list_scrollback 2016-12-21 15:43:18 -08:00
Daniel Imms be56c72b5f Fix when scrollback limit is reached 2016-12-21 15:43:04 -08:00
Paris Kasidiaris db92840ffc Merge pull request #415 from saswatds/saswatds-patch-1
Update README.md
2016-12-19 15:47:19 +02:00
Paris Kasidiaris 593a4ec0b0 Merge pull request #417 from BobReid/os_x_bash_arrow_fix
changed escape sequence for alt-arrow to work on bash on os x
2016-12-19 15:45:57 +02:00
Saswat Das d018a547a2 Update README.md
Added Getting started content from the xtermjs.org website
2016-12-18 04:48:19 +05:30
Paris Kasidiaris a246200675 Merge pull request #419 from blink1073/clean-up-npm-publish
Clean up npm publish
2016-12-16 20:46:27 +00:00
Steven Silvester 1cb6517812 Revert changes to other published files 2016-12-16 14:41:29 -06:00
Bob Reid 2824da371f Added macOS check to escape sequences and updated tests 2016-12-16 15:03:49 -05:00
Steven Silvester 22eb86089f Clean up npm publish 2016-12-16 13:28:10 -06:00
Bob Reid 2e17366bce changed escape sequence for alt-arrow to work on bash on os x 2016-12-16 10:29:42 -05:00
Paris Kasidiaris ef407ae93a Bump version to 2.2.3
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2016-12-15 21:56:32 +00:00
Paris Kasidiaris 9032ce99d3 Merge pull request #416 from sourcelair/issue-#414-css-files-in-npm
Include appropriate files in npm.
2016-12-15 21:53:19 +00:00
Paris Kasidiaris adaaeb6f36 Include appropriate files in npm.
Fix #414
2016-12-15 23:49:43 +02:00
Paris Kasidiaris 8a146b5401 Bump version to 2.2.2
Signed-off-by: Paris Kasidiaris <paris@sourcelair.com>
2016-12-15 17:16:04 +00:00
Saswat Das 4ee1e00808 Update README.md
Adding a getting started instruction for adding xterm to a parent div and listening for data output from xterm
2016-12-15 21:26:04 +05:30
Paris Kasidiaris 3a6368ba6c Merge pull request #411 from sourcelair/issue-#408-tslint
Add tslint
2016-12-15 12:13:23 +00:00
Paris Kasidiaris fbc314a74b Parallelise build 2016-12-15 14:05:37 +02:00
Paris Kasidiaris 850a238ca2 Include lint test into travis 2016-12-15 14:02:38 +02:00
Paris Kasidiaris 20b6f20908 Make linter happy 2016-12-15 13:57:25 +02:00
Paris Kasidiaris 33f7d7649a Add tslint
Fix #408
2016-12-15 13:53:26 +02:00
Paris Kasidiaris fb4d263211 Merge pull request #409 from sourcelair/issue-#405-firefox-paste
Fix linux firefox paste
2016-12-14 10:38:30 +00:00
Paris Kasidiaris ab87dece0b Fix weird paste issue: #405
Fix #405
2016-12-14 01:45:53 +02:00
Paris Kasidiaris 69e027394d 😱 Fix wrong event type and remove useless interface 2016-12-14 01:43:32 +02:00
Paris Kasidiaris 6639b2c731 Merge pull request #407 from sourcelair/build-ts-into-lib
Always build TypeScript in `lib/`
2016-12-13 23:32:49 +00:00
Paris Kasidiaris e23956cd77 Do not publish test files to npm 2016-12-13 23:28:33 +00:00
Paris Kasidiaris 56ca7743a8 Always build TypeScript in lib/ 2016-12-14 01:10:03 +02:00
Paris Kasidiaris fb17d57549 Merge pull request #398 from budde377/feat-npm
Add prepublish script and change main
2016-12-13 22:59:58 +00:00
Christian Budde Christensen e7045f2b8a Add prepublish script and change main
Building TS before publish and pointing the main entry to the builded files.
2016-12-13 20:34:19 +01:00
Daniel Imms fd25bd7ca2 Merge remote-tracking branch 'upstream/master' into 361_circular_list_scrollback 2016-12-12 15:05:19 -08:00
Paris Kasidiaris 852f587bd2 Merge pull request #400 from arcanis/patch-1
Use a fixed size to account for the scrollbar
2016-12-11 10:25:35 +00:00
Maël Nison e0e6f5e302 Use a fixed size to account for the scrollbar 2016-12-10 14:46:01 +01:00
Paris Kasidiaris 06a5ffdd1a Merge pull request #399 from bottleofwater/patch-1
Don't apply the 32 delta when in sgr mode - fix #394
2016-12-09 10:12:42 +00:00
bottleofwater a75bafc4ba Don't apply the 32 delta when in sgr mode - fix #394 2016-12-09 10:52:09 +01:00
Daniel Imms 607c819109 Progress 2016-11-27 03:27:36 -08:00
Daniel Imms 61fbbb0054 Add CiruclarList pop and splice 2016-11-27 02:20:53 -08:00
Daniel Imms 49b76baf3f Add CircularList and basic tests
Part of #361
2016-11-26 16:57:15 -08:00
67 changed files with 10199 additions and 9374 deletions
+16
View File
@@ -0,0 +1,16 @@
node_modules/
*.swp
.lock-wscript
lib/
Makefile.gyp
*.Makefile
*.target.gyp.mk
*.node
example/*.log
docs/
npm-debug.log
/.idea/
.env
build/
.vscode/
.git/
+1
View File
@@ -5,6 +5,7 @@ indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
[*.{j,t}s]
max_line_length = 100
+5 -1
View File
@@ -1,7 +1,7 @@
node_modules/
*.swp
.lock-wscript
out/
lib/
Makefile.gyp
*.Makefile
*.target.gyp.mk
@@ -12,3 +12,7 @@ npm-debug.log
/.idea/
.env
build/
.vscode/
# Directories needed for code coverage
/coverage/
+16
View File
@@ -0,0 +1,16 @@
node_modules/
*.swp
.lock-wscript
lib/*.test.js
lib/*.test.js.map
lib/test/
Makefile.gyp
*.Makefile
*.target.gyp.mk
*.node
example/*.log
docs/
npm-debug.log
/.idea/
.env
build/
+7 -1
View File
@@ -2,7 +2,11 @@ language: node_js
node_js:
- 6
env:
- CXX=g++-4.8
global:
- CXX=g++-4.8
matrix:
- NPM_COMMAND=lint
- NPM_COMMAND=test
addons:
apt:
sources:
@@ -11,3 +15,5 @@ addons:
- g++-4.8
notifications:
email: false
script: npm run $NPM_COMMAND
after_success: npm run coveralls
+23
View File
@@ -0,0 +1,23 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"cwd": "${workspaceRoot}",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/mocha",
"windows": {
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/mocha.cmd"
},
"runtimeArgs": [
"--colors",
"--recursive",
"${workspaceRoot}/lib"
],
"sourceMaps": true,
"outFiles": [ "${workspaceRoot}/lib/**/*.js" ],
"internalConsoleOptions": "openOnSessionStart"
}
]
}
+23
View File
@@ -1,5 +1,6 @@
List of xterm.js contributors. Updated before every release.
Aleksandr Andrienko <aandrienko@codenvy.com>
Alessandro Nadalin <alessandro.nadalin@gmail.com>
Alexander Olsson <noseglid@gmail.com>
Antonis Kalipetis <akalipetis@sourcelair.com>
@@ -7,25 +8,47 @@ Anton Skshidlevsky <meefik@gmail.com>
Anton Yurovskykh <anton.yurovskykh@gmail.com>
Austin Robertson <austinrobertson@gmail.com>
ayapi <colors.aya@gmail.com>
Ben Hall <ben@benhall.me.uk>
Benjamin Fischer <benjamin.fischer@rwth-aachen.de>
Bill Church <billchurch@users.noreply.github.com>
Bob Reid <bobreid@Bobs-MacBook-Pro.local>
bottleofwater <nison.mael+bottleofwater@gmail.com>
Brian Mock <brian@mockbrian.com>
Carson Anderson <carson@betterservers.com>
Christian Budde Christensen <budde377@gmail.com>
Christopher Jeffrey <chjjeffrey@gmail.com>
coderaiser <mnemonic.enemy@gmail.com>
Daniel Imms <daimms@microsoft.com>
Daniel Risacher <drisacher@gmail.com>
Dan Kaplun <dbkaplun@twitch.tv>
Darin Morrison <freebroccolo@users.noreply.github.com>
Edgar Andrés Margffoy Tuay <andfoy@gmail.com>
Elliot Saba <staticfloat@gmail.com>
Gary Ritchie <gary@rstudio.com>
hiro-su <h.sugipon@gmail.com>
Ian Lewis <ianlewis@google.com>
imoses <ido@twiggle.com>
InDieTasten <indietasten@gmail.com>
Jean Bruenn <himself@jeanbruenn.info>
Jörg Breitbart <jerch@rockborn.de>
Justin Mecham <justin@mecham.me>
Lucian Buzzo <lucian.buzzo@gmail.com>
Maël Nison <nison.mael@gmail.com>
Martin Chloride <i@martincl2.me>
Martin Wang <jiahaow@ca.ibm.com>
Michael Irwin <mikesir87@gmail.com>
Mikko Karvonen <mikko.karvonen@arm.com>
Nicolas Ramz <nicolas.ramz@gmail.com>
Paris Kasidiaris <pariskasidiaris@gmail.com>
Paris Kasidiaris <paris@sourcelair.com>
runarberg <runar@greenqloud.com>
Saswat Das <saswatds@users.noreply.github.com>
Saul Costa <saul@codevolve.com>
Shuanglei Tao <tsl0922@gmail.com>
Steven Silvester <steven.silvester@ieee.org>
Thanasis Daglis <thanasis@sourcelair.com>
Tine Jozelj <tine.jozelj@outlook.com>
Tyler Jewell <tjewell@codenvy.com>
Vincent Woo <me@vincentwoo.com>
yutaka <shigure@refy.net>
YuviPanda <yuvipanda@gmail.com>
+17 -2
View File
@@ -1,4 +1,19 @@
FROM node:4-onbuild
FROM node:6.9
MAINTAINER Paris Kasidiaris <paris@sourcelair.com>
EXPOSE 3000
# Set the working directory
WORKDIR /usr/src/app
# Set an entrypoint, to automatically install node modules
ENTRYPOINT ["/bin/bash", "-c", "if [[ ! -d node_modules ]]; then npm install; fi; exec \"${@:0}\";"]
CMD ["npm", "run", "dev"]
# First, install dependencies to improve layer caching
COPY package.json /usr/src/app/
RUN npm install
# Add the code
COPY . /usr/src/app
# Run the tests and build, to make sure everything is working nicely
RUN npm run build && npm run test
+1
View File
@@ -0,0 +1 @@
web: npm start
+1 -1
View File
@@ -1 +1 @@
web: npm start
web: npm run dev
+55 -19
View File
@@ -1,6 +1,6 @@
# xterm.js
# [![xterm.js logo](logo.png)](https://xtermjs.org)
[![xterm.js build status](https://api.travis-ci.org/sourcelair/xterm.js.svg)](https://travis-ci.org/sourcelair/xterm.js) [![Gitter](https://badges.gitter.im/sourcelair/xterm.js.svg)](https://gitter.im/sourcelair/xterm.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![xterm.js build status](https://api.travis-ci.org/sourcelair/xterm.js.svg)](https://travis-ci.org/sourcelair/xterm.js) [![Coverage Status](https://coveralls.io/repos/github/sourcelair/xterm.js/badge.svg)](https://coveralls.io/github/sourcelair/xterm.js) [![Gitter](https://badges.gitter.im/sourcelair/xterm.js.svg)](https://gitter.im/sourcelair/xterm.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Xterm.js is a terminal front-end component written in JavaScript that works in the browser.
@@ -25,6 +25,17 @@ Xterm.js is used in several world-class applications to provide great terminal e
- [**SourceLair**](https://www.sourcelair.com/): In-browser IDE that provides its users with fully-featured Linux terminals based on xterm.js
- [**Microsoft Visual Studio Code**](http://code.visualstudio.com/): Modern, versatile and powerful open source code editor that provides an integrated terminal based on xterm.js
- [**ttyd**](https://github.com/tsl0922/ttyd): A command-line tool for sharing terminal over the web, with fully-featured terminal emulation based on xterm.js
- [**Katacoda**](https://www.katacoda.com/): Katacoda is an Interactive Learning Platform for software developers, covering the latest Cloud Native technologies.
- [**Eclipse Che**](http://www.eclipse.org/che): Developer workspace server, cloud IDE, and Eclipse next-generation IDE.
- [**Codenvy**](http://www.codenvy.com): Cloud workspaces for development teams.
- [**CoderPad**](https://coderpad.io): Online interviewing platform for programmers. Run code in many programming languages, with results displayed by `xterm.js`.
- [**WebSSH2**](https://github.com/billchurch/WebSSH2): A web based SSH2 client using `xterm.js`, socket.io, and ssh2.
- [**Spyder Terminal**](https://github.com/spyder-ide/spyder-terminal): A full fledged system terminal embedded on Spyder IDE.
- [**Cloud Commander**](https://cloudcmd.io "Cloud Commander"): Orthodox web file manager with console and editor.
- [**Codevolve**](https://www.codevolve.com "Codevolve"): Online platform for interactive coding and web development courses. Live container-backed terminal uses `xterm.js`.
- [**RStudio**](https://www.rstudio.com/products/RStudio "RStudio"): RStudio is an integrated development environment (IDE) for R.
- [**Terminal for Atom**](https://github.com/jsmecham/atom-terminal-tab): A simple terminal for the Atom text editor.
- [**Eclipse Orion**](https://orionhub.org): A modern, open source software development environment that runs in the cloud. Code, deploy and run in the cloud.
Do you use xterm.js in your application as well? Please [open a Pull Request](https://github.com/sourcelair/xterm.js/pulls) to include it here. We would love to have it in our list.
@@ -43,14 +54,51 @@ Xterm.js works seamlessly in Electron apps and may even work on earlier versions
## Demo
To launch the demo simply run:
### Linux or macOS
Run the following commands:
```
npm install
npm start
$ npm install
$ npm start
```
Then open http://0.0.0.0:3000 in a web browser (use http://127.0.0.1:3000 if running under Windows).
Then open http://0.0.0.0:3000 in a web browser.
### Windows
First, ensure [node-gyp](https://github.com/nodejs/node-gyp) is installed and configured correctly, then run these commands.
Note: Do not use ConEmu, as it seems to break the demo for some reason.
```
> npm install
> npm start
```
Then open http://127.0.0.1:3000 in a web browser.
## Getting Started
To start using xterm.js on your browser, add the `xterm.js` and `xterm.css` to the head of your html page. Then create a `<div id="terminal"></div>` onto which xterm can attach itself.
```html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="bower_components/xterm.js/dist/xterm.css" />
<script src="bower_components/xterm.js/dist/xterm.js"></script>
</head>
<body>
<div id="terminal"></div>
<script>
var term = new Terminal();
term.open(document.getElementById('terminal'));
term.write('Hello from \033[1;3;31mxterm.js\033[0m $ ')
</script>
</body>
</html>
```
Finally instantiate the `Terminal` object and then call the `open` function with the DOM object of the `div`.
## Addons
@@ -79,19 +127,7 @@ The existing releases are available at this GitHub repo's [Releases](https://git
Xterm.js is maintained by [SourceLair](https://www.sourcelair.com/) and a few external contributors, but we would love to receive contributions from everyone!
To contribute either code, documentation or issues to xterm.js please read the [Contributing document](CONTRIBUTING.md) before.
The development of xterm.js does not require any special tool. All you need is an editor that supports JavaScript and a browser (if you would like to run the demo you will need Node.js to get all features).
It is recommended though to use a development tool that uses xterm.js internally, to develop for xterm.js. [Eating our own dogfood](https://en.wikipedia.org/wiki/Eating_your_own_dog_food) has been proved extremely beneficial for this project. Known tools that use xterm.js internally are:
#### [SourceLair](https://www.sourcelair.com)
Visit https://lair.io/sourcelair/xterm and follow the instructions. All development will happen in your browser.
#### [Visual Studio Code](http://code.visualstudio.com/)
[Download Visual Studio Code](http://code.visualstudio.com/Download), clone xterm.js and you are all set.
To contribute either code, documentation or issues to xterm.js please read the [Contributing document](CONTRIBUTING.md) beforehand. The development of xterm.js does not require any special tool. All you need is an editor that supports JavaScript/TypeScript and a browser. You will need Node.js installed locally to get all the features working in the demo.
## License Agreement
-35
View File
@@ -1,35 +0,0 @@
#! /usr/bin/env bash
set -e
# $BUILD_DIR should default to "build"
BUILD_DIR=${BUILD_DIR:=build}
# Create the build directory
mkdir -p $BUILD_DIR
# Clean out/* to prevent confusion if files were deleted in src/
rm -rf out/*
# Build all TypeScript files (including tests) to out/
tsc
# Concat all xterm.js files into a single file and output as a UMD to $BUILD_DIR/xterm.js
browserify ./out/xterm.js --standalone Terminal --debug --outfile ./$BUILD_DIR/xterm.js
cat ./$BUILD_DIR/xterm.js | exorcist ./$BUILD_DIR/xterm.js.map -b ./$BUILD_DIR > ./$BUILD_DIR/xterm.temp.js
rm ./$BUILD_DIR/xterm.js
mv ./$BUILD_DIR/xterm.temp.js ./$BUILD_DIR/xterm.js
# Resolve the chain of sourcemaps so that ./$BUILD_DIR/xterm.js.map points at ./src
sorcery -i $BUILD_DIR/xterm.js
# Copy all CSS files from src/ to $BUILD_DIR/
cd src
find . -name '*.css' | cpio -pdm ../$BUILD_DIR
cd ..
# Copy addons from out/ to $BUILD_DIR/
cd out/addons
find . -name '*.js' | cpio -pdm ../../$BUILD_DIR/addons
cd ../..
+1 -1
View File
@@ -21,7 +21,7 @@ CURRENT_BOWER_JSON_VERSION=$(cat bower.json \
# Build xterm.js into `dist`
export BUILD_DIR=dist
./bin/build
npm run build
# Update AUTHORS file
sh bin/generate-authors
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "xterm.js",
"version": "2.2.1",
"version": "2.6.0",
"ignore": ["demo", "test", ".gitignore"],
"main": [
"dist/xterm.js",
+2 -2
View File
@@ -2,7 +2,7 @@ var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var os = require('os');
var pty = require('pty.js');
var pty = require('node-pty');
var terminals = {},
logs = {};
@@ -69,7 +69,7 @@ app.ws('/terminals/:pid', function (ws, req) {
term.write(msg);
});
ws.on('close', function () {
process.kill(term.pid);
term.kill();
console.log('Closed terminal ' + term.pid);
// Clean things up
delete terminals[term.pid];
+19 -1
View File
@@ -16,7 +16,25 @@
<div id="terminal-container"></div>
<div>
<h2>Options</h2>
<label><input type="checkbox" id="option-cursor-blink"> cursorBlink</label>
<p>
<label><input type="checkbox" id="option-cursor-blink"> cursorBlink</label>
</p>
<p>
<label>
cursorStyle
<select id="option-cursor-style">
<option value="block">block</option>
<option value="underline">underline</option>
<option value="bar">bar</option>
</select>
</label>
</p>
<p>
<label>scrollback <input type="number" id="option-scrollback" value="1000" /></label>
</p>
<p>
<label>tabStopWidth <input type="number" id="option-tabstopwidth" value="8" /></label>
</p>
<div>
<h3>Size</h3>
<div>
+21 -6
View File
@@ -8,14 +8,17 @@ var term,
var terminalContainer = document.getElementById('terminal-container'),
optionElements = {
cursorBlink: document.querySelector('#option-cursor-blink')
cursorBlink: document.querySelector('#option-cursor-blink'),
cursorStyle: document.querySelector('#option-cursor-style'),
scrollback: document.querySelector('#option-scrollback'),
tabstopwidth: document.querySelector('#option-tabstopwidth')
},
colsElement = document.getElementById('cols'),
rowsElement = document.getElementById('rows');
function setTerminalSize () {
var cols = parseInt(colsElement.value),
rows = parseInt(rowsElement.value),
var cols = parseInt(colsElement.value, 10),
rows = parseInt(rowsElement.value, 10),
width = (cols * charWidth).toString() + 'px',
height = (rows * charHeight).toString() + 'px';
@@ -27,7 +30,18 @@ function setTerminalSize () {
colsElement.addEventListener('change', setTerminalSize);
rowsElement.addEventListener('change', setTerminalSize);
optionElements.cursorBlink.addEventListener('change', createTerminal);
optionElements.cursorBlink.addEventListener('change', function () {
term.setOption('cursorBlink', optionElements.cursorBlink.checked);
});
optionElements.cursorStyle.addEventListener('change', function () {
term.setOption('cursorStyle', optionElements.cursorStyle.value);
});
optionElements.scrollback.addEventListener('change', function () {
term.setOption('scrollback', parseInt(optionElements.scrollback.value, 10));
});
optionElements.tabstopwidth.addEventListener('change', function () {
term.setOption('tabStopWidth', parseInt(optionElements.tabstopwidth.value, 10));
});
createTerminal();
@@ -37,7 +51,9 @@ function createTerminal() {
terminalContainer.removeChild(terminalContainer.children[0]);
}
term = new Terminal({
cursorBlink: optionElements.cursorBlink.checked
cursorBlink: optionElements.cursorBlink.checked,
scrollback: parseInt(optionElements.scrollback.value, 10),
tabStopWidth: parseInt(optionElements.tabstopwidth.value, 10)
});
term.on('resize', function (size) {
if (!pid) {
@@ -78,7 +94,6 @@ function createTerminal() {
});
}
function runRealTerminal() {
term.attach(socket);
term._initialized = true;
-4
View File
@@ -20,7 +20,3 @@ h1 {
color: #fafafa;
padding: 2px;
}
#terminal-container .terminal:focus .terminal-cursor {
background-color: #fafafa;
}
+114 -102
View File
@@ -3,112 +3,124 @@
* @module xterm/addons/attach/attach
* @license MIT
*/
(function (attach) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = attach(require('../../xterm'));
}
else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], attach);
}
else {
/*
* Plain browser environment
*/
attach(window.Terminal);
}
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = attach(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], attach);
} else {
/*
* Plain browser environment
*/
attach(window.Terminal);
}
})(function (Xterm) {
'use strict';
var exports = {};
/**
* Attaches the given terminal to the given socket.
*
* @param {Xterm} term - The terminal to be attached to the given socket.
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
exports.attach = function (term, socket, bidirectional, buffered) {
bidirectional = (typeof bidirectional == 'undefined') ? true : bidirectional;
term.socket = socket;
term._flushBuffer = function () {
term.write(term._attachSocketBuffer);
term._attachSocketBuffer = null;
clearTimeout(term._attachSocketBufferTimer);
term._attachSocketBufferTimer = null;
};
term._pushToBuffer = function (data) {
if (term._attachSocketBuffer) {
term._attachSocketBuffer += data;
}
else {
term._attachSocketBuffer = data;
setTimeout(term._flushBuffer, 10);
}
};
term._getMessage = function (ev) {
if (buffered) {
term._pushToBuffer(ev.data);
}
else {
term.write(ev.data);
}
};
term._sendData = function (data) {
socket.send(data);
};
socket.addEventListener('message', term._getMessage);
if (bidirectional) {
term.on('data', term._sendData);
}
socket.addEventListener('close', term.detach.bind(term, socket));
socket.addEventListener('error', term.detach.bind(term, socket));
'use strict';
var exports = {};
/**
* Attaches the given terminal to the given socket.
*
* @param {Xterm} term - The terminal to be attached to the given socket.
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
exports.attach = function (term, socket, bidirectional, buffered) {
bidirectional = (typeof bidirectional == 'undefined') ? true : bidirectional;
term.socket = socket;
term._flushBuffer = function () {
term.write(term._attachSocketBuffer);
term._attachSocketBuffer = null;
clearTimeout(term._attachSocketBufferTimer);
term._attachSocketBufferTimer = null;
};
/**
* Detaches the given terminal from the given socket
*
* @param {Xterm} term - The terminal to be detached from the given socket.
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
exports.detach = function (term, socket) {
term.off('data', term._sendData);
socket = (typeof socket == 'undefined') ? term.socket : socket;
if (socket) {
socket.removeEventListener('message', term._getMessage);
}
delete term.socket;
term._pushToBuffer = function (data) {
if (term._attachSocketBuffer) {
term._attachSocketBuffer += data;
} else {
term._attachSocketBuffer = data;
setTimeout(term._flushBuffer, 10);
}
};
/**
* Attaches the current terminal to the given socket
*
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
Xterm.prototype.attach = function (socket, bidirectional, buffered) {
return exports.attach(this, socket, bidirectional, buffered);
term._getMessage = function (ev) {
if (buffered) {
term._pushToBuffer(ev.data);
} else {
term.write(ev.data);
}
};
/**
* Detaches the current terminal from the given socket.
*
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
Xterm.prototype.detach = function (socket) {
return exports.detach(this, socket);
term._sendData = function (data) {
socket.send(data);
};
return exports;
socket.addEventListener('message', term._getMessage);
if (bidirectional) {
term.on('data', term._sendData);
}
socket.addEventListener('close', term.detach.bind(term, socket));
socket.addEventListener('error', term.detach.bind(term, socket));
};
/**
* Detaches the given terminal from the given socket
*
* @param {Xterm} term - The terminal to be detached from the given socket.
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
exports.detach = function (term, socket) {
term.off('data', term._sendData);
socket = (typeof socket == 'undefined') ? term.socket : socket;
if (socket) {
socket.removeEventListener('message', term._getMessage);
}
delete term.socket;
};
/**
* Attaches the current terminal to the given socket
*
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
Xterm.prototype.attach = function (socket, bidirectional, buffered) {
return exports.attach(this, socket, bidirectional, buffered);
};
/**
* Detaches the current terminal from the given socket.
*
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
Xterm.prototype.detach = function (socket) {
return exports.detach(this, socket);
};
return exports;
});
//# sourceMappingURL=attach.js.map
+71 -44
View File
@@ -10,50 +10,77 @@
* @module xterm/addons/fit/fit
* @license MIT
*/
(function (fit) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = fit(require('../../xterm'));
}
else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], fit);
}
else {
/*
* Plain browser environment
*/
fit(window.Terminal);
}
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = fit(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], fit);
} else {
/*
* Plain browser environment
*/
fit(window.Terminal);
}
})(function (Xterm) {
var exports = {};
exports.proposeGeometry = function (term) {
var parentElementStyle = window.getComputedStyle(term.element.parentElement), parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height')), parentElementWidth = parseInt(parentElementStyle.getPropertyValue('width')), elementStyle = window.getComputedStyle(term.element), elementPaddingVer = parseInt(elementStyle.getPropertyValue('padding-top')) + parseInt(elementStyle.getPropertyValue('padding-bottom')), elementPaddingHor = parseInt(elementStyle.getPropertyValue('padding-right')) + parseInt(elementStyle.getPropertyValue('padding-left')), availableHeight = parentElementHeight - elementPaddingVer, availableWidth = parentElementWidth - elementPaddingHor, container = term.rowContainer, subjectRow = term.rowContainer.firstElementChild, contentBuffer = subjectRow.innerHTML, characterHeight, rows, characterWidth, cols, geometry;
subjectRow.style.display = 'inline';
subjectRow.innerHTML = 'W'; // Common character for measuring width, although on monospace
characterWidth = subjectRow.getBoundingClientRect().width;
subjectRow.style.display = ''; // Revert style before calculating height, since they differ.
characterHeight = parseInt(subjectRow.offsetHeight);
subjectRow.innerHTML = contentBuffer;
rows = parseInt(availableHeight / characterHeight);
cols = parseInt(availableWidth / characterWidth) - 1;
geometry = { cols: cols, rows: rows };
return geometry;
};
exports.fit = function (term) {
var geometry = exports.proposeGeometry(term);
term.resize(geometry.cols, geometry.rows);
};
Xterm.prototype.proposeGeometry = function () {
return exports.proposeGeometry(this);
};
Xterm.prototype.fit = function () {
return exports.fit(this);
};
return exports;
var exports = {};
exports.proposeGeometry = function (term) {
if (!term.element.parentElement) {
return null;
}
var parentElementStyle = window.getComputedStyle(term.element.parentElement),
parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height')),
parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')) - 17),
elementStyle = window.getComputedStyle(term.element),
elementPaddingVer = parseInt(elementStyle.getPropertyValue('padding-top')) + parseInt(elementStyle.getPropertyValue('padding-bottom')),
elementPaddingHor = parseInt(elementStyle.getPropertyValue('padding-right')) + parseInt(elementStyle.getPropertyValue('padding-left')),
availableHeight = parentElementHeight - elementPaddingVer,
availableWidth = parentElementWidth - elementPaddingHor,
container = term.rowContainer,
subjectRow = term.rowContainer.firstElementChild,
contentBuffer = subjectRow.innerHTML,
characterHeight,
rows,
characterWidth,
cols,
geometry;
subjectRow.style.display = 'inline';
subjectRow.innerHTML = 'W'; // Common character for measuring width, although on monospace
characterWidth = subjectRow.getBoundingClientRect().width;
subjectRow.style.display = ''; // Revert style before calculating height, since they differ.
characterHeight = subjectRow.getBoundingClientRect().height;
subjectRow.innerHTML = contentBuffer;
rows = parseInt(availableHeight / characterHeight);
cols = parseInt(availableWidth / characterWidth);
geometry = {cols: cols, rows: rows};
return geometry;
};
exports.fit = function (term) {
var geometry = exports.proposeGeometry(term);
if (geometry) {
term.resize(geometry.cols, geometry.rows);
}
};
Xterm.prototype.proposeGeometry = function () {
return exports.proposeGeometry(this);
};
Xterm.prototype.fit = function () {
return exports.fit(this);
};
return exports;
});
//# sourceMappingURL=fit.js.map
+42 -42
View File
@@ -4,47 +4,47 @@
* @license MIT
*/
(function (fullscreen) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = fullscreen(require('../../xterm'));
}
else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], fullscreen);
}
else {
/*
* Plain browser environment
*/
fullscreen(window.Terminal);
}
})(function (Xterm) {
var exports = {};
/**
* Toggle the given terminal's fullscreen mode.
* @param {Xterm} term - The terminal to toggle full screen mode
* @param {boolean} fullscreen - Toggle fullscreen on (true) or off (false)
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
exports.toggleFullScreen = function (term, fullscreen) {
var fn;
if (typeof fullscreen == 'undefined') {
fn = (term.element.classList.contains('fullscreen')) ? 'remove' : 'add';
}
else if (!fullscreen) {
fn = 'remove';
}
else {
fn = 'add';
}
term.element.classList[fn]('fullscreen');
};
Xterm.prototype.toggleFullscreen = function (fullscreen) {
exports.toggleFullScreen(this, fullscreen);
};
return exports;
module.exports = fullscreen(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], fullscreen);
} else {
/*
* Plain browser environment
*/
fullscreen(window.Terminal);
}
})(function (Xterm) {
var exports = {};
/**
* Toggle the given terminal's fullscreen mode.
* @param {Xterm} term - The terminal to toggle full screen mode
* @param {boolean} fullscreen - Toggle fullscreen on (true) or off (false)
*/
exports.toggleFullScreen = function (term, fullscreen) {
var fn;
if (typeof fullscreen == 'undefined') {
fn = (term.element.classList.contains('fullscreen')) ? 'remove' : 'add';
} else if (!fullscreen) {
fn = 'remove';
} else {
fn = 'add';
}
term.element.classList[fn]('fullscreen');
};
Xterm.prototype.toggleFullscreen = function (fullscreen) {
exports.toggleFullScreen(this, fullscreen);
};
return exports;
});
//# sourceMappingURL=fullscreen.js.map
+193 -151
View File
@@ -3,163 +3,205 @@
* @module xterm/addons/linkify/linkify
* @license MIT
*/
(function (linkify) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = linkify(require('../../xterm'));
}
else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], linkify);
}
else {
/*
* Plain browser environment
*/
linkify(window.Terminal);
}
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = linkify(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], linkify);
} else {
/*
* Plain browser environment
*/
linkify(window.Terminal);
}
})(function (Xterm) {
'use strict';
var exports = {}, protocolClause = '(https?:\\/\\/)', domainCharacterSet = '[\\da-z\\.-]+', negatedDomainCharacterSet = '[^\\da-z\\.-]+', domainBodyClause = '(' + domainCharacterSet + ')', tldClause = '([a-z\\.]{2,6})', ipClause = '((\\d{1,3}\\.){3}\\d{1,3})', portClause = '(:\\d{1,5})', hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + ')' + portClause + '?', pathClause = '(\\/[\\/\\w\\.-]*)*', negatedPathCharacterSet = '[^\\/\\w\\.-]+', bodyClause = hostClause + pathClause, start = '(?:^|' + negatedDomainCharacterSet + ')(', end = ')($|' + negatedPathCharacterSet + ')', lenientUrlClause = start + protocolClause + '?' + bodyClause + end, strictUrlClause = start + protocolClause + bodyClause + end, lenientUrlRegex = new RegExp(lenientUrlClause), strictUrlRegex = new RegExp(strictUrlClause);
'use strict';
var exports = {},
protocolClause = '(https?:\\/\\/)',
domainCharacterSet = '[\\da-z\\.-]+',
negatedDomainCharacterSet = '[^\\da-z\\.-]+',
domainBodyClause = '(' + domainCharacterSet + ')',
tldClause = '([a-z\\.]{2,6})',
ipClause = '((\\d{1,3}\\.){3}\\d{1,3})',
portClause = '(:\\d{1,5})',
hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + ')' + portClause + '?',
pathClause = '(\\/[\\/\\w\\.-]*)*',
negatedPathCharacterSet = '[^\\/\\w\\.-]+',
bodyClause = hostClause + pathClause,
start = '(?:^|' + negatedDomainCharacterSet + ')(',
end = ')($|' + negatedPathCharacterSet + ')',
lenientUrlClause = start + protocolClause + '?' + bodyClause + end,
strictUrlClause = start + protocolClause + bodyClause + end,
lenientUrlRegex = new RegExp(lenientUrlClause),
strictUrlRegex = new RegExp(strictUrlClause);
/**
* Converts all valid URLs found in the given terminal line into
* hyperlinks. The terminal line can be either the HTML element itself
* or the index of the termina line in the children of the terminal
* rows container.
*
* @param {Xterm} terminal - The terminal that owns the given line.
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
*/
exports.linkifyTerminalLine = function (terminal, line, lenient, target) {
if (typeof line == 'number') {
line = terminal.rowContainer.children[line];
} else if (! (line instanceof HTMLDivElement)) {
var message = 'The "line" argument should be either a number';
message += ' or an HTMLDivElement';
throw new TypeError(message);
}
if (typeof target === 'undefined') {
target = '';
} else {
target = 'target="' + target + '"';
}
var buffer = document.createElement('span'),
nodes = line.childNodes;
for (var j=0; j<nodes.length; j++) {
var node = nodes[j],
match;
/**
* Since we cannot access the TextNode's HTML representation
* from the instance itself, we assign its data as textContent
* to a dummy buffer span, in order to retrieve the TextNode's
* HTML representation from the buffer's innerHTML.
*/
buffer.textContent = node.data;
var nodeHTML = buffer.innerHTML;
/**
* Apply function only on TextNodes
*/
if (node.nodeType != node.TEXT_NODE) {
continue;
}
var url = exports.findLinkMatch(node.data, lenient);
if (!url) {
continue;
}
var startsWithProtocol = new RegExp('^' + protocolClause),
urlHasProtocol = url.match(startsWithProtocol),
href = (urlHasProtocol) ? url : 'http://' + url,
link = '<a href="' + href + '" ' + target + '>' + url + '</a>',
newHTML = nodeHTML.replace(url, link);
line.innerHTML = line.innerHTML.replace(nodeHTML, newHTML);
}
/**
* Converts all valid URLs found in the given terminal line into
* hyperlinks. The terminal line can be either the HTML element itself
* or the index of the termina line in the children of the terminal
* rows container.
* This event gets emitted when conversion of all URL susbtrings
* to HTML anchor elements (links) has finished, for a specific
* line of the current Xterm instance.
*
* @param {Xterm} terminal - The terminal that owns the given line.
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
* @event linkify:line
*/
exports.linkifyTerminalLine = function (terminal, line, lenient, target) {
if (typeof line == 'number') {
line = terminal.rowContainer.children[line];
}
else if (!(line instanceof HTMLDivElement)) {
var message = 'The "line" argument should be either a number';
message += ' or an HTMLDivElement';
throw new TypeError(message);
}
if (typeof target === 'undefined') {
target = '';
}
else {
target = 'target="' + target + '"';
}
var buffer = document.createElement('span'), nodes = line.childNodes;
for (var j = 0; j < nodes.length; j++) {
var node = nodes[j], match;
/**
* Since we cannot access the TextNode's HTML representation
* from the instance itself, we assign its data as textContent
* to a dummy buffer span, in order to retrieve the TextNode's
* HTML representation from the buffer's innerHTML.
*/
buffer.textContent = node.data;
var nodeHTML = buffer.innerHTML;
/**
* Apply function only on TextNodes
*/
if (node.nodeType != node.TEXT_NODE) {
continue;
}
var url = exports.findLinkMatch(node.data, lenient);
if (!url) {
continue;
}
var startsWithProtocol = new RegExp('^' + protocolClause), urlHasProtocol = url.match(startsWithProtocol), href = (urlHasProtocol) ? url : 'http://' + url, link = '<a href="' + href + '" ' + target + '>' + url + '</a>', newHTML = nodeHTML.replace(url, link);
line.innerHTML = line.innerHTML.replace(nodeHTML, newHTML);
}
/**
* This event gets emitted when conversion of all URL susbtrings
* to HTML anchor elements (links) has finished, for a specific
* line of the current Xterm instance.
*
* @event linkify:line
*/
terminal.emit('linkify:line', line);
};
terminal.emit('linkify:line', line);
};
/**
* Finds a link within a block of text.
*
* @param {string} text - The text to search .
* @param {boolean} lenient - Whether to use the lenient search.
* @return {string} A URL.
*/
exports.findLinkMatch = function (text, lenient) {
var match = text.match(lenient ? lenientUrlRegex : strictUrlRegex);
if (!match || match.length === 0) {
return null;
}
return match[1];
}
/**
* Converts all valid URLs found in the terminal view into hyperlinks.
*
* @param {Xterm} terminal - The terminal that should get "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
*/
exports.linkify = function (terminal, lenient, target) {
var rows = terminal.rowContainer.children;
lenient = (typeof lenient == "boolean") ? lenient : true;
for (var i=0; i<rows.length; i++) {
var line = rows[i];
exports.linkifyTerminalLine(terminal, line, lenient, target);
}
/**
* Finds a link within a block of text.
* This event gets emitted when conversion of all URL substrings to
* HTML anchor elements (links) has finished for the current Xterm
* instance's view.
*
* @param {string} text - The text to search .
* @param {boolean} lenient - Whether to use the lenient search.
* @return {string} A URL.
* @event linkify
*/
exports.findLinkMatch = function (text, lenient) {
var match = text.match(lenient ? lenientUrlRegex : strictUrlRegex);
if (!match || match.length === 0) {
return null;
}
return match[1];
};
/**
* Converts all valid URLs found in the terminal view into hyperlinks.
*
* @param {Xterm} terminal - The terminal that should get "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
*/
exports.linkify = function (terminal, lenient, target) {
var rows = terminal.rowContainer.children;
lenient = (typeof lenient == "boolean") ? lenient : true;
for (var i = 0; i < rows.length; i++) {
var line = rows[i];
exports.linkifyTerminalLine(terminal, line, lenient, target);
}
/**
* This event gets emitted when conversion of all URL substrings to
* HTML anchor elements (links) has finished for the current Xterm
* instance's view.
*
* @event linkify
*/
terminal.emit('linkify');
};
/**
* Extend Xterm prototype.
*/
/**
* Converts all valid URLs found in the current terminal linte into
* hyperlinks.
*
* @memberof Xterm
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkifyTerminalLine = function (line, lenient, target) {
return exports.linkifyTerminalLine(this, line, lenient, target);
};
/**
* Converts all valid URLs found in the current terminal into hyperlinks.
*
* @memberof Xterm
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkify = function (lenient, target) {
return exports.linkify(this, lenient, target);
};
return exports;
terminal.emit('linkify');
};
/**
* Extend Xterm prototype.
*/
/**
* Converts all valid URLs found in the current terminal linte into
* hyperlinks.
*
* @memberof Xterm
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkifyTerminalLine = function (line, lenient, target) {
return exports.linkifyTerminalLine(this, line, lenient, target);
};
/**
* Converts all valid URLs found in the current terminal into hyperlinks.
*
* @memberof Xterm
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkify = function (lenient, target) {
return exports.linkify(this, lenient, target);
};
return exports;
});
//# sourceMappingURL=linkify.js.map
+122 -109
View File
@@ -4,119 +4,132 @@
* @module xterm/addons/terminado/terminado
* @license MIT
*/
(function (attach) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = attach(require('../../xterm'));
}
else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], attach);
}
else {
/*
* Plain browser environment
*/
attach(window.Terminal);
}
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = attach(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], attach);
} else {
/*
* Plain browser environment
*/
attach(window.Terminal);
}
})(function (Xterm) {
'use strict';
var exports = {};
/**
* Attaches the given terminal to the given socket.
*
* @param {Xterm} term - The terminal to be attached to the given socket.
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
exports.terminadoAttach = function (term, socket, bidirectional, buffered) {
bidirectional = (typeof bidirectional == 'undefined') ? true : bidirectional;
term.socket = socket;
term._flushBuffer = function () {
term.write(term._attachSocketBuffer);
term._attachSocketBuffer = null;
clearTimeout(term._attachSocketBufferTimer);
term._attachSocketBufferTimer = null;
};
term._pushToBuffer = function (data) {
if (term._attachSocketBuffer) {
term._attachSocketBuffer += data;
}
else {
term._attachSocketBuffer = data;
setTimeout(term._flushBuffer, 10);
}
};
term._getMessage = function (ev) {
var data = JSON.parse(ev.data);
if (data[0] == "stdout") {
if (buffered) {
term._pushToBuffer(data[1]);
}
else {
term.write(data[1]);
}
}
};
term._sendData = function (data) {
socket.send(JSON.stringify(['stdin', data]));
};
term._setSize = function (size) {
socket.send(JSON.stringify(['set_size', size.rows, size.cols]));
};
socket.addEventListener('message', term._getMessage);
if (bidirectional) {
term.on('data', term._sendData);
'use strict';
var exports = {};
/**
* Attaches the given terminal to the given socket.
*
* @param {Xterm} term - The terminal to be attached to the given socket.
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
exports.terminadoAttach = function (term, socket, bidirectional, buffered) {
bidirectional = (typeof bidirectional == 'undefined') ? true : bidirectional;
term.socket = socket;
term._flushBuffer = function () {
term.write(term._attachSocketBuffer);
term._attachSocketBuffer = null;
clearTimeout(term._attachSocketBufferTimer);
term._attachSocketBufferTimer = null;
};
term._pushToBuffer = function (data) {
if (term._attachSocketBuffer) {
term._attachSocketBuffer += data;
} else {
term._attachSocketBuffer = data;
setTimeout(term._flushBuffer, 10);
}
};
term._getMessage = function (ev) {
var data = JSON.parse(ev.data)
if( data[0] == "stdout" ) {
if (buffered) {
term._pushToBuffer(data[1]);
} else {
term.write(data[1]);
}
term.on('resize', term._setSize);
socket.addEventListener('close', term.terminadoDetach.bind(term, socket));
socket.addEventListener('error', term.terminadoDetach.bind(term, socket));
}
};
/**
* Detaches the given terminal from the given socket
*
* @param {Xterm} term - The terminal to be detached from the given socket.
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
exports.terminadoDetach = function (term, socket) {
term.off('data', term._sendData);
socket = (typeof socket == 'undefined') ? term.socket : socket;
if (socket) {
socket.removeEventListener('message', term._getMessage);
}
delete term.socket;
term._sendData = function (data) {
socket.send(JSON.stringify(['stdin', data]));
};
/**
* Attaches the current terminal to the given socket
*
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
Xterm.prototype.terminadoAttach = function (socket, bidirectional, buffered) {
return exports.terminadoAttach(this, socket, bidirectional, buffered);
term._setSize = function (size) {
socket.send(JSON.stringify(['set_size', size.rows, size.cols]));
};
/**
* Detaches the current terminal from the given socket.
*
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
Xterm.prototype.terminadoDetach = function (socket) {
return exports.terminadoDetach(this, socket);
};
return exports;
socket.addEventListener('message', term._getMessage);
if (bidirectional) {
term.on('data', term._sendData);
}
term.on('resize', term._setSize);
socket.addEventListener('close', term.terminadoDetach.bind(term, socket));
socket.addEventListener('error', term.terminadoDetach.bind(term, socket));
};
/**
* Detaches the given terminal from the given socket
*
* @param {Xterm} term - The terminal to be detached from the given socket.
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
exports.terminadoDetach = function (term, socket) {
term.off('data', term._sendData);
socket = (typeof socket == 'undefined') ? term.socket : socket;
if (socket) {
socket.removeEventListener('message', term._getMessage);
}
delete term.socket;
};
/**
* Attaches the current terminal to the given socket
*
* @param {WebSocket} socket - The socket to attach the current terminal.
* @param {boolean} bidirectional - Whether the terminal should send data
* to the socket as well.
* @param {boolean} buffered - Whether the rendering of incoming data
* should happen instantly or at a maximum
* frequency of 1 rendering per 10ms.
*/
Xterm.prototype.terminadoAttach = function (socket, bidirectional, buffered) {
return exports.terminadoAttach(this, socket, bidirectional, buffered);
};
/**
* Detaches the current terminal from the given socket.
*
* @param {WebSocket} socket - The socket from which to detach the current
* terminal.
*/
Xterm.prototype.terminadoDetach = function (socket) {
return exports.terminadoDetach(this, socket);
};
return exports;
});
//# sourceMappingURL=terminado.js.map
+53 -12
View File
@@ -71,7 +71,22 @@
resize: none;
}
.terminal .terminal-cursor {
.terminal a {
color: inherit;
text-decoration: none;
}
.terminal a:hover {
cursor: pointer;
text-decoration: underline;
}
.terminal a.xterm-invalid-link:hover {
cursor: text;
text-decoration: none;
}
.terminal.focus:not(.xterm-cursor-style-underline):not(.xterm-cursor-style-bar) .terminal-cursor {
background-color: #fff;
color: #000;
}
@@ -82,19 +97,41 @@
background-color: transparent;
}
.terminal.focus .terminal-cursor.blinking {
animation: blink-cursor 1.2s infinite step-end;
.terminal:not(.xterm-cursor-style-underline):not(.xterm-cursor-style-bar).focus.xterm-cursor-blink-on .terminal-cursor {
background-color: transparent;
color: inherit;
}
@keyframes blink-cursor {
0% {
background-color: #fff;
color: #000;
}
50% {
background-color: transparent;
color: #FFF;
}
.terminal.xterm-cursor-style-bar .terminal-cursor,
.terminal.xterm-cursor-style-underline .terminal-cursor {
position: relative;
}
.terminal.xterm-cursor-style-bar .terminal-cursor::before,
.terminal.xterm-cursor-style-underline .terminal-cursor::before {
content: "";
display: block;
position: absolute;
background-color: #fff;
}
.terminal.xterm-cursor-style-bar .terminal-cursor::before {
top: 0;
bottom: 0;
left: 0;
width: 1px;
}
.terminal.xterm-cursor-style-underline .terminal-cursor::before {
bottom: 0;
left: 0;
right: 0;
height: 1px;
}
.terminal.xterm-cursor-style-bar.focus.xterm-cursor-blink.xterm-cursor-blink-on .terminal-cursor::before,
.terminal.xterm-cursor-style-underline.focus.xterm-cursor-blink.xterm-cursor-blink-on .terminal-cursor::before {
background-color: transparent;
}
.terminal.xterm-cursor-style-bar.focus.xterm-cursor-blink .terminal-cursor::before,
.terminal.xterm-cursor-style-underline.focus.xterm-cursor-blink .terminal-cursor::before {
background-color: #fff;
}
.terminal .composition-view {
@@ -116,6 +153,10 @@
overflow-y: scroll;
}
.terminal .xterm-wide-char {
display: inline-block;
}
.terminal .xterm-rows {
position: absolute;
left: 0;
+4097 -5035
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
version: '2'
services:
web:
build: ./
volumes:
- ./:/usr/src/app
ports:
- 3000:3000
+111
View File
@@ -0,0 +1,111 @@
const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const coveralls = require('gulp-coveralls');
const fs = require('fs-extra');
const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const merge = require('merge-stream');
const mocha = require('gulp-mocha');
const sorcery = require('sorcery');
const source = require('vinyl-source-stream');
const sourcemaps = require('gulp-sourcemaps');
const ts = require('gulp-typescript');
let buildDir = process.env.BUILD_DIR || 'build';
let tsProject = ts.createProject('tsconfig.json');
let srcDir = tsProject.config.compilerOptions.rootDir;
let outDir = tsProject.config.compilerOptions.outDir;
/**
* Compile TypeScript sources to JavaScript files and create a source map file for each TypeScript
* file compiled.
*/
gulp.task('tsc', function () {
// Remove the ${outDir}/ directory to prevent confusion if files were deleted in ${srcDir}/
fs.emptyDirSync(`${outDir}`);
// Build all TypeScript files (including tests) to ${outDir}/, based on the configuration defined in
// `tsconfig.json`.
let tsResult = tsProject.src().pipe(sourcemaps.init()).pipe(tsProject());
let tsc = tsResult.js.pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: ''})).pipe(gulp.dest(outDir));
// Copy all addons from ${srcDir}/ to ${outDir}/
let copyAddons = gulp.src(`${srcDir}/addons/**/*`).pipe(gulp.dest(`${outDir}/addons`));
// Copy stylesheets from ${srcDir}/ to ${outDir}/
let copyStylesheets = gulp.src(`${srcDir}/**/*.css`).pipe(gulp.dest(outDir));
return merge(tsc, copyAddons, copyStylesheets);
});
/**
* Bundle JavaScript files produced by the `tsc` task, into a single file named `xterm.js` with
* Browserify.
*/
gulp.task('browserify', ['tsc'], function() {
// Ensure that the build directory exists
fs.ensureDirSync(buildDir);
let browserifyOptions = {
basedir: buildDir,
debug: true,
entries: [`../${outDir}/xterm.js`],
standalone: 'Terminal',
cache: {},
packageCache: {}
};
let bundleStream = browserify(browserifyOptions)
.bundle()
.pipe(source('xterm.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true, sourceRoot: '..'}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(buildDir));
// Copy all add-ons from ${outDir}/ to buildDir
let copyAddons = gulp.src(`${outDir}/addons/**/*`).pipe(gulp.dest(`${buildDir}/addons`));
// Copy stylesheets from ${outDir}/ to ${buildDir}/
let copyStylesheets = gulp.src(`${outDir}/**/*.css`).pipe(gulp.dest(buildDir));
return merge(bundleStream, copyAddons, copyStylesheets);
});
gulp.task('instrument-test', function () {
return gulp.src([`${outDir}/**/*.js`])
// Covering files
.pipe(istanbul())
// Force `require` to return covered files
.pipe(istanbul.hookRequire());
});
gulp.task('mocha', ['instrument-test'], function () {
return gulp.src([`${outDir}/*test.js`, `${outDir}/**/*test.js`], {read: false})
.pipe(mocha())
.once('error', () => process.exit(1))
.pipe(istanbul.writeReports());
});
/**
* Use `sorcery` to resolve the source map chain and point back to the TypeScript files.
* (Without this task the source maps produced for the JavaScript bundle points into the
* compiled JavaScript files in ${outDir}/).
*/
gulp.task('sorcery', ['browserify'], function () {
var chain = sorcery.loadSync(`${buildDir}/xterm.js`);
chain.apply();
chain.writeSync();
});
/**
* Submit coverage results to coveralls.io
*/
gulp.task('coveralls', function () {
gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
gulp.task('build', ['sorcery']);
gulp.task('test', ['mocha']);
gulp.task('default', ['build']);
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

+51 -9
View File
@@ -1,37 +1,79 @@
{
"name": "xterm",
"version": "2.2.1",
"description": "Full xterm terminal, in your browser",
"version": "2.6.0",
"ignore": [
"demo",
"test",
".gitignore"
],
"main": "dist/xterm.js",
"main": "lib/xterm.js",
"repository": "https://github.com/sourcelair/xterm.js",
"license": "MIT",
"files": [
"*.js",
"*.json",
"dist/*.css",
"dist/**/*.css",
"dist/*.js",
"dist/*.js.map",
"dist/**/*.js",
"dist/**/*.js.map",
"lib/*.css",
"lib/**/*.css",
"lib/*.js",
"lib/*.js.map",
"lib/**/*.js",
"lib/**/*.js.map",
"src/*.css",
"src/**/*.css",
"src/*.js",
"src/*.js.map",
"src/*.ts",
"src/**/*.js",
"src/**/*.js.map",
"src/**/*.ts"
],
"devDependencies": {
"@types/chai": "^3.4.34",
"@types/jsdom": "^2.0.30",
"@types/mocha": "^2.2.33",
"@types/node": "^6.0.41",
"browserify": "^13.1.0",
"chai": "3.5.0",
"docdash": "0.4.0",
"exorcist": "^0.4.0",
"express": "4.13.4",
"express-ws": "2.0.0-rc.1",
"fs-extra": "^1.0.0",
"glob": "^7.0.5",
"gulp": "^3.9.1",
"gulp-cli": "^1.2.2",
"gulp-coveralls": "^0.1.4",
"gulp-istanbul": "^1.1.1",
"gulp-mocha": "^3.0.1",
"gulp-sourcemaps": "1.9.1",
"gulp-typescript": "^3.1.3",
"jsdoc": "3.4.3",
"mocha": "2.5.3",
"jsdom": "^9.11.0",
"merge-stream": "^1.0.1",
"node-pty": "^0.4.1",
"nodemon": "1.10.2",
"pty.js": "0.3.1",
"sleep": "^3.0.1",
"sorcery": "^0.10.0",
"typescript": "^2.0.3"
"tslint": "^4.0.2",
"typescript": "~2.2.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"scripts": {
"start": "nodemon --watch src --watch addons --watch demo --exec bash -c './bin/build && node demo/app'",
"test": "./bin/build && mocha --recursive ./out",
"prestart": "npm run build",
"start": "node demo/app",
"dev": "nodemon -e js,ts,css --watch src --watch demo --exec npm start",
"lint": "tslint src/*.ts src/**/*.ts",
"test": "gulp test",
"build:docs": "jsdoc -c jsdoc.json",
"build": "./bin/build"
"build": "gulp build",
"prepublish": "npm run build",
"coveralls": "gulp coveralls"
}
}
+252
View File
@@ -0,0 +1,252 @@
/**
* @license MIT
*/
/**
* The character sets supported by the terminal. These enable several languages
* to be represented within the terminal with only 8-bit encoding. See ISO 2022
* for a discussion on character sets. Only VT100 character sets are supported.
*/
export const CHARSETS: {[key: string]: {[key: string]: string}} = {};
/**
* The default character set, US.
*/
export const DEFAULT_CHARSET = CHARSETS['B'];
/**
* DEC Special Character and Line Drawing Set.
* Reference: http://vt100.net/docs/vt102-ug/table5-13.html
* A lot of curses apps use this if they see TERM=xterm.
* testing: echo -e '\e(0a\e(B'
* The xterm output sometimes seems to conflict with the
* reference above. xterm seems in line with the reference
* when running vttest however.
* The table below now uses xterm's output from vttest.
*/
CHARSETS['0'] = {
'`': '\u25c6', // '◆'
'a': '\u2592', // '▒'
'b': '\u0009', // '\t'
'c': '\u000c', // '\f'
'd': '\u000d', // '\r'
'e': '\u000a', // '\n'
'f': '\u00b0', // '°'
'g': '\u00b1', // '±'
'h': '\u2424', // '\u2424' (NL)
'i': '\u000b', // '\v'
'j': '\u2518', // '┘'
'k': '\u2510', // '┐'
'l': '\u250c', // '┌'
'm': '\u2514', // '└'
'n': '\u253c', // '┼'
'o': '\u23ba', // '⎺'
'p': '\u23bb', // '⎻'
'q': '\u2500', // '─'
'r': '\u23bc', // '⎼'
's': '\u23bd', // '⎽'
't': '\u251c', // '├'
'u': '\u2524', // '┤'
'v': '\u2534', // '┴'
'w': '\u252c', // '┬'
'x': '\u2502', // '│'
'y': '\u2264', // '≤'
'z': '\u2265', // '≥'
'{': '\u03c0', // 'π'
'|': '\u2260', // '≠'
'}': '\u00a3', // '£'
'~': '\u00b7' // '·'
};
/**
* British character set
* ESC (A
* Reference: http://vt100.net/docs/vt220-rm/table2-5.html
*/
CHARSETS['A'] = {
'#': '£'
};
/**
* United States character set
* ESC (B
*/
CHARSETS['B'] = null;
/**
* Dutch character set
* ESC (4
* Reference: http://vt100.net/docs/vt220-rm/table2-6.html
*/
CHARSETS['4'] = {
'#': '£',
'@': '¾',
'[': 'ij',
'\\': '½',
']': '|',
'{': '¨',
'|': 'f',
'}': '¼',
'~': '´'
};
/**
* Finnish character set
* ESC (C or ESC (5
* Reference: http://vt100.net/docs/vt220-rm/table2-7.html
*/
CHARSETS['C'] =
CHARSETS['5'] = {
'[': 'Ä',
'\\': 'Ö',
']': 'Å',
'^': 'Ü',
'`': 'é',
'{': 'ä',
'|': 'ö',
'}': 'å',
'~': 'ü'
};
/**
* French character set
* ESC (R
* Reference: http://vt100.net/docs/vt220-rm/table2-8.html
*/
CHARSETS['R'] = {
'#': '£',
'@': 'à',
'[': '°',
'\\': 'ç',
']': '§',
'{': 'é',
'|': 'ù',
'}': 'è',
'~': '¨'
};
/**
* French Canadian character set
* ESC (Q
* Reference: http://vt100.net/docs/vt220-rm/table2-9.html
*/
CHARSETS['Q'] = {
'@': 'à',
'[': 'â',
'\\': 'ç',
']': 'ê',
'^': 'î',
'`': 'ô',
'{': 'é',
'|': 'ù',
'}': 'è',
'~': 'û'
};
/**
* German character set
* ESC (K
* Reference: http://vt100.net/docs/vt220-rm/table2-10.html
*/
CHARSETS['K'] = {
'@': '§',
'[': 'Ä',
'\\': 'Ö',
']': 'Ü',
'{': 'ä',
'|': 'ö',
'}': 'ü',
'~': 'ß'
};
/**
* Italian character set
* ESC (Y
* Reference: http://vt100.net/docs/vt220-rm/table2-11.html
*/
CHARSETS['Y'] = {
'#': '£',
'@': '§',
'[': '°',
'\\': 'ç',
']': 'é',
'`': 'ù',
'{': 'à',
'|': 'ò',
'}': 'è',
'~': 'ì'
};
/**
* Norwegian/Danish character set
* ESC (E or ESC (6
* Reference: http://vt100.net/docs/vt220-rm/table2-12.html
*/
CHARSETS['E'] =
CHARSETS['6'] = {
'@': 'Ä',
'[': 'Æ',
'\\': 'Ø',
']': 'Å',
'^': 'Ü',
'`': 'ä',
'{': 'æ',
'|': 'ø',
'}': 'å',
'~': 'ü'
};
/**
* Spanish character set
* ESC (Z
* Reference: http://vt100.net/docs/vt220-rm/table2-13.html
*/
CHARSETS['Z'] = {
'#': '£',
'@': '§',
'[': '¡',
'\\': 'Ñ',
']': '¿',
'{': '°',
'|': 'ñ',
'}': 'ç'
};
/**
* Swedish character set
* ESC (H or ESC (7
* Reference: http://vt100.net/docs/vt220-rm/table2-14.html
*/
CHARSETS['H'] =
CHARSETS['7'] = {
'@': 'É',
'[': 'Ä',
'\\': 'Ö',
']': 'Å',
'^': 'Ü',
'`': 'é',
'{': 'ä',
'|': 'ö',
'}': 'å',
'~': 'ü'
};
/**
* Swiss character set
* ESC (=
* Reference: http://vt100.net/docs/vt220-rm/table2-15.html
*/
CHARSETS['='] = {
'#': 'ù',
'@': 'à',
'[': 'é',
'\\': 'ç',
']': 'ê',
'^': 'î',
'_': 'è',
'`': 'ô',
'{': 'ä',
'|': 'ö',
'}': 'ü',
'~': 'û'
};
+7 -7
View File
@@ -2,11 +2,11 @@ import { assert } from 'chai';
import { CompositionHelper } from './CompositionHelper';
describe('CompositionHelper', () => {
var terminal;
var compositionHelper;
var compositionView;
var textarea;
var handledText;
let terminal;
let compositionHelper;
let compositionView;
let textarea;
let handledText;
beforeEach(() => {
compositionView = {
@@ -125,7 +125,7 @@ describe('CompositionHelper', () => {
compositionHelper.compositionend();
compositionHelper.compositionstart();
compositionHelper.compositionupdate({ data: '아' });
textarea.value = '아아'
textarea.value = '아아';
setTimeout(() => { // wait for any textarea updates
compositionHelper.compositionend();
setTimeout(() => { // wait for any textarea updates
@@ -187,7 +187,7 @@ describe('CompositionHelper', () => {
}, 0);
}, 0);
}, 0);
})
});
it('Should insert multi-character compositions that are converted to other characters with different lengths', function (done) {
// First character 'い'
+25 -28
View File
@@ -24,7 +24,7 @@ export class CompositionHelper {
/**
* The position within the input textarea's value of the current composition.
*/
private compositionPosition: IPosition;;
private compositionPosition: IPosition;
/**
* Whether a composition is in the process of being sent, setting this to false will cancel any
@@ -65,9 +65,8 @@ export class CompositionHelper {
public compositionupdate(ev: CompositionEvent) {
this.compositionView.textContent = ev.data;
this.updateCompositionElements();
var self = this;
setTimeout(function() {
self.compositionPosition.end = self.textarea.value.length;
setTimeout(() => {
this.compositionPosition.end = this.textarea.value.length;
}, 0);
}
@@ -125,15 +124,15 @@ export class CompositionHelper {
if (!waitForPropogation) {
// Cancel any delayed composition send requests and send the input immediately.
this.isSendingComposition = false;
var input = this.textarea.value.substring(this.compositionPosition.start, this.compositionPosition.end);
const input = this.textarea.value.substring(this.compositionPosition.start, this.compositionPosition.end);
this.terminal.handler(input);
} else {
// Make a deep copy of the composition position here as a new compositionstart event may
// fire before the setTimeout executes.
var currentCompositionPosition = {
const currentCompositionPosition = {
start: this.compositionPosition.start,
end: this.compositionPosition.end,
}
};
// Since composition* events happen before the changes take place in the textarea on most
// browsers, use a setTimeout with 0ms time to allow the native compositionend event to
@@ -143,23 +142,22 @@ export class CompositionHelper {
// - The last compositionupdate event's data property does not always accurately describe
// the character, a counter example being Korean where an ending consonsant can move to
// the following character if the following input is a vowel.
var self = this;
this.isSendingComposition = true;
setTimeout(function () {
setTimeout(() => {
// Ensure that the input has not already been sent
if (self.isSendingComposition) {
self.isSendingComposition = false;
var input;
if (self.isComposing) {
if (this.isSendingComposition) {
this.isSendingComposition = false;
let input;
if (this.isComposing) {
// Use the end position to get the string if a new composition has started.
input = self.textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
input = this.textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
} else {
// Don't use the end position here in order to pick up any characters after the
// composition has finished, for example when typing a non-composition character
// (eg. 2) after a composition character.
input = self.textarea.value.substring(currentCompositionPosition.start);
input = this.textarea.value.substring(currentCompositionPosition.start);
}
self.terminal.handler(input);
this.terminal.handler(input);
}
}, 0);
}
@@ -172,15 +170,14 @@ export class CompositionHelper {
* IME is active.
*/
private handleAnyTextareaChanges() {
var oldValue = this.textarea.value;
var self = this;
setTimeout(function() {
const oldValue = this.textarea.value;
setTimeout(() => {
// Ignore if a composition has started since the timeout
if (!self.isComposing) {
var newValue = self.textarea.value;
var diff = newValue.replace(oldValue, '');
if (!this.isComposing) {
const newValue = this.textarea.value;
const diff = newValue.replace(oldValue, '');
if (diff.length > 0) {
self.terminal.handler(diff);
this.terminal.handler(diff);
}
}
}, 0);
@@ -196,12 +193,12 @@ export class CompositionHelper {
if (!this.isComposing) {
return;
}
var cursor = <HTMLElement>this.terminal.element.querySelector('.terminal-cursor');
const cursor = <HTMLElement>this.terminal.element.querySelector('.terminal-cursor');
if (cursor) {
// Take .xterm-rows offsetTop into account as well in case it's positioned absolutely within
// the .xterm element.
var xtermRows = <HTMLElement>this.terminal.element.querySelector('.xterm-rows');
var cursorTop = xtermRows.offsetTop + cursor.offsetTop;
const xtermRows = <HTMLElement>this.terminal.element.querySelector('.xterm-rows');
const cursorTop = xtermRows.offsetTop + cursor.offsetTop;
this.compositionView.style.left = cursor.offsetLeft + 'px';
this.compositionView.style.top = cursorTop + 'px';
@@ -209,7 +206,7 @@ export class CompositionHelper {
this.compositionView.style.lineHeight = cursor.offsetHeight + 'px';
// Sync the textarea to the exact position of the composition view so the IME knows where the
// text is.
var compositionViewBounds = this.compositionView.getBoundingClientRect();
const compositionViewBounds = this.compositionView.getBoundingClientRect();
this.textarea.style.left = cursor.offsetLeft + 'px';
this.textarea.style.top = cursorTop + 'px';
this.textarea.style.width = compositionViewBounds.width + 'px';
@@ -217,7 +214,7 @@ export class CompositionHelper {
this.textarea.style.lineHeight = compositionViewBounds.height + 'px';
}
if (!dontRecurse) {
setTimeout(this.updateCompositionElements.bind(this, true), 0);
setTimeout(() => this.updateCompositionElements(true), 0);
}
};
+78
View File
@@ -0,0 +1,78 @@
/**
* @license MIT
*/
/**
* C0 control codes
* See = https://en.wikipedia.org/wiki/C0_and_C1_control_codes
*/
export namespace C0 {
/** Null (Caret = ^@, C = \0) */
export const NUL = '\x00';
/** Start of Heading (Caret = ^A) */
export const SOH = '\x01';
/** Start of Text (Caret = ^B) */
export const STX = '\x02';
/** End of Text (Caret = ^C) */
export const ETX = '\x03';
/** End of Transmission (Caret = ^D) */
export const EOT = '\x04';
/** Enquiry (Caret = ^E) */
export const ENQ = '\x05';
/** Acknowledge (Caret = ^F) */
export const ACK = '\x06';
/** Bell (Caret = ^G, C = \a) */
export const BEL = '\x07';
/** Backspace (Caret = ^H, C = \b) */
export const BS = '\x08';
/** Character Tabulation, Horizontal Tabulation (Caret = ^I, C = \t) */
export const HT = '\x09';
/** Line Feed (Caret = ^J, C = \n) */
export const LF = '\x0a';
/** Line Tabulation, Vertical Tabulation (Caret = ^K, C = \v) */
export const VT = '\x0b';
/** Form Feed (Caret = ^L, C = \f) */
export const FF = '\x0c';
/** Carriage Return (Caret = ^M, C = \r) */
export const CR = '\x0d';
/** Shift Out (Caret = ^N) */
export const SO = '\x0e';
/** Shift In (Caret = ^O) */
export const SI = '\x0f';
/** Data Link Escape (Caret = ^P) */
export const DLE = '\x10';
/** Device Control One (XON) (Caret = ^Q) */
export const DC1 = '\x11';
/** Device Control Two (Caret = ^R) */
export const DC2 = '\x12';
/** Device Control Three (XOFF) (Caret = ^S) */
export const DC3 = '\x13';
/** Device Control Four (Caret = ^T) */
export const DC4 = '\x14';
/** Negative Acknowledge (Caret = ^U) */
export const NAK = '\x15';
/** Synchronous Idle (Caret = ^V) */
export const SYN = '\x16';
/** End of Transmission Block (Caret = ^W) */
export const ETB = '\x17';
/** Cancel (Caret = ^X) */
export const CAN = '\x18';
/** End of Medium (Caret = ^Y) */
export const EM = '\x19';
/** Substitute (Caret = ^Z) */
export const SUB = '\x1a';
/** Escape (Caret = ^[, C = \e) */
export const ESC = '\x1b';
/** File Separator (Caret = ^\) */
export const FS = '\x1c';
/** Group Separator (Caret = ^]) */
export const GS = '\x1d';
/** Record Separator (Caret = ^^) */
export const RS = '\x1e';
/** Unit Separator (Caret = ^_) */
export const US = '\x1f';
/** Space */
export const SP = '\x20';
/** Delete (Caret = ^?) */
export const DEL = '\x7f';
};
-64
View File
@@ -1,64 +0,0 @@
/**
* @license MIT
*/
function EventEmitter() {
this._events = this._events || {};
}
EventEmitter.prototype.addListener = function(type, listener) {
this._events[type] = this._events[type] || [];
this._events[type].push(listener);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.removeListener = function(type, listener) {
if (!this._events[type]) return;
var obj = this._events[type]
, i = obj.length;
while (i--) {
if (obj[i] === listener || obj[i].listener === listener) {
obj.splice(i, 1);
return;
}
}
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners = function(type) {
if (this._events[type]) delete this._events[type];
};
EventEmitter.prototype.once = function(type, listener) {
var self = this;
function on() {
var args = Array.prototype.slice.call(arguments);
this.removeListener(type, on);
return listener.apply(this, args);
}
on.listener = listener;
return this.on(type, on);
};
EventEmitter.prototype.emit = function(type) {
if (!this._events[type]) return;
var args = Array.prototype.slice.call(arguments, 1)
, obj = this._events[type]
, l = obj.length
, i = 0;
for (; i < l; i++) {
obj[i].apply(this, args);
}
};
EventEmitter.prototype.listeners = function(type) {
return this._events[type] = this._events[type] || [];
};
export { EventEmitter };
+84
View File
@@ -0,0 +1,84 @@
import { assert } from 'chai';
import { EventEmitter } from './EventEmitter';
describe('EventEmitter', () => {
let eventEmitter: EventEmitter;
beforeEach(() => {
eventEmitter = new EventEmitter();
});
describe('once', () => {
it('should trigger the listener only once', () => {
let count = 0;
const listener = () => count++;
eventEmitter.once('test', listener);
eventEmitter.emit('test');
assert.equal(count, 1);
eventEmitter.emit('test');
assert.equal(count, 1);
});
});
describe('emit', () => {
it('should emit events to listeners', () => {
let count1 = 0;
let count2 = 0;
const listener1 = () => count1++;
const listener2 = () => count2++;
eventEmitter.on('test', listener1);
eventEmitter.on('test', listener2);
eventEmitter.emit('test');
assert.equal(count1, 1);
assert.equal(count2, 1);
eventEmitter.emit('test');
assert.equal(count1, 2);
assert.equal(count2, 2);
});
it('should manage multiple listener types', () => {
let count1 = 0;
let count2 = 0;
const listener1 = () => count1++;
const listener2 = () => count2++;
eventEmitter.on('test', listener1);
eventEmitter.on('foo', listener2);
eventEmitter.emit('test');
assert.equal(count1, 1);
assert.equal(count2, 0);
eventEmitter.emit('foo');
assert.equal(count1, 1);
assert.equal(count2, 1);
});
});
describe('listeners', () => {
it('should return listeners for the type requested', () => {
assert.equal(eventEmitter.listeners('test').length, 0);
const listener = () => {};
eventEmitter.on('test', listener);
assert.deepEqual(eventEmitter.listeners('test'), [listener]);
});
});
describe('off', () => {
it('should remove the specific listener', () => {
const listener1 = () => {};
const listener2 = () => {};
eventEmitter.on('foo', listener1);
eventEmitter.on('foo', listener2);
assert.equal(eventEmitter.listeners('foo').length, 2);
eventEmitter.off('foo', listener1);
assert.deepEqual(eventEmitter.listeners('foo'), [listener2]);
});
});
describe('removeAllListeners', () => {
it('should clear all listeners', () => {
eventEmitter.on('foo', () => {});
assert.equal(eventEmitter.listeners('foo').length, 1);
eventEmitter.removeAllListeners('foo');
assert.equal(eventEmitter.listeners('foo').length, 0);
});
});
});
+72
View File
@@ -0,0 +1,72 @@
/**
* @license MIT
*/
interface ListenerType {
(): void;
listener?: () => void;
};
export class EventEmitter {
private _events: {[type: string]: ListenerType[]};
constructor() {
// Restore the previous events if available, this will happen if the
// constructor is called multiple times on the same object (terminal reset).
this._events = this._events || {};
}
public on(type, listener): void {
this._events[type] = this._events[type] || [];
this._events[type].push(listener);
}
public off(type, listener): void {
if (!this._events[type]) {
return;
}
let obj = this._events[type];
let i = obj.length;
while (i--) {
if (obj[i] === listener || obj[i].listener === listener) {
obj.splice(i, 1);
return;
}
}
}
public removeAllListeners(type): void {
if (this._events[type]) {
delete this._events[type];
}
}
public once(type, listener): any {
function on() {
let args = Array.prototype.slice.call(arguments);
this.off(type, on);
return listener.apply(this, args);
}
(<any>on).listener = listener;
return this.on(type, on);
}
public emit(type): void {
if (!this._events[type]) {
return;
}
let args = Array.prototype.slice.call(arguments, 1);
let obj = this._events[type];
for (let i = 0; i < obj.length; i++) {
obj[i].apply(this, args);
}
}
public listeners(type): ListenerType[] {
return this._events[type] || [];
}
}
+49
View File
@@ -0,0 +1,49 @@
import { assert } from 'chai';
import { InputHandler } from './InputHandler';
describe('InputHandler', () => {
describe('setCursorStyle', () => {
it('should call Terminal.setOption with correct params', () => {
let options = {};
let terminal = {
setOption: (option, value) => options[option] = value
};
let inputHandler = new InputHandler(terminal);
inputHandler.setCursorStyle([0]);
assert.equal(options['cursorStyle'], 'block');
assert.equal(options['cursorBlink'], true);
options = {};
inputHandler.setCursorStyle([1]);
assert.equal(options['cursorStyle'], 'block');
assert.equal(options['cursorBlink'], true);
options = {};
inputHandler.setCursorStyle([2]);
assert.equal(options['cursorStyle'], 'block');
assert.equal(options['cursorBlink'], false);
options = {};
inputHandler.setCursorStyle([3]);
assert.equal(options['cursorStyle'], 'underline');
assert.equal(options['cursorBlink'], true);
options = {};
inputHandler.setCursorStyle([4]);
assert.equal(options['cursorStyle'], 'underline');
assert.equal(options['cursorBlink'], false);
options = {};
inputHandler.setCursorStyle([5]);
assert.equal(options['cursorStyle'], 'bar');
assert.equal(options['cursorBlink'], true);
options = {};
inputHandler.setCursorStyle([6]);
assert.equal(options['cursorStyle'], 'bar');
assert.equal(options['cursorBlink'], false);
});
});
});
+1584
View File
File diff suppressed because it is too large Load Diff
+113 -1
View File
@@ -2,6 +2,9 @@
* @license MIT
*/
import { LinkMatcherOptions } from './Interfaces';
import { LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
export interface IBrowser {
isNode: boolean;
userAgent: string;
@@ -18,10 +21,19 @@ export interface ITerminal {
element: HTMLElement;
rowContainer: HTMLElement;
textarea: HTMLTextAreaElement;
ybase: number;
ydisp: number;
lines: string[];
lines: ICircularList<string>;
rows: number;
cols: number;
browser: IBrowser;
writeBuffer: string[];
children: HTMLElement[];
cursorHidden: boolean;
cursorState: number;
x: number;
y: number;
defAttr: number;
/**
* Emit the 'data' event and populate the given data.
@@ -31,4 +43,104 @@ export interface ITerminal {
on(event: string, callback: () => void);
scrollDisp(disp: number, suppressScrollEvent: boolean);
cancel(ev: Event, force?: boolean);
log(text: string): void;
emit(event: string, data: any);
}
export interface ICharMeasure {
width: number;
height: number;
measure(): void;
}
export interface ILinkifier {
linkifyRow(rowIndex: number): void;
attachHypertextLinkHandler(handler: LinkMatcherHandler): void;
registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?: LinkMatcherOptions): number;
deregisterLinkMatcher(matcherId: number): boolean;
}
interface ICircularList<T> {
length: number;
maxLength: number;
forEach(callbackfn: (value: T, index: number, array: T[]) => void): void;
get(index: number): T;
set(index: number, value: T): void;
push(value: T): void;
pop(): T;
splice(start: number, deleteCount: number, ...items: T[]): void;
trimStart(count: number): void;
shiftElements(start: number, count: number, offset: number): void;
}
export interface LinkMatcherOptions {
/**
* The index of the link from the regex.match(text) call. This defaults to 0
* (for regular expressions without capture groups).
*/
matchIndex?: number;
/**
* A callback that validates an individual link, returning true if valid and
* false if invalid.
*/
validationCallback?: LinkMatcherValidationCallback;
/**
* The priority of the link matcher, this defines the order in which the link
* matcher is evaluated relative to others, from highest to lowest. The
* default value is 0.
*/
priority?: number;
}
/**
* Handles actions generated by the parser.
*/
export interface IInputHandler {
addChar(char: string, code: number): void;
/** C0 BEL */ bell(): void;
/** C0 LF */ lineFeed(): void;
/** C0 CR */ carriageReturn(): void;
/** C0 BS */ backspace(): void;
/** C0 HT */ tab(): void;
/** C0 SO */ shiftOut(): void;
/** C0 SI */ shiftIn(): void;
/** CSI @ */ insertChars(params?: number[]): void;
/** CSI A */ cursorUp(params?: number[]): void;
/** CSI B */ cursorDown(params?: number[]): void;
/** CSI C */ cursorForward(params?: number[]): void;
/** CSI D */ cursorBackward(params?: number[]): void;
/** CSI E */ cursorNextLine(params?: number[]): void;
/** CSI F */ cursorPrecedingLine(params?: number[]): void;
/** CSI G */ cursorCharAbsolute(params?: number[]): void;
/** CSI H */ cursorPosition(params?: number[]): void;
/** CSI I */ cursorForwardTab(params?: number[]): void;
/** CSI J */ eraseInDisplay(params?: number[]): void;
/** CSI K */ eraseInLine(params?: number[]): void;
/** CSI L */ insertLines(params?: number[]): void;
/** CSI M */ deleteLines(params?: number[]): void;
/** CSI P */ deleteChars(params?: number[]): void;
/** CSI S */ scrollUp(params?: number[]): void;
/** CSI T */ scrollDown(params?: number[]): void;
/** CSI X */ eraseChars(params?: number[]): void;
/** CSI Z */ cursorBackwardTab(params?: number[]): void;
/** CSI ` */ charPosAbsolute(params?: number[]): void;
/** CSI a */ HPositionRelative(params?: number[]): void;
/** CSI b */ repeatPrecedingCharacter(params?: number[]): void;
/** CSI c */ sendDeviceAttributes(params?: number[]): void;
/** CSI d */ linePosAbsolute(params?: number[]): void;
/** CSI e */ VPositionRelative(params?: number[]): void;
/** CSI f */ HVPosition(params?: number[]): void;
/** CSI g */ tabClear(params?: number[]): void;
/** CSI h */ setMode(params?: number[]): void;
/** CSI l */ resetMode(params?: number[]): void;
/** CSI m */ charAttributes(params?: number[]): void;
/** CSI n */ deviceStatus(params?: number[]): void;
/** CSI p */ softReset(params?: number[]): void;
/** CSI q */ setCursorStyle(params?: number[]): void;
/** CSI r */ setScrollRegion(params?: number[]): void;
/** CSI s */ saveCursor(params?: number[]): void;
/** CSI u */ restoreCursor(params?: number[]): void;
}
+187
View File
@@ -0,0 +1,187 @@
/**
* @license MIT
*/
import jsdom = require('jsdom');
import { assert } from 'chai';
import { ITerminal, ILinkifier } from './Interfaces';
import { Linkifier } from './Linkifier';
import { LinkMatcher } from './Types';
class TestLinkifier extends Linkifier {
constructor() {
Linkifier.TIME_BEFORE_LINKIFY = 0;
super();
}
public get linkMatchers(): LinkMatcher[] { return this._linkMatchers; }
}
describe('Linkifier', () => {
let window: Window;
let document: Document;
let container: HTMLElement;
let rows: HTMLElement[];
let linkifier: TestLinkifier;
beforeEach(done => {
jsdom.env('', (err, w) => {
window = w;
document = window.document;
linkifier = new TestLinkifier();
done();
});
});
function addRow(html: string) {
const element = document.createElement('div');
element.innerHTML = html;
container.appendChild(element);
rows.push(element);
}
describe('before attachToDom', () => {
it('should allow link matcher registration', done => {
assert.doesNotThrow(() => {
const linkMatcherId = linkifier.registerLinkMatcher(/foo/, () => {});
assert.isTrue(linkifier.deregisterLinkMatcher(linkMatcherId));
done();
});
});
});
describe('after attachToDom', () => {
beforeEach(() => {
rows = [];
linkifier.attachToDom(document, rows);
container = document.createElement('div');
document.body.appendChild(container);
});
function clickElement(element: Node) {
const event = document.createEvent('MouseEvent');
event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
element.dispatchEvent(event);
}
function assertLinkifiesEntireRow(uri: string, done: MochaDone) {
addRow(uri);
linkifier.linkifyRow(0);
setTimeout(() => {
assert.equal((<HTMLElement>rows[0].firstChild).tagName, 'A');
assert.equal((<HTMLElement>rows[0].firstChild).textContent, uri);
done();
}, 0);
}
describe('http links', () => {
function assertLinkifiesEntireRow(uri: string, done: MochaDone) {
addRow(uri);
linkifier.linkifyRow(0);
setTimeout(() => {
assert.equal((<HTMLElement>rows[0].firstChild).tagName, 'A');
assert.equal((<HTMLElement>rows[0].firstChild).textContent, uri);
done();
}, 0);
}
it('should allow ~ character in URI path', done => assertLinkifiesEntireRow('http://foo.com/a~b#c~d?e~f', done));
});
describe('link matcher', () => {
function assertLinkifiesRow(rowText: string, linkMatcherRegex: RegExp, expectedHtml: string, done: MochaDone) {
addRow(rowText);
linkifier.registerLinkMatcher(linkMatcherRegex, () => {});
linkifier.linkifyRow(0);
// Allow linkify to happen
setTimeout(() => {
assert.equal(rows[0].innerHTML, expectedHtml);
done();
}, 0);
}
it('should match a single link', done => {
assertLinkifiesRow('foo', /foo/, '<a>foo</a>', done);
});
it('should match a single link at the start of a text node', done => {
assertLinkifiesRow('foo bar', /foo/, '<a>foo</a> bar', done);
});
it('should match a single link in the middle of a text node', done => {
assertLinkifiesRow('foo bar baz', /bar/, 'foo <a>bar</a> baz', done);
});
it('should match a single link at the end of a text node', done => {
assertLinkifiesRow('foo bar', /bar/, 'foo <a>bar</a>', done);
});
it('should match a link after a link at the start of a text node', done => {
assertLinkifiesRow('foo bar', /foo|bar/, '<a>foo</a> <a>bar</a>', done);
});
it('should match a link after a link in the middle of a text node', done => {
assertLinkifiesRow('foo bar baz', /bar|baz/, 'foo <a>bar</a> <a>baz</a>', done);
});
it('should match a link immediately after a link at the end of a text node', done => {
assertLinkifiesRow('<span>foo bar</span>baz', /bar|baz/, '<span>foo <a>bar</a></span><a>baz</a>', done);
});
});
describe('validationCallback', () => {
it('should enable link if true', done => {
addRow('test');
linkifier.registerLinkMatcher(/test/, () => done(), {
validationCallback: (url, element, cb) => {
cb(true);
assert.equal((<HTMLElement>rows[0].firstChild).tagName, 'A');
setTimeout(() => clickElement(rows[0].firstChild), 0);
}
});
linkifier.linkifyRow(0);
});
it('should disable link if false', done => {
addRow('test');
linkifier.registerLinkMatcher(/test/, () => assert.fail(), {
validationCallback: (url, element, cb) => {
cb(false);
assert.equal((<HTMLElement>rows[0].firstChild).tagName, 'A');
setTimeout(() => clickElement(rows[0].firstChild), 0);
}
});
linkifier.linkifyRow(0);
// Allow time for the click to be performed
setTimeout(() => done(), 10);
});
it('should trigger for multiple link matches on one row', done => {
addRow('test test');
let count = 0;
linkifier.registerLinkMatcher(/test/, () => assert.fail(), {
validationCallback: (url, element, cb) => {
count += 1;
if (count === 2) {
done();
}
cb(false);
}
});
linkifier.linkifyRow(0);
});
});
describe('priority', () => {
it('should order the list from highest priority to lowest #1', () => {
const aId = linkifier.registerLinkMatcher(/a/, () => {}, { priority: 1 });
const bId = linkifier.registerLinkMatcher(/b/, () => {}, { priority: -1 });
assert.deepEqual(linkifier.linkMatchers.map(lm => lm.id), [aId, 0, bId]);
});
it('should order the list from highest priority to lowest #2', () => {
const aId = linkifier.registerLinkMatcher(/a/, () => {}, { priority: -1 });
const bId = linkifier.registerLinkMatcher(/b/, () => {}, { priority: 1 });
assert.deepEqual(linkifier.linkMatchers.map(lm => lm.id), [bId, 0, aId]);
});
it('should order items of equal priority in the order they are added', () => {
const aId = linkifier.registerLinkMatcher(/a/, () => {}, { priority: 0 });
const bId = linkifier.registerLinkMatcher(/b/, () => {}, { priority: 0 });
assert.deepEqual(linkifier.linkMatchers.map(lm => lm.id), [0, aId, bId]);
});
});
});
});
+349
View File
@@ -0,0 +1,349 @@
/**
* @license MIT
*/
import { LinkMatcherOptions } from './Interfaces';
import { LinkMatcher, LinkMatcherHandler, LinkMatcherValidationCallback } from './Types';
const INVALID_LINK_CLASS = 'xterm-invalid-link';
const protocolClause = '(https?:\\/\\/)';
const domainCharacterSet = '[\\da-z\\.-]+';
const negatedDomainCharacterSet = '[^\\da-z\\.-]+';
const domainBodyClause = '(' + domainCharacterSet + ')';
const tldClause = '([a-z\\.]{2,6})';
const ipClause = '((\\d{1,3}\\.){3}\\d{1,3})';
const localHostClause = '(localhost)';
const portClause = '(:\\d{1,5})';
const hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + '|' + localHostClause + ')' + portClause + '?';
const pathClause = '(\\/[\\/\\w\\.\\-%~]*)*';
const queryStringHashFragmentCharacterSet = '[0-9\\w\\[\\]\\(\\)\\/\\?\\!#@$%&\'*+,:;~\\=\\.\\-]*';
const queryStringClause = '(\\?' + queryStringHashFragmentCharacterSet + ')?';
const hashFragmentClause = '(#' + queryStringHashFragmentCharacterSet + ')?';
const negatedPathCharacterSet = '[^\\/\\w\\.\\-%]+';
const bodyClause = hostClause + pathClause + queryStringClause + hashFragmentClause;
const start = '(?:^|' + negatedDomainCharacterSet + ')(';
const end = ')($|' + negatedPathCharacterSet + ')';
const strictUrlRegex = new RegExp(start + protocolClause + bodyClause + end);
/**
* The ID of the built in http(s) link matcher.
*/
const HYPERTEXT_LINK_MATCHER_ID = 0;
/**
* The Linkifier applies links to rows shortly after they have been refreshed.
*/
export class Linkifier {
/**
* The time to wait after a row is changed before it is linkified. This prevents
* the costly operation of searching every row multiple times, potentially a
* huge amount of times.
*/
protected static TIME_BEFORE_LINKIFY = 200;
protected _linkMatchers: LinkMatcher[];
private _document: Document;
private _rows: HTMLElement[];
private _rowTimeoutIds: number[];
private _nextLinkMatcherId = HYPERTEXT_LINK_MATCHER_ID;
constructor() {
this._rowTimeoutIds = [];
this._linkMatchers = [];
this.registerLinkMatcher(strictUrlRegex, null, { matchIndex: 1 });
}
/**
* Attaches the linkifier to the DOM, enabling linkification.
* @param document The document object.
* @param rows The array of rows to apply links to.
*/
public attachToDom(document: Document, rows: HTMLElement[]) {
this._document = document;
this._rows = rows;
}
/**
* Queues a row for linkification.
* @param {number} rowIndex The index of the row to linkify.
*/
public linkifyRow(rowIndex: number): void {
// Don't attempt linkify if not yet attached to DOM
if (!this._document) {
return;
}
const timeoutId = this._rowTimeoutIds[rowIndex];
if (timeoutId) {
clearTimeout(timeoutId);
}
this._rowTimeoutIds[rowIndex] = setTimeout(this._linkifyRow.bind(this, rowIndex), Linkifier.TIME_BEFORE_LINKIFY);
}
/**
* Attaches a handler for hypertext links, overriding default <a> behavior
* for standard http(s) links.
* @param {LinkHandler} handler The handler to use, this can be cleared with
* null.
*/
public setHypertextLinkHandler(handler: LinkMatcherHandler): void {
this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].handler = handler;
}
/**
* Attaches a validation callback for hypertext links.
* @param {LinkMatcherValidationCallback} callback The callback to use, this
* can be cleared with null.
*/
public setHypertextValidationCallback(callback: LinkMatcherValidationCallback): void {
this._linkMatchers[HYPERTEXT_LINK_MATCHER_ID].validationCallback = callback;
}
/**
* Registers a link matcher, allowing custom link patterns to be matched and
* handled.
* @param {RegExp} regex The regular expression to search for, specifically
* this searches the textContent of the rows. You will want to use \s to match
* a space ' ' character for example.
* @param {LinkHandler} handler The callback when the link is called.
* @param {LinkMatcherOptions} [options] Options for the link matcher.
* @return {number} The ID of the new matcher, this can be used to deregister.
*/
public registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options: LinkMatcherOptions = {}): number {
if (this._nextLinkMatcherId !== HYPERTEXT_LINK_MATCHER_ID && !handler) {
throw new Error('handler must be defined');
}
const matcher: LinkMatcher = {
id: this._nextLinkMatcherId++,
regex,
handler,
matchIndex: options.matchIndex,
validationCallback: options.validationCallback,
priority: options.priority || 0
};
this._addLinkMatcherToList(matcher);
return matcher.id;
}
/**
* Inserts a link matcher to the list in the correct position based on the
* priority of each link matcher. New link matchers of equal priority are
* considered after older link matchers.
* @param matcher The link matcher to be added.
*/
private _addLinkMatcherToList(matcher: LinkMatcher): void {
if (this._linkMatchers.length === 0) {
this._linkMatchers.push(matcher);
return;
}
for (let i = this._linkMatchers.length - 1; i >= 0; i--) {
if (matcher.priority <= this._linkMatchers[i].priority) {
this._linkMatchers.splice(i + 1, 0, matcher);
return;
}
}
this._linkMatchers.splice(0, 0, matcher);
}
/**
* Deregisters a link matcher if it has been registered.
* @param {number} matcherId The link matcher's ID (returned after register)
* @return {boolean} Whether a link matcher was found and deregistered.
*/
public deregisterLinkMatcher(matcherId: number): boolean {
// ID 0 is the hypertext link matcher which cannot be deregistered
for (let i = 1; i < this._linkMatchers.length; i++) {
if (this._linkMatchers[i].id === matcherId) {
this._linkMatchers.splice(i, 1);
return true;
}
}
return false;
}
/**
* Linkifies a row.
* @param {number} rowIndex The index of the row to linkify.
*/
private _linkifyRow(rowIndex: number): void {
const row = this._rows[rowIndex];
if (!row) {
return;
}
const text = row.textContent;
for (let i = 0; i < this._linkMatchers.length; i++) {
const matcher = this._linkMatchers[i];
const linkElements = this._doLinkifyRow(row, matcher);
if (linkElements.length > 0) {
// Fire validation callback
if (matcher.validationCallback) {
for (let j = 0; j < linkElements.length; j++) {
const element = linkElements[j];
matcher.validationCallback(element.textContent, element, isValid => {
if (!isValid) {
element.classList.add(INVALID_LINK_CLASS);
}
});
}
}
// Only allow a single LinkMatcher to trigger on any given row.
return;
}
}
}
/**
* Linkifies a row given a specific handler.
* @param {HTMLElement} row The row to linkify.
* @param {LinkMatcher} matcher The link matcher for this line.
* @return The link element if it was added, otherwise undefined.
*/
private _doLinkifyRow(row: HTMLElement, matcher: LinkMatcher): HTMLElement[] {
// Iterate over nodes as we want to consider text nodes
let result = [];
const isHttpLinkMatcher = matcher.id === HYPERTEXT_LINK_MATCHER_ID;
const nodes = row.childNodes;
// Find the first match
let match = row.textContent.match(matcher.regex);
if (!match || match.length === 0) {
return result;
}
let uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
// Set the next searches start index
let rowStartIndex = match.index + uri.length;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const searchIndex = node.textContent.indexOf(uri);
if (searchIndex >= 0) {
const linkElement = this._createAnchorElement(uri, matcher.handler, isHttpLinkMatcher);
if (node.textContent.length === uri.length) {
// Matches entire string
if (node.nodeType === 3 /*Node.TEXT_NODE*/) {
this._replaceNode(node, linkElement);
} else {
const element = (<HTMLElement>node);
if (element.nodeName === 'A') {
// This row has already been linkified
return result;
}
element.innerHTML = '';
element.appendChild(linkElement);
}
} else {
// Matches part of string
const nodesAdded = this._replaceNodeSubstringWithNode(node, linkElement, uri, searchIndex);
// No need to consider the new nodes
i += nodesAdded;
}
result.push(linkElement);
// Find the next match
match = row.textContent.substring(rowStartIndex).match(matcher.regex);
if (!match || match.length === 0) {
return result;
}
uri = match[typeof matcher.matchIndex !== 'number' ? 0 : matcher.matchIndex];
rowStartIndex += match.index + uri.length;
}
}
return result;
}
/**
* Creates a link anchor element.
* @param {string} uri The uri of the link.
* @return {HTMLAnchorElement} The link.
*/
private _createAnchorElement(uri: string, handler: LinkMatcherHandler, isHypertextLinkHandler: boolean): HTMLAnchorElement {
const element = this._document.createElement('a');
element.textContent = uri;
element.draggable = false;
if (isHypertextLinkHandler) {
element.href = uri;
// Force link on another tab so work is not lost
element.target = '_blank';
element.addEventListener('click', (event: MouseEvent) => {
if (handler) {
return handler(event, uri);
}
});
} else {
element.addEventListener('click', (event: MouseEvent) => {
// Don't execute the handler if the link is flagged as invalid
if (element.classList.contains(INVALID_LINK_CLASS)) {
return;
}
return handler(event, uri);
});
}
return element;
}
/**
* Replace a node with 1 or more other nodes.
* @param {Node} oldNode The node to replace.
* @param {Node[]} newNodes The new nodes to insert in order.
*/
private _replaceNode(oldNode: Node, ...newNodes: Node[]): void {
const parent = oldNode.parentNode;
for (let i = 0; i < newNodes.length; i++) {
parent.insertBefore(newNodes[i], oldNode);
}
parent.removeChild(oldNode);
}
/**
* Replace a substring within a node with a new node.
* @param {Node} targetNode The target node; either a text node or a <span>
* containing a single text node.
* @param {Node} newNode The new node to insert.
* @param {string} substring The substring to replace.
* @param {number} substringIndex The index of the substring within the string.
* @return The number of nodes to skip when searching for the next uri.
*/
private _replaceNodeSubstringWithNode(targetNode: Node, newNode: Node, substring: string, substringIndex: number): number {
let node = targetNode;
if (node.nodeType !== 3/*Node.TEXT_NODE*/) {
node = node.childNodes[0];
}
// The targetNode will be either a text node or a <span>. The text node
// (targetNode or its only-child) needs to be replaced with newNode plus new
// text nodes potentially on either side.
if (node.childNodes.length === 0 && node.nodeType !== 3/*Node.TEXT_NODE*/) {
throw new Error('targetNode must be a text node or only contain a single text node');
}
const fullText = node.textContent;
if (substringIndex === 0) {
// Replace with <newNode><textnode>
const rightText = fullText.substring(substring.length);
const rightTextNode = this._document.createTextNode(rightText);
this._replaceNode(node, newNode, rightTextNode);
return 0;
}
if (substringIndex === targetNode.textContent.length - substring.length) {
// Replace with <textnode><newNode>
const leftText = fullText.substring(0, substringIndex);
const leftTextNode = this._document.createTextNode(leftText);
this._replaceNode(node, leftTextNode, newNode);
return 0;
}
// Replace with <textnode><newNode><textnode>
const leftText = fullText.substring(0, substringIndex);
const leftTextNode = this._document.createTextNode(leftText);
const rightText = fullText.substring(substringIndex + substring.length);
const rightTextNode = this._document.createTextNode(rightText);
this._replaceNode(node, leftTextNode, newNode, rightTextNode);
return 1;
}
}
+636
View File
@@ -0,0 +1,636 @@
/**
* @license MIT
*/
import { C0 } from './EscapeSequences';
import { IInputHandler } from './Interfaces';
import { CHARSETS, DEFAULT_CHARSET } from './Charsets';
const normalStateHandler: {[key: string]: (parser: Parser, handler: IInputHandler) => void} = {};
normalStateHandler[C0.BEL] = (parser, handler) => handler.bell();
normalStateHandler[C0.LF] = (parser, handler) => handler.lineFeed();
normalStateHandler[C0.VT] = normalStateHandler[C0.LF];
normalStateHandler[C0.FF] = normalStateHandler[C0.LF];
normalStateHandler[C0.CR] = (parser, handler) => handler.carriageReturn();
normalStateHandler[C0.BS] = (parser, handler) => handler.backspace();
normalStateHandler[C0.HT] = (parser, handler) => handler.tab();
normalStateHandler[C0.SO] = (parser, handler) => handler.shiftOut();
normalStateHandler[C0.SI] = (parser, handler) => handler.shiftIn();
normalStateHandler[C0.ESC] = (parser, handler) => parser.setState(ParserState.ESCAPED);
// TODO: Remove terminal when parser owns params and currentParam
const escapedStateHandler: {[key: string]: (parser: Parser, terminal: any) => void} = {};
escapedStateHandler['['] = (parser, terminal) => {
// ESC [ Control Sequence Introducer (CSI is 0x9b)
terminal.params = [];
terminal.currentParam = 0;
parser.setState(ParserState.CSI_PARAM);
};
escapedStateHandler[']'] = (parser, terminal) => {
// ESC ] Operating System Command (OSC is 0x9d)
terminal.params = [];
terminal.currentParam = 0;
parser.setState(ParserState.OSC);
};
escapedStateHandler['P'] = (parser, terminal) => {
// ESC P Device Control String (DCS is 0x90)
terminal.params = [];
terminal.currentParam = 0;
parser.setState(ParserState.DCS);
};
escapedStateHandler['_'] = (parser, terminal) => {
// ESC _ Application Program Command ( APC is 0x9f).
parser.setState(ParserState.IGNORE);
};
escapedStateHandler['^'] = (parser, terminal) => {
// ESC ^ Privacy Message ( PM is 0x9e).
parser.setState(ParserState.IGNORE);
};
escapedStateHandler['c'] = (parser, terminal) => {
// ESC c Full Reset (RIS).
terminal.reset();
};
escapedStateHandler['E'] = (parser, terminal) => {
// ESC E Next Line ( NEL is 0x85).
terminal.x = 0;
terminal.index();
parser.setState(ParserState.NORMAL);
};
escapedStateHandler['D'] = (parser, terminal) => {
// ESC D Index ( IND is 0x84).
terminal.index();
parser.setState(ParserState.NORMAL);
};
escapedStateHandler['M'] = (parser, terminal) => {
// ESC M Reverse Index ( RI is 0x8d).
terminal.reverseIndex();
parser.setState(ParserState.NORMAL);
};
escapedStateHandler['%'] = (parser, terminal) => {
// ESC % Select default/utf-8 character set.
// @ = default, G = utf-8
terminal.setgLevel(0);
terminal.setgCharset(0, DEFAULT_CHARSET); // US (default)
parser.setState(ParserState.NORMAL);
parser.skipNextChar();
};
escapedStateHandler[C0.CAN] = (parser) => parser.setState(ParserState.NORMAL);
const csiParamStateHandler: {[key: string]: (parser: Parser) => void} = {};
csiParamStateHandler['?'] = (parser) => parser.setPrefix('?');
csiParamStateHandler['>'] = (parser) => parser.setPrefix('>');
csiParamStateHandler['!'] = (parser) => parser.setPrefix('!');
csiParamStateHandler['0'] = (parser) => parser.setParam(parser.getParam() * 10);
csiParamStateHandler['1'] = (parser) => parser.setParam(parser.getParam() * 10 + 1);
csiParamStateHandler['2'] = (parser) => parser.setParam(parser.getParam() * 10 + 2);
csiParamStateHandler['3'] = (parser) => parser.setParam(parser.getParam() * 10 + 3);
csiParamStateHandler['4'] = (parser) => parser.setParam(parser.getParam() * 10 + 4);
csiParamStateHandler['5'] = (parser) => parser.setParam(parser.getParam() * 10 + 5);
csiParamStateHandler['6'] = (parser) => parser.setParam(parser.getParam() * 10 + 6);
csiParamStateHandler['7'] = (parser) => parser.setParam(parser.getParam() * 10 + 7);
csiParamStateHandler['8'] = (parser) => parser.setParam(parser.getParam() * 10 + 8);
csiParamStateHandler['9'] = (parser) => parser.setParam(parser.getParam() * 10 + 9);
csiParamStateHandler['$'] = (parser) => parser.setPostfix('$');
csiParamStateHandler['"'] = (parser) => parser.setPostfix('"');
csiParamStateHandler[' '] = (parser) => parser.setPostfix(' ');
csiParamStateHandler['\''] = (parser) => parser.setPostfix('\'');
csiParamStateHandler[';'] = (parser) => parser.finalizeParam();
csiParamStateHandler[C0.CAN] = (parser) => parser.setState(ParserState.NORMAL);
const csiStateHandler: {[key: string]: (handler: IInputHandler, params: number[], prefix: string, postfix: string, parser: Parser) => void} = {};
csiStateHandler['@'] = (handler, params, prefix) => handler.insertChars(params);
csiStateHandler['A'] = (handler, params, prefix) => handler.cursorUp(params);
csiStateHandler['B'] = (handler, params, prefix) => handler.cursorDown(params);
csiStateHandler['C'] = (handler, params, prefix) => handler.cursorForward(params);
csiStateHandler['D'] = (handler, params, prefix) => handler.cursorBackward(params);
csiStateHandler['E'] = (handler, params, prefix) => handler.cursorNextLine(params);
csiStateHandler['F'] = (handler, params, prefix) => handler.cursorPrecedingLine(params);
csiStateHandler['G'] = (handler, params, prefix) => handler.cursorCharAbsolute(params);
csiStateHandler['H'] = (handler, params, prefix) => handler.cursorPosition(params);
csiStateHandler['I'] = (handler, params, prefix) => handler.cursorForwardTab(params);
csiStateHandler['J'] = (handler, params, prefix) => handler.eraseInDisplay(params);
csiStateHandler['K'] = (handler, params, prefix) => handler.eraseInLine(params);
csiStateHandler['L'] = (handler, params, prefix) => handler.insertLines(params);
csiStateHandler['M'] = (handler, params, prefix) => handler.deleteLines(params);
csiStateHandler['P'] = (handler, params, prefix) => handler.deleteChars(params);
csiStateHandler['S'] = (handler, params, prefix) => handler.scrollUp(params);
csiStateHandler['T'] = (handler, params, prefix) => {
if (params.length < 2 && !prefix) {
handler.scrollDown(params);
}
};
csiStateHandler['X'] = (handler, params, prefix) => handler.eraseChars(params);
csiStateHandler['Z'] = (handler, params, prefix) => handler.cursorBackwardTab(params);
csiStateHandler['`'] = (handler, params, prefix) => handler.charPosAbsolute(params);
csiStateHandler['a'] = (handler, params, prefix) => handler.HPositionRelative(params);
csiStateHandler['b'] = (handler, params, prefix) => handler.repeatPrecedingCharacter(params);
csiStateHandler['c'] = (handler, params, prefix) => handler.sendDeviceAttributes(params);
csiStateHandler['d'] = (handler, params, prefix) => handler.linePosAbsolute(params);
csiStateHandler['e'] = (handler, params, prefix) => handler.VPositionRelative(params);
csiStateHandler['f'] = (handler, params, prefix) => handler.HVPosition(params);
csiStateHandler['g'] = (handler, params, prefix) => handler.tabClear(params);
csiStateHandler['h'] = (handler, params, prefix) => handler.setMode(params);
csiStateHandler['l'] = (handler, params, prefix) => handler.resetMode(params);
csiStateHandler['m'] = (handler, params, prefix) => handler.charAttributes(params);
csiStateHandler['n'] = (handler, params, prefix) => handler.deviceStatus(params);
csiStateHandler['p'] = (handler, params, prefix) => {
switch (prefix) {
case '!': handler.softReset(params); break;
}
};
csiStateHandler['q'] = (handler, params, prefix, postfix) => {
if (postfix === ' ') {
handler.setCursorStyle(params);
}
};
csiStateHandler['r'] = (handler, params) => handler.setScrollRegion(params);
csiStateHandler['s'] = (handler, params) => handler.saveCursor(params);
csiStateHandler['u'] = (handler, params) => handler.restoreCursor(params);
csiStateHandler[C0.CAN] = (handler, params, prefix, postfix, parser) => parser.setState(ParserState.NORMAL);
enum ParserState {
NORMAL = 0,
ESCAPED = 1,
CSI_PARAM = 2,
CSI = 3,
OSC = 4,
CHARSET = 5,
DCS = 6,
IGNORE = 7
}
/**
* The terminal's parser, all input into the terminal goes through the parser
* which parses and defers the actual input handling the the IInputHandler
* specified in the constructor.
*/
export class Parser {
private _state: ParserState;
private _position: number;
// TODO: Remove terminal when handler can do everything
constructor(
private _inputHandler: IInputHandler,
private _terminal: any
) {
this._state = ParserState.NORMAL;
}
/**
* Parse and handle data.
*
* @param data The data to parse.
*/
public parse(data: string) {
let l = data.length, j, cs, ch, code, low;
this._position = 0;
// apply leftover surrogate high from last write
if (this._terminal.surrogate_high) {
data = this._terminal.surrogate_high + data;
this._terminal.surrogate_high = '';
}
for (; this._position < l; this._position++) {
ch = data[this._position];
// FIXME: higher chars than 0xa0 are not allowed in escape sequences
// --> maybe move to default
code = data.charCodeAt(this._position);
if (0xD800 <= code && code <= 0xDBFF) {
// we got a surrogate high
// get surrogate low (next 2 bytes)
low = data.charCodeAt(this._position + 1);
if (isNaN(low)) {
// end of data stream, save surrogate high
this._terminal.surrogate_high = ch;
continue;
}
code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
ch += data.charAt(this._position + 1);
}
// surrogate low - already handled above
if (0xDC00 <= code && code <= 0xDFFF)
continue;
switch (this._state) {
case ParserState.NORMAL:
if (ch in normalStateHandler) {
normalStateHandler[ch](this, this._inputHandler);
} else {
this._inputHandler.addChar(ch, code);
}
break;
case ParserState.ESCAPED:
if (ch in escapedStateHandler) {
escapedStateHandler[ch](this, this._terminal);
// Skip switch as it was just handled
break;
}
switch (ch) {
// ESC (,),*,+,-,. Designate G0-G2 Character Set.
case '(': // <-- this seems to get all the attention
case ')':
case '*':
case '+':
case '-':
case '.':
switch (ch) {
case '(':
this._terminal.gcharset = 0;
break;
case ')':
this._terminal.gcharset = 1;
break;
case '*':
this._terminal.gcharset = 2;
break;
case '+':
this._terminal.gcharset = 3;
break;
case '-':
this._terminal.gcharset = 1;
break;
case '.':
this._terminal.gcharset = 2;
break;
}
this._state = ParserState.CHARSET;
break;
// Designate G3 Character Set (VT300).
// A = ISO Latin-1 Supplemental.
// Not implemented.
case '/':
this._terminal.gcharset = 3;
this._state = ParserState.CHARSET;
this._position--;
break;
// ESC N
// Single Shift Select of G2 Character Set
// ( SS2 is 0x8e). This affects next character only.
case 'N':
break;
// ESC O
// Single Shift Select of G3 Character Set
// ( SS3 is 0x8f). This affects next character only.
case 'O':
break;
// ESC n
// Invoke the G2 Character Set as GL (LS2).
case 'n':
this._terminal.setgLevel(2);
break;
// ESC o
// Invoke the G3 Character Set as GL (LS3).
case 'o':
this._terminal.setgLevel(3);
break;
// ESC |
// Invoke the G3 Character Set as GR (LS3R).
case '|':
this._terminal.setgLevel(3);
break;
// ESC }
// Invoke the G2 Character Set as GR (LS2R).
case '}':
this._terminal.setgLevel(2);
break;
// ESC ~
// Invoke the G1 Character Set as GR (LS1R).
case '~':
this._terminal.setgLevel(1);
break;
// ESC 7 Save Cursor (DECSC).
case '7':
this._inputHandler.saveCursor();
this._state = ParserState.NORMAL;
break;
// ESC 8 Restore Cursor (DECRC).
case '8':
this._inputHandler.restoreCursor();
this._state = ParserState.NORMAL;
break;
// ESC # 3 DEC line height/width
case '#':
this._state = ParserState.NORMAL;
this._position++;
break;
// ESC H Tab Set (HTS is 0x88).
case 'H':
this._terminal.tabSet();
this._state = ParserState.NORMAL;
break;
// ESC = Application Keypad (DECKPAM).
case '=':
this._terminal.log('Serial port requested application keypad.');
this._terminal.applicationKeypad = true;
this._terminal.viewport.syncScrollArea();
this._state = ParserState.NORMAL;
break;
// ESC > Normal Keypad (DECKPNM).
case '>':
this._terminal.log('Switching back to normal keypad.');
this._terminal.applicationKeypad = false;
this._terminal.viewport.syncScrollArea();
this._state = ParserState.NORMAL;
break;
default:
this._state = ParserState.NORMAL;
this._terminal.error('Unknown ESC control: %s.', ch);
break;
}
break;
case ParserState.CHARSET:
if (ch in CHARSETS) {
cs = CHARSETS[ch];
if (ch === '/') { // ISOLatin is actually /A
this.skipNextChar();
}
} else {
cs = DEFAULT_CHARSET;
}
this._terminal.setgCharset(this._terminal.gcharset, cs);
this._terminal.gcharset = null;
this._state = ParserState.NORMAL;
break;
case ParserState.OSC:
// OSC Ps ; Pt ST
// OSC Ps ; Pt BEL
// Set Text Parameters.
if (ch === C0.ESC || ch === C0.BEL) {
if (ch === C0.ESC) this._position++;
this._terminal.params.push(this._terminal.currentParam);
switch (this._terminal.params[0]) {
case 0:
case 1:
case 2:
if (this._terminal.params[1]) {
this._terminal.title = this._terminal.params[1];
this._terminal.handleTitle(this._terminal.title);
}
break;
case 3:
// set X property
break;
case 4:
case 5:
// change dynamic colors
break;
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
// change dynamic ui colors
break;
case 46:
// change log file
break;
case 50:
// dynamic font
break;
case 51:
// emacs shell
break;
case 52:
// manipulate selection data
break;
case 104:
case 105:
case 110:
case 111:
case 112:
case 113:
case 114:
case 115:
case 116:
case 117:
case 118:
// reset colors
break;
}
this._terminal.params = [];
this._terminal.currentParam = 0;
this._state = ParserState.NORMAL;
} else {
if (!this._terminal.params.length) {
if (ch >= '0' && ch <= '9') {
this._terminal.currentParam =
this._terminal.currentParam * 10 + ch.charCodeAt(0) - 48;
} else if (ch === ';') {
this._terminal.params.push(this._terminal.currentParam);
this._terminal.currentParam = '';
}
} else {
this._terminal.currentParam += ch;
}
}
break;
case ParserState.CSI_PARAM:
if (ch in csiParamStateHandler) {
csiParamStateHandler[ch](this);
break;
}
this.finalizeParam();
// Fall through the CSI as this character should be the CSI code.
this._state = ParserState.CSI;
case ParserState.CSI:
if (ch in csiStateHandler) {
csiStateHandler[ch](this._inputHandler, this._terminal.params, this._terminal.prefix, this._terminal.postfix, this);
} else {
this._terminal.error('Unknown CSI code: %s.', ch);
}
this._state = ParserState.NORMAL;
this._terminal.prefix = '';
this._terminal.postfix = '';
break;
case ParserState.DCS:
if (ch === C0.ESC || ch === C0.BEL) {
if (ch === C0.ESC) this._position++;
switch (this._terminal.prefix) {
// User-Defined Keys (DECUDK).
case '':
break;
// Request Status String (DECRQSS).
// test: echo -e '\eP$q"p\e\\'
case '$q':
let pt = this._terminal.currentParam
, valid = false;
switch (pt) {
// DECSCA
case '"q':
pt = '0"q';
break;
// DECSCL
case '"p':
pt = '61"p';
break;
// DECSTBM
case 'r':
pt = ''
+ (this._terminal.scrollTop + 1)
+ ';'
+ (this._terminal.scrollBottom + 1)
+ 'r';
break;
// SGR
case 'm':
pt = '0m';
break;
default:
this._terminal.error('Unknown DCS Pt: %s.', pt);
pt = '';
break;
}
this._terminal.send(C0.ESC + 'P' + +valid + '$r' + pt + C0.ESC + '\\');
break;
// Set Termcap/Terminfo Data (xterm, experimental).
case '+p':
break;
// Request Termcap/Terminfo String (xterm, experimental)
// Regular xterm does not even respond to this sequence.
// This can cause a small glitch in vim.
// test: echo -ne '\eP+q6b64\e\\'
case '+q':
// TODO: Don't declare pt twice
/*let*/ pt = this._terminal.currentParam
, valid = false;
this._terminal.send(C0.ESC + 'P' + +valid + '+r' + pt + C0.ESC + '\\');
break;
default:
this._terminal.error('Unknown DCS prefix: %s.', this._terminal.prefix);
break;
}
this._terminal.currentParam = 0;
this._terminal.prefix = '';
this._state = ParserState.NORMAL;
} else if (!this._terminal.currentParam) {
if (!this._terminal.prefix && ch !== '$' && ch !== '+') {
this._terminal.currentParam = ch;
} else if (this._terminal.prefix.length === 2) {
this._terminal.currentParam = ch;
} else {
this._terminal.prefix += ch;
}
} else {
this._terminal.currentParam += ch;
}
break;
case ParserState.IGNORE:
// For PM and APC.
if (ch === C0.ESC || ch === C0.BEL) {
if (ch === C0.ESC) this._position++;
this._state = ParserState.NORMAL;
}
break;
}
}
}
/**
* Set the parser's current parsing state.
*
* @param state The new state.
*/
public setState(state: ParserState): void {
this._state = state;
}
/**
* Sets the parsier's current prefix. CSI codes can have prefixes of '?', '>'
* or '!'.
*
* @param prefix The prefix.
*/
public setPrefix(prefix: string): void {
this._terminal.prefix = prefix;
}
/**
* Sets the parsier's current prefix. CSI codes can have postfixes of '$',
* '"', ' ', '\''.
*
* @param postfix The postfix.
*/
public setPostfix(postfix: string): void {
this._terminal.postfix = postfix;
}
/**
* Sets the parser's current parameter.
*
* @param param the parameter.
*/
public setParam(param: number) {
this._terminal.currentParam = param;
}
/**
* Gets the parser's current parameter.
*/
public getParam(): number {
return this._terminal.currentParam;
}
/**
* Finalizes the parser's current parameter, adding it to the list of
* parameters and setting the new current parameter to 0.
*/
public finalizeParam(): void {
this._terminal.params.push(this._terminal.currentParam);
this._terminal.currentParam = 0;
}
/**
* Tell the parser to skip the next character.
*/
public skipNextChar(): void {
this._position++;
}
/**
* Tell the parser to repeat parsing the current character (for example if it
* needs parsing using a different state.
*/
// public repeatChar(): void {
// this._position--;
// }
}
+306
View File
@@ -0,0 +1,306 @@
/**
* @license MIT
*/
import { ITerminal } from './Interfaces';
/**
* The maximum number of refresh frames to skip when the write buffer is non-
* empty. Note that these frames may be intermingled with frames that are
* skipped via requestAnimationFrame's mechanism.
*/
const MAX_REFRESH_FRAME_SKIP = 5;
/**
* Flags used to render terminal text properly.
*/
enum FLAGS {
BOLD = 1,
UNDERLINE = 2,
BLINK = 4,
INVERSE = 8,
INVISIBLE = 16
};
let brokenBold: boolean = null;
export class Renderer {
/** A queue of the rows to be refreshed */
private _refreshRowsQueue: {start: number, end: number}[] = [];
private _refreshFramesSkipped = 0;
private _refreshAnimationFrame = null;
constructor(private _terminal: ITerminal) {
// Figure out whether boldness affects
// the character width of monospace fonts.
if (brokenBold === null) {
brokenBold = checkBoldBroken((<any>this._terminal).element);
}
// TODO: Pull more DOM interactions into Renderer.constructor, element for
// example should be owned by Renderer (and also exposed by Terminal due to
// to established public API).
}
/**
* Queues a refresh between two rows (inclusive), to be done on next animation
* frame.
* @param {number} start The start row.
* @param {number} end The end row.
*/
public queueRefresh(start: number, end: number): void {
this._refreshRowsQueue.push({ start: start, end: end });
if (!this._refreshAnimationFrame) {
this._refreshAnimationFrame = window.requestAnimationFrame(this._refreshLoop.bind(this));
}
}
/**
* Performs the refresh loop callback, calling refresh only if a refresh is
* necessary before queueing up the next one.
*/
private _refreshLoop(): void {
// Skip MAX_REFRESH_FRAME_SKIP frames if the writeBuffer is non-empty as it
// will need to be immediately refreshed anyway. This saves a lot of
// rendering time as the viewport DOM does not need to be refreshed, no
// scroll events, no layouts, etc.
const skipFrame = this._terminal.writeBuffer.length > 0 && this._refreshFramesSkipped++ <= MAX_REFRESH_FRAME_SKIP;
if (skipFrame) {
this._refreshAnimationFrame = window.requestAnimationFrame(this._refreshLoop.bind(this));
return;
}
this._refreshFramesSkipped = 0;
let start;
let end;
if (this._refreshRowsQueue.length > 4) {
// Just do a full refresh when 5+ refreshes are queued
start = 0;
end = this._terminal.rows - 1;
} else {
// Get start and end rows that need refreshing
start = this._refreshRowsQueue[0].start;
end = this._refreshRowsQueue[0].end;
for (let i = 1; i < this._refreshRowsQueue.length; i++) {
if (this._refreshRowsQueue[i].start < start) {
start = this._refreshRowsQueue[i].start;
}
if (this._refreshRowsQueue[i].end > end) {
end = this._refreshRowsQueue[i].end;
}
}
}
this._refreshRowsQueue = [];
this._refreshAnimationFrame = null;
this._refresh(start, end);
}
/**
* Refreshes (re-renders) terminal content within two rows (inclusive)
*
* Rendering Engine:
*
* In the screen buffer, each character is stored as a an array with a character
* and a 32-bit integer:
* - First value: a utf-16 character.
* - Second value:
* - Next 9 bits: background color (0-511).
* - Next 9 bits: foreground color (0-511).
* - Next 14 bits: a mask for misc. flags:
* - 1=bold
* - 2=underline
* - 4=blink
* - 8=inverse
* - 16=invisible
*
* @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
* @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
*/
private _refresh(start: number, end: number): void {
let x, y, i, line, out, ch, ch_width, width, data, attr, bg, fg, flags, row, parent, focused = document.activeElement;
// If this is a big refresh, remove the terminal rows from the DOM for faster calculations
if (end - start >= this._terminal.rows / 2) {
parent = this._terminal.element.parentNode;
if (parent) {
this._terminal.element.removeChild(this._terminal.rowContainer);
}
}
width = this._terminal.cols;
y = start;
if (end >= this._terminal.rows) {
this._terminal.log('`end` is too large. Most likely a bad CSR.');
end = this._terminal.rows - 1;
}
for (; y <= end; y++) {
row = y + this._terminal.ydisp;
line = this._terminal.lines.get(row);
if (!line || !this._terminal.children[y]) {
// Continue if the line is not available, this means a resize is currently in progress
continue;
}
out = '';
if (this._terminal.y === y - (this._terminal.ybase - this._terminal.ydisp)
&& this._terminal.cursorState
&& !this._terminal.cursorHidden) {
x = this._terminal.x;
} else {
x = -1;
}
attr = this._terminal.defAttr;
i = 0;
for (; i < width; i++) {
if (!line[i]) {
// Continue if the character is not available, this means a resize is currently in progress
continue;
}
data = line[i][0];
ch = line[i][1];
ch_width = line[i][2];
if (!ch_width)
continue;
if (i === x) data = -1;
if (data !== attr) {
if (attr !== this._terminal.defAttr) {
out += '</span>';
}
if (data !== this._terminal.defAttr) {
if (data === -1) {
out += '<span class="reverse-video terminal-cursor">';
} else {
let classNames = [];
bg = data & 0x1ff;
fg = (data >> 9) & 0x1ff;
flags = data >> 18;
if (flags & FLAGS.BOLD) {
if (!brokenBold) {
classNames.push('xterm-bold');
}
// See: XTerm*boldColors
if (fg < 8) fg += 8;
}
if (flags & FLAGS.UNDERLINE) {
classNames.push('xterm-underline');
}
if (flags & FLAGS.BLINK) {
classNames.push('xterm-blink');
}
// If inverse flag is on, then swap the foreground and background variables.
if (flags & FLAGS.INVERSE) {
/* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
bg = [fg, fg = bg][0];
// Should inverse just be before the
// above boldColors effect instead?
if ((flags & 1) && fg < 8) fg += 8;
}
if (flags & FLAGS.INVISIBLE) {
classNames.push('xterm-hidden');
}
/**
* Weird situation: Invert flag used black foreground and white background results
* in invalid background color, positioned at the 256 index of the 256 terminal
* color map. Pin the colors manually in such a case.
*
* Source: https://github.com/sourcelair/xterm.js/issues/57
*/
if (flags & FLAGS.INVERSE) {
if (bg === 257) {
bg = 15;
}
if (fg === 256) {
fg = 0;
}
}
if (bg < 256) {
classNames.push('xterm-bg-color-' + bg);
}
if (fg < 256) {
classNames.push('xterm-color-' + fg);
}
out += '<span';
if (classNames.length) {
out += ' class="' + classNames.join(' ') + '"';
}
out += '>';
}
}
}
if (ch_width === 2) {
out += '<span class="xterm-wide-char">';
}
switch (ch) {
case '&':
out += '&amp;';
break;
case '<':
out += '&lt;';
break;
case '>':
out += '&gt;';
break;
default:
if (ch <= ' ') {
out += '&nbsp;';
} else {
out += ch;
}
break;
}
if (ch_width === 2) {
out += '</span>';
}
attr = data;
}
if (attr !== this._terminal.defAttr) {
out += '</span>';
}
this._terminal.children[y].innerHTML = out;
}
if (parent) {
this._terminal.element.appendChild(this._terminal.rowContainer);
}
this._terminal.emit('refresh', {element: this._terminal.element, start: start, end: end});
};
}
// if bold is broken, we can't
// use it in the terminal.
function checkBoldBroken(terminal) {
const document = terminal.ownerDocument;
const el = document.createElement('span');
el.innerHTML = 'hello world';
terminal.appendChild(el);
const w1 = el.offsetWidth;
const h1 = el.offsetHeight;
el.style.fontWeight = 'bold';
const w2 = el.offsetWidth;
const h2 = el.offsetHeight;
terminal.removeChild(el);
return w1 !== w2 || h1 !== h2;
}
+14
View File
@@ -0,0 +1,14 @@
/**
* @license MIT
*/
export type LinkMatcher = {
id: number,
regex: RegExp,
handler: LinkMatcherHandler,
matchIndex?: number,
validationCallback?: LinkMatcherValidationCallback,
priority?: number
};
export type LinkMatcherHandler = (event: MouseEvent, uri: string) => boolean | void;
export type LinkMatcherValidationCallback = (uri: string, element: HTMLElement, callback: (isValid: boolean) => void) => void;
+35 -33
View File
@@ -2,11 +2,11 @@ import { assert } from 'chai';
import { Viewport } from './Viewport';
describe('Viewport', () => {
var terminal;
var viewportElement;
var charMeasureElement;
var viewport;
var scrollAreaElement;
let terminal;
let viewportElement;
let charMeasure;
let viewport;
let scrollAreaElement;
const CHARACTER_HEIGHT = 10;
@@ -34,24 +34,24 @@ describe('Viewport', () => {
height: 0
}
};
charMeasureElement = {
getBoundingClientRect: () => {
return { width: null, height: CHARACTER_HEIGHT };
}
charMeasure = {
height: CHARACTER_HEIGHT
};
viewport = new Viewport(terminal, viewportElement, scrollAreaElement, charMeasureElement);
viewport = new Viewport(terminal, viewportElement, scrollAreaElement, charMeasure);
});
describe('refresh', () => {
it('should set the line-height of the terminal', () => {
assert.equal(viewportElement.style.lineHeight, CHARACTER_HEIGHT + 'px');
assert.equal(terminal.rowContainer.style.lineHeight, CHARACTER_HEIGHT + 'px');
charMeasureElement.getBoundingClientRect = () => {
return { width: null, height: 1 };
};
viewport.refresh();
assert.equal(viewportElement.style.lineHeight, '1px');
assert.equal(terminal.rowContainer.style.lineHeight, '1px');
it('should set the line-height of the terminal', done => {
// Allow CharMeasure to be initialized
setTimeout(() => {
assert.equal(viewportElement.style.lineHeight, CHARACTER_HEIGHT + 'px');
assert.equal(terminal.rowContainer.style.lineHeight, CHARACTER_HEIGHT + 'px');
charMeasure.height = 1;
viewport.refresh();
assert.equal(viewportElement.style.lineHeight, '1px');
assert.equal(terminal.rowContainer.style.lineHeight, '1px');
done();
}, 0);
});
it('should set the height of the viewport when the line-height changed', () => {
terminal.lines.push('');
@@ -59,26 +59,28 @@ describe('Viewport', () => {
terminal.rows = 1;
viewport.refresh();
assert.equal(viewportElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
charMeasureElement.getBoundingClientRect = () => {
return { width: null, height: 20 };
};
charMeasure.height = 20;
viewport.refresh();
assert.equal(viewportElement.style.height, 20 + 'px');
});
});
describe('syncScrollArea', () => {
it('should sync the scroll area', () => {
terminal.lines.push('');
terminal.rows = 1;
assert.equal(scrollAreaElement.style.height, 0 * CHARACTER_HEIGHT + 'px');
viewport.syncScrollArea();
assert.equal(viewportElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
assert.equal(scrollAreaElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
terminal.lines.push('');
viewport.syncScrollArea();
assert.equal(viewportElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
assert.equal(scrollAreaElement.style.height, 2 * CHARACTER_HEIGHT + 'px');
it('should sync the scroll area', done => {
// Allow CharMeasure to be initialized
setTimeout(() => {
terminal.lines.push('');
terminal.rows = 1;
assert.equal(scrollAreaElement.style.height, 0 * CHARACTER_HEIGHT + 'px');
viewport.syncScrollArea();
assert.equal(viewportElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
assert.equal(scrollAreaElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
terminal.lines.push('');
viewport.syncScrollArea();
assert.equal(viewportElement.style.height, 1 * CHARACTER_HEIGHT + 'px');
assert.equal(scrollAreaElement.style.height, 2 * CHARACTER_HEIGHT + 'px');
done();
}, 0);
});
});
});
+19 -19
View File
@@ -3,6 +3,7 @@
*/
import { ITerminal } from './Interfaces';
import { CharMeasure } from './utils/CharMeasure';
/**
* Represents the viewport of a terminal, the visible area within the larger buffer of output.
@@ -24,7 +25,7 @@ export class Viewport {
private terminal: ITerminal,
private viewportElement: HTMLElement,
private scrollArea: HTMLElement,
private charMeasureElement: HTMLElement
private charMeasure: CharMeasure
) {
this.currentRowHeight = 0;
this.lastRecordedBufferLength = 0;
@@ -34,7 +35,8 @@ export class Viewport {
this.terminal.on('resize', this.syncScrollArea.bind(this));
this.viewportElement.addEventListener('scroll', this.onScroll.bind(this));
this.syncScrollArea();
// Perform this async to ensure the CharMeasure is ready.
setTimeout(() => this.syncScrollArea(), 0);
}
/**
@@ -43,21 +45,20 @@ export class Viewport {
* @param charSize A character size measurement bounding rect object, if it doesn't exist it will
* be created.
*/
private refresh(charSize?: ClientRect): void {
var size = charSize || this.charMeasureElement.getBoundingClientRect();
if (size.height > 0) {
var rowHeightChanged = size.height !== this.currentRowHeight;
private refresh(): void {
if (this.charMeasure.height > 0) {
const rowHeightChanged = this.charMeasure.height !== this.currentRowHeight;
if (rowHeightChanged) {
this.currentRowHeight = size.height;
this.viewportElement.style.lineHeight = size.height + 'px';
this.terminal.rowContainer.style.lineHeight = size.height + 'px';
this.currentRowHeight = this.charMeasure.height;
this.viewportElement.style.lineHeight = this.charMeasure.height + 'px';
this.terminal.rowContainer.style.lineHeight = this.charMeasure.height + 'px';
}
var viewportHeightChanged = this.lastRecordedViewportHeight !== this.terminal.rows;
const viewportHeightChanged = this.lastRecordedViewportHeight !== this.terminal.rows;
if (rowHeightChanged || viewportHeightChanged) {
this.lastRecordedViewportHeight = this.terminal.rows;
this.viewportElement.style.height = size.height * this.terminal.rows + 'px';
this.viewportElement.style.height = this.charMeasure.height * this.terminal.rows + 'px';
}
this.scrollArea.style.height = (size.height * this.lastRecordedBufferLength) + 'px';
this.scrollArea.style.height = (this.charMeasure.height * this.lastRecordedBufferLength) + 'px';
}
}
@@ -74,14 +75,13 @@ export class Viewport {
this.refresh();
} else {
// If size has changed, refresh viewport
var size = this.charMeasureElement.getBoundingClientRect();
if (size.height !== this.currentRowHeight) {
this.refresh(size);
if (this.charMeasure.height !== this.currentRowHeight) {
this.refresh();
}
}
// Sync scrollTop
var scrollTop = this.terminal.ydisp * this.currentRowHeight;
const scrollTop = this.terminal.ydisp * this.currentRowHeight;
if (this.viewportElement.scrollTop !== scrollTop) {
this.viewportElement.scrollTop = scrollTop;
}
@@ -93,8 +93,8 @@ export class Viewport {
* @param ev The scroll event.
*/
private onScroll(ev: Event) {
var newRow = Math.round(this.viewportElement.scrollTop / this.currentRowHeight);
var diff = newRow - this.terminal.ydisp;
const newRow = Math.round(this.viewportElement.scrollTop / this.currentRowHeight);
const diff = newRow - this.terminal.ydisp;
this.terminal.scrollDisp(diff, true);
}
@@ -110,7 +110,7 @@ export class Viewport {
return;
}
// Fallback to WheelEvent.DOM_DELTA_PIXEL
var multiplier = 1;
let multiplier = 1;
if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
multiplier = this.currentRowHeight;
} else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+9 -4
View File
@@ -32,9 +32,12 @@
var exports = {};
exports.proposeGeometry = function (term) {
if (!term.element.parentElement) {
return null;
}
var parentElementStyle = window.getComputedStyle(term.element.parentElement),
parentElementHeight = parseInt(parentElementStyle.getPropertyValue('height')),
parentElementWidth = parseInt(parentElementStyle.getPropertyValue('width')),
parentElementWidth = Math.max(0, parseInt(parentElementStyle.getPropertyValue('width')) - 17),
elementStyle = window.getComputedStyle(term.element),
elementPaddingVer = parseInt(elementStyle.getPropertyValue('padding-top')) + parseInt(elementStyle.getPropertyValue('padding-bottom')),
elementPaddingHor = parseInt(elementStyle.getPropertyValue('padding-right')) + parseInt(elementStyle.getPropertyValue('padding-left')),
@@ -53,11 +56,11 @@
subjectRow.innerHTML = 'W'; // Common character for measuring width, although on monospace
characterWidth = subjectRow.getBoundingClientRect().width;
subjectRow.style.display = ''; // Revert style before calculating height, since they differ.
characterHeight = parseInt(subjectRow.offsetHeight);
characterHeight = subjectRow.getBoundingClientRect().height;
subjectRow.innerHTML = contentBuffer;
rows = parseInt(availableHeight / characterHeight);
cols = parseInt(availableWidth / characterWidth) - 1;
cols = parseInt(availableWidth / characterWidth);
geometry = {cols: cols, rows: rows};
return geometry;
@@ -66,7 +69,9 @@
exports.fit = function (term) {
var geometry = exports.proposeGeometry(term);
term.resize(geometry.cols, geometry.rows);
if (geometry) {
term.resize(geometry.cols, geometry.rows);
}
};
Xterm.prototype.proposeGeometry = function () {
-36
View File
@@ -1,36 +0,0 @@
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="../../src/xterm.css" />
<link rel="stylesheet" href="../../demo/style.css" />
<script src="../../src/xterm.js"></script>
<script src="linkify.js"></script>
<style>
body {
color: #111;
}
#terminal-container {
max-width: 900px;
margin: 0 auto;
}
#terminal-container a {
color: #fff;
}
</style>
</head>
<body>
<div id="terminal-container"></div>
<script>
var term = new Terminal(),
container = document.getElementById('terminal-container');
term.open(container);
term.writeln('Hello, welcome to xterm.js');
term.writeln('');
term.writeln('Check it out at github.com/sourcelair/xterm.js');
term.linkify();
</script>
</body>
</html>
-207
View File
@@ -1,207 +0,0 @@
/**
* Methods for turning URL subscrings in the terminal's content into links (`a` DOM elements).
* @module xterm/addons/linkify/linkify
* @license MIT
*/
(function (linkify) {
if (typeof exports === 'object' && typeof module === 'object') {
/*
* CommonJS environment
*/
module.exports = linkify(require('../../xterm'));
} else if (typeof define == 'function') {
/*
* Require.js is available
*/
define(['../../xterm'], linkify);
} else {
/*
* Plain browser environment
*/
linkify(window.Terminal);
}
})(function (Xterm) {
'use strict';
var exports = {},
protocolClause = '(https?:\\/\\/)',
domainCharacterSet = '[\\da-z\\.-]+',
negatedDomainCharacterSet = '[^\\da-z\\.-]+',
domainBodyClause = '(' + domainCharacterSet + ')',
tldClause = '([a-z\\.]{2,6})',
ipClause = '((\\d{1,3}\\.){3}\\d{1,3})',
portClause = '(:\\d{1,5})',
hostClause = '((' + domainBodyClause + '\\.' + tldClause + ')|' + ipClause + ')' + portClause + '?',
pathClause = '(\\/[\\/\\w\\.-]*)*',
negatedPathCharacterSet = '[^\\/\\w\\.-]+',
bodyClause = hostClause + pathClause,
start = '(?:^|' + negatedDomainCharacterSet + ')(',
end = ')($|' + negatedPathCharacterSet + ')',
lenientUrlClause = start + protocolClause + '?' + bodyClause + end,
strictUrlClause = start + protocolClause + bodyClause + end,
lenientUrlRegex = new RegExp(lenientUrlClause),
strictUrlRegex = new RegExp(strictUrlClause);
/**
* Converts all valid URLs found in the given terminal line into
* hyperlinks. The terminal line can be either the HTML element itself
* or the index of the termina line in the children of the terminal
* rows container.
*
* @param {Xterm} terminal - The terminal that owns the given line.
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
*/
exports.linkifyTerminalLine = function (terminal, line, lenient, target) {
if (typeof line == 'number') {
line = terminal.rowContainer.children[line];
} else if (! (line instanceof HTMLDivElement)) {
var message = 'The "line" argument should be either a number';
message += ' or an HTMLDivElement';
throw new TypeError(message);
}
if (typeof target === 'undefined') {
target = '';
} else {
target = 'target="' + target + '"';
}
var buffer = document.createElement('span'),
nodes = line.childNodes;
for (var j=0; j<nodes.length; j++) {
var node = nodes[j],
match;
/**
* Since we cannot access the TextNode's HTML representation
* from the instance itself, we assign its data as textContent
* to a dummy buffer span, in order to retrieve the TextNode's
* HTML representation from the buffer's innerHTML.
*/
buffer.textContent = node.data;
var nodeHTML = buffer.innerHTML;
/**
* Apply function only on TextNodes
*/
if (node.nodeType != node.TEXT_NODE) {
continue;
}
var url = exports.findLinkMatch(node.data, lenient);
if (!url) {
continue;
}
var startsWithProtocol = new RegExp('^' + protocolClause),
urlHasProtocol = url.match(startsWithProtocol),
href = (urlHasProtocol) ? url : 'http://' + url,
link = '<a href="' + href + '" ' + target + '>' + url + '</a>',
newHTML = nodeHTML.replace(url, link);
line.innerHTML = line.innerHTML.replace(nodeHTML, newHTML);
}
/**
* This event gets emitted when conversion of all URL susbtrings
* to HTML anchor elements (links) has finished, for a specific
* line of the current Xterm instance.
*
* @event linkify:line
*/
terminal.emit('linkify:line', line);
};
/**
* Finds a link within a block of text.
*
* @param {string} text - The text to search .
* @param {boolean} lenient - Whether to use the lenient search.
* @return {string} A URL.
*/
exports.findLinkMatch = function (text, lenient) {
var match = text.match(lenient ? lenientUrlRegex : strictUrlRegex);
if (!match || match.length === 0) {
return null;
}
return match[1];
}
/**
* Converts all valid URLs found in the terminal view into hyperlinks.
*
* @param {Xterm} terminal - The terminal that should get "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
* @emits linkify
* @emits linkify:line
*/
exports.linkify = function (terminal, lenient, target) {
var rows = terminal.rowContainer.children;
lenient = (typeof lenient == "boolean") ? lenient : true;
for (var i=0; i<rows.length; i++) {
var line = rows[i];
exports.linkifyTerminalLine(terminal, line, lenient, target);
}
/**
* This event gets emitted when conversion of all URL substrings to
* HTML anchor elements (links) has finished for the current Xterm
* instance's view.
*
* @event linkify
*/
terminal.emit('linkify');
};
/**
* Extend Xterm prototype.
*/
/**
* Converts all valid URLs found in the current terminal linte into
* hyperlinks.
*
* @memberof Xterm
* @param {number|HTMLDivElement} line - The terminal line that should get
* "linkified".
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkifyTerminalLine = function (line, lenient, target) {
return exports.linkifyTerminalLine(this, line, lenient, target);
};
/**
* Converts all valid URLs found in the current terminal into hyperlinks.
*
* @memberof Xterm
* @param {boolean} lenient - The regex type that will be used to identify links. If lenient is
* false, the regex requires a protocol clause. Defaults to true.
* @param {string} target - Sets target="" attribute with value provided to links.
* Default doesn't set target attribute
*/
Xterm.prototype.linkify = function (lenient, target) {
return exports.linkify(this, lenient, target);
};
return exports;
});
-5
View File
@@ -1,5 +0,0 @@
{
"name": "xterm.linkify",
"main": "linkify.js",
"private": true
}
+1 -1
View File
@@ -5,7 +5,7 @@ import * as Clipboard from './Clipboard';
describe('evaluateCopiedTextProcessing', function () {
it('should strip trailing whitespaces and replace nbsps with spaces', function () {
var nonBreakingSpace = String.fromCharCode(160),
let nonBreakingSpace = String.fromCharCode(160),
copiedText = 'echo' + nonBreakingSpace + 'hello' + nonBreakingSpace,
processedText = Clipboard.prepareTextForClipboard(copiedText);
+8 -15
View File
@@ -7,13 +7,6 @@
import { ITerminal } from '../Interfaces';
// We are extending the ClipboardEvent interface, since TypeScript has not declared the
// clientX and clientY properties that we use.
interface IClipboardEvent extends ClipboardEvent {
clientX: number;
clientY: number;
}
interface IWindow extends Window {
clipboardData?: {
getData(format: string): string;
@@ -49,7 +42,7 @@ export function prepareTextForClipboard(text: string): string {
* Binds copy functionality to the given terminal.
* @param {ClipboardEvent} ev The original copy event to be handled
*/
export function copyHandler(ev: IClipboardEvent, term: ITerminal) {
export function copyHandler(ev: ClipboardEvent, term: ITerminal) {
// We cast `window` to `any` type, because TypeScript has not declared the `clipboardData`
// property that we use below for Internet Explorer.
let copiedText = window.getSelection().toString(),
@@ -69,7 +62,7 @@ export function copyHandler(ev: IClipboardEvent, term: ITerminal) {
* @param {ClipboardEvent} ev The original paste event to be handled
* @param {Terminal} term The terminal on which to apply the handled paste event
*/
export function pasteHandler(ev: IClipboardEvent, term: ITerminal) {
export function pasteHandler(ev: ClipboardEvent, term: ITerminal) {
ev.stopPropagation();
let text: string;
@@ -103,10 +96,10 @@ export function pasteHandler(ev: IClipboardEvent, term: ITerminal) {
* area, then bring the terminal's input below the cursor, in order to
* trigger the event on the textarea and allow-right click paste, without
* caring about disappearing selection.
* @param {ClipboardEvent} ev The original paste event to be handled
* @param {MouseEvent} ev The original right click event to be handled
* @param {Terminal} term The terminal on which to apply the handled paste event
*/
export function rightClickHandler(ev: IClipboardEvent, term: ITerminal) {
export function rightClickHandler(ev: MouseEvent, term: ITerminal) {
let s = document.getSelection(),
selectedText = prepareTextForClipboard(s.toString()),
clickIsOnSelection = false,
@@ -115,11 +108,11 @@ export function rightClickHandler(ev: IClipboardEvent, term: ITerminal) {
if (s.rangeCount) {
let r = s.getRangeAt(0),
cr = r.getClientRects(),
i, rect;
cr = r.getClientRects();
for (let i = 0; i < cr.length; i++) {
let rect = cr[i];
for (i=0; i<cr.length; i++) {
rect = cr[i];
clickIsOnSelection = (
(x > rect.left) && (x < rect.right) &&
(y > rect.top) && (y < rect.bottom)
-48
View File
@@ -1,48 +0,0 @@
var assert = require('chai').assert;
var Terminal = require('../../xterm');
var linkify = require('../../addons/linkify/linkify');
describe('linkify addon', function () {
var xterm;
describe('API', function () {
it('should define Terminal.prototype.linkify', function () {
assert.isDefined(Terminal.prototype.linkify);
});
it('should define Terminal.prototype.linkifyTerminalLine', function () {
assert.isDefined(Terminal.prototype.linkifyTerminalLine);
});
});
describe('findUrlMatchOnLine', function () {
describe('strict regex', function () {
it('should match when the entire text is a match', function () {
assert.equal(linkify.findLinkMatch('http://github.com', false), 'http://github.com');
assert.equal(linkify.findLinkMatch('http://127.0.0.1', false), 'http://127.0.0.1');
});
it('should match simple domains', function () {
assert.equal(linkify.findLinkMatch('foo http://github.com bar', false), 'http://github.com');
assert.equal(linkify.findLinkMatch('foo http://www.github.com bar', false), 'http://www.github.com');
assert.equal(linkify.findLinkMatch('foo https://github.com bar', false), 'https://github.com');
assert.equal(linkify.findLinkMatch('foo https://www.github.com bar', false), 'https://www.github.com');
});
it('should match web addresses with alpha paths', function () {
assert.equal(linkify.findLinkMatch('foo http://github.com/a/b/c bar', false), 'http://github.com/a/b/c');
assert.equal(linkify.findLinkMatch('foo http://www.github.com/a/b/c bar', false), 'http://www.github.com/a/b/c');
});
it('should not include whitespace surrounding a match', function () {
assert.equal(linkify.findLinkMatch(' http://github.com', false), 'http://github.com');
assert.equal(linkify.findLinkMatch('http://github.com ', false), 'http://github.com');
assert.equal(linkify.findLinkMatch(' http://github.com ', false), 'http://github.com');
});
it('should match IP addresses', function () {
assert.equal(linkify.findLinkMatch('foo http://127.0.0.1 bar', false), 'http://127.0.0.1');
assert.equal(linkify.findLinkMatch('foo https://127.0.0.1 bar', false), 'https://127.0.0.1');
});
it('should match ports on both domains and IP addresses', function () {
assert.equal(linkify.findLinkMatch('foo http://127.0.0.1:8080 bar', false), 'http://127.0.0.1:8080');
assert.equal(linkify.findLinkMatch('foo http://www.github.com:8080 bar', false), 'http://www.github.com:8080');
});
});
});
});
+37 -13
View File
@@ -1,9 +1,15 @@
var glob = require('glob');
var fs = require('fs');
var pty = require('pty.js');
var os = require('os');
var pty = require('node-pty');
var sleep = require('sleep');
var Terminal = require('../xterm');
if (os.platform() === 'win32') {
// Skip tests on Windows since pty.open isn't supported
return;
}
var CONSOLE_LOG = console.log;
// expect files need terminal at 80x25!
@@ -56,10 +62,10 @@ function formatError(in_, out_, expected) {
function terminalToString(term) {
var result = '';
var line_s = '';
for (var line=0; line<term.rows; ++line) {
for (var line = term.ybase; line < term.ybase + term.rows; line++) {
line_s = '';
for (var cell=0; cell<term.cols; ++cell) {
line_s += term.lines[line][cell][1];
line_s += term.lines.get(line)[cell][1];
}
// rtrim empty cells as xterm does
line_s = line_s.replace(/\s+$/, '');
@@ -76,31 +82,49 @@ describe('xterm output comparison', function() {
beforeEach(function () {
xterm = new Terminal(COLS, ROWS);
xterm.refresh = function() {};
xterm.viewport = {
syncScrollArea: function() {}
};
});
// omit stack trace for escape sequence files
Error.stackTraceLimit = 0;
var files = glob.sync('**/escape_sequence_files/*.in');
// only successful tests for now
var successful = [0, 2, 6, 12, 13, 18, 20, 22, 27, 28];
console.log(files);
for (var a in successful) {
var i = successful[a];
(function(filename){
var skip = [
10, 16, 17, 19, 32, 33, 34, 35, 36, 39,
40, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 54, 55, 56, 57, 58, 59, 60, 61,
63, 68
];
for (var i = 0; i < files.length; i++) {
if (skip.indexOf(i) >= 0) {
continue;
}
(function(filename) {
it(filename.split('/').slice(-1)[0], function () {
pty_reset();
var in_file = fs.readFileSync(filename, 'utf8');
var from_pty = pty_write_read(in_file);
// uncomment this to get log from terminal
console.log = function(){};
xterm.write(from_pty);
//console.log = function(){};
// Perform a synchronous .write(data)
xterm.writeBuffer.push(from_pty);
xterm.innerWrite();
var from_emulator = terminalToString(xterm);
console.log = CONSOLE_LOG;
var expected = fs.readFileSync(filename.split('.')[0] + '.text', 'utf8');
if (from_emulator != expected) {
// Some of the tests have whitespace on the right of lines, we trim all the linex
// from xterm.js so ignore this for now at least.
var expectedRightTrimmed = expected.split('\n').map(function (l) {
return l.replace(/\s+$/, '');
}).join('\n');
if (from_emulator != expectedRightTrimmed) {
// uncomment to get noisy output
//throw new Error(formatError(in_file, from_emulator, expected));
throw new Error('mismatch');
throw new Error(formatError(in_file, from_emulator, expected));
// throw new Error('mismatch');
}
});
})(files[i]);
+108 -76
View File
@@ -14,6 +14,17 @@ describe('xterm.js', function() {
xterm.compositionHelper = {
keydown: function(){ return true; }
};
// Force synchronous writes
xterm.write = function(data) {
xterm.writeBuffer.push(data);
xterm.innerWrite();
};
xterm.element = {
classList: {
toggle: function(){},
remove: function(){}
}
};
});
describe('getOption', function() {
@@ -48,15 +59,15 @@ describe('xterm.js', function() {
describe('clear', function() {
it('should clear a buffer equal to rows', function() {
var promptLine = xterm.lines[xterm.ybase + xterm.y];
var promptLine = xterm.lines.get(xterm.ybase + xterm.y);
xterm.clear();
assert.equal(xterm.y, 0);
assert.equal(xterm.ybase, 0);
assert.equal(xterm.ydisp, 0);
assert.equal(xterm.lines.length, xterm.rows);
assert.deepEqual(xterm.lines[0], promptLine);
assert.deepEqual(xterm.lines.get(0), promptLine);
for (var i = 1; i < xterm.rows; i++) {
assert.deepEqual(xterm.lines[0], xterm.blankLine());
assert.deepEqual(xterm.lines.get(i), xterm.blankLine());
}
});
it('should clear a buffer larger than rows', function() {
@@ -65,28 +76,28 @@ describe('xterm.js', function() {
xterm.write('test\n');
}
var promptLine = xterm.lines[xterm.ybase + xterm.y];
var promptLine = xterm.lines.get(xterm.ybase + xterm.y);
xterm.clear();
assert.equal(xterm.y, 0);
assert.equal(xterm.ybase, 0);
assert.equal(xterm.ydisp, 0);
assert.equal(xterm.lines.length, xterm.rows);
assert.deepEqual(xterm.lines[0], promptLine);
assert.deepEqual(xterm.lines.get(0), promptLine);
for (var i = 1; i < xterm.rows; i++) {
assert.deepEqual(xterm.lines[i], xterm.blankLine());
assert.deepEqual(xterm.lines.get(i), xterm.blankLine());
}
});
it('should not break the prompt when cleared twice', function() {
var promptLine = xterm.lines[xterm.ybase + xterm.y];
var promptLine = xterm.lines.get(xterm.ybase + xterm.y);
xterm.clear();
xterm.clear();
assert.equal(xterm.y, 0);
assert.equal(xterm.ybase, 0);
assert.equal(xterm.ydisp, 0);
assert.equal(xterm.lines.length, xterm.rows);
assert.deepEqual(xterm.lines[0], promptLine);
assert.deepEqual(xterm.lines.get(0), promptLine);
for (var i = 1; i < xterm.rows; i++) {
assert.deepEqual(xterm.lines[i], xterm.blankLine());
assert.deepEqual(xterm.lines.get(i), xterm.blankLine());
}
});
});
@@ -286,14 +297,33 @@ describe('xterm.js', function() {
it('should return \\x1b[5B for ctrl+down', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ ctrlKey: true, keyCode: 40 }).key, '\x1b[1;5B'); // CSI 5 B
});
// Evalueate alt + arrow key movement, which is a feature of terminal emulators but not VT100
// http://unix.stackexchange.com/a/108106
it('should return \\x1b[5D for alt+left', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 37 }).key, '\x1b[1;5D'); // CSI 5 D
describe('On non-macOS platforms', function() {
beforeEach(function() {
xterm.browser.isMac = false;
});
// Evalueate alt + arrow key movement, which is a feature of terminal emulators but not VT100
// http://unix.stackexchange.com/a/108106
it('should return \\x1b[5D for alt+left', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 37 }).key, '\x1b[1;5D'); // CSI 5 D
});
it('should return \\x1b[5C for alt+right', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 39 }).key, '\x1b[1;5C'); // CSI 5 C
});
});
it('should return \\x1b[5C for alt+right', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 39 }).key, '\x1b[1;5C'); // CSI 5 C
describe('On macOS platforms', function() {
beforeEach(function() {
xterm.browser.isMac = true;
});
it('should return \\x1bb for alt+left', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 37 }).key, '\x1bb'); // CSI 5 D
});
it('should return \\x1bf for alt+right', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 39 }).key, '\x1bf'); // CSI 5 C
});
});
it('should return \\x1b[5A for alt+up', function() {
assert.equal(xterm.evaluateKeyEscapeSequence({ altKey: true, keyCode: 38 }).key, '\x1b[1;5A'); // CSI 5 A
});
@@ -521,14 +551,15 @@ describe('xterm.js', function() {
describe('unicode - surrogates', function() {
it('2 characters per cell', function () {
this.timeout(10000); // This is needed because istanbul patches code and slows it down
var high = String.fromCharCode(0xD800);
for (var i=0xDC00; i<=0xDCFF; ++i) {
xterm.write(high + String.fromCharCode(i));
var tchar = xterm.lines[0][0];
var tchar = xterm.lines.get(0)[0];
expect(tchar[1]).eql(high + String.fromCharCode(i));
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(1);
expect(xterm.lines[0][1][1]).eql(' ');
expect(xterm.lines.get(0)[1][1]).eql(' ');
xterm.reset();
}
});
@@ -537,9 +568,9 @@ describe('xterm.js', function() {
for (var i=0xDC00; i<=0xDCFF; ++i) {
xterm.x = xterm.cols - 1;
xterm.write(high + String.fromCharCode(i));
expect(xterm.lines[0][xterm.x-1][1]).eql(high + String.fromCharCode(i));
expect(xterm.lines[0][xterm.x-1][1].length).eql(2);
expect(xterm.lines[1][0][1]).eql(' ');
expect(xterm.lines.get(0)[xterm.x-1][1]).eql(high + String.fromCharCode(i));
expect(xterm.lines.get(0)[xterm.x-1][1].length).eql(2);
expect(xterm.lines.get(1)[0][1]).eql(' ');
xterm.reset();
}
});
@@ -549,10 +580,10 @@ describe('xterm.js', function() {
xterm.x = xterm.cols - 1;
xterm.wraparoundMode = true;
xterm.write('a' + high + String.fromCharCode(i));
expect(xterm.lines[0][xterm.cols-1][1]).eql('a');
expect(xterm.lines[1][0][1]).eql(high + String.fromCharCode(i));
expect(xterm.lines[1][0][1].length).eql(2);
expect(xterm.lines[1][1][1]).eql(' ');
expect(xterm.lines.get(0)[xterm.cols-1][1]).eql('a');
expect(xterm.lines.get(1)[0][1]).eql(high + String.fromCharCode(i));
expect(xterm.lines.get(1)[0][1].length).eql(2);
expect(xterm.lines.get(1)[1][1]).eql(' ');
xterm.reset();
}
});
@@ -562,9 +593,10 @@ describe('xterm.js', function() {
xterm.x = xterm.cols - 1;
xterm.wraparoundMode = false;
xterm.write('a' + high + String.fromCharCode(i));
expect(xterm.lines[0][xterm.cols-1][1]).eql(high + String.fromCharCode(i));
expect(xterm.lines[0][xterm.cols-1][1].length).eql(2);
expect(xterm.lines[1][1][1]).eql(' ');
// auto wraparound mode should cut off the rest of the line
expect(xterm.lines.get(0)[xterm.cols-1][1]).eql('a');
expect(xterm.lines.get(0)[xterm.cols-1][1].length).eql(1);
expect(xterm.lines.get(1)[1][1]).eql(' ');
xterm.reset();
}
});
@@ -573,11 +605,11 @@ describe('xterm.js', function() {
for (var i=0xDC00; i<=0xDCFF; ++i) {
xterm.write(high);
xterm.write(String.fromCharCode(i));
var tchar = xterm.lines[0][0];
var tchar = xterm.lines.get(0)[0];
expect(tchar[1]).eql(high + String.fromCharCode(i));
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(1);
expect(xterm.lines[0][1][1]).eql(' ');
expect(xterm.lines.get(0)[1][1]).eql(' ');
xterm.reset();
}
});
@@ -586,30 +618,30 @@ describe('xterm.js', function() {
describe('unicode - combining characters', function() {
it('café', function () {
xterm.write('cafe\u0301');
expect(xterm.lines[0][3][1]).eql('e\u0301');
expect(xterm.lines[0][3][1].length).eql(2);
expect(xterm.lines[0][3][2]).eql(1);
expect(xterm.lines.get(0)[3][1]).eql('e\u0301');
expect(xterm.lines.get(0)[3][1].length).eql(2);
expect(xterm.lines.get(0)[3][2]).eql(1);
});
it('café - end of line', function() {
xterm.x = xterm.cols - 1 - 3;
xterm.write('cafe\u0301');
expect(xterm.lines[0][xterm.cols-1][1]).eql('e\u0301');
expect(xterm.lines[0][xterm.cols-1][1].length).eql(2);
expect(xterm.lines[0][xterm.cols-1][2]).eql(1);
expect(xterm.lines[0][1][1]).eql(' ');
expect(xterm.lines[0][1][1].length).eql(1);
expect(xterm.lines[0][1][2]).eql(1);
expect(xterm.lines.get(0)[xterm.cols-1][1]).eql('e\u0301');
expect(xterm.lines.get(0)[xterm.cols-1][1].length).eql(2);
expect(xterm.lines.get(0)[xterm.cols-1][2]).eql(1);
expect(xterm.lines.get(0)[1][1]).eql(' ');
expect(xterm.lines.get(0)[1][1].length).eql(1);
expect(xterm.lines.get(0)[1][2]).eql(1);
});
it('multiple combined é', function() {
xterm.wraparoundMode = true;
xterm.write(Array(100).join('e\u0301'));
for (var i=0; i<xterm.cols; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
expect(tchar[1]).eql('e\u0301');
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(1);
}
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('e\u0301');
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(1);
@@ -618,12 +650,12 @@ describe('xterm.js', function() {
xterm.wraparoundMode = true;
xterm.write(Array(100).join('\uD800\uDC00\u0301'));
for (var i=0; i<xterm.cols; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
expect(tchar[1]).eql('\uD800\uDC00\u0301');
expect(tchar[1].length).eql(3);
expect(tchar[2]).eql(1);
}
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('\uD800\uDC00\u0301');
expect(tchar[1].length).eql(3);
expect(tchar[2]).eql(1);
@@ -646,7 +678,7 @@ describe('xterm.js', function() {
xterm.wraparoundMode = true;
xterm.write(Array(50).join('¥'));
for (var i=0; i<xterm.cols; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (i % 2) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -657,7 +689,7 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('¥');
expect(tchar[1].length).eql(1);
expect(tchar[2]).eql(2);
@@ -667,7 +699,7 @@ describe('xterm.js', function() {
xterm.x = 1;
xterm.write(Array(50).join('¥'));
for (var i=1; i<xterm.cols-1; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (!(i % 2)) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -678,11 +710,11 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[0][xterm.cols-1];
tchar = xterm.lines.get(0)[xterm.cols-1];
expect(tchar[1]).eql(' ');
expect(tchar[1].length).eql(1);
expect(tchar[2]).eql(1);
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('¥');
expect(tchar[1].length).eql(1);
expect(tchar[2]).eql(2);
@@ -692,7 +724,7 @@ describe('xterm.js', function() {
xterm.x = 1;
xterm.write(Array(50).join('¥\u0301'));
for (var i=1; i<xterm.cols-1; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (!(i % 2)) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -703,11 +735,11 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[0][xterm.cols-1];
tchar = xterm.lines.get(0)[xterm.cols-1];
expect(tchar[1]).eql(' ');
expect(tchar[1].length).eql(1);
expect(tchar[2]).eql(1);
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('¥\u0301');
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(2);
@@ -716,7 +748,7 @@ describe('xterm.js', function() {
xterm.wraparoundMode = true;
xterm.write(Array(50).join('¥\u0301'));
for (var i=0; i<xterm.cols; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (i % 2) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -727,7 +759,7 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('¥\u0301');
expect(tchar[1].length).eql(2);
expect(tchar[2]).eql(2);
@@ -737,7 +769,7 @@ describe('xterm.js', function() {
xterm.x = 1;
xterm.write(Array(50).join('\ud843\ude6d\u0301'));
for (var i=1; i<xterm.cols-1; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (!(i % 2)) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -748,11 +780,11 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[0][xterm.cols-1];
tchar = xterm.lines.get(0)[xterm.cols-1];
expect(tchar[1]).eql(' ');
expect(tchar[1].length).eql(1);
expect(tchar[2]).eql(1);
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('\ud843\ude6d\u0301');
expect(tchar[1].length).eql(3);
expect(tchar[2]).eql(2);
@@ -761,7 +793,7 @@ describe('xterm.js', function() {
xterm.wraparoundMode = true;
xterm.write(Array(50).join('\ud843\ude6d\u0301'));
for (var i=0; i<xterm.cols; ++i) {
var tchar = xterm.lines[0][i];
var tchar = xterm.lines.get(0)[i];
if (i % 2) {
expect(tchar[1]).eql('');
expect(tchar[1].length).eql(0);
@@ -772,7 +804,7 @@ describe('xterm.js', function() {
expect(tchar[2]).eql(2);
}
}
tchar = xterm.lines[1][0];
tchar = xterm.lines.get(1)[0];
expect(tchar[1]).eql('\ud843\ude6d\u0301');
expect(tchar[1].length).eql(3);
expect(tchar[2]).eql(2);
@@ -786,11 +818,11 @@ describe('xterm.js', function() {
xterm.y = 0;
xterm.insertMode = true;
xterm.write('abcde');
expect(xterm.lines[0].length).eql(xterm.cols);
expect(xterm.lines[0][10][1]).eql('a');
expect(xterm.lines[0][14][1]).eql('e');
expect(xterm.lines[0][15][1]).eql('0');
expect(xterm.lines[0][79][1]).eql('4');
expect(xterm.lines.get(0).length).eql(xterm.cols);
expect(xterm.lines.get(0)[10][1]).eql('a');
expect(xterm.lines.get(0)[14][1]).eql('e');
expect(xterm.lines.get(0)[15][1]).eql('0');
expect(xterm.lines.get(0)[79][1]).eql('4');
});
it('fullwidth - insert', function() {
xterm.write(Array(9).join('0123456789').slice(-80));
@@ -798,12 +830,12 @@ describe('xterm.js', function() {
xterm.y = 0;
xterm.insertMode = true;
xterm.write('¥¥¥');
expect(xterm.lines[0].length).eql(xterm.cols);
expect(xterm.lines[0][10][1]).eql('¥');
expect(xterm.lines[0][11][1]).eql('');
expect(xterm.lines[0][14][1]).eql('¥');
expect(xterm.lines[0][15][1]).eql('');
expect(xterm.lines[0][79][1]).eql('3');
expect(xterm.lines.get(0).length).eql(xterm.cols);
expect(xterm.lines.get(0)[10][1]).eql('¥');
expect(xterm.lines.get(0)[11][1]).eql('');
expect(xterm.lines.get(0)[14][1]).eql('¥');
expect(xterm.lines.get(0)[15][1]).eql('');
expect(xterm.lines.get(0)[79][1]).eql('3');
});
it('fullwidth - right border', function() {
xterm.write(Array(41).join('¥'));
@@ -811,15 +843,15 @@ describe('xterm.js', function() {
xterm.y = 0;
xterm.insertMode = true;
xterm.write('a');
expect(xterm.lines[0].length).eql(xterm.cols);
expect(xterm.lines[0][10][1]).eql('a');
expect(xterm.lines[0][11][1]).eql('¥');
expect(xterm.lines[0][79][1]).eql(' '); // fullwidth char got replaced
expect(xterm.lines.get(0).length).eql(xterm.cols);
expect(xterm.lines.get(0)[10][1]).eql('a');
expect(xterm.lines.get(0)[11][1]).eql('¥');
expect(xterm.lines.get(0)[79][1]).eql(' '); // fullwidth char got replaced
xterm.write('b');
expect(xterm.lines[0].length).eql(xterm.cols);
expect(xterm.lines[0][11][1]).eql('b');
expect(xterm.lines[0][12][1]).eql('¥');
expect(xterm.lines[0][79][1]).eql(''); // empty cell after fullwidth
expect(xterm.lines.get(0).length).eql(xterm.cols);
expect(xterm.lines.get(0)[11][1]).eql('b');
expect(xterm.lines.get(0)[12][1]).eql('¥');
expect(xterm.lines.get(0)[79][1]).eql(''); // empty cell after fullwidth
});
});
});
-22
View File
@@ -1,22 +0,0 @@
/**
* Attributes and methods to help with identifying the current browser and platform.
* @module xterm/utils/Browser
* @license MIT
*/
import { contains } from './Generic.js';
let isNode = (typeof navigator == 'undefined') ? true : false;
let userAgent = (isNode) ? 'node' : navigator.userAgent;
let platform = (isNode) ? 'node' : navigator.platform;
export let isFirefox = !!~userAgent.indexOf('Firefox');
export let isMSIE = !!~userAgent.indexOf('MSIE') || !!~userAgent.indexOf('Trident');
// Find the users platform. We use this to interpret the meta key
// and ISO third level shifts.
// http://stackoverflow.com/q/19877924/577598
export let isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);
export let isIpad = platform === 'iPad';
export let isIphone = platform === 'iPhone';
export let isMSWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);
+22
View File
@@ -0,0 +1,22 @@
/**
* Attributes and methods to help with identifying the current browser and platform.
* @module xterm/utils/Browser
* @license MIT
*/
import { contains } from './Generic';
const isNode = (typeof navigator === 'undefined') ? true : false;
const userAgent = (isNode) ? 'node' : navigator.userAgent;
const platform = (isNode) ? 'node' : navigator.platform;
export const isFirefox = !!~userAgent.indexOf('Firefox');
export const isMSIE = !!~userAgent.indexOf('MSIE') || !!~userAgent.indexOf('Trident');
// Find the users platform. We use this to interpret the meta key
// and ISO third level shifts.
// http://stackoverflow.com/q/19877924/577598
export const isMac = contains(['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], platform);
export const isIpad = platform === 'iPad';
export const isIphone = platform === 'iPhone';
export const isMSWindows = contains(['Windows', 'Win16', 'Win32', 'WinCE'], platform);
+77
View File
@@ -0,0 +1,77 @@
/**
* @license MIT
*/
import jsdom = require('jsdom');
import { assert } from 'chai';
import { ICharMeasure, ITerminal } from '../Interfaces';
import { CharMeasure } from './CharMeasure';
describe('CharMeasure', () => {
let window: Window;
let document: Document;
let container: HTMLElement;
let charMeasure: ICharMeasure;
beforeEach(done => {
jsdom.env('', (err, w) => {
window = w;
document = window.document;
container = document.createElement('div');
document.body.appendChild(container);
charMeasure = new CharMeasure(document, container);
done();
});
});
describe('measure', () => {
it('should set _measureElement on first call', () => {
charMeasure.measure();
assert.isDefined((<any>charMeasure)._measureElement, 'CharMeasure.measure should have created _measureElement');
});
it('should be performed async on first call', done => {
assert.equal(charMeasure.width, null);
charMeasure.measure();
// Mock getBoundingClientRect since jsdom doesn't have a layout engine
(<any>charMeasure)._measureElement.getBoundingClientRect = () => {
return { width: 1, height: 1 };
};
assert.equal(charMeasure.width, null);
setTimeout(() => {
assert.equal(charMeasure.width, 1);
done();
}, 0);
});
it('should be performed sync on successive calls', done => {
charMeasure.measure();
// Mock getBoundingClientRect since jsdom doesn't have a layout engine
(<any>charMeasure)._measureElement.getBoundingClientRect = () => {
return { width: 1, height: 1 };
};
setTimeout(() => {
const firstWidth = charMeasure.width;
// Mock getBoundingClientRect since jsdom doesn't have a layout engine
(<any>charMeasure)._measureElement.getBoundingClientRect = () => {
return { width: 2, height: 2 };
};
charMeasure.measure();
assert.equal(charMeasure.width, firstWidth * 2);
done();
}, 0);
});
it('should NOT do a measure when the parent is hidden', done => {
charMeasure.measure();
setTimeout(() => {
const firstWidth = charMeasure.width;
container.style.display = 'none';
container.style.fontSize = '2em';
charMeasure.measure();
assert.equal(charMeasure.width, firstWidth);
done();
}, 0);
});
});
});
+62
View File
@@ -0,0 +1,62 @@
/**
* @module xterm/utils/CharMeasure
* @license MIT
*/
import { EventEmitter } from '../EventEmitter.js';
/**
* Utility class that measures the size of a character.
*/
export class CharMeasure extends EventEmitter {
private _document: Document;
private _parentElement: HTMLElement;
private _measureElement: HTMLElement;
private _width: number;
private _height: number;
constructor(document: Document, parentElement: HTMLElement) {
super();
this._document = document;
this._parentElement = parentElement;
}
public get width(): number {
return this._width;
}
public get height(): number {
return this._height;
}
public measure(): void {
if (!this._measureElement) {
this._measureElement = this._document.createElement('span');
this._measureElement.style.position = 'absolute';
this._measureElement.style.top = '0';
this._measureElement.style.left = '-9999em';
this._measureElement.textContent = 'W';
this._measureElement.setAttribute('aria-hidden', 'true');
this._parentElement.appendChild(this._measureElement);
// Perform _doMeasure async if the element was just attached as sometimes
// getBoundingClientRect does not return accurate values without this.
setTimeout(() => this._doMeasure(), 0);
} else {
this._doMeasure();
}
}
private _doMeasure(): void {
const geometry = this._measureElement.getBoundingClientRect();
// The element is likely currently display:none, we should retain the
// previous value.
if (geometry.width === 0 || geometry.height === 0) {
return;
}
if (this._width !== geometry.width || this._height !== geometry.height) {
this._width = geometry.width;
this._height = geometry.height;
this.emit('charsizechanged');
}
}
}
+255
View File
@@ -0,0 +1,255 @@
import { assert } from 'chai';
import { CircularList } from './CircularList';
describe('CircularList', () => {
describe('push', () => {
it('should push values onto the array', () => {
const list = new CircularList<string>(5);
list.push('1');
list.push('2');
list.push('3');
list.push('4');
list.push('5');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
assert.equal(list.get(2), '3');
assert.equal(list.get(3), '4');
assert.equal(list.get(4), '5');
});
it('should push old values from the start out of the array when max length is reached', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
list.push('3');
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '3');
list.push('4');
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
});
});
describe('maxLength', () => {
it('should increase the size of the list', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
list.maxLength = 4;
list.push('3');
list.push('4');
assert.equal(list.get(0), '1');
assert.equal(list.get(1), '2');
assert.equal(list.get(2), '3');
assert.equal(list.get(3), '4');
list.push('wrapped');
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '3');
assert.equal(list.get(2), '4');
assert.equal(list.get(3), 'wrapped');
});
it('should return the maximum length of the list', () => {
const list = new CircularList<string>(2);
assert.equal(list.maxLength, 2);
list.push('1');
list.push('2');
assert.equal(list.maxLength, 2);
list.push('3');
assert.equal(list.maxLength, 2);
list.maxLength = 4;
assert.equal(list.maxLength, 4);
});
});
describe('length', () => {
it('should return the current length of the list, capped at the maximum length', () => {
const list = new CircularList<string>(2);
assert.equal(list.length, 0);
list.push('1');
assert.equal(list.length, 1);
list.push('2');
assert.equal(list.length, 2);
list.push('3');
assert.equal(list.length, 2);
});
});
describe('splice', () => {
it('should delete items', () => {
const list = new CircularList<string>(2);
list.push('1');
list.push('2');
list.splice(0, 1);
assert.equal(list.length, 1);
assert.equal(list.get(0), '2');
list.push('3');
list.splice(1, 1);
assert.equal(list.length, 1);
assert.equal(list.get(0), '2');
});
it('should insert items', () => {
const list = new CircularList<string>(2);
list.push('1');
list.splice(0, 0, '2');
assert.equal(list.length, 2);
assert.equal(list.get(0), '2');
assert.equal(list.get(1), '1');
list.splice(1, 0, '3');
assert.equal(list.length, 2);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '1');
});
it('should delete items then insert items', () => {
const list = new CircularList<string>(3);
list.push('1');
list.push('2');
list.splice(0, 1, '3', '4');
assert.equal(list.length, 3);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
assert.equal(list.get(2), '2');
});
it('should wrap the array correctly when more items are inserted than deleted', () => {
const list = new CircularList<string>(3);
list.push('1');
list.push('2');
list.splice(1, 0, '3', '4');
assert.equal(list.length, 3);
assert.equal(list.get(0), '3');
assert.equal(list.get(1), '4');
assert.equal(list.get(2), '2');
});
});
describe('trimStart', () => {
it('should remove items from the beginning of the list', () => {
const list = new CircularList<string>(5);
list.push('1');
list.push('2');
list.push('3');
list.push('4');
list.push('5');
list.trimStart(1);
assert.equal(list.length, 4);
assert.deepEqual(list.get(0), '2');
assert.deepEqual(list.get(1), '3');
assert.deepEqual(list.get(2), '4');
assert.deepEqual(list.get(3), '5');
list.trimStart(2);
assert.equal(list.length, 2);
assert.deepEqual(list.get(0), '4');
assert.deepEqual(list.get(1), '5');
});
it('should remove all items if the requested trim amount is larger than the list\'s length', () => {
const list = new CircularList<string>(5);
list.push('1');
list.trimStart(2);
assert.equal(list.length, 0);
});
});
describe('shiftElements', () => {
it('should not mutate the list when count is 0', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 0, 1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
});
it('should throw for invalid args', () => {
const list = new CircularList<number>(5);
list.push(1);
assert.throws(() => list.shiftElements(-1, 1, 1), 'start argument out of range');
assert.throws(() => list.shiftElements(1, 1, 1), 'start argument out of range');
assert.throws(() => list.shiftElements(0, 1, -1), 'Cannot shift elements in list beyond index 0');
});
it('should shift an element forward', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 1, 1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 1);
});
it('should shift elements forward', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.shiftElements(0, 2, 2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
assert.equal(list.get(2), 1);
assert.equal(list.get(3), 2);
});
it('should shift elements forward, expanding the list if needed', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(0, 2, 2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 1);
assert.equal(list.get(1), 2);
assert.equal(list.get(2), 1);
assert.equal(list.get(3), 2);
});
it('should shift elements forward, wrapping the list if needed', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
list.shiftElements(2, 2, 3);
assert.equal(list.length, 5);
assert.equal(list.get(0), 3);
assert.equal(list.get(1), 4);
assert.equal(list.get(2), 5);
assert.equal(list.get(3), 3);
assert.equal(list.get(4), 4);
});
it('should shift an element backwards', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.shiftElements(1, 1, -1);
assert.equal(list.length, 2);
assert.equal(list.get(0), 2);
assert.equal(list.get(1), 2);
});
it('should shift elements backwards', () => {
const list = new CircularList<number>(5);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.shiftElements(2, 2, -2);
assert.equal(list.length, 4);
assert.equal(list.get(0), 3);
assert.equal(list.get(1), 4);
assert.equal(list.get(2), 3);
assert.equal(list.get(3), 4);
});
});
});
+183
View File
@@ -0,0 +1,183 @@
/**
* Represents a circular list; a list with a maximum size that wraps around when push is called,
* overriding values at the start of the list.
* @module xterm/utils/CircularList
* @license MIT
*/
export class CircularList<T> {
private _array: T[];
private _startIndex: number;
private _length: number;
constructor(maxLength: number) {
this._array = new Array<T>(maxLength);
this._startIndex = 0;
this._length = 0;
}
public get maxLength(): number {
return this._array.length;
}
public set maxLength(newMaxLength: number) {
// Reconstruct array, starting at index 0. Only transfer values from the
// indexes 0 to length.
let newArray = new Array<T>(newMaxLength);
for (let i = 0; i < Math.min(newMaxLength, this.length); i++) {
newArray[i] = this._array[this._getCyclicIndex(i)];
}
this._array = newArray;
this._startIndex = 0;
}
public get length(): number {
return this._length;
}
public set length(newLength: number) {
if (newLength > this._length) {
for (let i = this._length; i < newLength; i++) {
this._array[i] = undefined;
}
}
this._length = newLength;
}
public get forEach(): (callbackfn: (value: T, index: number, array: T[]) => void) => void {
return this._array.forEach;
}
/**
* Gets the value at an index.
*
* Note that for performance reasons there is no bounds checking here, the index reference is
* circular so this should always return a value and never throw.
* @param index The index of the value to get.
* @return The value corresponding to the index.
*/
public get(index: number): T {
return this._array[this._getCyclicIndex(index)];
}
/**
* Sets the value at an index.
*
* Note that for performance reasons there is no bounds checking here, the index reference is
* circular so this should always return a value and never throw.
* @param index The index to set.
* @param value The value to set.
*/
public set(index: number, value: T): void {
this._array[this._getCyclicIndex(index)] = value;
}
/**
* Pushes a new value onto the list, wrapping around to the start of the array, overriding index 0
* if the maximum length is reached.
* @param value The value to push onto the list.
*/
public push(value: T): void {
this._array[this._getCyclicIndex(this._length)] = value;
if (this._length === this.maxLength) {
this._startIndex++;
if (this._startIndex === this.maxLength) {
this._startIndex = 0;
}
} else {
this._length++;
}
}
/**
* Removes and returns the last value on the list.
* @return The popped value.
*/
public pop(): T {
return this._array[this._getCyclicIndex(this._length-- - 1)];
}
/**
* Deletes and/or inserts items at a particular index (in that order). Unlike
* Array.prototype.splice, this operation does not return the deleted items as a new array in
* order to save creating a new array. Note that this operation may shift all values in the list
* in the worst case.
* @param start The index to delete and/or insert.
* @param deleteCount The number of elements to delete.
* @param items The items to insert.
*/
public splice(start: number, deleteCount: number, ...items: T[]): void {
if (deleteCount) {
for (let i = start; i < this._length - deleteCount; i++) {
this._array[this._getCyclicIndex(i)] = this._array[this._getCyclicIndex(i + deleteCount)];
}
this._length -= deleteCount;
}
if (items && items.length) {
for (let i = this._length - 1; i >= start; i--) {
this._array[this._getCyclicIndex(i + items.length)] = this._array[this._getCyclicIndex(i)];
}
for (let i = 0; i < items.length; i++) {
this._array[this._getCyclicIndex(start + i)] = items[i];
}
if (this._length + items.length > this.maxLength) {
this._startIndex += (this._length + items.length) - this.maxLength;
this._length = this.maxLength;
} else {
this._length += items.length;
}
}
}
/**
* Trims a number of items from the start of the list.
* @param count The number of items to remove.
*/
public trimStart(count: number): void {
if (count > this._length) {
count = this._length;
}
this._startIndex += count;
this._length -= count;
}
public shiftElements(start: number, count: number, offset: number): void {
if (count <= 0) {
return;
}
if (start < 0 || start >= this._length) {
throw new Error('start argument out of range');
}
if (start + offset < 0) {
throw new Error('Cannot shift elements in list beyond index 0');
}
if (offset > 0) {
for (let i = count - 1; i >= 0; i--) {
this.set(start + i + offset, this.get(start + i));
}
const expandListBy = (start + count + offset) - this._length;
if (expandListBy > 0) {
this._length += expandListBy;
while (this._length > this.maxLength) {
this._length--;
this._startIndex++;
}
}
} else {
for (let i = 0; i < count; i++) {
this.set(start + i + offset, this.get(start + i));
}
}
}
/**
* Gets the cyclic index for the specified regular index. The cyclic index can then be used on the
* backing array to get the element associated with the regular index.
* @param index The regular index.
* @returns The cyclic index.
*/
private _getCyclicIndex(index: number): number {
return (this._startIndex + index) % this.maxLength;
}
}
@@ -9,6 +9,6 @@
* @param {Array} array The array to search for the given element.
* @param {Object} el The element to look for into the array
*/
export let contains = function(arr, el) {
export function contains(arr: any[], el: any) {
return arr.indexOf(el) >= 0;
};
+53 -12
View File
@@ -71,7 +71,22 @@
resize: none;
}
.terminal .terminal-cursor {
.terminal a {
color: inherit;
text-decoration: none;
}
.terminal a:hover {
cursor: pointer;
text-decoration: underline;
}
.terminal a.xterm-invalid-link:hover {
cursor: text;
text-decoration: none;
}
.terminal.focus:not(.xterm-cursor-style-underline):not(.xterm-cursor-style-bar) .terminal-cursor {
background-color: #fff;
color: #000;
}
@@ -82,19 +97,41 @@
background-color: transparent;
}
.terminal.focus .terminal-cursor.blinking {
animation: blink-cursor 1.2s infinite step-end;
.terminal:not(.xterm-cursor-style-underline):not(.xterm-cursor-style-bar).focus.xterm-cursor-blink-on .terminal-cursor {
background-color: transparent;
color: inherit;
}
@keyframes blink-cursor {
0% {
background-color: #fff;
color: #000;
}
50% {
background-color: transparent;
color: #FFF;
}
.terminal.xterm-cursor-style-bar .terminal-cursor,
.terminal.xterm-cursor-style-underline .terminal-cursor {
position: relative;
}
.terminal.xterm-cursor-style-bar .terminal-cursor::before,
.terminal.xterm-cursor-style-underline .terminal-cursor::before {
content: "";
display: block;
position: absolute;
background-color: #fff;
}
.terminal.xterm-cursor-style-bar .terminal-cursor::before {
top: 0;
bottom: 0;
left: 0;
width: 1px;
}
.terminal.xterm-cursor-style-underline .terminal-cursor::before {
bottom: 0;
left: 0;
right: 0;
height: 1px;
}
.terminal.xterm-cursor-style-bar.focus.xterm-cursor-blink.xterm-cursor-blink-on .terminal-cursor::before,
.terminal.xterm-cursor-style-underline.focus.xterm-cursor-blink.xterm-cursor-blink-on .terminal-cursor::before {
background-color: transparent;
}
.terminal.xterm-cursor-style-bar.focus.xterm-cursor-blink .terminal-cursor::before,
.terminal.xterm-cursor-style-underline.focus.xterm-cursor-blink .terminal-cursor::before {
background-color: #fff;
}
.terminal .composition-view {
@@ -116,6 +153,10 @@
overflow-y: scroll;
}
.terminal .xterm-wide-char {
display: inline-block;
}
.terminal .xterm-rows {
position: absolute;
left: 0;
+440 -3194
View File
File diff suppressed because it is too large Load Diff
+7 -9
View File
@@ -4,16 +4,14 @@
"target": "es5",
"rootDir": "src",
"allowJs": true,
"outDir": "out",
"sourceMap": true
"outDir": "lib",
"sourceMap": true,
"removeComments": true
},
"include": [
"src/**/*"
],
"exclude": [
"addons",
"build",
"demo",
"dist",
"out",
"test",
"node_modules"
"src/addons/**/*"
]
}
+53
View File
@@ -0,0 +1,53 @@
{
"rules": {
"class-name": true,
"comment-format": [
true,
"check-space"
],
"indent": [
true,
"spaces"
],
"eofline": true,
"no-eval": true,
"no-internal-module": true,
"no-trailing-whitespace": true,
"no-unsafe-finally": true,
"no-var-keyword": true,
"quotemark": [
true,
"single"
],
"semicolon": [
true,
"always"
],
"triple-equals": [
true,
"allow-null-check"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"variable-name": [
true,
"ban-keywords"
],
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
]
}
}