summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/feedback/js/feedback.js
blob: 6cd19b693287b16c2017311f2a0a78ecf4218efd (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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/** @type {string}
 * @const
 */
var FEEDBACK_LANDING_PAGE =
    'https://support.google.com/chrome/go/feedback_confirmation';

/** @type {number}
 * @const
 */
var MAX_ATTACH_FILE_SIZE = 3 * 1024 * 1024;

/**
 * @type {number}
 * @const
 */
var FEEDBACK_MIN_WIDTH = 500;

/**
 * @type {number}
 * @const
 */
var FEEDBACK_MIN_HEIGHT = 585;

/**
 * @type {number}
 * @const
 */
var FEEDBACK_MIN_HEIGHT_LOGIN = 482;

/** @type {number}
 * @const
 */
var CONTENT_MARGIN_HEIGHT = 40;

/** @type {number}
 * @const
 */
var MAX_SCREENSHOT_WIDTH = 100;

/** @type {string}
 * @const
 */
var SYSINFO_WINDOW_ID = 'sysinfo_window';

/** @type {string}
 * @const
 */
var STATS_WINDOW_ID = 'stats_window';

/**
 * Feedback flow defined in feedback_private.idl.
 * @enum {string}
 */
var FeedbackFlow = {
  REGULAR: 'regular',  // Flow in a regular user session.
  LOGIN: 'login'       // Flow on the login screen.
};

var attachedFileBlob = null;
var lastReader = null;

var feedbackInfo = null;

/**
 * The callback used by the sys_info_page to receive the event that the system
 * information is ready.
 * @type {function(sysInfo)}
 */
var sysInfoPageOnSysInfoReadyCallback = null;

/**
 * Reads the selected file when the user selects a file.
 * @param {Event} fileSelectedEvent The onChanged event for the file input box.
 */
function onFileSelected(fileSelectedEvent) {
  $('attach-error').hidden = true;
  var file = fileSelectedEvent.target.files[0];
  if (!file) {
    // User canceled file selection.
    attachedFileBlob = null;
    return;
  }

  if (file.size > MAX_ATTACH_FILE_SIZE) {
    $('attach-error').hidden = false;

    // Clear our selected file.
    $('attach-file').value = '';
    attachedFileBlob = null;
    return;
  }

  attachedFileBlob = file.slice();
}

/**
 * Clears the file that was attached to the report with the initial request.
 * Instead we will now show the attach file button in case the user wants to
 * attach another file.
 */
function clearAttachedFile() {
  $('custom-file-container').hidden = true;
  attachedFileBlob = null;
  feedbackInfo.attachedFile = null;
  $('attach-file').hidden = false;
}

/**
 * Creates a closure that creates or shows a window with the given url.
 * @param {string} windowId A string with the ID of the window we are opening.
 * @param {string} url The destination URL of the new window.
 * @return {function()} A function to be called to open the window.
 */
function windowOpener(windowId, url) {
  return function(e) {
    e.preventDefault();
    chrome.app.window.create(url, {id: windowId});
  };
}

/**
 * Opens a new window with chrome://slow_trace, downloading performance data.
 */
function openSlowTraceWindow() {
  chrome.app.window.create(
      'chrome://slow_trace/tracing.zip#' + feedbackInfo.traceId);
}

/**
 * Sends the report; after the report is sent, we need to be redirected to
 * the landing page, but we shouldn't be able to navigate back, hence
 * we open the landing page in a new tab and sendReport closes this tab.
 * @return {boolean} True if the report was sent.
 */
function sendReport() {
  if ($('description-text').value.length == 0) {
    var description = $('description-text');
    description.placeholder = loadTimeData.getString('no-description');
    description.focus();
    return false;
  }

  // Prevent double clicking from sending additional reports.
  $('send-report-button').disabled = true;
  console.log('Feedback: Sending report');
  if (!feedbackInfo.attachedFile && attachedFileBlob) {
    feedbackInfo.attachedFile = { name: $('attach-file').value,
                                  data: attachedFileBlob };
  }

  feedbackInfo.description = $('description-text').value;
  feedbackInfo.pageUrl = $('page-url-text').value;
  feedbackInfo.email = $('user-email-text').value;

  var useSystemInfo = false;
  var useHistograms = false;
  if ($('sys-info-checkbox') != null &&
      $('sys-info-checkbox').checked) {
    // Send histograms along with system info.
    useSystemInfo = useHistograms = true;
  }
<if expr="chromeos">
  if ($('performance-info-checkbox') == null ||
      !($('performance-info-checkbox').checked)) {
    feedbackInfo.traceId = null;
  }
</if>

  feedbackInfo.sendHistograms = useHistograms;

  // If the user doesn't want to send the screenshot.
  if (!$('screenshot-checkbox').checked)
    feedbackInfo.screenshot = null;

  if (useSystemInfo) {
    // The user chose to include the system information as part of the report.
    // If they are not ready yet, we have to send the report later.
    if (!isSystemInfoReady()) {
      // The report will be sent later by the feedback extension's background
      // page (see event_handler.js).
      sendReportLater(feedbackInfo);

      // No landing page for login screen feedback.
      if (feedbackInfo.flow != FeedbackFlow.LOGIN)
        window.open(FEEDBACK_LANDING_PAGE, '_blank');
      window.close();
      return true;
    }
  }

  chrome.feedbackPrivate.sendFeedback(feedbackInfo, function(result) {
    // No landing page for login screen feedback.
    if (feedbackInfo.flow != FeedbackFlow.LOGIN)
      window.open(FEEDBACK_LANDING_PAGE, '_blank');
    window.close();
  });

  return true;
}

/**
 * Click listener for the cancel button.
 * @param {Event} e The click event being handled.
 */
function cancel(e) {
  e.preventDefault();
  window.close();
}

/**
 * Converts a blob data URL to a blob object.
 * @param {string} url The data URL to convert.
 * @return {Blob} Blob object containing the data.
 */
function dataUrlToBlob(url) {
  var mimeString = url.split(',')[0].split(':')[1].split(';')[0];
  var data = atob(url.split(',')[1]);
  var dataArray = [];
  for (var i = 0; i < data.length; ++i)
    dataArray.push(data.charCodeAt(i));

  return new Blob([new Uint8Array(dataArray)], {type: mimeString});
}

<if expr="chromeos">
/**
 * Update the page when performance feedback state is changed.
 */
function performanceFeedbackChanged() {
  if ($('performance-info-checkbox').checked) {
    $('attach-file').disabled = true;
    $('attach-file').checked = false;

    $('screenshot-checkbox').disabled = true;
    $('screenshot-checkbox').checked = false;
  } else {
    $('attach-file').disabled = false;
    $('screenshot-checkbox').disabled = false;
  }
}
</if>

function resizeAppWindow() {
  // We pick the width from the titlebar, which has no margins.
  var width = $('title-bar').scrollWidth;
  if (width < FEEDBACK_MIN_WIDTH)
    width = FEEDBACK_MIN_WIDTH;

  // We get the height by adding the titlebar height and the content height +
  // margins. We can't get the margins for the content-pane here by using
  // style.margin - the variable seems to not exist.
  var height = $('title-bar').scrollHeight +
      $('content-pane').scrollHeight + CONTENT_MARGIN_HEIGHT;

  var minHeight = FEEDBACK_MIN_HEIGHT;
  if (feedbackInfo.flow == FeedbackFlow.LOGIN)
    minHeight = FEEDBACK_MIN_HEIGHT_LOGIN;
  height = Math.max(height, minHeight);

  chrome.app.window.current().resizeTo(width, height);
}

/**
 * A callback to be invoked when the background page of this extension receives
 * the system information.
 * @param {Object} sysInfo The received system information.
 */
function onSystemInformation(sysInfo) {
  // Concatenate the feedbackInfo's systemInformation with the newly received
  // sysInfo once (if any).
  if (feedbackInfo.systemInformation) {
    feedbackInfo.systemInformation =
      feedbackInfo.systemInformation.concat(sysInfo);
  } else {
    feedbackInfo.systemInformation = sysInfo;
  }

  // In case the sys_info_page needs to be notified by this event, do so.
  if (sysInfoPageOnSysInfoReadyCallback != null) {
    sysInfoPageOnSysInfoReadyCallback(feedbackInfo.systemInformation);
    sysInfoPageOnSysInfoReadyCallback = null;
  }
}

/**
 * Initializes our page.
 * Flow:
 * .) DOMContent Loaded        -> . Request feedbackInfo object
 *                                . Setup page event handlers
 * .) Feedback Object Received -> . take screenshot
 *                                . request email
 *                                . request System info
 *                                . request i18n strings
 * .) Screenshot taken         -> . Show Feedback window.
 */
function initialize() {
  // Add listener to receive the feedback info object.
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.sentFromEventPage) {
      feedbackInfo = request.data;

      if (!feedbackInfo.flow)
        feedbackInfo.flow = FeedbackFlow.REGULAR;

      $('description-text').textContent = feedbackInfo.description;
      if (feedbackInfo.pageUrl)
        $('page-url-text').value = feedbackInfo.pageUrl;

      takeScreenshot(function(screenshotCanvas) {
        // We've taken our screenshot, show the feedback page without any
        // further delay.
        window.webkitRequestAnimationFrame(function() {
          resizeAppWindow();
        });
        chrome.app.window.current().show();

        var screenshotDataUrl = screenshotCanvas.toDataURL('image/png');
        $('screenshot-image').src = screenshotDataUrl;
        $('screenshot-image').classList.toggle('wide-screen',
            $('screenshot-image').width > MAX_SCREENSHOT_WIDTH);
        feedbackInfo.screenshot = dataUrlToBlob(screenshotDataUrl);
      });

      chrome.feedbackPrivate.getUserEmail(function(email) {
        $('user-email-text').value = email;
      });

      // Initiate getting the system info and use it to prepare the full
      // feedback info.
      getSystemInformation(onSystemInformation);

      // An extension called us with an attached file.
      if (feedbackInfo.attachedFile) {
        $('attached-filename-text').textContent =
            feedbackInfo.attachedFile.name;
        attachedFileBlob = feedbackInfo.attachedFile.data;
        $('custom-file-container').hidden = false;
        $('attach-file').hidden = true;
      }

      // No URL and file attachment for login screen feedback.
      if (feedbackInfo.flow == FeedbackFlow.LOGIN) {
        $('page-url').hidden = true;
        $('attach-file-container').hidden = true;
        $('attach-file-note').hidden = true;
      }

<if expr="chromeos">
      if (feedbackInfo.traceId && ($('performance-info-area'))) {
        $('performance-info-area').hidden = false;
        $('performance-info-checkbox').checked = true;
        performanceFeedbackChanged();
        $('performance-info-link').onclick = openSlowTraceWindow;
      }
</if>

      chrome.feedbackPrivate.getStrings(function(strings) {
        loadTimeData.data = strings;
        i18nTemplate.process(document, loadTimeData);

        if ($('sys-info-url')) {
          // Opens a new window showing the full anonymized system+app
          // information.
          $('sys-info-url').onclick = function() {
            var win = chrome.app.window.get(SYSINFO_WINDOW_ID);
            if (win) {
              win.show();
              return;
            }
            chrome.app.window.create(
              '/html/sys_info.html', {
                frame: 'chrome',
                id: SYSINFO_WINDOW_ID,
                width: 600,
                height: 400,
                hidden: false,
                resizable: true
              }, function(appWindow) {
                // Define functions for the newly created window.

                // Gets the full system information for the new window.
                appWindow.contentWindow.getFullSystemInfo =
                    function(callback) {
                      if (isSystemInfoReady()) {
                        callback(feedbackInfo.systemInformation);
                        return;
                      }

                      sysInfoPageOnSysInfoReadyCallback = callback;
                    };

                // Returns the loadTimeData for the new window.
                appWindow.contentWindow.getLoadTimeData = function() {
                  return loadTimeData;
                };
            });
          };
        }
        if ($('histograms-url')) {
          // Opens a new window showing the histogram metrics.
          $('histograms-url').onclick =
              windowOpener(STATS_WINDOW_ID, 'chrome://histograms');
        }
        // Make sure our focus starts on the description field.
        $('description-text').focus();
      });
    }
  });

  window.addEventListener('DOMContentLoaded', function() {
    // Ready to receive the feedback object.
    chrome.runtime.sendMessage({ready: true});

    // Setup our event handlers.
    $('attach-file').addEventListener('change', onFileSelected);
    $('send-report-button').onclick = sendReport;
    $('cancel-button').onclick = cancel;
    $('remove-attached-file').onclick = clearAttachedFile;
<if expr="chromeos">
    $('performance-info-checkbox').addEventListener(
        'change', performanceFeedbackChanged);
</if>
  });
}

initialize();