summaryrefslogtreecommitdiffstats
path: root/comm/mail/test/browser/composition/browser_attachmentDragDrop.js
blob: bc826574c72bdf654a1277aaee6fd71f95729057 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Tests the Drag and Drop functionalities of the attachment bucket in the
 * message compose window.
 */

"use strict";

var { CloudFileTestProvider } = ChromeUtils.import(
  "resource://testing-common/mozmill/CloudfileHelpers.jsm"
);
var { gMockFilePicker, gMockFilePickReg } = ChromeUtils.import(
  "resource://testing-common/mozmill/AttachmentHelpers.jsm"
);

var { open_compose_new_mail, close_compose_window, add_attachments } =
  ChromeUtils.import("resource://testing-common/mozmill/ComposeHelpers.jsm");
var {
  add_message_to_folder,
  be_in_folder,
  create_folder,
  create_message,
  FAKE_SERVER_HOSTNAME,
  get_about_message,
  inboxFolder,
  mc,
  select_click_row,
} = ChromeUtils.import(
  "resource://testing-common/mozmill/FolderDisplayHelpers.jsm"
);

const dragService = Cc["@mozilla.org/widget/dragservice;1"].getService(
  Ci.nsIDragService
);

var gCloudFileProvider;
var gCloudFileAccount;
const kFiles = [
  "./data/attachment.txt",
  "./data/base64-bug1586890.eml",
  "./data/base64-encoded-msg.eml",
  "./data/base64-with-whitespace.eml",
  "./data/body-greek.eml",
  "./data/body-utf16.eml",
];

add_setup(async function () {
  // Prepare the mock file picker.
  gMockFilePickReg.register();
  gMockFilePicker.returnFiles = collectFiles(kFiles);

  // Register an extension based cloudFile provider.
  gCloudFileProvider = new CloudFileTestProvider("testProvider");
  await gCloudFileProvider.register(this);
  gCloudFileAccount = await gCloudFileProvider.createAccount("testAccount");
});

registerCleanupFunction(async function () {
  gMockFilePickReg.unregister();
  // Remove the cloudFile account and unregister the provider.
  await gCloudFileProvider.removeAccount(gCloudFileAccount);
  await gCloudFileProvider.unregister();
});

function getDragOverTarget(win) {
  return win.document.getElementById("messageArea");
}

function getDropTarget(win) {
  return win.document.getElementById("dropAttachmentOverlay");
}

function initDragSession({ dragData, dropEffect }) {
  let dropAction;
  switch (dropEffect) {
    case null:
    case undefined:
    case "move":
      dropAction = Ci.nsIDragService.DRAGDROP_ACTION_MOVE;
      break;
    case "copy":
      dropAction = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
      break;
    case "link":
      dropAction = Ci.nsIDragService.DRAGDROP_ACTION_LINK;
      break;
    default:
      throw new Error(`${dropEffect} is an invalid drop effect value`);
  }

  const dataTransfer = new DataTransfer();
  dataTransfer.dropEffect = dropEffect;

  for (let i = 0; i < dragData.length; i++) {
    const item = dragData[i];
    for (let j = 0; j < item.length; j++) {
      dataTransfer.mozSetDataAt(item[j].type, item[j].data, i);
    }
  }

  dragService.startDragSessionForTests(dropAction);
  const session = dragService.getCurrentSession();
  session.dataTransfer = dataTransfer;

  return session;
}

/**
 * Helper method to simulate a drag and drop action above the window.
 */
async function simulateDragAndDrop(win, dragData, type) {
  let dropTarget = getDropTarget(win);
  let dragOverTarget = getDragOverTarget(win);
  let dropEffect = "move";

  let session = initDragSession({ dragData, dropEffect });

  info("Simulate drag over and wait for the drop target to be visible");

  EventUtils.synthesizeDragOver(
    dragOverTarget,
    dragOverTarget,
    dragData,
    dropEffect,
    win
  );

  // This make sure that the fake dataTransfer has still
  // the expected drop effect after the synthesizeDragOver call.
  session.dataTransfer.dropEffect = "move";

  await BrowserTestUtils.waitForCondition(
    () => dropTarget.classList.contains("show"),
    "Wait for the drop target element to be visible"
  );

  // If the dragged file is an image, the attach inline container should be
  // visible.
  if (type == "image" || type == "inline" || type == "link") {
    await BrowserTestUtils.waitForCondition(
      () =>
        !win.document.getElementById("addInline").classList.contains("hidden"),
      "Wait for the addInline element to be visible"
    );
  } else {
    await BrowserTestUtils.waitForCondition(
      () =>
        win.document.getElementById("addInline").classList.contains("hidden"),
      "Wait for the addInline element to be hidden"
    );
  }

  if (type == "inline") {
    // Change the drop target to the #addInline container.
    dropTarget = win.document.getElementById("addInline");
  }

  info("Simulate drop dragData on drop target");

  EventUtils.synthesizeDropAfterDragOver(
    null,
    session.dataTransfer,
    dropTarget,
    win,
    { _domDispatchOnly: true }
  );

  if (type == "inline") {
    let editor = win.GetCurrentEditor();

    await BrowserTestUtils.waitForCondition(() => {
      editor.selectAll();
      return editor.getSelectedElement("img");
    }, "Confirm the image was added to the message body");

    Assert.equal(
      win.document.getElementById("attachmentBucket").itemCount,
      0,
      "Confirm the file hasn't been attached"
    );
  } else {
    // The dropped files should have been attached.
    await BrowserTestUtils.waitForCondition(
      () =>
        win.document.getElementById("attachmentBucket").itemCount ==
        dragData.length,
      "Wait for the file to be attached"
    );
  }

  dragService.endDragSession(true);
}

/**
 * Test how the attachment overlay reacts to an image file being dragged above
 * the message compose window.
 */
add_task(async function test_image_file_drag() {
  let file = new FileUtils.File(getTestFilePath("data/tb-logo.png"));
  let cwc = open_compose_new_mail();

  await simulateDragAndDrop(
    cwc.window,
    [[{ type: "application/x-moz-file", data: file }]],
    "image"
  );

  close_compose_window(cwc);
});

/**
 * Test how the attachment overlay reacts to an image file being dragged above
 * the message compose window and dropped above the inline container.
 */
add_task(async function test_image_file_drag() {
  let file = new FileUtils.File(getTestFilePath("data/tb-logo.png"));
  let cwc = open_compose_new_mail();

  await simulateDragAndDrop(
    cwc.window,
    [[{ type: "application/x-moz-file", data: file }]],
    "inline"
  );

  close_compose_window(cwc);
});

/**
 * Test how the attachment overlay reacts to a text file being dragged above
 * the message compose window.
 */
add_task(async function test_text_file_drag() {
  let file = new FileUtils.File(getTestFilePath("data/attachment.txt"));
  let cwc = open_compose_new_mail();

  await simulateDragAndDrop(
    cwc.window,
    [[{ type: "application/x-moz-file", data: file }]],
    "text"
  );

  close_compose_window(cwc);
});

add_task(async function test_message_drag() {
  let folder = await create_folder("dragondrop");
  let subject = "Dragons don't drop from the sky";
  let body = "Dragons can fly after all.";
  await be_in_folder(folder);
  await add_message_to_folder(
    [folder],
    create_message({ subject, body: { body } })
  );
  select_click_row(0);

  let msgStr = get_about_message().gMessageURI;
  let msgUrl = MailServices.messageServiceFromURI(msgStr).getUrlForUri(msgStr);

  let cwc = open_compose_new_mail();
  let attachmentBucket = cwc.window.document.getElementById("attachmentBucket");

  await simulateDragAndDrop(
    cwc.window,
    [
      [
        { type: "text/x-moz-message", data: msgStr },
        { type: "text/x-moz-url", data: msgUrl.spec },
        {
          type: "application/x-moz-file-promise-url",
          data: msgUrl.spec + "?fileName=" + encodeURIComponent("message.eml"),
        },
        {
          type: "application/x-moz-file-promise",
          data: new window.messageFlavorDataProvider(),
        },
      ],
    ],
    "message"
  );

  let attachment = attachmentBucket.childNodes[0].attachment;
  Assert.equal(
    attachment.name,
    "Dragons don't drop from the sky.eml",
    "attachment should have expected file name"
  );
  Assert.equal(
    attachment.contentType,
    "message/rfc822",
    "attachment should say it's a message"
  );
  Assert.notEqual(attachment, 0, "attachment should not be 0 bytes");

  // Clear the added attachment.
  await cwc.window.RemoveAttachments([attachmentBucket.childNodes[0]]);

  // Try the same with mail.forward_add_extension false.
  Services.prefs.setBoolPref("mail.forward_add_extension", false);

  await simulateDragAndDrop(
    cwc.window,
    [
      [
        { type: "text/x-moz-message", data: msgStr },
        { type: "text/x-moz-url", data: msgUrl.spec },
        {
          type: "application/x-moz-file-promise-url",
          data: msgUrl.spec + "?fileName=" + encodeURIComponent("message.eml"),
        },
        {
          type: "application/x-moz-file-promise",
          data: new window.messageFlavorDataProvider(),
        },
      ],
    ],
    "message"
  );

  let attachment2 = attachmentBucket.childNodes[0].attachment;
  Assert.equal(
    attachment2.name,
    "Dragons don't drop from the sky",
    "attachment2 should have expected file name"
  );
  Assert.equal(
    attachment2.contentType,
    "message/rfc822",
    "attachment2 should say it's a message"
  );
  Assert.notEqual(attachment2, 0, "attachment2 should not be 0 bytes");

  Services.prefs.clearUserPref("mail.forward_add_extension");

  close_compose_window(cwc);
  await be_in_folder(inboxFolder);
  folder.deleteSelf(null);
});

add_task(async function test_link_drag() {
  let cwc = open_compose_new_mail();
  await simulateDragAndDrop(
    cwc.window,
    [
      [
        {
          type: "text/uri-list",
          data: "https://example.com",
        },
        {
          type: "text/x-moz-url",
          data: "https://example.com\nExample website",
        },
        { type: "application/x-moz-file", data: "" },
      ],
    ],
    "link"
  );

  let attachment =
    cwc.window.document.getElementById("attachmentBucket").childNodes[0]
      .attachment;
  Assert.equal(
    attachment.name,
    "Example website",
    "Attached link has expected name"
  );
  Assert.equal(
    attachment.url,
    "https://example.com",
    "Attached link has correct URL"
  );

  close_compose_window(cwc);
});

/**
 * Get the attachment item for the given url.
 *
 * @param {Element} bucket - The element to search in for the attachment item.
 * @param {string} url - The url of the attachment to find.
 *
 * @returns {Element?} - The item with the given attachment url, or null if none
 *   was found.
 */
function getAttachmentItem(bucket, url) {
  for (let child of bucket.childNodes) {
    if (child.attachment.url == url) {
      return child;
    }
  }
  return null;
}

/**
 * Assert that the given bucket has the given selected items.
 *
 * @param {Element} bucket - The bucket to check.
 * @param {Element[]} selectedItems - The expected selected items in the bucket.
 */
function assertSelection(bucket, selectedItems) {
  for (let child of bucket.childNodes) {
    if (selectedItems.includes(child)) {
      Assert.ok(
        child.selected,
        `${child.attachment.url} item should be selected`
      );
    } else {
      Assert.ok(
        !child.selected,
        `${child.attachment.url} item should not be selected`
      );
    }
  }
}

/**
 * Select the given attachment items in the bucket.
 *
 * @param {Element} bucket - The attachment bucket to select from.
 * @param {Element[]} itemSet - The set of attachment items to select. This must
 *   contain at least one item.
 */
function selectAttachments(bucket, itemSet) {
  let win = bucket.ownerGlobal;
  let first = true;
  for (let item of itemSet) {
    item.scrollIntoView();
    EventUtils.synthesizeMouseAtCenter(item, { ctrlKey: !first }, win);
    first = false;
  }
  assertSelection(bucket, itemSet);
}

/**
 * Perform a single drag operation between attachment buckets.
 *
 * @param {Element} dragSrc - The attachment item to start dragging from.
 * @param {Element} destBucket - The attachment bucket to drag to.
 * @param {string[]} expectUrls - The expected list of all the attachment urls
 *   in the destBucket after the drop. Note this should include both the current
 *   attachments as well as the expected gained attachments.
 */
async function moveAttachments(dragSrc, destBucket, expectUrls) {
  let srcWindow = dragSrc.ownerGlobal;
  let destWindow = destBucket.ownerGlobal;
  let dragOverTarget = getDragOverTarget(destWindow);
  let dropTarget = getDropTarget(destWindow);

  let [dragOverResult, dataTransfer] = EventUtils.synthesizeDragOver(
    dragSrc,
    dragOverTarget,
    null,
    null,
    srcWindow,
    destWindow
  );

  EventUtils.synthesizeDropAfterDragOver(
    dragOverResult,
    dataTransfer,
    dropTarget,
    destWindow
  );

  await TestUtils.waitForCondition(
    () => destBucket.itemCount == expectUrls.length,
    `Destination bucket has ${expectUrls.length} attachments`
  );
  let items = Array.from(destBucket.childNodes);
  for (let i = 0; i < items.length; i++) {
    Assert.ok(
      items[i].attachment.url.startsWith("file://") &&
        items[i].attachment.url.includes(expectUrls[i].split(".")[0]),
      `Attachment url ${items[i].attachment.url} should be the correct file:// url`
    );
  }
}

/**
 * Perform a series of drag and drop of attachments from the given source bucket
 * to the given destination bucket.
 *
 * The dragged attachment will be saved as a local temporary file. This test
 * extracts the filename from the url and checks if the url of the attachment
 * in the destBucket is a file:// url and has the correct file name.
 * The original url is a mailbox:// url:
 *   mailbox:///something?number=1&part=1.4&filename=file2.txt
 *
 * @param {Element} srcBucket - The bucket to drag from. It must contain 6
 *   attachment items and be open.
 * @param {Element} destBucket - The bucket to drag to. It must be empty.
 */
async function drag_between_buckets(srcBucket, destBucket) {
  Assert.equal(srcBucket.itemCount, 6, "Src bucket starts with 6 attachments");
  Assert.equal(
    destBucket.itemCount,
    0,
    "Dest bucket starts with no attachments"
  );

  let attachmentSet = Array.from(srcBucket.childNodes, item => {
    return { url: item.attachment.url, srcItem: item };
  });

  let dragSession = Cc["@mozilla.org/widget/dragservice;1"].getService(
    Ci.nsIDragService
  );
  dragSession.startDragSessionForTests(Ci.nsIDragService.DRAGDROP_ACTION_MOVE);

  // NOTE: Attachment #4 is never dragged from the source to the destination
  // bucket as part of this test.

  let destUrls = [];

  // Select attachment #2, and drag it.
  selectAttachments(srcBucket, [attachmentSet[2].srcItem]);
  destUrls.push(attachmentSet[2].url.split("=").pop());
  await moveAttachments(attachmentSet[2].srcItem, destBucket, destUrls);

  // Start with attachment #3 selected, but drag attachment #1.
  // The drag operation should at first change the selection to attachment #1,
  // such that it becomes the transferred file.
  selectAttachments(srcBucket, [attachmentSet[3].srcItem]);
  destUrls.push(attachmentSet[1].url.split("=").pop());
  await moveAttachments(attachmentSet[1].srcItem, destBucket, destUrls);
  // Confirm that attachment #1 was selected.
  assertSelection(srcBucket, [attachmentSet[1].srcItem]);

  // Select two attachments. And then start a drag on one of them.
  // We expect both the selected attachments to move.
  selectAttachments(srcBucket, [
    attachmentSet[0].srcItem,
    attachmentSet[3].srcItem,
  ]);
  destUrls.push(
    attachmentSet[0].url.split("=").pop(),
    attachmentSet[3].url.split("=").pop()
  );
  await moveAttachments(attachmentSet[3].srcItem, destBucket, destUrls);

  // Select three attachments, two of which are already added.
  // Expect the new one to be added.
  selectAttachments(srcBucket, [
    attachmentSet[1].srcItem,
    attachmentSet[5].srcItem,
    attachmentSet[2].srcItem,
  ]);
  destUrls.push(attachmentSet[5].url.split("=").pop());
  await moveAttachments(attachmentSet[1].srcItem, destBucket, destUrls);
  dragService.endDragSession(true);
}

/**
 * Test dragging regular attachments from one composition window to another.
 */
add_task(async function test_drag_and_drop_between_composition_windows() {
  let ctrlSrc = open_compose_new_mail();
  let ctrlDest = open_compose_new_mail();

  // Add attachments (via mocked file picker).
  await ctrlSrc.window.AttachFile();

  let srcAttachmentArea =
    ctrlSrc.window.document.getElementById("attachmentArea");

  // Wait for attachment area to be visible and open in response.
  await TestUtils.waitForCondition(
    () =>
      BrowserTestUtils.is_visible(srcAttachmentArea) && srcAttachmentArea.open,
    "Attachment area is visible and open"
  );

  let srcBucket = ctrlSrc.window.document.getElementById("attachmentBucket");
  let dstBucket = ctrlDest.window.document.getElementById("attachmentBucket");
  await drag_between_buckets(srcBucket, dstBucket);

  // Make sure a dragged attachment can be converted to a cloudFile attachment.
  try {
    await ctrlSrc.window.UpdateAttachment(dstBucket.childNodes[0], {
      cloudFileAccount: gCloudFileAccount,
    });
    Assert.ok(
      dstBucket.childNodes[0].attachment.sendViaCloud,
      "Regular attachment should have been converted to a cloudFile attachment."
    );
  } catch (ex) {
    Assert.ok(
      false,
      `Converting a drag'n'dropped regular attachment to a cloudFile attachment should succeed: ${ex.message}`
    );
  }

  close_compose_window(ctrlSrc);
  close_compose_window(ctrlDest);
});

/**
 * Test dragging cloudFile attachments from one composition window to another.
 */
add_task(async function test_cloud_drag_and_drop_between_composition_windows() {
  let ctrlSrc = open_compose_new_mail();
  let ctrlDest = open_compose_new_mail();

  // Add cloudFile attachments (via mocked file picker).
  await ctrlSrc.window.attachToCloudNew(gCloudFileAccount);

  let srcAttachmentArea =
    ctrlSrc.window.document.getElementById("attachmentArea");

  // Wait for attachment area to be visible and open in response.
  await TestUtils.waitForCondition(
    () =>
      BrowserTestUtils.is_visible(srcAttachmentArea) && srcAttachmentArea.open,
    "Attachment area is visible and open"
  );

  let srcBucket = ctrlSrc.window.document.getElementById("attachmentBucket");
  let dstBucket = ctrlDest.window.document.getElementById("attachmentBucket");
  await drag_between_buckets(srcBucket, dstBucket);

  // Make sure a dragged cloudFile attachment can be converted to a regular
  // attachment.
  try {
    await ctrlSrc.window.UpdateAttachment(dstBucket.childNodes[0], {
      cloudFileAccount: null,
    });
    Assert.ok(
      !dstBucket.childNodes[0].attachment.sendViaCloud,
      "CloudFile Attachment should have been converted to a regular attachment."
    );
  } catch (ex) {
    Assert.ok(
      false,
      `Converting a drag'n'dropped cloudFile attachment to a regular attachment should succeed: ${ex.message}`
    );
  }

  close_compose_window(ctrlSrc);
  close_compose_window(ctrlDest);
});

/**
 * Test dragging attachments from a message into a composition window.
 */
add_task(async function test_drag_and_drop_between_composition_windows() {
  let ctrlDest = open_compose_new_mail();

  let folder = await create_folder("AttachmentsForComposition");
  await add_message_to_folder(
    [folder],
    create_message({
      attachments: [0, 1, 2, 3, 4, 5].map(num => {
        return {
          body: "Some Text",
          filename: `file${num}.txt`,
          format: "text/plain",
        };
      }),
    })
  );
  await be_in_folder(folder);
  select_click_row(0);
  let aboutMessage = get_about_message();
  let srcAttachmentArea =
    aboutMessage.document.getElementById("attachmentView");
  Assert.ok(!srcAttachmentArea.collapsed, "Attachment area is visible");

  let srcBucket = aboutMessage.document.getElementById("attachmentList");
  EventUtils.synthesizeMouseAtCenter(
    aboutMessage.document.getElementById("attachmentBar"),
    {},
    aboutMessage
  );
  Assert.ok(!srcBucket.collapsed, "Attachment list is visible");

  await drag_between_buckets(
    srcBucket,
    ctrlDest.window.document.getElementById("attachmentBucket")
  );

  close_compose_window(ctrlDest);
});

function collectFiles(files) {
  return files.map(filename => new FileUtils.File(getTestFilePath(filename)));
}