1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsCopySupport.h"
8 #include "nsIDocumentEncoder.h"
9 #include "nsISupports.h"
10 #include "nsIContent.h"
11 #include "nsIComponentManager.h"
12 #include "nsIServiceManager.h"
13 #include "nsIClipboard.h"
14 #include "nsIFormControl.h"
15 #include "nsWidgetsCID.h"
17 #include "nsISupportsPrimitives.h"
19 #include "imgIContainer.h"
20 #include "imgIRequest.h"
21 #include "nsFocusManager.h"
22 #include "mozilla/dom/DataTransfer.h"
24 #include "nsIDocShell.h"
25 #include "nsIContentViewerEdit.h"
26 #include "nsIClipboardHelper.h"
27 #include "nsISelectionController.h"
29 #include "nsPIDOMWindow.h"
30 #include "mozilla/dom/Document.h"
31 #include "nsIHTMLDocument.h"
32 #include "nsGkAtoms.h"
35 #include "nsIURIMutator.h"
36 #include "nsISimpleEnumerator.h"
37 #include "nsGenericHTMLElement.h"
40 #include "nsIImageLoadingContent.h"
41 #include "nsIInterfaceRequestorUtils.h"
42 #include "nsContentUtils.h"
43 #include "nsContentCID.h"
46 # include "nsCExternalHandlerService.h"
47 # include "nsEscape.h"
48 # include "nsIMIMEInfo.h"
49 # include "nsIMIMEService.h"
51 # include "nsReadableUtils.h"
52 # include "nsXULAppAPI.h"
55 #include "mozilla/ContentEvents.h"
56 #include "mozilla/dom/Element.h"
57 #include "mozilla/EventDispatcher.h"
58 #include "mozilla/Preferences.h"
59 #include "mozilla/PresShell.h"
60 #include "mozilla/dom/Selection.h"
61 #include "mozilla/IntegerRange.h"
63 using namespace mozilla
;
64 using namespace mozilla::dom
;
66 static NS_DEFINE_CID(kCClipboardCID
, NS_CLIPBOARD_CID
);
67 static NS_DEFINE_CID(kCTransferableCID
, NS_TRANSFERABLE_CID
);
68 static NS_DEFINE_CID(kHTMLConverterCID
, NS_HTMLFORMATCONVERTER_CID
);
70 // copy string data onto the transferable
71 static nsresult
AppendString(nsITransferable
* aTransferable
,
72 const nsAString
& aString
, const char* aFlavor
);
74 // copy HTML node data
75 static nsresult
AppendDOMNode(nsITransferable
* aTransferable
,
79 // copy image as file promise onto the transferable
80 static nsresult
AppendImagePromise(nsITransferable
* aTransferable
,
81 imgIRequest
* aImgRequest
,
82 nsIImageLoadingContent
* aImageElement
);
85 static nsresult
EncodeForTextUnicode(nsIDocumentEncoder
& aEncoder
,
86 Document
& aDocument
, Selection
* aSelection
,
87 uint32_t aAdditionalEncoderFlags
,
88 bool& aEncodedAsTextHTMLResult
,
89 nsAutoString
& aSerializationResult
) {
90 // note that we assign text/unicode as mime type, but in fact
91 // nsHTMLCopyEncoder ignore it and use text/html or text/plain depending where
92 // the selection is. if it is a selection into input/textarea element or in a
93 // html content with pre-wrap style : text/plain. Otherwise text/html. see
94 // nsHTMLCopyEncoder::SetSelection
95 nsAutoString mimeType
;
96 mimeType
.AssignLiteral(kUnicodeMime
);
98 // Do the first and potentially trial encoding as preformatted and raw.
99 uint32_t flags
= aAdditionalEncoderFlags
|
100 nsIDocumentEncoder::OutputPreformatted
|
101 nsIDocumentEncoder::OutputRaw
|
102 nsIDocumentEncoder::OutputForPlainTextClipboardCopy
;
104 nsresult rv
= aEncoder
.Init(&aDocument
, mimeType
, flags
);
105 NS_ENSURE_SUCCESS(rv
, rv
);
107 rv
= aEncoder
.SetSelection(aSelection
);
108 NS_ENSURE_SUCCESS(rv
, rv
);
110 // SetSelection set the mime type to text/plain if the selection is inside a
112 rv
= aEncoder
.GetMimeType(mimeType
);
113 NS_ENSURE_SUCCESS(rv
, rv
);
114 bool selForcedTextPlain
= mimeType
.EqualsLiteral(kTextMime
);
117 rv
= aEncoder
.EncodeToString(buf
);
118 NS_ENSURE_SUCCESS(rv
, rv
);
120 rv
= aEncoder
.GetMimeType(mimeType
);
121 NS_ENSURE_SUCCESS(rv
, rv
);
123 if (!selForcedTextPlain
&& mimeType
.EqualsLiteral(kTextMime
)) {
124 // SetSelection and EncodeToString use this case to signal that text/plain
125 // was forced because the document is either not an nsIHTMLDocument or it's
126 // XHTML. We want to pretty print XHTML but not non-nsIHTMLDocuments.
127 nsCOMPtr
<nsIHTMLDocument
> htmlDoc
= do_QueryInterface(&aDocument
);
129 selForcedTextPlain
= true;
133 // The mime type is ultimately text/html if the encoder successfully encoded
134 // the selection as text/html.
135 aEncodedAsTextHTMLResult
= mimeType
.EqualsLiteral(kHTMLMime
);
137 if (selForcedTextPlain
) {
138 // Nothing to do. buf contains the final, preformatted, raw text/plain.
139 aSerializationResult
.Assign(buf
);
141 // Redo the encoding, but this time use pretty printing.
143 nsIDocumentEncoder::OutputSelectionOnly
|
144 nsIDocumentEncoder::OutputAbsoluteLinks
|
145 nsIDocumentEncoder::SkipInvisibleContent
|
146 nsIDocumentEncoder::OutputDropInvisibleBreak
|
147 (aAdditionalEncoderFlags
& (nsIDocumentEncoder::OutputNoScriptContent
|
148 nsIDocumentEncoder::OutputRubyAnnotation
));
150 mimeType
.AssignLiteral(kTextMime
);
151 rv
= aEncoder
.Init(&aDocument
, mimeType
, flags
);
152 NS_ENSURE_SUCCESS(rv
, rv
);
154 rv
= aEncoder
.SetSelection(aSelection
);
155 NS_ENSURE_SUCCESS(rv
, rv
);
157 rv
= aEncoder
.EncodeToString(aSerializationResult
);
158 NS_ENSURE_SUCCESS(rv
, rv
);
164 static nsresult
EncodeAsTextHTMLWithContext(
165 nsIDocumentEncoder
& aEncoder
, Document
& aDocument
, Selection
* aSelection
,
166 uint32_t aEncoderFlags
, nsAutoString
& aTextHTMLEncodingResult
,
167 nsAutoString
& aHTMLParentsBufResult
, nsAutoString
& aHTMLInfoBufResult
) {
168 nsAutoString mimeType
;
169 mimeType
.AssignLiteral(kHTMLMime
);
170 nsresult rv
= aEncoder
.Init(&aDocument
, mimeType
, aEncoderFlags
);
171 NS_ENSURE_SUCCESS(rv
, rv
);
173 rv
= aEncoder
.SetSelection(aSelection
);
174 NS_ENSURE_SUCCESS(rv
, rv
);
176 rv
= aEncoder
.EncodeToStringWithContext(
177 aHTMLParentsBufResult
, aHTMLInfoBufResult
, aTextHTMLEncodingResult
);
178 NS_ENSURE_SUCCESS(rv
, rv
);
182 struct EncodedDocumentWithContext
{
183 // When determening `mSerializationForTextUnicode`, `text/unicode` is passed
184 // as mime type to the encoder. It uses this as a switch to decide whether to
185 // encode the document as `text/html` or `text/plain`. It is `true` iff
186 // `text/html` was used.
187 bool mUnicodeEncodingIsTextHTML
= false;
189 // The serialized document when encoding the document with `text/unicode`. See
190 // comment of `mUnicodeEncodingIsTextHTML`.
191 nsAutoString mSerializationForTextUnicode
;
193 // When `mUnicodeEncodingIsTextHTML` is true, this is the serialized document
194 // using `text/html`. Its value may differ from `mSerializationForTextHTML`,
195 // because different flags were passed to the encoder.
196 nsAutoString mSerializationForTextHTML
;
198 // When `mUnicodeEncodingIsTextHTML` is true, this contains the serialized
199 // ancestor elements.
200 nsAutoString mHTMLContextBuffer
;
202 // When `mUnicodeEncodingIsTextHTML` is true, this contains numbers
203 // identifying where in the context the serialization came from.
204 nsAutoString mHTMLInfoBuffer
;
208 * @param aSelection Can be nullptr.
209 * @param aAdditionalEncoderFlags nsIDocumentEncoder flags.
211 static nsresult
EncodeDocumentWithContext(
212 Document
& aDocument
, Selection
* aSelection
,
213 uint32_t aAdditionalEncoderFlags
,
214 EncodedDocumentWithContext
& aEncodedDocumentWithContext
) {
215 nsCOMPtr
<nsIDocumentEncoder
> docEncoder
= do_createHTMLCopyEncoder();
217 bool unicodeEncodingIsTextHTML
{false};
218 nsAutoString serializationForTextUnicode
;
219 nsresult rv
= EncodeForTextUnicode(
220 *docEncoder
, aDocument
, aSelection
, aAdditionalEncoderFlags
,
221 unicodeEncodingIsTextHTML
, serializationForTextUnicode
);
222 NS_ENSURE_SUCCESS(rv
, rv
);
224 nsAutoString serializationForTextHTML
;
225 nsAutoString htmlContextBuffer
;
226 nsAutoString htmlInfoBuffer
;
227 if (unicodeEncodingIsTextHTML
) {
228 // Redo the encoding, but this time use the passed-in flags.
229 // Don't allow wrapping of CJK strings.
230 rv
= EncodeAsTextHTMLWithContext(
231 *docEncoder
, aDocument
, aSelection
,
232 aAdditionalEncoderFlags
|
233 nsIDocumentEncoder::OutputDisallowLineBreaking
,
234 serializationForTextHTML
, htmlContextBuffer
, htmlInfoBuffer
);
235 NS_ENSURE_SUCCESS(rv
, rv
);
238 aEncodedDocumentWithContext
= {
239 unicodeEncodingIsTextHTML
, std::move(serializationForTextUnicode
),
240 std::move(serializationForTextHTML
), std::move(htmlContextBuffer
),
241 std::move(htmlInfoBuffer
)};
246 static nsresult
CreateTransferable(
247 const EncodedDocumentWithContext
& aEncodedDocumentWithContext
,
248 Document
& aDocument
, nsCOMPtr
<nsITransferable
>& aTransferable
) {
251 aTransferable
= do_CreateInstance(kCTransferableCID
);
252 NS_ENSURE_TRUE(aTransferable
, NS_ERROR_NULL_POINTER
);
254 aTransferable
->Init(aDocument
.GetLoadContext());
255 if (aEncodedDocumentWithContext
.mUnicodeEncodingIsTextHTML
) {
256 // Set up a format converter so that clipboard flavor queries work.
257 // This converter isn't really used for conversions.
258 nsCOMPtr
<nsIFormatConverter
> htmlConverter
=
259 do_CreateInstance(kHTMLConverterCID
);
260 aTransferable
->SetConverter(htmlConverter
);
262 if (!aEncodedDocumentWithContext
.mSerializationForTextHTML
.IsEmpty()) {
263 // Add the html DataFlavor to the transferable
264 rv
= AppendString(aTransferable
,
265 aEncodedDocumentWithContext
.mSerializationForTextHTML
,
267 NS_ENSURE_SUCCESS(rv
, rv
);
270 // Add the htmlcontext DataFlavor to the transferable. Even if the context
271 // buffer is empty, this flavor should be attached to the transferable.
272 rv
= AppendString(aTransferable
,
273 aEncodedDocumentWithContext
.mHTMLContextBuffer
,
275 NS_ENSURE_SUCCESS(rv
, rv
);
277 if (!aEncodedDocumentWithContext
.mHTMLInfoBuffer
.IsEmpty()) {
278 // Add the htmlinfo DataFlavor to the transferable
279 rv
= AppendString(aTransferable
,
280 aEncodedDocumentWithContext
.mHTMLInfoBuffer
, kHTMLInfo
);
281 NS_ENSURE_SUCCESS(rv
, rv
);
284 if (!aEncodedDocumentWithContext
.mSerializationForTextUnicode
.IsEmpty()) {
286 // Add the unicode DataFlavor to the transferable
287 // If we didn't have this, then nsDataObj::GetData matches
288 // text/unicode against the kURLMime flavour which is not desirable
289 // (eg. when pasting into Notepad)
291 AppendString(aTransferable
,
292 aEncodedDocumentWithContext
.mSerializationForTextUnicode
,
294 NS_ENSURE_SUCCESS(rv
, rv
);
297 // Try and get source URI of the items that are being dragged
298 nsIURI
* uri
= aDocument
.GetDocumentURI();
301 nsresult rv
= uri
->GetSpec(spec
);
302 NS_ENSURE_SUCCESS(rv
, rv
);
303 if (!spec
.IsEmpty()) {
304 nsAutoString shortcut
;
305 AppendUTF8toUTF16(spec
, shortcut
);
307 // Add the URL DataFlavor to the transferable. Don't use kURLMime,
308 // as it will cause an unnecessary UniformResourceLocator to be
309 // added which confuses some apps eg. Outlook 2000 - (See Bug
310 // 315370). Don't use kURLDataMime, as it will cause a bogus 'url '
311 // flavor to show up on the Mac clipboard, confusing other apps,
312 // like Terminal (see bug 336012).
313 rv
= AppendString(aTransferable
, shortcut
, kURLPrivateMime
);
314 NS_ENSURE_SUCCESS(rv
, rv
);
318 if (!aEncodedDocumentWithContext
.mSerializationForTextUnicode
.IsEmpty()) {
319 // Add the unicode DataFlavor to the transferable
321 AppendString(aTransferable
,
322 aEncodedDocumentWithContext
.mSerializationForTextUnicode
,
324 NS_ENSURE_SUCCESS(rv
, rv
);
331 static nsresult
PutToClipboard(
332 const EncodedDocumentWithContext
& aEncodedDocumentWithContext
,
333 int16_t aClipboardID
, Document
& aDocument
) {
335 nsCOMPtr
<nsIClipboard
> clipboard
= do_GetService(kCClipboardCID
, &rv
);
336 NS_ENSURE_SUCCESS(rv
, rv
);
337 NS_ENSURE_TRUE(clipboard
, NS_ERROR_NULL_POINTER
);
339 nsCOMPtr
<nsITransferable
> transferable
;
340 rv
= CreateTransferable(aEncodedDocumentWithContext
, aDocument
, transferable
);
341 NS_ENSURE_SUCCESS(rv
, rv
);
343 rv
= clipboard
->SetData(transferable
, nullptr, aClipboardID
);
344 NS_ENSURE_SUCCESS(rv
, rv
);
349 nsresult
nsCopySupport::EncodeDocumentWithContextAndPutToClipboard(
350 Selection
* aSel
, Document
* aDoc
, int16_t aClipboardID
,
351 bool aWithRubyAnnotation
) {
352 NS_ENSURE_TRUE(aDoc
, NS_ERROR_NULL_POINTER
);
354 uint32_t additionalFlags
= nsIDocumentEncoder::SkipInvisibleContent
;
355 if (aWithRubyAnnotation
) {
356 additionalFlags
|= nsIDocumentEncoder::OutputRubyAnnotation
;
359 EncodedDocumentWithContext encodedDocumentWithContext
;
360 nsresult rv
= EncodeDocumentWithContext(*aDoc
, aSel
, additionalFlags
,
361 encodedDocumentWithContext
);
362 NS_ENSURE_SUCCESS(rv
, rv
);
364 rv
= PutToClipboard(encodedDocumentWithContext
, aClipboardID
, *aDoc
);
365 NS_ENSURE_SUCCESS(rv
, rv
);
370 nsresult
nsCopySupport::ClearSelectionCache() {
372 nsCOMPtr
<nsIClipboard
> clipboard
= do_GetService(kCClipboardCID
, &rv
);
373 clipboard
->EmptyClipboard(nsIClipboard::kSelectionCache
);
378 * @param aAdditionalEncoderFlags flags of `nsIDocumentEncoder`.
379 * @param aTransferable Needs to be not `nullptr`.
381 static nsresult
EncodeDocumentWithContextAndCreateTransferable(
382 Document
& aDocument
, Selection
* aSelection
,
383 uint32_t aAdditionalEncoderFlags
, nsITransferable
** aTransferable
) {
384 NS_ENSURE_TRUE(aTransferable
, NS_ERROR_NULL_POINTER
);
386 // Clear the output parameter for the transferable.
387 *aTransferable
= nullptr;
389 EncodedDocumentWithContext encodedDocumentWithContext
;
391 EncodeDocumentWithContext(aDocument
, aSelection
, aAdditionalEncoderFlags
,
392 encodedDocumentWithContext
);
393 NS_ENSURE_SUCCESS(rv
, rv
);
395 nsCOMPtr
<nsITransferable
> transferable
;
396 rv
= CreateTransferable(encodedDocumentWithContext
, aDocument
, transferable
);
397 NS_ENSURE_SUCCESS(rv
, rv
);
399 transferable
.swap(*aTransferable
);
403 nsresult
nsCopySupport::GetTransferableForSelection(
404 Selection
* aSel
, Document
* aDoc
, nsITransferable
** aTransferable
) {
405 NS_ENSURE_TRUE(aDoc
, NS_ERROR_NULL_POINTER
);
406 NS_ENSURE_TRUE(aTransferable
, NS_ERROR_NULL_POINTER
);
408 const uint32_t additionalFlags
= nsIDocumentEncoder::SkipInvisibleContent
;
409 return EncodeDocumentWithContextAndCreateTransferable(
410 *aDoc
, aSel
, additionalFlags
, aTransferable
);
413 nsresult
nsCopySupport::GetTransferableForNode(
414 nsINode
* aNode
, Document
* aDoc
, nsITransferable
** aTransferable
) {
415 NS_ENSURE_TRUE(aNode
, NS_ERROR_NULL_POINTER
);
416 NS_ENSURE_TRUE(aDoc
, NS_ERROR_NULL_POINTER
);
417 NS_ENSURE_TRUE(aTransferable
, NS_ERROR_NULL_POINTER
);
419 // Make a temporary selection with aNode in a single range.
420 // XXX We should try to get rid of the Selection object here.
422 RefPtr
<Selection
> selection
= new Selection();
423 RefPtr
<nsRange
> range
= new nsRange(aNode
);
425 range
->SelectNode(*aNode
, result
);
426 if (NS_WARN_IF(result
.Failed())) {
427 return result
.StealNSResult();
429 selection
->AddRangeInternal(*range
, aDoc
, result
);
430 if (NS_WARN_IF(result
.Failed())) {
431 return result
.StealNSResult();
433 // It's not the primary selection - so don't skip invisible content.
434 uint32_t additionalFlags
= 0;
435 return EncodeDocumentWithContextAndCreateTransferable(
436 *aDoc
, selection
, additionalFlags
, aTransferable
);
439 nsresult
nsCopySupport::GetContents(const nsACString
& aMimeType
,
440 uint32_t aFlags
, Selection
* aSel
,
441 Document
* aDoc
, nsAString
& outdata
) {
442 nsCOMPtr
<nsIDocumentEncoder
> docEncoder
=
443 do_createDocumentEncoder(PromiseFlatCString(aMimeType
).get());
444 NS_ENSURE_TRUE(docEncoder
, NS_ERROR_FAILURE
);
446 uint32_t flags
= aFlags
| nsIDocumentEncoder::SkipInvisibleContent
;
448 if (aMimeType
.EqualsLiteral("text/plain"))
449 flags
|= nsIDocumentEncoder::OutputPreformatted
;
451 NS_ConvertASCIItoUTF16
unicodeMimeType(aMimeType
);
453 nsresult rv
= docEncoder
->Init(aDoc
, unicodeMimeType
, flags
);
454 if (NS_FAILED(rv
)) return rv
;
457 rv
= docEncoder
->SetSelection(aSel
);
458 if (NS_FAILED(rv
)) return rv
;
461 // encode the selection
462 return docEncoder
->EncodeToString(outdata
);
465 nsresult
nsCopySupport::ImageCopy(nsIImageLoadingContent
* aImageElement
,
466 nsILoadContext
* aLoadContext
,
467 int32_t aCopyFlags
) {
470 // create a transferable for putting data on the Clipboard
471 nsCOMPtr
<nsITransferable
> trans(do_CreateInstance(kCTransferableCID
, &rv
));
472 NS_ENSURE_SUCCESS(rv
, rv
);
473 trans
->Init(aLoadContext
);
475 if (aCopyFlags
& nsIContentViewerEdit::COPY_IMAGE_TEXT
) {
476 // get the location from the element
477 nsCOMPtr
<nsIURI
> uri
;
478 rv
= aImageElement
->GetCurrentURI(getter_AddRefs(uri
));
479 NS_ENSURE_SUCCESS(rv
, rv
);
480 NS_ENSURE_TRUE(uri
, NS_ERROR_FAILURE
);
482 nsAutoCString location
;
483 rv
= uri
->GetSpec(location
);
484 NS_ENSURE_SUCCESS(rv
, rv
);
486 // append the string to the transferable
487 rv
= AppendString(trans
, NS_ConvertUTF8toUTF16(location
), kUnicodeMime
);
488 NS_ENSURE_SUCCESS(rv
, rv
);
491 if (aCopyFlags
& nsIContentViewerEdit::COPY_IMAGE_HTML
) {
492 // append HTML data to the transferable
493 nsCOMPtr
<nsINode
> node(do_QueryInterface(aImageElement
, &rv
));
494 NS_ENSURE_SUCCESS(rv
, rv
);
496 rv
= AppendDOMNode(trans
, node
);
497 NS_ENSURE_SUCCESS(rv
, rv
);
500 if (aCopyFlags
& nsIContentViewerEdit::COPY_IMAGE_DATA
) {
501 // get the image data and its request from the element
502 nsCOMPtr
<imgIRequest
> imgRequest
;
503 nsCOMPtr
<imgIContainer
> image
= nsContentUtils::GetImageFromContent(
504 aImageElement
, getter_AddRefs(imgRequest
));
505 NS_ENSURE_TRUE(image
, NS_ERROR_FAILURE
);
508 rv
= AppendImagePromise(trans
, imgRequest
, aImageElement
);
509 NS_ENSURE_SUCCESS(rv
, rv
);
512 // copy the image data onto the transferable
513 rv
= trans
->SetTransferData(kNativeImageMime
, image
);
514 NS_ENSURE_SUCCESS(rv
, rv
);
518 nsCOMPtr
<nsIClipboard
> clipboard(do_GetService(kCClipboardCID
, &rv
));
519 NS_ENSURE_SUCCESS(rv
, rv
);
521 // check whether the system supports the selection clipboard or not.
522 bool selectionSupported
;
523 rv
= clipboard
->SupportsSelectionClipboard(&selectionSupported
);
524 NS_ENSURE_SUCCESS(rv
, rv
);
526 // put the transferable on the clipboard
527 if (selectionSupported
) {
528 rv
= clipboard
->SetData(trans
, nullptr, nsIClipboard::kSelectionClipboard
);
529 NS_ENSURE_SUCCESS(rv
, rv
);
532 return clipboard
->SetData(trans
, nullptr, nsIClipboard::kGlobalClipboard
);
535 static nsresult
AppendString(nsITransferable
* aTransferable
,
536 const nsAString
& aString
, const char* aFlavor
) {
539 nsCOMPtr
<nsISupportsString
> data(
540 do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID
, &rv
));
541 NS_ENSURE_SUCCESS(rv
, rv
);
543 rv
= data
->SetData(aString
);
544 NS_ENSURE_SUCCESS(rv
, rv
);
546 rv
= aTransferable
->AddDataFlavor(aFlavor
);
547 NS_ENSURE_SUCCESS(rv
, rv
);
549 return aTransferable
->SetTransferData(aFlavor
, data
);
552 static nsresult
AppendDOMNode(nsITransferable
* aTransferable
,
557 nsCOMPtr
<nsIDocumentEncoder
> docEncoder
= do_createHTMLCopyEncoder();
559 // get document for the encoder
560 nsCOMPtr
<Document
> document
= aDOMNode
->OwnerDoc();
562 // Note that XHTML is not counted as HTML here, because we can't copy it
563 // properly (all the copy code for non-plaintext assumes using HTML
564 // serializers and parsers is OK, and those mess up XHTML).
565 DebugOnly
<nsCOMPtr
<nsIHTMLDocument
>> htmlDoc
=
566 nsCOMPtr
<nsIHTMLDocument
>(do_QueryInterface(document
, &rv
));
567 NS_ENSURE_SUCCESS(rv
, NS_OK
);
569 NS_ENSURE_TRUE(document
->IsHTMLDocument(), NS_OK
);
571 // init encoder with document and node
573 docEncoder
->NativeInit(document
, NS_LITERAL_STRING(kHTMLMime
),
574 nsIDocumentEncoder::OutputAbsoluteLinks
|
575 nsIDocumentEncoder::OutputEncodeBasicEntities
);
576 NS_ENSURE_SUCCESS(rv
, rv
);
578 rv
= docEncoder
->SetNode(aDOMNode
);
579 NS_ENSURE_SUCCESS(rv
, rv
);
581 // serialize to string
582 nsAutoString html
, context
, info
;
583 rv
= docEncoder
->EncodeToStringWithContext(context
, info
, html
);
584 NS_ENSURE_SUCCESS(rv
, rv
);
586 // copy them to the transferable
587 if (!html
.IsEmpty()) {
588 rv
= AppendString(aTransferable
, html
, kHTMLMime
);
589 NS_ENSURE_SUCCESS(rv
, rv
);
592 if (!info
.IsEmpty()) {
593 rv
= AppendString(aTransferable
, info
, kHTMLInfo
);
594 NS_ENSURE_SUCCESS(rv
, rv
);
597 // add a special flavor, even if we don't have html context data
598 return AppendString(aTransferable
, context
, kHTMLContext
);
602 static nsresult
AppendImagePromise(nsITransferable
* aTransferable
,
603 imgIRequest
* aImgRequest
,
604 nsIImageLoadingContent
* aImageElement
) {
607 NS_ENSURE_TRUE(aImgRequest
, NS_OK
);
609 uint32_t imageStatus
;
610 rv
= aImgRequest
->GetImageStatus(&imageStatus
);
611 NS_ENSURE_SUCCESS(rv
, rv
);
612 if (!(imageStatus
& imgIRequest::STATUS_FRAME_COMPLETE
) ||
613 (imageStatus
& imgIRequest::STATUS_ERROR
)) {
618 rv
= aImgRequest
->GetMultipart(&isMultipart
);
619 NS_ENSURE_SUCCESS(rv
, rv
);
624 nsCOMPtr
<nsINode
> node
= do_QueryInterface(aImageElement
, &rv
);
625 NS_ENSURE_SUCCESS(rv
, rv
);
627 // Fix the file extension in the URL if necessary
628 nsCOMPtr
<nsIMIMEService
> mimeService
=
629 do_GetService(NS_MIMESERVICE_CONTRACTID
);
630 NS_ENSURE_TRUE(mimeService
, NS_OK
);
632 nsCOMPtr
<nsIURI
> imgUri
;
633 rv
= aImgRequest
->GetFinalURI(getter_AddRefs(imgUri
));
634 NS_ENSURE_SUCCESS(rv
, rv
);
636 nsCOMPtr
<nsIURL
> imgUrl
= do_QueryInterface(imgUri
);
637 NS_ENSURE_TRUE(imgUrl
, NS_OK
);
639 nsAutoCString extension
;
640 rv
= imgUrl
->GetFileExtension(extension
);
641 NS_ENSURE_SUCCESS(rv
, rv
);
644 rv
= aImgRequest
->GetMimeType(getter_Copies(mimeType
));
645 NS_ENSURE_SUCCESS(rv
, rv
);
647 nsCOMPtr
<nsIMIMEInfo
> mimeInfo
;
648 mimeService
->GetFromTypeAndExtension(mimeType
, EmptyCString(),
649 getter_AddRefs(mimeInfo
));
650 NS_ENSURE_TRUE(mimeInfo
, NS_OK
);
653 rv
= imgUrl
->GetSpec(spec
);
654 NS_ENSURE_SUCCESS(rv
, rv
);
656 // pass out the image source string
657 nsString imageSourceString
;
658 CopyUTF8toUTF16(spec
, imageSourceString
);
661 if (extension
.IsEmpty() ||
662 NS_FAILED(mimeInfo
->ExtensionExists(extension
, &validExtension
)) ||
664 // Fix the file extension in the URL
665 nsAutoCString primaryExtension
;
666 mimeInfo
->GetPrimaryExtension(primaryExtension
);
668 rv
= NS_MutateURI(imgUri
)
669 .Apply(NS_MutatorMethod(&nsIURLMutator::SetFileExtension
,
670 primaryExtension
, nullptr))
672 NS_ENSURE_SUCCESS(rv
, rv
);
675 nsAutoCString fileName
;
676 imgUrl
->GetFileName(fileName
);
678 NS_UnescapeURL(fileName
);
680 // make the filename safe for the filesystem
681 fileName
.ReplaceChar(FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS
, '-');
683 nsString imageDestFileName
;
684 CopyUTF8toUTF16(fileName
, imageDestFileName
);
686 rv
= AppendString(aTransferable
, imageSourceString
, kFilePromiseURLMime
);
687 NS_ENSURE_SUCCESS(rv
, rv
);
689 rv
= AppendString(aTransferable
, imageDestFileName
, kFilePromiseDestFilename
);
690 NS_ENSURE_SUCCESS(rv
, rv
);
692 aTransferable
->SetRequestingPrincipal(node
->NodePrincipal());
693 aTransferable
->SetContentPolicyType(nsIContentPolicy::TYPE_INTERNAL_IMAGE
);
695 // add the dataless file promise flavor
696 return aTransferable
->AddDataFlavor(kFilePromiseMime
);
700 nsIContent
* nsCopySupport::GetSelectionForCopy(Document
* aDocument
,
701 Selection
** aSelection
) {
702 *aSelection
= nullptr;
704 PresShell
* presShell
= aDocument
->GetPresShell();
709 nsCOMPtr
<nsIContent
> focusedContent
;
710 nsCOMPtr
<nsISelectionController
> selectionController
=
711 presShell
->GetSelectionControllerForFocusedContent(
712 getter_AddRefs(focusedContent
));
713 if (!selectionController
) {
717 RefPtr
<Selection
> sel
= selectionController
->GetSelection(
718 nsISelectionController::SELECTION_NORMAL
);
719 sel
.forget(aSelection
);
720 return focusedContent
;
723 bool nsCopySupport::CanCopy(Document
* aDocument
) {
724 if (!aDocument
) return false;
726 RefPtr
<Selection
> sel
;
727 GetSelectionForCopy(aDocument
, getter_AddRefs(sel
));
728 NS_ENSURE_TRUE(sel
, false);
730 return !sel
->IsCollapsed();
733 static bool IsInsideRuby(nsINode
* aNode
) {
734 for (; aNode
; aNode
= aNode
->GetParent()) {
735 if (aNode
->IsHTMLElement(nsGkAtoms::ruby
)) {
742 static bool IsSelectionInsideRuby(Selection
* aSelection
) {
743 uint32_t rangeCount
= aSelection
->RangeCount();
745 for (auto i
: IntegerRange(rangeCount
)) {
746 nsRange
* range
= aSelection
->GetRangeAt(i
);
747 if (!IsInsideRuby(range
->GetCommonAncestor())) {
754 static Element
* GetElementOrNearestFlattenedTreeParentElement(nsINode
* aNode
) {
755 if (!aNode
->IsContent()) {
758 for (nsIContent
* content
= aNode
->AsContent(); content
;
759 content
= content
->GetFlattenedTreeParent()) {
760 if (content
->IsElement()) {
761 return content
->AsElement();
767 bool nsCopySupport::FireClipboardEvent(EventMessage aEventMessage
,
768 int32_t aClipboardType
,
769 PresShell
* aPresShell
,
770 Selection
* aSelection
,
771 bool* aActionTaken
) {
773 *aActionTaken
= false;
776 EventMessage originalEventMessage
= aEventMessage
;
777 if (originalEventMessage
== ePasteNoFormatting
) {
778 originalEventMessage
= ePaste
;
781 NS_ASSERTION(originalEventMessage
== eCut
|| originalEventMessage
== eCopy
||
782 originalEventMessage
== ePaste
,
783 "Invalid clipboard event type");
785 RefPtr
<PresShell
> presShell
= aPresShell
;
790 nsCOMPtr
<Document
> doc
= presShell
->GetDocument();
791 if (!doc
) return false;
793 nsCOMPtr
<nsPIDOMWindowOuter
> piWindow
= doc
->GetWindow();
794 if (!piWindow
) return false;
796 // Event target of clipboard events should be an element node which
797 // contains selection start container.
798 RefPtr
<Element
> targetElement
;
800 // If a selection was not supplied, try to find it.
801 RefPtr
<Selection
> sel
= aSelection
;
803 GetSelectionForCopy(doc
, getter_AddRefs(sel
));
806 // Retrieve the event target node from the start of the selection.
808 nsRange
* range
= sel
->GetRangeAt(0);
810 targetElement
= GetElementOrNearestFlattenedTreeParentElement(
811 range
->GetStartContainer());
815 // If there is no selection ranges, use the <body> or <frameset> element.
816 if (!targetElement
) {
817 targetElement
= doc
->GetBody();
818 if (!targetElement
) {
823 // It seems to be unsafe to fire an event handler during reflow (bug 393696)
824 if (!nsContentUtils::IsSafeToRunScript()) {
825 nsContentUtils::WarnScriptWasIgnored(doc
);
829 nsCOMPtr
<nsIDocShell
> docShell
= piWindow
->GetDocShell();
830 const bool chromeShell
=
831 docShell
&& docShell
->ItemType() == nsIDocShellTreeItem::typeChrome
;
833 // next, fire the cut, copy or paste event
834 bool doDefault
= true;
835 RefPtr
<DataTransfer
> clipboardData
;
836 if (chromeShell
|| StaticPrefs::dom_event_clipboardevents_enabled()) {
838 new DataTransfer(doc
->GetScopeObject(), aEventMessage
,
839 originalEventMessage
== ePaste
, aClipboardType
);
841 nsEventStatus status
= nsEventStatus_eIgnore
;
842 InternalClipboardEvent
evt(true, originalEventMessage
);
843 evt
.mClipboardData
= clipboardData
;
844 EventDispatcher::Dispatch(targetElement
, presShell
->GetPresContext(), &evt
,
846 // If the event was cancelled, don't do the clipboard operation
847 doDefault
= (status
!= nsEventStatus_eConsumeNoDefault
);
850 // When this function exits, the event dispatch is over. We want to disconnect
851 // our DataTransfer, which means setting its mode to `Protected` and clearing
852 // all stored data, before we return.
853 auto clearAfter
= MakeScopeExit([&] {
855 clipboardData
->Disconnect();
857 // NOTE: Disconnect may not actually clear the DataTransfer if the
858 // dom.events.dataTransfer.protected.enabled pref is not on, so we make
859 // sure we clear here, as not clearing could provide the DataTransfer
860 // access to information from the system clipboard at an arbitrary point
862 if (originalEventMessage
== ePaste
) {
863 clipboardData
->ClearAll();
868 // No need to do anything special during a paste. Either an event listener
869 // took care of it and cancelled the event, or the caller will handle it.
870 // Return true to indicate that the event wasn't cancelled.
871 if (originalEventMessage
== ePaste
) {
873 *aActionTaken
= true;
878 // Update the presentation in case the event handler modified the selection,
880 presShell
->FlushPendingNotifications(FlushType::Frames
);
881 if (presShell
->IsDestroying()) {
885 // if the event was not cancelled, do the default copy. If the event was
886 // cancelled, use the data added to the data transfer and copy that instead.
889 // find the focused node
890 nsIContent
* sourceContent
= targetElement
.get();
891 if (targetElement
->IsInNativeAnonymousSubtree()) {
892 sourceContent
= targetElement
->FindFirstNonChromeOnlyAccessContent();
895 // check if we are looking at a password input
896 nsCOMPtr
<nsIFormControl
> formControl
= do_QueryInterface(sourceContent
);
898 if (formControl
->ControlType() == NS_FORM_INPUT_PASSWORD
) {
903 // when cutting non-editable content, do nothing
904 // XXX this is probably the wrong editable flag to check
905 if (originalEventMessage
!= eCut
|| targetElement
->IsEditable()) {
906 // get the data from the selection if any
907 if (sel
->IsCollapsed()) {
909 *aActionTaken
= true;
913 // XXX Code which decides whether we should copy text with ruby
914 // annotation is currenct depending on whether each range of the
915 // selection is inside a same ruby container. But we really should
916 // expose the full functionality in browser. See bug 1130891.
917 bool withRubyAnnotation
= IsSelectionInsideRuby(sel
);
918 nsresult rv
= EncodeDocumentWithContextAndPutToClipboard(
919 sel
, doc
, aClipboardType
, withRubyAnnotation
);
926 } else if (clipboardData
) {
927 // check to see if any data was put on the data transfer.
928 count
= clipboardData
->MozItemCount();
930 nsCOMPtr
<nsIClipboard
> clipboard(
931 do_GetService("@mozilla.org/widget/clipboard;1"));
932 NS_ENSURE_TRUE(clipboard
, false);
934 nsCOMPtr
<nsITransferable
> transferable
=
935 clipboardData
->GetTransferable(0, doc
->GetLoadContext());
937 NS_ENSURE_TRUE(transferable
, false);
939 // put the transferable on the clipboard
940 nsresult rv
= clipboard
->SetData(transferable
, nullptr, aClipboardType
);
947 // Now that we have copied, update the clipboard commands. This should have
948 // the effect of updating the enabled state of the paste menu item.
949 if (doDefault
|| count
) {
950 piWindow
->UpdateCommands(NS_LITERAL_STRING("clipboard"), nullptr, 0);
954 *aActionTaken
= true;