How is copy paste possible?

2020-07-30 02:49发布

问题:

I was wondering after using computer for a long times it feels like copy paste was fundamental feature but I know it is not. So the question is how does this really work?

I thought of all ideas how this could have been implemented but I get stuck every time I come up with the different file formats like gif, jpg, txt, png, mp3, mp4, JSON, YML etc. and the further you go the complex it gets like shortcuts ,links and then there's directories. Like how it copies images that are in the search result in chrome whereas sometimes you can't copy something due to restriction also you can't select something then you can't copy it whereas sometimes even if you can't select in hierarchy the children are copied so how is it implemented.

But when someone asks me how does copy paste work generally I reply like: When something is copied then it puts the copied item to memory and when pasting it to somewhere the OS finds out the location to where it should be copied and replicates all the file to binary and copies it.

Which might not be true so can you explain how does it exactly work. Also it would be helpful to know how the code was written for copy paste.

回答1:

The first thing you need to realize is that "copy and paste" as well as "drag and drop" are a form of IPC (Inter-process communication) since the data is being transferred from one application to another. This mechanism is usually provided by the same subsystem or service which is responsible for managing the graphical user interface.

This subsystem provides a mechanism for "source" and "destination" applications to negotiate about the format of the data that should be transferred and if they "agree" on some common format then the data can be transferred.

An example to illustrate the concept:

  1. User selects the text in the web-browser and presses Ctrl+C.
  2. Browser tells the windowing system that it has some data available for copying. Note that no data is copied at this step.
  3. User opens a text editor and presses Ctrl+V.
  4. Text editor tells the windowing system to provide it the contents on the clipboard in plain-text format.
  5. Windowing system tells the browser to provide its shared data in plain-text format.
  6. Browser converts its data from HTML (or something else) to plain-text and transfers it to the text editor via windowing system. Note that this conversion is not always possible (depending on the formats and applications), hence you sometimes can't paste the copied data.

Technical details

  • On Windows this functionality is provided via Clipboard API as Ken White mentioned.
  • On Linux (and probably everywhere else) the clipboard functionality is not strictly speaking a part of the OS and is provided by the Window Server/Manager (which is really just a service process) via a windowing system protocol such as X protocol or Wayland.