Skip to content
This repository was archived by the owner on Mar 3, 2023. It is now read-only.

Use new native text-buffer implementation - #14435

Merged
maxbrunsfeld merged 44 commits into
masterfrom
mb-use-native-text-buffer
Jun 8, 2017
Merged

maxbrunsfeld merged 44 commits into
masterfrom
mb-use-native-text-buffer

Conversation

@maxbrunsfeld

@maxbrunsfeld maxbrunsfeld commented May 17, 2017 •

Copy link
Copy Markdown
Contributor

Summary

This pull request completely reimplements the TextBuffer class - Atom's core data structure representing editable text. The new implementation differs from the old one in several major ways:

  • The class is now implemented primarily in C++, as part of our native library superstring.
  • Instead of storing the text as a mutable array of lines, we store it as flat immutable string representing the file's original content, plus a Patch representing the user's unsaved changes. This is somewhat similar to the piece table data structure used in some other editors.
  • At the native level, the buffer supports snapshots - read-only views of the buffer that can be processed in background threads with no copying or locking, even while the buffer is being mutated on the main thread.
  • File I/O and transcoding is now handled by the native library, entirely on background threads and exposed via promises.

Motivation

For many purposes, the existing array-of-lines implementation was actually very fast; we've never observed slowness associated with the querying or mutating of the text itself. This is a testament to V8's highly efficient String operations. However, there are many operations in Atom that use the TextBuffer and would benefit from being dropped to C++ and/or being moved to a background thread.

Here are some examples of this that have already been addressed in this PR:

  • Previously, saving and loading a TextBuffer required its entire contents to be represented as a single JavaScript String. V8 has a hard limit on string length, so this would cause errors (Uncaught RangeError: Invalid string length #7210). Now, saving and loading are done in a background thread in C++, with minimal copying of data.
  • When the file associated with an unmodified TextBuffer changes on disk, we diff the file's new contents with the buffer's contents in order to update the buffer in a way that preserves marker positions. Previously, this diff computation caused unresponsiveness in large files (Add file-size threshold for diff-based reload text-buffer#153). Now the diff is performed in C++ and on a background thread.
  • Whenever the application is idle, we serialize the state of the window and persist it, so that we can restore it even if Atom crashes or power is lost. Previously, persisting a large file's text would cause hangs, so we had to disable this safety feature for large files (Disable periodic serialization for buffers > 2MB #13583). Now, because of our new representation of the buffer, we are able to efficiently serialize just the outstanding changes, so we can re-enable the feature for arbitrarily large files.
  • The line-ending-selector needs to detect what type of line endings a TextBuffer uses. Because we support files with mixed line endings, this entails scanning the entire buffer. Previously, this would take upwards of 50ms for a large file. Now, the search is performed asynchronously so that it causes no noticeable lag.

In addition to these improvements, this PR will make it very easy to optimize other features. Here are some follow-up PRs that I have in mind:

  • When changing a large amount of text at once, indexing the new text in the DisplayLayer takes a long time. This is one of the main reasons that pasting a huge amount of text is slow. Some of this character-by-character computation could probably be done much faster in C++.
  • Currently, using the find-and-replace package in a very large file can cause hangs when searches produce more than a hundred thousand results. We will now be able to run searches entirely in a background thread, eliminating any lag.
  • Populating the autocomplete-plus package's SymbolStore can take a very long time for large files, so we had to disable it for large files. Fuzzy matching should be able to be performed in C++ on a background thread, eliminating this restriction.

Implementation details

Our new representation of the buffer:

Suppose I create a TextBuffer with some initial text and then make three edits:

const buffer = new TextBuffer('abc\ndefg\nhijkl')
buffer.setTextInRange([[0, 2], [0, 3]], "C")
buffer.setTextInRange([[2, 0], [2, 1]], "H")
buffer.setTextInRange([[1, 1], [1, 2]], "E")
assert.equal(buffer.getText(), 'abC\ndEfg\nHijkl')

This buffer is now represented internally like this:

graph-1

The buffer is composed of two layers. The first layer stores the buffer's initial text as a flat, immutable string. This makes freshly-opened files very compact in memory. The second layer stores the unsaved edits in an object that we call a Patch. The Patch is structured as a splay tree so that mutations and queries are very efficient, especially in areas that have recently been accessed.

Then, suppose I begin some asynchronous operation like saving the buffer to disk, or searching
the buffer for a regex. Then, while that operation is still happening, I make some additional edits:

const savePromise = buffer.save()
buffer.setTextInRange([[0, 0], [0, 1]], 'A')
buffer.setTextInRange([[2, 4], [2, 5]], 'L')
assert.equal(buffer.getText(), 'AbC\ndEfg\nHijkL')

At that point, the buffer's internal state would look like this:

graph2

There are now three layers. Because the asynchronous save is still in progress, further changes that we make to the buffer are saved in a new Patch. When the save completes, we flatten the text down into one layer again.

Effect on packages

I don't believe making save async has affected any of our bundled packages' functionality, though it has caused some test failures that I've had to fix:

Depends on atom/text-buffer#225
Depends on atom/superstring#5
Depends on atom/node-pathwatcher#121
Depends on atom/whitespace#157

Closes #7210
Closes #11554
Closes #11012

@maxbrunsfeld
maxbrunsfeld force-pushed the mb-use-native-text-buffer branch from ffe27b4 to abc9b36 Compare May 17, 2017 14:27
@maxbrunsfeld
maxbrunsfeld changed the base branch from tj-upgrade-electron to master May 19, 2017 14:37
@maxbrunsfeld
maxbrunsfeld force-pushed the mb-use-native-text-buffer branch from abc9b36 to a8594d4 Compare May 19, 2017 14:45
We used to emit buffer added events before the buffers were loaded, so we
would end up fetching their git status soon afterwords, when they emitted
the did-reload event.
@maxbrunsfeld

maxbrunsfeld commented May 31, 2017 •

Copy link
Copy Markdown
Contributor Author

@atom/maintainers I think this PR is ready for others to test.

@ungb @Ben3eeE Some areas that could use testing:

Loading and saving buffers. This includes actual I/O as well as encoding/decoding. Areas in which I could imagine regressions:

  • Opening a file on a slow drive (e.g. sshfs and other network file systems)
  • Opening files in non-UTF8 encodings
  • Changing files on disk while they are open in Atom
  • Handling errors when reading/writing files (e.g. permissions issues)
  • Lots of simultaneous IO operations (e.g. multiple saves at the same time, multiple on-disk changes in rapid succession)

Working with buffers with large numbers of unsaved edits. All the operations that I've tested perform as well or better than before, but because of the new buffer representation, I could imagine some operations getting slower. We need to make sure that doesn't happen. Some types of operations I'm thinking of:

  • Performing a regex replace with lots of search results
  • Indenting large chunks of the buffer
  • Pasting large amounts of text
  • Normal editing after doing any of the above

Editing very large files. This PR expands the size of files that can be reasonably edited in Atom. But there are still issues with files that are sufficiently large. I'm aware of some issues, like the fact that cursors and scrollbars don't work after a certain number of lines (#13459). Overall, what I care about is that this PR significantly increases the file size that we can work with and does not make any behaviors worse with large files.

32-bit platforms. I did some testing on a 32-bit linux VM, but possibly not enough.

@maxbrunsfeld

Copy link
Copy Markdown
Contributor Author

Download links for convenience:

miketheman added a commit to miketheman/language-diff that referenced this pull request Jun 15, 2017
Resolves #12
Refs atom/atom#14435

Signed-off-by: Mike Fiedler <[email protected]>
@maxbrunsfeld maxbrunsfeld mentioned this pull request Jun 15, 2017
1 task
kuychaco added a commit to atom/github that referenced this pull request Jun 24, 2017
Context: the `TextBuffer.save` method became async in atom/atom#14435;
instead of doing a synchronous write, it initiates an asynchronous write
and return a promise when the write completes.
Comment thread src/pane.coffee
@destroyItem(item) for item in @getItems()
return
Promise.all(
@getItems().map(@destroyItem.bind(this))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maxbrunsfeld
Noticed while I read code, using bind here is bad.
Since Array.prototype.map pass item index as 2nd arg, which goes to @destroyItems which treat 2nd arg as force switch. Which is not intentional I believe.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, thanks for catching that @t9md! Are you interested in opening a PR fixing that bug?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I will try tommorrow.

Comment thread src/pane.coffee
Promise.all(
@getItems()
.filter((item) => item isnt @activeItem)
.map(@destroyItem.bind(this))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here too.

@maxbrunsfeld

Copy link
Copy Markdown
Contributor Author

@Glavin001 @joefitzgerald The TextBuffer.onWillSave hook now allows you do perform async work before the buffer is saved. You just need to return a promise from the event handler. For example:

buffer.onWillSave(async () => {
  await somethingSlow()
})

See atom/text-buffer#254.

This change has been released in Atom v1.21.0-beta1.

@Glavin001

Copy link
Copy Markdown
Contributor

Awesome! Thank you, @maxbrunsfeld!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Uncaught Error: toString failed Atom hangs when an opened file is written to Uncaught RangeError: Invalid string length

8 participants