mirror of
https://github.com/mozilla/gecko-dev.git
synced 2024-10-12 04:45:45 +00:00
Merge fx-team to m-c
This commit is contained in:
commit
d059fe67b7
2
CLOBBER
2
CLOBBER
@ -22,4 +22,4 @@
|
||||
# changes to stick? As of bug 928195, this shouldn't be necessary! Please
|
||||
# don't change CLOBBER for WebIDL changes any more.
|
||||
|
||||
Intermittent Android startup crashes leading to test bustage.
|
||||
Bug 983185 requires a clobber. This may not affect all platforms.
|
||||
|
@ -297,6 +297,7 @@
|
||||
@BINPATH@/components/storage.xpt
|
||||
@BINPATH@/components/telemetry.xpt
|
||||
@BINPATH@/components/toolkit_finalizationwitness.xpt
|
||||
@BINPATH@/components/toolkit_osfile.xpt
|
||||
@BINPATH@/components/toolkitprofile.xpt
|
||||
#ifdef MOZ_ENABLE_XREMOTE
|
||||
@BINPATH@/components/toolkitremote.xpt
|
||||
|
@ -460,6 +460,7 @@ const PanelUI = {
|
||||
* @return the selected locale or "en-US" if none is selected
|
||||
*/
|
||||
function getLocale() {
|
||||
const PREF_SELECTED_LOCALE = "general.useragent.locale";
|
||||
try {
|
||||
let locale = Services.prefs.getComplexValue(PREF_SELECTED_LOCALE,
|
||||
Ci.nsIPrefLocalizedString);
|
||||
|
@ -3681,7 +3681,11 @@ OverflowableToolbar.prototype = {
|
||||
if (!this._enabled)
|
||||
return;
|
||||
|
||||
this._moveItemsBackToTheirOrigin();
|
||||
if (this._target.scrollLeftMax > 0) {
|
||||
this.onOverflow();
|
||||
} else {
|
||||
this._moveItemsBackToTheirOrigin();
|
||||
}
|
||||
},
|
||||
|
||||
_disable: function() {
|
||||
|
@ -65,6 +65,7 @@ skip-if = os == "linux"
|
||||
[browser_948985_non_removable_defaultArea.js]
|
||||
[browser_952963_areaType_getter_no_area.js]
|
||||
[browser_956602_remove_special_widget.js]
|
||||
[browser_963639_customizing_attribute_non_customizable_toolbar.js]
|
||||
[browser_968447_bookmarks_toolbar_items_in_panel.js]
|
||||
[browser_968565_insert_before_hidden_items.js]
|
||||
[browser_969427_recreate_destroyed_widget_after_reset.js]
|
||||
|
@ -0,0 +1,34 @@
|
||||
/* 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/. */
|
||||
|
||||
"use strict";
|
||||
|
||||
const kToolbar = "test-toolbar-963639-non-customizable-customizing-attribute";
|
||||
|
||||
add_task(function() {
|
||||
info("Test for Bug 963639 - CustomizeMode _onToolbarVisibilityChange sets @customizing on non-customizable toolbars");
|
||||
|
||||
let toolbar = document.createElement("toolbar");
|
||||
toolbar.id = kToolbar;
|
||||
gNavToolbox.appendChild(toolbar);
|
||||
|
||||
let testToolbar = document.getElementById(kToolbar)
|
||||
ok(testToolbar, "Toolbar was created.");
|
||||
is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 1,
|
||||
"Toolbar was added to the navigator toolbox");
|
||||
|
||||
toolbar.setAttribute("toolbarname", "NonCustomizableToolbarCustomizingAttribute");
|
||||
toolbar.setAttribute("collapsed", "true");
|
||||
|
||||
yield startCustomizing();
|
||||
window.setToolbarVisibility(toolbar, "true");
|
||||
isnot(toolbar.getAttribute("customizing"), "true",
|
||||
"Toolbar doesn't have the customizing attribute");
|
||||
|
||||
yield endCustomizing();
|
||||
gNavToolbox.removeChild(toolbar);
|
||||
|
||||
is(gNavToolbox.getElementsByAttribute("id", kToolbar).length, 0,
|
||||
"Toolbar was removed from the navigator toolbox");
|
||||
});
|
@ -23,7 +23,7 @@ function test() {
|
||||
Task.spawn(function* () {
|
||||
try {
|
||||
|
||||
yield waitForSourceShown(gPanel, CODE_URL);
|
||||
yield ensureSourceIs(gPanel, CODE_URL, true);
|
||||
|
||||
// Pause and set our breakpoints.
|
||||
yield doInterrupt();
|
||||
|
@ -10,6 +10,9 @@ function test() {
|
||||
initNetMonitor(FILTERING_URL).then(([aTab, aDebuggee, aMonitor]) => {
|
||||
info("Starting test... ");
|
||||
|
||||
// It seems that this test may be slow on Ubuntu builds running on ec2.
|
||||
requestLongerTimeout(2);
|
||||
|
||||
let { $, NetMonitorView } = aMonitor.panelWin;
|
||||
let { RequestsMenu } = NetMonitorView;
|
||||
|
||||
|
@ -310,6 +310,7 @@
|
||||
@BINPATH@/components/spellchecker.xpt
|
||||
@BINPATH@/components/storage.xpt
|
||||
@BINPATH@/components/toolkit_finalizationwitness.xpt
|
||||
@BINPATH@/components/toolkit_osfile.xpt
|
||||
@BINPATH@/components/toolkitprofile.xpt
|
||||
#ifdef MOZ_ENABLE_XREMOTE
|
||||
@BINPATH@/components/toolkitremote.xpt
|
||||
|
@ -84,6 +84,10 @@ browser.jar:
|
||||
* skin/classic/browser/customizableui/panelUIOverlay.css (customizableui/panelUIOverlay.css)
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted.png (../shared/customizableui/subView-arrow-back-inverted.png)
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted-rtl.png (../shared/customizableui/subView-arrow-back-inverted-rtl.png)
|
||||
skin/classic/browser/customizableui/whimsy.png (../shared/customizableui/whimsy.png)
|
||||
skin/classic/browser/customizableui/whimsy@2x.png (../shared/customizableui/whimsy@2x.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw.png (../shared/customizableui/whimsy-bw.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw@2x.png (../shared/customizableui/whimsy-bw@2x.png)
|
||||
skin/classic/browser/downloads/allDownloadsViewOverlay.css (downloads/allDownloadsViewOverlay.css)
|
||||
skin/classic/browser/downloads/buttons.png (downloads/buttons.png)
|
||||
skin/classic/browser/downloads/contentAreaDownloadsView.css (downloads/contentAreaDownloadsView.css)
|
||||
|
@ -141,6 +141,10 @@ browser.jar:
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted-rtl.png (../shared/customizableui/subView-arrow-back-inverted-rtl.png)
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted-rtl@2x.png (../shared/customizableui/subView-arrow-back-inverted-rtl@2x.png)
|
||||
* skin/classic/browser/customizableui/panelUIOverlay.css (customizableui/panelUIOverlay.css)
|
||||
skin/classic/browser/customizableui/whimsy.png (../shared/customizableui/whimsy.png)
|
||||
skin/classic/browser/customizableui/whimsy@2x.png (../shared/customizableui/whimsy@2x.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw.png (../shared/customizableui/whimsy-bw.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw@2x.png (../shared/customizableui/whimsy-bw@2x.png)
|
||||
skin/classic/browser/downloads/allDownloadsViewOverlay.css (downloads/allDownloadsViewOverlay.css)
|
||||
skin/classic/browser/downloads/buttons.png (downloads/buttons.png)
|
||||
skin/classic/browser/downloads/buttons@2x.png (downloads/buttons@2x.png)
|
||||
|
@ -19,6 +19,44 @@
|
||||
|
||||
%include ../browser.inc
|
||||
|
||||
#PanelUI-popup #PanelUI-contents:empty {
|
||||
height: 128px;
|
||||
}
|
||||
|
||||
#PanelUI-popup #PanelUI-contents:empty::before {
|
||||
content: "";
|
||||
background-image: url(chrome://browser/skin/customizableui/whimsy-bw.png);
|
||||
display: block;
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
position: absolute;
|
||||
animation: moveX 3.05s linear 0s infinite alternate,
|
||||
moveY 3.4s linear 0s infinite alternate;
|
||||
}
|
||||
|
||||
#PanelUI-popup #PanelUI-contents:empty:hover::before {
|
||||
background-image: url(chrome://browser/skin/customizableui/whimsy.png);
|
||||
}
|
||||
|
||||
@media (min-resolution: 2dppx) {
|
||||
#PanelUI-popup #PanelUI-contents:empty::before {
|
||||
background-image: url(chrome://browser/skin/customizableui/whimsy-bw@2x.png);
|
||||
background-size: 64px 64px;
|
||||
}
|
||||
#PanelUI-popup #PanelUI-contents:empty:hover::before {
|
||||
background-image: url(chrome://browser/skin/customizableui/whimsy@2x.png);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes moveX {
|
||||
/* These values are adjusted for the padding on the panel. */
|
||||
from { margin-left: -15px; } to { margin-left: calc(100% - 49px); }
|
||||
}
|
||||
@keyframes moveY {
|
||||
/* These values are adjusted for the padding and height of the panel. */
|
||||
from { margin-top: -6px; } to { margin-top: 58px; }
|
||||
}
|
||||
|
||||
#PanelUI-button {
|
||||
background-image: linear-gradient(to bottom, hsla(0,0%,100%,0), hsla(0,0%,100%,.3) 30%, hsla(0,0%,100%,.3) 70%, hsla(0,0%,100%,0)),
|
||||
linear-gradient(to bottom, hsla(210,54%,20%,0), hsla(210,54%,20%,.3) 30%, hsla(210,54%,20%,.3) 70%, hsla(210,54%,20%,0)),
|
||||
|
BIN
browser/themes/shared/customizableui/whimsy-bw.png
Normal file
BIN
browser/themes/shared/customizableui/whimsy-bw.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.2 KiB |
BIN
browser/themes/shared/customizableui/whimsy-bw@2x.png
Normal file
BIN
browser/themes/shared/customizableui/whimsy-bw@2x.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 11 KiB |
BIN
browser/themes/shared/customizableui/whimsy.png
Normal file
BIN
browser/themes/shared/customizableui/whimsy.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 6.5 KiB |
BIN
browser/themes/shared/customizableui/whimsy@2x.png
Normal file
BIN
browser/themes/shared/customizableui/whimsy@2x.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 18 KiB |
@ -103,6 +103,10 @@ browser.jar:
|
||||
* skin/classic/browser/customizableui/panelUIOverlay.css (customizableui/panelUIOverlay.css)
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted.png (../shared/customizableui/subView-arrow-back-inverted.png)
|
||||
skin/classic/browser/customizableui/subView-arrow-back-inverted-rtl.png (../shared/customizableui/subView-arrow-back-inverted-rtl.png)
|
||||
skin/classic/browser/customizableui/whimsy.png (../shared/customizableui/whimsy.png)
|
||||
skin/classic/browser/customizableui/whimsy@2x.png (../shared/customizableui/whimsy@2x.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw.png (../shared/customizableui/whimsy-bw.png)
|
||||
skin/classic/browser/customizableui/whimsy-bw@2x.png (../shared/customizableui/whimsy-bw@2x.png)
|
||||
* skin/classic/browser/downloads/allDownloadsViewOverlay.css (downloads/allDownloadsViewOverlay.css)
|
||||
skin/classic/browser/downloads/buttons.png (downloads/buttons.png)
|
||||
skin/classic/browser/downloads/contentAreaDownloadsView.css (downloads/contentAreaDownloadsView.css)
|
||||
@ -431,6 +435,10 @@ browser.jar:
|
||||
* skin/classic/aero/browser/customizableui/panelUIOverlay.css (customizableui/panelUIOverlay-aero.css)
|
||||
skin/classic/aero/browser/customizableui/subView-arrow-back-inverted.png (../shared/customizableui/subView-arrow-back-inverted.png)
|
||||
skin/classic/aero/browser/customizableui/subView-arrow-back-inverted-rtl.png (../shared/customizableui/subView-arrow-back-inverted-rtl.png)
|
||||
skin/classic/aero/browser/customizableui/whimsy.png (../shared/customizableui/whimsy.png)
|
||||
skin/classic/aero/browser/customizableui/whimsy@2x.png (../shared/customizableui/whimsy@2x.png)
|
||||
skin/classic/aero/browser/customizableui/whimsy-bw.png (../shared/customizableui/whimsy-bw.png)
|
||||
skin/classic/aero/browser/customizableui/whimsy-bw@2x.png (../shared/customizableui/whimsy-bw@2x.png)
|
||||
* skin/classic/aero/browser/downloads/allDownloadsViewOverlay.css (downloads/allDownloadsViewOverlay-aero.css)
|
||||
skin/classic/aero/browser/downloads/buttons.png (downloads/buttons-aero.png)
|
||||
skin/classic/aero/browser/downloads/contentAreaDownloadsView.css (downloads/contentAreaDownloadsView.css)
|
||||
|
@ -709,6 +709,8 @@ static const dom::ConstantSpec gWinProperties[] =
|
||||
INT_CONSTANT(ERROR_FILE_NOT_FOUND),
|
||||
INT_CONSTANT(ERROR_NO_MORE_FILES),
|
||||
INT_CONSTANT(ERROR_PATH_NOT_FOUND),
|
||||
INT_CONSTANT(ERROR_BAD_ARGUMENTS),
|
||||
INT_CONSTANT(ERROR_NOT_SUPPORTED),
|
||||
|
||||
PROP_END
|
||||
};
|
||||
|
21
dom/webidl/NativeOSFileInternals.webidl
Normal file
21
dom/webidl/NativeOSFileInternals.webidl
Normal file
@ -0,0 +1,21 @@
|
||||
/* 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 obtaone at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/**
|
||||
* Options for nsINativeOSFileInternals::Read
|
||||
*/
|
||||
dictionary NativeOSFileReadOptions
|
||||
{
|
||||
/**
|
||||
* If specified, convert the raw bytes to a String
|
||||
* with the specified encoding. Otherwise, return
|
||||
* the raw bytes as a TypedArray.
|
||||
*/
|
||||
DOMString? encoding;
|
||||
|
||||
/**
|
||||
* If specified, limit the number of bytes to read.
|
||||
*/
|
||||
unsigned long long? bytes;
|
||||
};
|
@ -244,6 +244,7 @@ WEBIDL_FILES = [
|
||||
'MozWakeLock.webidl',
|
||||
'MutationEvent.webidl',
|
||||
'MutationObserver.webidl',
|
||||
'NativeOSFileInternals.webidl',
|
||||
'NetDashboard.webidl',
|
||||
'NetworkOptions.webidl',
|
||||
'Node.webidl',
|
||||
|
@ -20,6 +20,7 @@ import org.mozilla.gecko.GeckoProfileDirectories.NoMozillaDirectoryException;
|
||||
import org.mozilla.gecko.animation.PropertyAnimator;
|
||||
import org.mozilla.gecko.animation.ViewHelper;
|
||||
import org.mozilla.gecko.db.BrowserContract.Combined;
|
||||
import org.mozilla.gecko.db.BrowserContract.ReadingListItems;
|
||||
import org.mozilla.gecko.db.BrowserDB;
|
||||
import org.mozilla.gecko.favicons.Favicons;
|
||||
import org.mozilla.gecko.favicons.LoadFaviconTask;
|
||||
@ -59,6 +60,7 @@ import org.mozilla.gecko.widget.GeckoActionProvider;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
@ -385,7 +387,7 @@ abstract public class BrowserApp extends GeckoApp
|
||||
});
|
||||
}
|
||||
|
||||
void handleReaderAdded(int result, final String title, final String url) {
|
||||
private void handleReaderAdded(int result, final ContentValues values) {
|
||||
if (result != READER_ADD_SUCCESS) {
|
||||
if (result == READER_ADD_FAILED) {
|
||||
showToast(R.string.reading_list_failed, Toast.LENGTH_SHORT);
|
||||
@ -399,7 +401,7 @@ abstract public class BrowserApp extends GeckoApp
|
||||
ThreadUtils.postToBackgroundThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
BrowserDB.addReadingListItem(getContentResolver(), title, url);
|
||||
BrowserDB.addReadingListItem(getContentResolver(), values);
|
||||
showToast(R.string.reading_list_added, Toast.LENGTH_SHORT);
|
||||
|
||||
final int count = BrowserDB.getReadingListCount(getContentResolver());
|
||||
@ -408,6 +410,15 @@ abstract public class BrowserApp extends GeckoApp
|
||||
});
|
||||
}
|
||||
|
||||
private ContentValues messageToReadingListContentValues(JSONObject message) {
|
||||
final ContentValues values = new ContentValues();
|
||||
values.put(ReadingListItems.URL, message.optString("url"));
|
||||
values.put(ReadingListItems.TITLE, message.optString("title"));
|
||||
values.put(ReadingListItems.LENGTH, message.optInt("length"));
|
||||
values.put(ReadingListItems.EXCERPT, message.optString("excerpt"));
|
||||
return values;
|
||||
}
|
||||
|
||||
void handleReaderRemoved(final String url) {
|
||||
ThreadUtils.postToBackgroundThread(new Runnable() {
|
||||
@Override
|
||||
@ -1127,9 +1138,7 @@ abstract public class BrowserApp extends GeckoApp
|
||||
handleReaderListStatusRequest(message.getString("url"));
|
||||
} else if (event.equals("Reader:Added")) {
|
||||
final int result = message.getInt("result");
|
||||
final String title = message.getString("title");
|
||||
final String url = message.getString("url");
|
||||
handleReaderAdded(result, title, url);
|
||||
handleReaderAdded(result, messageToReadingListContentValues(message));
|
||||
} else if (event.equals("Reader:Removed")) {
|
||||
final String url = message.getString("url");
|
||||
handleReaderRemoved(url);
|
||||
@ -1645,17 +1654,21 @@ abstract public class BrowserApp extends GeckoApp
|
||||
final ViewStub homePagerStub = (ViewStub) findViewById(R.id.home_pager_stub);
|
||||
mHomePager = (HomePager) homePagerStub.inflate();
|
||||
|
||||
final HomeBanner homeBanner = (HomeBanner) findViewById(R.id.home_banner);
|
||||
mHomePager.setBanner(homeBanner);
|
||||
// Don't show the banner in guest mode.
|
||||
if (!getProfile().inGuestMode()) {
|
||||
final ViewStub homeBannerStub = (ViewStub) findViewById(R.id.home_banner_stub);
|
||||
final HomeBanner homeBanner = (HomeBanner) homeBannerStub.inflate();
|
||||
mHomePager.setBanner(homeBanner);
|
||||
|
||||
// Remove the banner from the view hierarchy if it is dismissed.
|
||||
homeBanner.setOnDismissListener(new HomeBanner.OnDismissListener() {
|
||||
@Override
|
||||
public void onDismiss() {
|
||||
mHomePager.setBanner(null);
|
||||
mHomePagerContainer.removeView(homeBanner);
|
||||
}
|
||||
});
|
||||
// Remove the banner from the view hierarchy if it is dismissed.
|
||||
homeBanner.setOnDismissListener(new HomeBanner.OnDismissListener() {
|
||||
@Override
|
||||
public void onDismiss() {
|
||||
mHomePager.setBanner(null);
|
||||
mHomePagerContainer.removeView(homeBanner);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
mHomePagerContainer.setVisibility(View.VISIBLE);
|
||||
|
@ -106,7 +106,7 @@ public class DynamicToolbar {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean immediate = transition.equals(VisibilityTransition.ANIMATE);
|
||||
final boolean immediate = transition.equals(VisibilityTransition.IMMEDIATE);
|
||||
if (visible) {
|
||||
layerView.getLayerMarginsAnimator().showMargins(immediate);
|
||||
} else {
|
||||
|
@ -1197,10 +1197,10 @@ public class GeckoAppShell
|
||||
* @return an <code>Intent</code>, or <code>null</code> if none could be
|
||||
* produced.
|
||||
*/
|
||||
static Intent getShareIntent(final Context context,
|
||||
final String targetURI,
|
||||
final String mimeType,
|
||||
final String title) {
|
||||
public static Intent getShareIntent(final Context context,
|
||||
final String targetURI,
|
||||
final String mimeType,
|
||||
final String title) {
|
||||
Intent shareIntent = getIntentForActionString(Intent.ACTION_SEND);
|
||||
shareIntent.putExtra(Intent.EXTRA_TEXT, targetURI);
|
||||
shareIntent.putExtra(Intent.EXTRA_SUBJECT, title);
|
||||
|
@ -396,6 +396,9 @@ public class BrowserContract {
|
||||
public static final String DEFAULT_SORT_ORDER = _ID + " DESC";
|
||||
public static final String[] DEFAULT_PROJECTION = new String[] { _ID, URL, TITLE, EXCERPT, LENGTH };
|
||||
|
||||
// Minimum fields required to create a reading list item.
|
||||
public static final String[] REQUIRED_FIELDS = { Bookmarks.URL, Bookmarks.TITLE };
|
||||
|
||||
public static final String TABLE_NAME = "reading_list";
|
||||
}
|
||||
|
||||
|
@ -13,6 +13,7 @@ import org.mozilla.gecko.favicons.decoders.LoadFaviconResult;
|
||||
import org.mozilla.gecko.mozglue.RobocopTarget;
|
||||
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentValues;
|
||||
import android.database.ContentObserver;
|
||||
import android.database.Cursor;
|
||||
import android.database.CursorWrapper;
|
||||
@ -98,7 +99,7 @@ public class BrowserDB {
|
||||
@RobocopTarget
|
||||
public void updateBookmark(ContentResolver cr, int id, String uri, String title, String keyword);
|
||||
|
||||
public void addReadingListItem(ContentResolver cr, String title, String uri);
|
||||
public void addReadingListItem(ContentResolver cr, ContentValues values);
|
||||
|
||||
public void removeReadingListItemWithURL(ContentResolver cr, String uri);
|
||||
|
||||
@ -271,8 +272,8 @@ public class BrowserDB {
|
||||
sDb.updateBookmark(cr, id, uri, title, keyword);
|
||||
}
|
||||
|
||||
public static void addReadingListItem(ContentResolver cr, String title, String uri) {
|
||||
sDb.addReadingListItem(cr, title, uri);
|
||||
public static void addReadingListItem(ContentResolver cr, ContentValues values) {
|
||||
sDb.addReadingListItem(cr, values);
|
||||
}
|
||||
|
||||
public static void removeReadingListItemWithURL(ContentResolver cr, String uri) {
|
||||
|
@ -699,11 +699,16 @@ public class LocalBrowserDB implements BrowserDB.BrowserDBIface {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addReadingListItem(ContentResolver cr, String title, String uri) {
|
||||
final ContentValues values = new ContentValues();
|
||||
public void addReadingListItem(ContentResolver cr, ContentValues values) {
|
||||
// Check that required fields are present.
|
||||
for (String field: ReadingListItems.REQUIRED_FIELDS) {
|
||||
if (!values.containsKey(field)) {
|
||||
throw new IllegalArgumentException("Missing required field for reading list item: " + field);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear delete flag if necessary
|
||||
values.put(ReadingListItems.IS_DELETED, 0);
|
||||
values.put(ReadingListItems.URL, uri);
|
||||
values.put(ReadingListItems.TITLE, title);
|
||||
|
||||
// Restore deleted record if possible
|
||||
final Uri insertUri = mReadingListUriWithProfile
|
||||
@ -714,7 +719,7 @@ public class LocalBrowserDB implements BrowserDB.BrowserDBIface {
|
||||
final int updated = cr.update(insertUri,
|
||||
values,
|
||||
ReadingListItems.URL + " = ? ",
|
||||
new String[] { uri });
|
||||
new String[] { values.getAsString(ReadingListItems.URL) });
|
||||
|
||||
debug("Updated " + updated + " rows to new modified time.");
|
||||
}
|
||||
|
@ -70,7 +70,7 @@ public class HomeBanner extends LinearLayout
|
||||
public HomeBanner(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
|
||||
LayoutInflater.from(context).inflate(R.layout.home_banner, this);
|
||||
LayoutInflater.from(context).inflate(R.layout.home_banner_content, this);
|
||||
|
||||
mTextView = (TextView) findViewById(R.id.text);
|
||||
mIconView = (ImageView) findViewById(R.id.icon);
|
||||
|
@ -335,6 +335,10 @@ size. -->
|
||||
as alternate text for accessibility. It is not visible in the UI. -->
|
||||
<!ENTITY home_reading_list_hint_accessible "TIP: Save articles to your reading list by long pressing the reader mode button when it appears in the title bar.">
|
||||
|
||||
<!-- Localization note (home_default_empty): This string is used as the default text when there
|
||||
is no data to show in an about:home panel that was created by an add-on. -->
|
||||
<!ENTITY home_default_empty "No content could be found for this panel.">
|
||||
|
||||
<!ENTITY pin_site_dialog_hint "Enter a search keyword">
|
||||
|
||||
<!ENTITY filepicker_title "Choose File">
|
||||
|
@ -102,6 +102,25 @@ public class MenuItemActionView extends LinearLayout
|
||||
mMenuItem.setShowIcon(show);
|
||||
}
|
||||
|
||||
public void setIcon(Drawable icon) {
|
||||
mMenuItem.setIcon(icon);
|
||||
mMenuButton.setIcon(icon);
|
||||
}
|
||||
|
||||
public void setIcon(int icon) {
|
||||
mMenuItem.setIcon(icon);
|
||||
mMenuButton.setIcon(icon);
|
||||
}
|
||||
|
||||
public void setTitle(CharSequence title) {
|
||||
mMenuItem.setTitle(title);
|
||||
mMenuButton.setContentDescription(title);
|
||||
}
|
||||
|
||||
public void setSubMenuIndicator(boolean hasSubMenu) {
|
||||
mMenuItem.setSubMenuIndicator(hasSubMenu);
|
||||
}
|
||||
|
||||
public void addActionButton(Drawable drawable) {
|
||||
// If this is the first icon, retain the text.
|
||||
// If not, make the menu item an icon.
|
||||
|
@ -142,7 +142,7 @@ public class MenuItemDefault extends TextView
|
||||
}
|
||||
}
|
||||
|
||||
private void setSubMenuIndicator(boolean hasSubMenu) {
|
||||
void setSubMenuIndicator(boolean hasSubMenu) {
|
||||
if (mHasSubMenu != hasSubMenu) {
|
||||
mHasSubMenu = hasSubMenu;
|
||||
refreshDrawableState();
|
||||
|
@ -61,7 +61,7 @@ public class IntentChooserPrompt {
|
||||
|
||||
// If there's only one item in the intent list, just return it
|
||||
if (mItems.size() == 1) {
|
||||
handler.onIntentSelected(mItems.get(0).intent, 0);
|
||||
handler.onIntentSelected(mItems.get(0).getIntent(), 0);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -82,7 +82,7 @@ public class IntentChooserPrompt {
|
||||
if (itemId == -1) {
|
||||
handler.onCancelled();
|
||||
} else {
|
||||
handler.onIntentSelected(mItems.get(itemId).intent, itemId);
|
||||
handler.onIntentSelected(mItems.get(itemId).getIntent(), itemId);
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -128,12 +128,14 @@ public class IntentChooserPrompt {
|
||||
|
||||
private PromptListItem getItemForResolveInfo(ResolveInfo info, PackageManager pm, Intent intent) {
|
||||
PromptListItem item = new PromptListItem(info.loadLabel(pm).toString());
|
||||
item.icon = info.loadIcon(pm);
|
||||
item.intent = new Intent(intent);
|
||||
item.setIcon(info.loadIcon(pm));
|
||||
|
||||
Intent i = new Intent(intent);
|
||||
// These intents should be implicit.
|
||||
item.intent.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName,
|
||||
info.activityInfo.name));
|
||||
i.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName,
|
||||
info.activityInfo.name));
|
||||
item.setIntent(new Intent(i));
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
|
@ -1,12 +1,17 @@
|
||||
package org.mozilla.gecko.prompts;
|
||||
|
||||
import org.mozilla.gecko.menu.MenuItemActionView;
|
||||
import org.mozilla.gecko.R;
|
||||
import org.mozilla.gecko.GeckoAppShell;
|
||||
import org.mozilla.gecko.gfx.BitmapUtils;
|
||||
import org.mozilla.gecko.widget.GeckoActionProvider;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONException;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.Bitmap;
|
||||
@ -14,18 +19,20 @@ import android.graphics.drawable.BitmapDrawable;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.CheckedTextView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.ListView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.AdapterView;
|
||||
import android.util.TypedValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
private static final int VIEW_TYPE_ITEM = 0;
|
||||
private static final int VIEW_TYPE_GROUP = 1;
|
||||
private static final int VIEW_TYPE_COUNT = 2;
|
||||
private static final int VIEW_TYPE_ACTIONS = 2;
|
||||
private static final int VIEW_TYPE_COUNT = 3;
|
||||
|
||||
private static final String LOGTAG = "GeckoPromptListAdapter";
|
||||
|
||||
@ -38,6 +45,7 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
private static int mIconSize;
|
||||
private static int mMinRowSize;
|
||||
private static int mIconTextPadding;
|
||||
private static float mTextSize;
|
||||
private static boolean mInitialized = false;
|
||||
|
||||
PromptListAdapter(Context context, int textViewResourceId, PromptListItem[] objects) {
|
||||
@ -55,6 +63,8 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
mIconTextPadding = (int) (res.getDimension(R.dimen.prompt_service_icon_text_padding));
|
||||
mIconSize = (int) (res.getDimension(R.dimen.prompt_service_icon_size));
|
||||
mMinRowSize = (int) (res.getDimension(R.dimen.prompt_service_min_list_item_height));
|
||||
mTextSize = res.getDimension(R.dimen.menu_item_textsize);
|
||||
|
||||
mInitialized = true;
|
||||
}
|
||||
}
|
||||
@ -64,6 +74,8 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
PromptListItem item = getItem(position);
|
||||
if (item.isGroup) {
|
||||
return VIEW_TYPE_GROUP;
|
||||
} else if (item.showAsActions) {
|
||||
return VIEW_TYPE_ACTIONS;
|
||||
} else {
|
||||
return VIEW_TYPE_ITEM;
|
||||
}
|
||||
@ -90,11 +102,11 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
|
||||
public void toggleSelected(int position) {
|
||||
PromptListItem item = getItem(position);
|
||||
item.selected = !item.selected;
|
||||
item.setSelected(!item.getSelected());
|
||||
}
|
||||
|
||||
private void maybeUpdateIcon(PromptListItem item, TextView t) {
|
||||
if (item.icon == null && !item.inGroup && !item.isParent) {
|
||||
if (item.getIcon() == null && !item.inGroup && !item.isParent) {
|
||||
t.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
|
||||
return;
|
||||
}
|
||||
@ -103,10 +115,10 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
Resources res = getContext().getResources();
|
||||
// Set the padding between the icon and the text.
|
||||
t.setCompoundDrawablePadding(mIconTextPadding);
|
||||
if (item.icon != null) {
|
||||
if (item.getIcon() != null) {
|
||||
// We want the icon to be of a specific size. Some do not
|
||||
// follow this rule so we have to resize them.
|
||||
Bitmap bitmap = ((BitmapDrawable) item.icon).getBitmap();
|
||||
Bitmap bitmap = ((BitmapDrawable) item.getIcon()).getBitmap();
|
||||
d = new BitmapDrawable(res, Bitmap.createScaledBitmap(bitmap, mIconSize, mIconSize, true));
|
||||
} else if (item.inGroup) {
|
||||
// We don't currently support "indenting" items with icons
|
||||
@ -130,12 +142,12 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
// Apparently just using ct.setChecked(true) doesn't work, so this
|
||||
// is stolen from the android source code as a way to set the checked
|
||||
// state of these items
|
||||
list.setItemChecked(position, item.selected);
|
||||
list.setItemChecked(position, item.getSelected());
|
||||
}
|
||||
}
|
||||
|
||||
boolean isSelected(int position){
|
||||
return getItem(position).selected;
|
||||
return getItem(position).getSelected();
|
||||
}
|
||||
|
||||
ArrayList<Integer> getSelected() {
|
||||
@ -161,6 +173,41 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
return -1;
|
||||
}
|
||||
|
||||
private View getActionView(PromptListItem item) {
|
||||
GeckoActionProvider provider = GeckoActionProvider.getForType(item.getIntent().getType(), getContext());
|
||||
provider.setIntent(item.getIntent());
|
||||
return provider.onCreateActionView();
|
||||
}
|
||||
|
||||
private void updateActionView(final PromptListItem item, final MenuItemActionView view, final ListView list, final int position) {
|
||||
view.setTitle(item.label);
|
||||
view.setIcon(item.getIcon());
|
||||
view.setSubMenuIndicator(item.isParent);
|
||||
view.setMenuItemClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
ListView.OnItemClickListener listener = list.getOnItemClickListener();
|
||||
if (listener != null) {
|
||||
listener.onItemClick(list, view, position, position);
|
||||
}
|
||||
|
||||
final GeckoActionProvider provider = GeckoActionProvider.getForType(item.getIntent().getType(), getContext());
|
||||
IntentChooserPrompt prompt = new IntentChooserPrompt(getContext(), provider);
|
||||
prompt.show(item.label, getContext(), new IntentHandler() {
|
||||
@Override
|
||||
public void onIntentSelected(final Intent intent, final int p) {
|
||||
provider.chooseActivity(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancelled() {
|
||||
// do nothing
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
PromptListItem item = getItem(position);
|
||||
@ -168,26 +215,36 @@ public class PromptListAdapter extends ArrayAdapter<PromptListItem> {
|
||||
ViewHolder viewHolder = null;
|
||||
|
||||
if (convertView == null) {
|
||||
int resourceId = mResourceId;
|
||||
if (item.isGroup) {
|
||||
resourceId = R.layout.list_item_header;
|
||||
if (type == VIEW_TYPE_ACTIONS) {
|
||||
convertView = getActionView(item);
|
||||
} else {
|
||||
int resourceId = mResourceId;
|
||||
if (item.isGroup) {
|
||||
resourceId = R.layout.list_item_header;
|
||||
}
|
||||
|
||||
LayoutInflater mInflater = LayoutInflater.from(getContext());
|
||||
convertView = mInflater.inflate(resourceId, null);
|
||||
convertView.setMinimumHeight(mMinRowSize);
|
||||
|
||||
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
|
||||
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
|
||||
viewHolder = new ViewHolder(tv, tv.getPaddingLeft(), tv.getPaddingRight(),
|
||||
tv.getPaddingTop(), tv.getPaddingBottom());
|
||||
|
||||
convertView.setTag(viewHolder);
|
||||
}
|
||||
LayoutInflater mInflater = LayoutInflater.from(getContext());
|
||||
convertView = mInflater.inflate(resourceId, null);
|
||||
convertView.setMinimumHeight(mMinRowSize);
|
||||
|
||||
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
|
||||
viewHolder = new ViewHolder(tv, tv.getPaddingLeft(), tv.getPaddingRight(),
|
||||
tv.getPaddingTop(), tv.getPaddingBottom());
|
||||
|
||||
convertView.setTag(viewHolder);
|
||||
} else {
|
||||
viewHolder = (ViewHolder) convertView.getTag();
|
||||
}
|
||||
|
||||
viewHolder.textView.setText(item.label);
|
||||
maybeUpdateCheckedState((ListView) parent, position, item, viewHolder);
|
||||
maybeUpdateIcon(item, viewHolder.textView);
|
||||
if (type == VIEW_TYPE_ACTIONS) {
|
||||
updateActionView(item, (MenuItemActionView) convertView, (ListView) parent, position);
|
||||
} else {
|
||||
viewHolder.textView.setText(item.label);
|
||||
maybeUpdateCheckedState((ListView) parent, position, item, viewHolder);
|
||||
maybeUpdateIcon(item, viewHolder.textView);
|
||||
}
|
||||
|
||||
return convertView;
|
||||
}
|
||||
|
@ -1,11 +1,15 @@
|
||||
package org.mozilla.gecko.prompts;
|
||||
|
||||
import org.mozilla.gecko.gfx.BitmapUtils;
|
||||
import org.mozilla.gecko.GeckoAppShell;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONException;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
@ -18,28 +22,74 @@ public class PromptListItem {
|
||||
public final boolean inGroup;
|
||||
public final boolean disabled;
|
||||
public final int id;
|
||||
public boolean selected;
|
||||
public Intent intent;
|
||||
public final boolean showAsActions;
|
||||
public final boolean isParent;
|
||||
|
||||
public boolean isParent;
|
||||
public Drawable icon;
|
||||
public Intent mIntent;
|
||||
public boolean mSelected;
|
||||
public Drawable mIcon;
|
||||
|
||||
PromptListItem(JSONObject aObject) {
|
||||
label = aObject.optString("label");
|
||||
label = aObject.isNull("label") ? "" : aObject.optString("label");
|
||||
isGroup = aObject.optBoolean("isGroup");
|
||||
inGroup = aObject.optBoolean("inGroup");
|
||||
disabled = aObject.optBoolean("disabled");
|
||||
id = aObject.optInt("id");
|
||||
isParent = aObject.optBoolean("isParent");
|
||||
selected = aObject.optBoolean("selected");
|
||||
mSelected = aObject.optBoolean("selected");
|
||||
|
||||
JSONObject obj = aObject.optJSONObject("shareData");
|
||||
if (obj != null) {
|
||||
showAsActions = true;
|
||||
String uri = obj.isNull("uri") ? "" : obj.optString("uri");
|
||||
String type = obj.isNull("type") ? "" : obj.optString("type");
|
||||
mIntent = GeckoAppShell.getShareIntent(GeckoAppShell.getContext(), uri, type, "");
|
||||
isParent = true;
|
||||
} else {
|
||||
mIntent = null;
|
||||
showAsActions = false;
|
||||
isParent = aObject.optBoolean("isParent");
|
||||
}
|
||||
|
||||
BitmapUtils.getDrawable(GeckoAppShell.getContext(), aObject.optString("icon"), new BitmapUtils.BitmapLoader() {
|
||||
@Override
|
||||
public void onBitmapFound(Drawable d) {
|
||||
mIcon = d;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setIntent(Intent i) {
|
||||
mIntent = i;
|
||||
}
|
||||
|
||||
public Intent getIntent() {
|
||||
return mIntent;
|
||||
}
|
||||
|
||||
public void setIcon(Drawable icon) {
|
||||
mIcon = icon;
|
||||
}
|
||||
|
||||
public Drawable getIcon() {
|
||||
return mIcon;
|
||||
}
|
||||
|
||||
public void setSelected(boolean selected) {
|
||||
mSelected = selected;
|
||||
}
|
||||
|
||||
public boolean getSelected() {
|
||||
return mSelected;
|
||||
}
|
||||
|
||||
public PromptListItem(String aLabel) {
|
||||
label = aLabel;
|
||||
isGroup = false;
|
||||
inGroup = false;
|
||||
isParent = false;
|
||||
disabled = false;
|
||||
id = 0;
|
||||
showAsActions = false;
|
||||
}
|
||||
|
||||
static PromptListItem[] getArray(JSONArray items) {
|
||||
|
@ -36,17 +36,12 @@
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent"/>
|
||||
|
||||
<org.mozilla.gecko.home.HomeBanner android:id="@+id/home_banner"
|
||||
style="@style/Widget.HomeBanner"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="@dimen/home_banner_height"
|
||||
android:background="@drawable/home_banner"
|
||||
android:layout_gravity="bottom"
|
||||
android:gravity="center_vertical"
|
||||
android:visibility="gone"
|
||||
android:clickable="true"
|
||||
android:focusable="true"
|
||||
android:translationY="@dimen/home_banner_height"/>
|
||||
<ViewStub android:id="@+id/home_banner_stub"
|
||||
android:layout="@layout/home_banner"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="@dimen/home_banner_height"
|
||||
android:layout_gravity="bottom"
|
||||
android:translationY="@dimen/home_banner_height"/>
|
||||
|
||||
</FrameLayout>
|
||||
|
||||
|
@ -3,34 +3,13 @@
|
||||
- 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/. -->
|
||||
|
||||
<merge xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<ImageView android:id="@+id/icon"
|
||||
android:layout_width="48dip"
|
||||
android:layout_height="48dip"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:scaleType="centerInside"/>
|
||||
|
||||
<TextView android:id="@+id/text"
|
||||
android:layout_width="0dip"
|
||||
android:layout_height="fill_parent"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:paddingTop="7dp"
|
||||
android:paddingBottom="7dp"
|
||||
android:textAppearance="@style/TextAppearance.Widget.HomeBanner"
|
||||
android:layout_gravity="bottom"
|
||||
android:singleLine="false"
|
||||
android:maxLines="3"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_vertical"/>
|
||||
|
||||
<ImageButton android:id="@+id/close"
|
||||
android:layout_width="34dip"
|
||||
android:layout_height="fill_parent"
|
||||
android:background="@drawable/home_banner"
|
||||
android:scaleType="center"
|
||||
android:contentDescription="@string/close_tab"
|
||||
android:src="@drawable/tab_close"/>
|
||||
|
||||
</merge>
|
||||
<org.mozilla.gecko.home.HomeBanner xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/home_banner"
|
||||
style="@style/Widget.HomeBanner"
|
||||
android:layout_width="fill_parent"
|
||||
android:layout_height="fill_parent"
|
||||
android:background="@drawable/home_banner"
|
||||
android:gravity="center_vertical"
|
||||
android:visibility="gone"
|
||||
android:clickable="true"
|
||||
android:focusable="true"/>
|
||||
|
36
mobile/android/base/resources/layout/home_banner_content.xml
Normal file
36
mobile/android/base/resources/layout/home_banner_content.xml
Normal file
@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 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/. -->
|
||||
|
||||
<merge xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<ImageView android:id="@+id/icon"
|
||||
android:layout_width="48dip"
|
||||
android:layout_height="48dip"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:scaleType="centerInside"/>
|
||||
|
||||
<TextView android:id="@+id/text"
|
||||
android:layout_width="0dip"
|
||||
android:layout_height="fill_parent"
|
||||
android:layout_weight="1"
|
||||
android:layout_marginLeft="10dp"
|
||||
android:paddingTop="7dp"
|
||||
android:paddingBottom="7dp"
|
||||
android:textAppearance="@style/TextAppearance.Widget.HomeBanner"
|
||||
android:layout_gravity="bottom"
|
||||
android:singleLine="false"
|
||||
android:maxLines="3"
|
||||
android:ellipsize="end"
|
||||
android:gravity="center_vertical"/>
|
||||
|
||||
<ImageButton android:id="@+id/close"
|
||||
android:layout_width="34dip"
|
||||
android:layout_height="fill_parent"
|
||||
android:background="@drawable/home_banner"
|
||||
android:scaleType="center"
|
||||
android:contentDescription="@string/close_tab"
|
||||
android:src="@drawable/tab_close"/>
|
||||
|
||||
</merge>
|
@ -46,10 +46,12 @@
|
||||
|
||||
<dimen name="flow_layout_spacing">6dp</dimen>
|
||||
<dimen name="menu_item_icon">21dp</dimen>
|
||||
<dimen name="menu_item_textsize">16sp</dimen>
|
||||
<dimen name="menu_item_state_icon">18dp</dimen>
|
||||
<dimen name="menu_item_row_height">44dp</dimen>
|
||||
<dimen name="menu_item_row_width">240dp</dimen>
|
||||
<dimen name="menu_item_more_offset">5dp</dimen>
|
||||
<dimen name="menu_item_textsize">16sp</dimen>
|
||||
<dimen name="menu_popup_arrow_offset">8dp</dimen>
|
||||
<dimen name="menu_popup_arrow_margin">5dip</dimen>
|
||||
<dimen name="menu_popup_arrow_width">40dip</dimen>
|
||||
@ -57,7 +59,7 @@
|
||||
<dimen name="menu_popup_width">256dp</dimen>
|
||||
<dimen name="nav_button_border_width">0.75dp</dimen>
|
||||
<dimen name="prompt_service_group_padding_size">32dp</dimen>
|
||||
<dimen name="prompt_service_icon_size">72dp</dimen>
|
||||
<dimen name="prompt_service_icon_size">36dp</dimen>
|
||||
<dimen name="prompt_service_icon_text_padding">10dp</dimen>
|
||||
<dimen name="prompt_service_inputs_padding">16dp</dimen>
|
||||
<dimen name="prompt_service_left_right_text_with_icon_padding">10dp</dimen>
|
||||
|
@ -107,6 +107,7 @@
|
||||
<item name="android:textAppearance">@style/TextAppearance</item>
|
||||
<item name="android:singleLine">true</item>
|
||||
<item name="android:ellipsize">middle</item>
|
||||
<item name="android:textSize">@dimen/menu_item_textsize</item>
|
||||
</style>
|
||||
|
||||
<style name="Widget.TwoLinePageRow" />
|
||||
@ -258,7 +259,7 @@
|
||||
<item name="android:textColorHighlight">@color/text_color_highlight</item>
|
||||
<item name="android:textColorHint">?android:attr/textColorHint</item>
|
||||
<item name="android:textColorLink">?android:attr/textColorLink</item>
|
||||
<item name="android:textSize">16sp</item>
|
||||
<item name="android:textSize">@dimen/menu_item_textsize</item>
|
||||
<item name="android:textStyle">normal</item>
|
||||
</style>
|
||||
|
||||
|
@ -304,6 +304,7 @@
|
||||
<string name="home_reading_list_empty">&home_reading_list_empty;</string>
|
||||
<string name="home_reading_list_hint">&home_reading_list_hint2;</string>
|
||||
<string name="home_reading_list_hint_accessible">&home_reading_list_hint_accessible;</string>
|
||||
<string name="home_default_empty">&home_default_empty;</string>
|
||||
<string name="pin_site_dialog_hint">&pin_site_dialog_hint;</string>
|
||||
|
||||
<string name="filepicker_title">&filepicker_title;</string>
|
||||
|
@ -20,6 +20,7 @@ import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class GeckoActionProvider extends ActionProvider {
|
||||
private static int MAX_HISTORY_SIZE = 2;
|
||||
@ -44,6 +45,20 @@ public class GeckoActionProvider extends ActionProvider {
|
||||
|
||||
private final Callbacks mCallbacks = new Callbacks();
|
||||
|
||||
private static HashMap<String, GeckoActionProvider> mProviders = new HashMap<String, GeckoActionProvider>();
|
||||
|
||||
// Gets the action provider for a particular mimetype
|
||||
public static GeckoActionProvider getForType(String type, Context context) {
|
||||
if (!mProviders.keySet().contains(type)) {
|
||||
GeckoActionProvider provider = new GeckoActionProvider(context);
|
||||
|
||||
String subType = type.substring(0, type.indexOf("/"));
|
||||
provider.setHistoryFileName("history-" + subType + ".xml");
|
||||
mProviders.put(type, provider);
|
||||
}
|
||||
return mProviders.get(type);
|
||||
}
|
||||
|
||||
public GeckoActionProvider(Context context) {
|
||||
super(context);
|
||||
mContext = context;
|
||||
@ -141,6 +156,10 @@ public class GeckoActionProvider extends ActionProvider {
|
||||
return infos;
|
||||
}
|
||||
|
||||
public void chooseActivity(int position) {
|
||||
mCallbacks.chooseActivity(position);
|
||||
}
|
||||
|
||||
/**
|
||||
* Listener for handling default activity / menu item clicks.
|
||||
*/
|
||||
@ -168,7 +187,6 @@ public class GeckoActionProvider extends ActionProvider {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
Integer index = (Integer) view.getTag();
|
||||
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mHistoryFileName);
|
||||
chooseActivity(index);
|
||||
}
|
||||
}
|
||||
|
@ -718,6 +718,77 @@ Readability.prototype = {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Attempts to get the excerpt from these
|
||||
* sources in the following order:
|
||||
* - meta description tag
|
||||
* - open-graph description
|
||||
* - twitter cards description
|
||||
* - article's first paragraph
|
||||
* If no excerpt is found, an empty string will be
|
||||
* returned.
|
||||
*
|
||||
* @param Element - root element of the processed version page
|
||||
* @return String - excerpt of the article
|
||||
**/
|
||||
_getExcerpt: function(articleContent) {
|
||||
let values = {};
|
||||
let metaElements = this._doc.getElementsByTagName("meta");
|
||||
|
||||
// Match "description", or Twitter's "twitter:description" (Cards)
|
||||
// in name attribute.
|
||||
let namePattern = /^\s*((twitter)\s*:\s*)?description\s*$/gi;
|
||||
|
||||
// Match Facebook's og:description (Open Graph) in property attribute.
|
||||
let propertyPattern = /^\s*og\s*:\s*description\s*$/gi;
|
||||
|
||||
// Find description tags.
|
||||
for (let i = 0; i < metaElements.length; i++) {
|
||||
let element = metaElements[i];
|
||||
let elementName = element.getAttribute("name");
|
||||
let elementProperty = element.getAttribute("property");
|
||||
|
||||
let name;
|
||||
if (namePattern.test(elementName)) {
|
||||
name = elementName;
|
||||
} else if (propertyPattern.test(elementProperty)) {
|
||||
name = elementProperty;
|
||||
}
|
||||
|
||||
if (name) {
|
||||
let content = element.getAttribute("content");
|
||||
if (content) {
|
||||
// Convert to lowercase and remove any whitespace
|
||||
// so we can match below.
|
||||
name = name.toLowerCase().replace(/\s/g, '');
|
||||
values[name] = content.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ("description" in values) {
|
||||
return values["description"];
|
||||
}
|
||||
|
||||
if ("og:description" in values) {
|
||||
// Use facebook open graph description.
|
||||
return values["og:description"];
|
||||
}
|
||||
|
||||
if ("twitter:description" in values) {
|
||||
// Use twitter cards description.
|
||||
return values["twitter:description"];
|
||||
}
|
||||
|
||||
// No description meta tags, use the article's first paragraph.
|
||||
let paragraphs = articleContent.getElementsByTagName("p");
|
||||
if (paragraphs.length > 0) {
|
||||
return paragraphs[0].textContent;
|
||||
}
|
||||
|
||||
return "";
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes script tags from the document.
|
||||
*
|
||||
@ -1434,9 +1505,13 @@ Readability.prototype = {
|
||||
// }).bind(this), 500);
|
||||
// }
|
||||
|
||||
let excerpt = this._getExcerpt(articleContent);
|
||||
|
||||
return { title: articleTitle,
|
||||
byline: this._articleByline,
|
||||
dir: this._articleDir,
|
||||
content: articleContent.innerHTML };
|
||||
content: articleContent.innerHTML,
|
||||
length: articleContent.textContent.length,
|
||||
excerpt: excerpt };
|
||||
}
|
||||
};
|
||||
|
@ -349,6 +349,8 @@ AboutReader.prototype = {
|
||||
result: result,
|
||||
title: this._article.title,
|
||||
url: this._article.url,
|
||||
length: this._article.length,
|
||||
excerpt: this._article.excerpt
|
||||
});
|
||||
}.bind(this));
|
||||
} else {
|
||||
|
@ -7433,33 +7433,36 @@ let Reader = {
|
||||
throw new Error("Reader:Add requires a tabID or an URL as argument");
|
||||
}
|
||||
|
||||
let sendResult = function(result, title) {
|
||||
this.log("Reader:Add success=" + result + ", url=" + url + ", title=" + title);
|
||||
let sendResult = function(result, article) {
|
||||
article = article || {};
|
||||
this.log("Reader:Add success=" + result + ", url=" + url + ", title=" + article.title + ", excerpt=" + article.excerpt);
|
||||
|
||||
sendMessageToJava({
|
||||
type: "Reader:Added",
|
||||
result: result,
|
||||
title: title,
|
||||
title: article.title,
|
||||
url: url,
|
||||
length: article.length,
|
||||
excerpt: article.excerpt
|
||||
});
|
||||
}.bind(this);
|
||||
|
||||
let handleArticle = function(article) {
|
||||
if (!article) {
|
||||
sendResult(this.READER_ADD_FAILED, "");
|
||||
sendResult(this.READER_ADD_FAILED, null);
|
||||
return;
|
||||
}
|
||||
|
||||
this.storeArticleInCache(article, function(success) {
|
||||
let result = (success ? this.READER_ADD_SUCCESS : this.READER_ADD_FAILED);
|
||||
sendResult(result, article.title);
|
||||
sendResult(result, article);
|
||||
}.bind(this));
|
||||
}.bind(this);
|
||||
|
||||
this.getArticleFromCache(urlWithoutRef, function (article) {
|
||||
// If the article is already in reading list, bail
|
||||
if (article) {
|
||||
sendResult(this.READER_ADD_DUPLICATE, "");
|
||||
sendResult(this.READER_ADD_DUPLICATE, null);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -7473,13 +7476,14 @@ let Reader = {
|
||||
}
|
||||
|
||||
case "Reader:Remove": {
|
||||
this.removeArticleFromCache(aData, function(success) {
|
||||
this.log("Reader:Remove success=" + success + ", url=" + aData);
|
||||
let url = aData;
|
||||
this.removeArticleFromCache(url, function(success) {
|
||||
this.log("Reader:Remove success=" + success + ", url=" + url);
|
||||
|
||||
if (success) {
|
||||
sendMessageToJava({
|
||||
type: "Reader:Removed",
|
||||
url: aData
|
||||
url: url
|
||||
});
|
||||
}
|
||||
}.bind(this));
|
||||
|
@ -246,6 +246,7 @@
|
||||
@BINPATH@/components/storage.xpt
|
||||
@BINPATH@/components/telemetry.xpt
|
||||
@BINPATH@/components/toolkit_finalizationwitness.xpt
|
||||
@BINPATH@/components/toolkit_osfile.xpt
|
||||
@BINPATH@/components/toolkitprofile.xpt
|
||||
#ifdef MOZ_ENABLE_XREMOTE
|
||||
@BINPATH@/components/toolkitremote.xpt
|
||||
|
@ -320,3 +320,10 @@ openInApp.pageAction = Open in App
|
||||
openInApp.ok = OK
|
||||
openInApp.cancel = Cancel
|
||||
|
||||
#Tabs in context menus
|
||||
browser.menu.context.default = Link
|
||||
browser.menu.context.img = Image
|
||||
browser.menu.context.video = Video
|
||||
browser.menu.context.audio = Audio
|
||||
browser.menu.context.tel = Phone
|
||||
browser.menu.context.mailto = Mail
|
||||
|
@ -398,7 +398,7 @@ FxAccountsInternal.prototype = {
|
||||
getAssertion: function getAssertion(audience) {
|
||||
log.debug("enter getAssertion()");
|
||||
let currentState = this.currentAccountState;
|
||||
let mustBeValidUntil = this.now() + ASSERTION_LIFETIME;
|
||||
let mustBeValidUntil = this.now() + ASSERTION_USE_PERIOD;
|
||||
return currentState.getUserAccountData().then(data => {
|
||||
if (!data) {
|
||||
// No signed-in user
|
||||
@ -540,6 +540,7 @@ FxAccountsInternal.prototype = {
|
||||
let payload = {};
|
||||
let d = Promise.defer();
|
||||
let options = {
|
||||
duration: ASSERTION_LIFETIME,
|
||||
localtimeOffsetMsec: this.localtimeOffsetMsec,
|
||||
now: this.now()
|
||||
};
|
||||
|
@ -33,7 +33,14 @@ this.DATA_FORMAT_VERSION = 1;
|
||||
this.DEFAULT_STORAGE_FILENAME = "signedInUser.json";
|
||||
|
||||
// Token life times.
|
||||
this.ASSERTION_LIFETIME = 1000 * 60 * 5; // 5 minutes
|
||||
// Having this parameter be short has limited security value and can cause
|
||||
// spurious authentication values if the client's clock is skewed and
|
||||
// we fail to adjust. See Bug 983256.
|
||||
this.ASSERTION_LIFETIME = 1000 * 3600 * 24 * 365 * 25; // 25 years
|
||||
// This is a time period we want to guarantee that the assertion will be
|
||||
// valid after we generate it (e.g., the signed cert won't expire in this
|
||||
// period).
|
||||
this.ASSERTION_USE_PERIOD = 1000 * 60 * 5; // 5 minutes
|
||||
this.CERT_LIFETIME = 1000 * 3600 * 6; // 6 hours
|
||||
this.KEY_LIFETIME = 1000 * 3600 * 12; // 12 hours
|
||||
|
||||
|
@ -418,7 +418,7 @@ add_task(function test_getAssertion() {
|
||||
_("delta: " + Date.parse(payload.exp - start) + "\n");
|
||||
let exp = Number(payload.exp);
|
||||
|
||||
do_check_eq(exp, now + TWO_MINUTES_MS);
|
||||
do_check_eq(exp, now + ASSERTION_LIFETIME);
|
||||
|
||||
// Reset for next call.
|
||||
fxa.internal._d_signCertificate = Promise.defer();
|
||||
@ -430,7 +430,7 @@ add_task(function test_getAssertion() {
|
||||
// There were no additional calls - same number of getcert calls as before
|
||||
do_check_eq(fxa.internal._getCertificateSigned_calls.length, 1);
|
||||
|
||||
// Wait an hour; assertion expires, but not the certificate
|
||||
// Wait an hour; assertion use period expires, but not the certificate
|
||||
now += ONE_HOUR_MS;
|
||||
fxa.internal._now_is = now;
|
||||
|
||||
@ -456,7 +456,7 @@ add_task(function test_getAssertion() {
|
||||
do_check_eq(keyPair.validUntil, start + KEY_LIFETIME);
|
||||
do_check_eq(cert.validUntil, start + CERT_LIFETIME);
|
||||
exp = Number(payload.exp);
|
||||
do_check_eq(exp, now + TWO_MINUTES_MS);
|
||||
do_check_eq(exp, now + ASSERTION_LIFETIME);
|
||||
|
||||
// Now we wait even longer, and expect both assertion and cert to expire. So
|
||||
// we will have to get a new keypair and cert.
|
||||
@ -479,7 +479,7 @@ add_task(function test_getAssertion() {
|
||||
do_check_eq(cert.validUntil, now + CERT_LIFETIME);
|
||||
exp = Number(payload.exp);
|
||||
|
||||
do_check_eq(exp, now + TWO_MINUTES_MS);
|
||||
do_check_eq(exp, now + ASSERTION_LIFETIME);
|
||||
_("----- DONE ----\n");
|
||||
});
|
||||
|
||||
|
@ -35,6 +35,7 @@
|
||||
|
||||
#include "nsBrowserStatusFilter.h"
|
||||
#include "mozilla/FinalizationWitnessService.h"
|
||||
#include "mozilla/NativeOSFileInternals.h"
|
||||
|
||||
using namespace mozilla;
|
||||
|
||||
@ -89,6 +90,7 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsBrowserStatusFilter)
|
||||
NS_GENERIC_FACTORY_CONSTRUCTOR(nsUpdateProcessor)
|
||||
#endif
|
||||
NS_GENERIC_FACTORY_CONSTRUCTOR(FinalizationWitnessService)
|
||||
NS_GENERIC_FACTORY_CONSTRUCTOR(NativeOSFileInternalsService)
|
||||
|
||||
NS_DEFINE_NAMED_CID(NS_TOOLKIT_APPSTARTUP_CID);
|
||||
NS_DEFINE_NAMED_CID(NS_USERINFO_CID);
|
||||
@ -114,6 +116,7 @@ NS_DEFINE_NAMED_CID(NS_CHARSETMENU_CID);
|
||||
NS_DEFINE_NAMED_CID(NS_UPDATEPROCESSOR_CID);
|
||||
#endif
|
||||
NS_DEFINE_NAMED_CID(FINALIZATIONWITNESSSERVICE_CID);
|
||||
NS_DEFINE_NAMED_CID(NATIVE_OSFILE_INTERNALS_SERVICE_CID);
|
||||
|
||||
static const Module::CIDEntry kToolkitCIDs[] = {
|
||||
{ &kNS_TOOLKIT_APPSTARTUP_CID, false, nullptr, nsAppStartupConstructor },
|
||||
@ -140,6 +143,7 @@ static const Module::CIDEntry kToolkitCIDs[] = {
|
||||
{ &kNS_UPDATEPROCESSOR_CID, false, nullptr, nsUpdateProcessorConstructor },
|
||||
#endif
|
||||
{ &kFINALIZATIONWITNESSSERVICE_CID, false, nullptr, FinalizationWitnessServiceConstructor },
|
||||
{ &kNATIVE_OSFILE_INTERNALS_SERVICE_CID, false, nullptr, NativeOSFileInternalsServiceConstructor },
|
||||
{ nullptr }
|
||||
};
|
||||
|
||||
@ -169,6 +173,7 @@ static const Module::ContractIDEntry kToolkitContracts[] = {
|
||||
{ NS_UPDATEPROCESSOR_CONTRACTID, &kNS_UPDATEPROCESSOR_CID },
|
||||
#endif
|
||||
{ FINALIZATIONWITNESSSERVICE_CONTRACTID, &kFINALIZATIONWITNESSSERVICE_CID },
|
||||
{ NATIVE_OSFILE_INTERNALS_SERVICE_CONTRACTID, &kNATIVE_OSFILE_INTERNALS_SERVICE_CID },
|
||||
{ nullptr }
|
||||
};
|
||||
|
||||
|
@ -603,7 +603,7 @@ CrashStore.prototype = Object.freeze({
|
||||
|
||||
try {
|
||||
let decoder = new TextDecoder();
|
||||
let data = yield OS.File.read(this._storePath, null, {compression: "lz4"});
|
||||
let data = yield OS.File.read(this._storePath, {compression: "lz4"});
|
||||
data = JSON.parse(decoder.decode(data));
|
||||
|
||||
if (data.corruptDate) {
|
||||
|
@ -113,6 +113,8 @@ private:
|
||||
// An array of strings created from certificate information used to whitelist
|
||||
// the downloaded file.
|
||||
nsTArray<nsCString> mAllowlistSpecs;
|
||||
// The source URI of the download, the referrer and possibly any redirects.
|
||||
nsTArray<nsCString> mAnylistSpecs;
|
||||
|
||||
// When we started this query
|
||||
TimeStamp mStartTime;
|
||||
@ -199,7 +201,7 @@ public:
|
||||
// Look up the given URI in the safebrowsing DBs, optionally on both the allow
|
||||
// list and the blocklist. If there is a match, call
|
||||
// PendingLookup::OnComplete. Otherwise, call PendingLookup::LookupNext.
|
||||
nsresult LookupSpec(const nsACString& aSpec, bool aAllowListOnly);
|
||||
nsresult LookupSpec(const nsACString& aSpec, bool aAllowlistOnly);
|
||||
private:
|
||||
// The download appeared on the allowlist, blocklist, or no list (and thus
|
||||
// could trigger a remote query.
|
||||
@ -210,7 +212,7 @@ private:
|
||||
};
|
||||
|
||||
nsCString mSpec;
|
||||
bool mAllowListOnly;
|
||||
bool mAllowlistOnly;
|
||||
nsRefPtr<PendingLookup> mPendingLookup;
|
||||
nsresult LookupSpecInternal(const nsACString& aSpec);
|
||||
};
|
||||
@ -219,7 +221,7 @@ NS_IMPL_ISUPPORTS1(PendingDBLookup,
|
||||
nsIUrlClassifierCallback)
|
||||
|
||||
PendingDBLookup::PendingDBLookup(PendingLookup* aPendingLookup) :
|
||||
mAllowListOnly(false),
|
||||
mAllowlistOnly(false),
|
||||
mPendingLookup(aPendingLookup)
|
||||
{
|
||||
LOG(("Created pending DB lookup [this = %p]", this));
|
||||
@ -233,11 +235,11 @@ PendingDBLookup::~PendingDBLookup()
|
||||
|
||||
nsresult
|
||||
PendingDBLookup::LookupSpec(const nsACString& aSpec,
|
||||
bool aAllowListOnly)
|
||||
bool aAllowlistOnly)
|
||||
{
|
||||
LOG(("Checking principal %s", aSpec.Data()));
|
||||
mSpec = aSpec;
|
||||
mAllowListOnly = aAllowListOnly;
|
||||
mAllowlistOnly = aAllowlistOnly;
|
||||
nsresult rv = LookupSpecInternal(aSpec);
|
||||
if (NS_FAILED(rv)) {
|
||||
LOG(("Error in LookupSpecInternal"));
|
||||
@ -280,7 +282,15 @@ PendingDBLookup::HandleEvent(const nsACString& tables)
|
||||
// HandleEvent is guaranteed to call either:
|
||||
// 1) PendingLookup::OnComplete if the URL can be classified locally, or
|
||||
// 2) PendingLookup::LookupNext if the URL can be cannot classified locally.
|
||||
// Allow listing trumps block listing.
|
||||
// Blocklisting trumps allowlisting.
|
||||
nsAutoCString blockList;
|
||||
Preferences::GetCString(PREF_DOWNLOAD_BLOCK_TABLE, &blockList);
|
||||
if (!mAllowlistOnly && FindInReadable(tables, blockList)) {
|
||||
Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, BLOCK_LIST);
|
||||
LOG(("Found principal %s on blocklist [this = %p]", mSpec.get(), this));
|
||||
return mPendingLookup->OnComplete(true, NS_OK);
|
||||
}
|
||||
|
||||
nsAutoCString allowList;
|
||||
Preferences::GetCString(PREF_DOWNLOAD_ALLOW_TABLE, &allowList);
|
||||
if (FindInReadable(tables, allowList)) {
|
||||
@ -289,14 +299,6 @@ PendingDBLookup::HandleEvent(const nsACString& tables)
|
||||
return mPendingLookup->OnComplete(false, NS_OK);
|
||||
}
|
||||
|
||||
nsAutoCString blockList;
|
||||
Preferences::GetCString(PREF_DOWNLOAD_BLOCK_TABLE, &blockList);
|
||||
if (!mAllowListOnly && FindInReadable(tables, blockList)) {
|
||||
Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, BLOCK_LIST);
|
||||
LOG(("Found principal %s on blocklist [this = %p]", mSpec.get(), this));
|
||||
return mPendingLookup->OnComplete(true, NS_OK);
|
||||
}
|
||||
|
||||
LOG(("Didn't find principal %s on any list [this = %p]", mSpec.get(), this));
|
||||
Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, NO_LIST);
|
||||
return mPendingLookup->LookupNext();
|
||||
@ -324,18 +326,26 @@ PendingLookup::LookupNext()
|
||||
{
|
||||
// We must call LookupNext or SendRemoteQuery upon return.
|
||||
// Look up all of the URLs that could whitelist this download.
|
||||
int index = mAllowlistSpecs.Length() - 1;
|
||||
// Blacklist first.
|
||||
int index = mAnylistSpecs.Length() - 1;
|
||||
nsCString spec;
|
||||
bool allowlistOnly = false;
|
||||
if (index >= 0) {
|
||||
nsCString spec = mAllowlistSpecs[index];
|
||||
mAllowlistSpecs.RemoveElementAt(index);
|
||||
nsRefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));
|
||||
bool allowListOnly = true;
|
||||
if (index == 0) {
|
||||
// The last URI is the target URI, which may be used for blacklisting as
|
||||
// well as whitelisting.
|
||||
allowListOnly = false;
|
||||
// Check the source URI and referrer.
|
||||
spec = mAnylistSpecs[index];
|
||||
mAnylistSpecs.RemoveElementAt(index);
|
||||
} else {
|
||||
// Check the allowlists next.
|
||||
index = mAllowlistSpecs.Length() - 1;
|
||||
if (index >= 0) {
|
||||
allowlistOnly = true;
|
||||
spec = mAllowlistSpecs[index];
|
||||
mAllowlistSpecs.RemoveElementAt(index);
|
||||
}
|
||||
return lookup->LookupSpec(spec, allowListOnly);
|
||||
}
|
||||
if (index >= 0) {
|
||||
nsRefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));
|
||||
return lookup->LookupSpec(spec, allowlistOnly);
|
||||
}
|
||||
// There are no more URIs to check against local list, so send the remote
|
||||
// query if we can.
|
||||
@ -506,7 +516,16 @@ PendingLookup::DoLookupInternal()
|
||||
nsCString spec;
|
||||
rv = uri->GetSpec(spec);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
mAllowlistSpecs.AppendElement(spec);
|
||||
mAnylistSpecs.AppendElement(spec);
|
||||
|
||||
nsCOMPtr<nsIURI> referrer = nullptr;
|
||||
rv = mQuery->GetReferrerURI(getter_AddRefs(referrer));
|
||||
if (referrer) {
|
||||
nsCString spec;
|
||||
rv = referrer->GetSpec(spec);
|
||||
NS_ENSURE_SUCCESS(rv, rv);
|
||||
mAnylistSpecs.AppendElement(spec);
|
||||
}
|
||||
|
||||
// Extract the signature and parse certificates so we can use it to check
|
||||
// whitelists.
|
||||
|
@ -44,13 +44,18 @@ interface nsIApplicationReputationService : nsISupports {
|
||||
* downloaded file. nsIApplicationReputationService.Start() may only be called
|
||||
* once with a single query.
|
||||
*/
|
||||
[scriptable, uuid(5a054991-e489-4a1c-a0aa-ea7c69b20e3d)]
|
||||
[scriptable, uuid(2c781cbe-ab0c-4c53-b06e-f0cb56f8a30b)]
|
||||
interface nsIApplicationReputationQuery : nsISupports {
|
||||
/*
|
||||
* The nsIURI from which the file was downloaded. This may not be null.
|
||||
*/
|
||||
readonly attribute nsIURI sourceURI;
|
||||
|
||||
/*
|
||||
* The reference, if any.
|
||||
*/
|
||||
readonly attribute nsIURI referrerURI;
|
||||
|
||||
/*
|
||||
* The target filename for the downloaded file, as inferred from the source
|
||||
* URI or provided by the Content-Disposition attachment file name. If this
|
||||
|
@ -0,0 +1,2 @@
|
||||
a:5:32:37
|
||||
,AÎJ,AÎJ„ä8æW´<57>bbòñ_e‹;OÏÏ„CVù
|
@ -134,8 +134,10 @@ add_test(function test_local_list() {
|
||||
.getService(Ci.nsIUrlClassifierStreamUpdater);
|
||||
streamUpdater.updateUrl = "http://localhost:4444/downloads";
|
||||
|
||||
// Load up some update chunks for the safebrowsing server to serve. This
|
||||
// particular chunk contains the hash of whitelisted.com/.
|
||||
// Load up some update chunks for the safebrowsing server to serve.
|
||||
// This chunk contains the hash of whitelisted.com/.
|
||||
registerTableUpdate("goog-badbinurl-shavar", "data/block_digest.chunk");
|
||||
// This chunk contains the hash of blocklisted.com/.
|
||||
registerTableUpdate("goog-downloadwhite-digest256", "data/digest.chunk");
|
||||
|
||||
// Download some updates, and don't continue until the downloads are done.
|
||||
@ -151,22 +153,61 @@ add_test(function test_local_list() {
|
||||
do_throw("We didn't download or update correctly: " + aEvent);
|
||||
}
|
||||
streamUpdater.downloadUpdates(
|
||||
"goog-downloadwhite-digest256",
|
||||
"goog-downloadwhite-digest256;\n",
|
||||
"goog-downloadwhite-digest256,goog-badbinurl-shavar",
|
||||
"goog-downloadwhite-digest256,goog-badbinurl-shavar;\n",
|
||||
updateSuccess, handleError, handleError);
|
||||
});
|
||||
|
||||
// After being whitelisted, we shouldn't throw.
|
||||
add_test(function test_local_whitelist() {
|
||||
add_test(function test_unlisted() {
|
||||
Services.prefs.setCharPref("browser.safebrowsing.appRepURL",
|
||||
"http://localhost:4444/download");
|
||||
gAppRep.queryReputation({
|
||||
sourceURI: createURI("http://whitelisted.com"),
|
||||
sourceURI: createURI("http://example.com"),
|
||||
fileSize: 12,
|
||||
}, function onComplete(aShouldBlock, aStatus) {
|
||||
// We would get garbage if this query made it to the remote server.
|
||||
do_check_eq(Cr.NS_OK, aStatus);
|
||||
do_check_false(aShouldBlock);
|
||||
run_next_test();
|
||||
});
|
||||
});
|
||||
|
||||
add_test(function test_local_blacklist() {
|
||||
Services.prefs.setCharPref("browser.safebrowsing.appRepURL",
|
||||
"http://localhost:4444/download");
|
||||
gAppRep.queryReputation({
|
||||
sourceURI: createURI("http://blocklisted.com"),
|
||||
fileSize: 12,
|
||||
}, function onComplete(aShouldBlock, aStatus) {
|
||||
do_check_eq(Cr.NS_OK, aStatus);
|
||||
do_check_true(aShouldBlock);
|
||||
run_next_test();
|
||||
});
|
||||
});
|
||||
|
||||
add_test(function test_referer_blacklist() {
|
||||
Services.prefs.setCharPref("browser.safebrowsing.appRepURL",
|
||||
"http://localhost:4444/download");
|
||||
gAppRep.queryReputation({
|
||||
sourceURI: createURI("http://example.com"),
|
||||
referrerURI: createURI("http://blocklisted.com"),
|
||||
fileSize: 12,
|
||||
}, function onComplete(aShouldBlock, aStatus) {
|
||||
do_check_eq(Cr.NS_OK, aStatus);
|
||||
do_check_true(aShouldBlock);
|
||||
run_next_test();
|
||||
});
|
||||
});
|
||||
|
||||
add_test(function test_blocklist_trumps_allowlist() {
|
||||
Services.prefs.setCharPref("browser.safebrowsing.appRepURL",
|
||||
"http://localhost:4444/download");
|
||||
gAppRep.queryReputation({
|
||||
sourceURI: createURI("http://whitelisted.com"),
|
||||
referrerURI: createURI("http://blocklisted.com"),
|
||||
fileSize: 12,
|
||||
}, function onComplete(aShouldBlock, aStatus) {
|
||||
do_check_eq(Cr.NS_OK, aStatus);
|
||||
do_check_true(aShouldBlock);
|
||||
run_next_test();
|
||||
});
|
||||
});
|
||||
|
@ -6,6 +6,7 @@ support-files =
|
||||
downloads_manifest.js
|
||||
test_downloads.manifest
|
||||
data/digest.chunk
|
||||
data/block_digest.chunk
|
||||
data/signed_win.exe
|
||||
|
||||
[test_app_rep.js]
|
||||
|
@ -513,7 +513,7 @@ this.DownloadIntegration = {
|
||||
let sigInfo;
|
||||
try {
|
||||
hash = aDownload.saver.getSha256Hash();
|
||||
sigInfo = aDownload.saver.getSignatureInfo();
|
||||
sigInfo = aDownload.saver.getSignatureInfo();
|
||||
} catch (ex) {
|
||||
// Bail if DownloadSaver doesn't have a hash.
|
||||
return Promise.resolve(false);
|
||||
@ -522,8 +522,13 @@ this.DownloadIntegration = {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
let deferred = Promise.defer();
|
||||
let aReferrer = null;
|
||||
if (aDownload.source.referrer) {
|
||||
aReferrer: NetUtil.newURI(aDownload.source.referrer);
|
||||
}
|
||||
gApplicationReputationService.queryReputation({
|
||||
sourceURI: NetUtil.newURI(aDownload.source.url),
|
||||
referrerURI: aReferrer,
|
||||
fileSize: aDownload.currentBytes,
|
||||
sha256Hash: hash,
|
||||
signatureInfo: sigInfo },
|
||||
|
921
toolkit/components/osfile/NativeOSFileInternals.cpp
Normal file
921
toolkit/components/osfile/NativeOSFileInternals.cpp
Normal file
@ -0,0 +1,921 @@
|
||||
/* 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/. */
|
||||
|
||||
/**
|
||||
* Native implementation of some OS.File operations.
|
||||
*/
|
||||
|
||||
#include "nsString.h"
|
||||
#include "nsNetCID.h"
|
||||
#include "nsThreadUtils.h"
|
||||
#include "nsXPCOMCID.h"
|
||||
#include "nsCycleCollectionParticipant.h"
|
||||
#include "nsServiceManagerUtils.h"
|
||||
#include "nsProxyRelease.h"
|
||||
|
||||
#include "nsINativeOSFileInternals.h"
|
||||
#include "NativeOSFileInternals.h"
|
||||
#include "mozilla/dom/NativeOSFileInternalsBinding.h"
|
||||
|
||||
#include "nsIUnicodeDecoder.h"
|
||||
#include "nsIEventTarget.h"
|
||||
|
||||
#include "mozilla/dom/EncodingUtils.h"
|
||||
#include "mozilla/DebugOnly.h"
|
||||
#include "mozilla/Scoped.h"
|
||||
#include "mozilla/HoldDropJSObjects.h"
|
||||
#include "mozilla/TimeStamp.h"
|
||||
|
||||
#include "prio.h"
|
||||
#include "prerror.h"
|
||||
#include "private/pprio.h"
|
||||
|
||||
#include "jsapi.h"
|
||||
#include "jsfriendapi.h"
|
||||
#include "js/Utility.h"
|
||||
#include "xpcpublic.h"
|
||||
|
||||
#include <algorithm>
|
||||
#if defined(XP_UNIX)
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/uio.h>
|
||||
#endif // defined (XP_UNIX)
|
||||
|
||||
#if defined(XP_WIN)
|
||||
#include <Windows.h>
|
||||
#endif // defined (XP_WIN)
|
||||
|
||||
namespace mozilla {
|
||||
|
||||
MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, PR_Close)
|
||||
|
||||
namespace {
|
||||
|
||||
// Utilities for safely manipulating ArrayBuffer contents even in the
|
||||
// absence of a JSContext.
|
||||
|
||||
/**
|
||||
* The C buffer underlying to an ArrayBuffer. Throughout the code, we manipulate
|
||||
* this instead of a void* buffer, as this lets us transfer data across threads
|
||||
* and into JavaScript without copy.
|
||||
*/
|
||||
struct ArrayBufferContents {
|
||||
/**
|
||||
* The header of the ArrayBuffer. This is the pointer actually used by JSAPI.
|
||||
*/
|
||||
void* header;
|
||||
/**
|
||||
* The data of the ArrayBuffer. This is the pointer manipulated to
|
||||
* read/write the contents of the buffer.
|
||||
*/
|
||||
uint8_t* data;
|
||||
/**
|
||||
* The number of bytes in the ArrayBuffer.
|
||||
*/
|
||||
size_t nbytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* RAII for ArrayBufferContents.
|
||||
*/
|
||||
struct ScopedArrayBufferContentsTraits {
|
||||
typedef ArrayBufferContents type;
|
||||
const static type empty() {
|
||||
type result = {0, 0, 0};
|
||||
return result;
|
||||
}
|
||||
const static void release(type ptr) {
|
||||
js_free(ptr.header);
|
||||
ptr.header = nullptr;
|
||||
ptr.data = nullptr;
|
||||
ptr.nbytes = 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct ScopedArrayBufferContents: public Scoped<ScopedArrayBufferContentsTraits> {
|
||||
ScopedArrayBufferContents(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM):
|
||||
Scoped<ScopedArrayBufferContentsTraits>(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT)
|
||||
{ }
|
||||
ScopedArrayBufferContents(const ArrayBufferContents& v
|
||||
MOZ_GUARD_OBJECT_NOTIFIER_PARAM):
|
||||
Scoped<ScopedArrayBufferContentsTraits>(v MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
|
||||
{ }
|
||||
ScopedArrayBufferContents& operator=(ArrayBufferContents ptr) {
|
||||
Scoped<ScopedArrayBufferContentsTraits>::operator=(ptr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request memory for this ArrayBufferContent. This memory may later
|
||||
* be used to create an ArrayBuffer object (possibly on another
|
||||
* thread) without copy.
|
||||
*
|
||||
* @return true In case of success, false otherwise.
|
||||
*/
|
||||
bool Allocate(uint32_t length) {
|
||||
dispose();
|
||||
ArrayBufferContents& value = rwget();
|
||||
if (JS_AllocateArrayBufferContents(/*no context available*/nullptr,
|
||||
length,
|
||||
&value.header,
|
||||
&value.data)) {
|
||||
value.nbytes = length;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private:
|
||||
explicit ScopedArrayBufferContents(ScopedArrayBufferContents& source) MOZ_DELETE;
|
||||
ScopedArrayBufferContents& operator=(ScopedArrayBufferContents& source) MOZ_DELETE;
|
||||
};
|
||||
|
||||
///////// Cross-platform issues
|
||||
|
||||
// Platform specific constants. As OS.File always uses OS-level
|
||||
// errors, we need to map a few high-level errors to OS-level
|
||||
// constants.
|
||||
#if defined(XP_UNIX)
|
||||
#define OS_ERROR_NOMEM ENOMEM
|
||||
#define OS_ERROR_INVAL EINVAL
|
||||
#define OS_ERROR_TOO_LARGE EFBIG
|
||||
#define OS_ERROR_RACE EIO
|
||||
#elif defined(XP_WIN)
|
||||
#define OS_ERROR_NOMEM ERROR_NOT_ENOUGH_MEMORY
|
||||
#define OS_ERROR_INVAL ERROR_BAD_ARGUMENTS
|
||||
#define OS_ERROR_TOO_LARGE ERROR_FILE_TOO_LARGE
|
||||
#define OS_ERROR_RACE ERROR_SHARING_VIOLATION
|
||||
#else
|
||||
#error "We do not have platform-specific constants for this platform"
|
||||
#endif
|
||||
|
||||
///////// Results of OS.File operations
|
||||
|
||||
/**
|
||||
* Base class for results passed to the callbacks.
|
||||
*
|
||||
* This base class implements caching of JS values returned to the client.
|
||||
* We make use of this caching in derived classes e.g. to avoid accidents
|
||||
* when we transfer data allocated on another thread into JS. Note that
|
||||
* this caching can lead to cycles (e.g. if a client adds a back-reference
|
||||
* in the JS value), so we implement all Cycle Collector primitives in
|
||||
* AbstractResult.
|
||||
*/
|
||||
class AbstractResult: public nsINativeOSFileResult {
|
||||
public:
|
||||
NS_DECL_NSINATIVEOSFILERESULT
|
||||
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
|
||||
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(AbstractResult)
|
||||
|
||||
/**
|
||||
* Construct the result object. Must be called on the main thread
|
||||
* as the AbstractResult is cycle-collected.
|
||||
*
|
||||
* @param aStartDate The instant at which the operation was
|
||||
* requested. Used to collect Telemetry statistics.
|
||||
*/
|
||||
AbstractResult(TimeStamp aStartDate)
|
||||
: mStartDate(aStartDate)
|
||||
{
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
mozilla::HoldJSObjects(this);
|
||||
}
|
||||
virtual ~AbstractResult() {
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
DropJSData();
|
||||
mozilla::DropJSObjects(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the AbstractResult once data is available.
|
||||
*
|
||||
* @param aDispatchDate The instant at which the IO thread received
|
||||
* the operation request. Used to collect Telemetry statistics.
|
||||
* @param aExecutionDuration The duration of the operation on the
|
||||
* IO thread.
|
||||
*/
|
||||
void Init(TimeStamp aDispatchDate,
|
||||
TimeDuration aExecutionDuration) {
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
|
||||
mDispatchDuration = (aDispatchDate - mStartDate);
|
||||
mExecutionDuration = aExecutionDuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop any data that could lead to a cycle.
|
||||
*/
|
||||
void DropJSData() {
|
||||
mCachedResult = JS::UndefinedValue();
|
||||
}
|
||||
|
||||
protected:
|
||||
virtual nsresult GetCacheableResult(JSContext *cx, JS::MutableHandleValue aResult) = 0;
|
||||
|
||||
private:
|
||||
TimeStamp mStartDate;
|
||||
TimeDuration mDispatchDuration;
|
||||
TimeDuration mExecutionDuration;
|
||||
JS::Heap<JS::Value> mCachedResult;
|
||||
};
|
||||
|
||||
NS_IMPL_CYCLE_COLLECTING_ADDREF(AbstractResult)
|
||||
NS_IMPL_CYCLE_COLLECTING_RELEASE(AbstractResult)
|
||||
|
||||
NS_IMPL_CYCLE_COLLECTION_CLASS(AbstractResult)
|
||||
|
||||
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AbstractResult)
|
||||
NS_INTERFACE_MAP_ENTRY(nsINativeOSFileResult)
|
||||
NS_INTERFACE_MAP_ENTRY(nsISupports)
|
||||
NS_INTERFACE_MAP_END
|
||||
|
||||
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(AbstractResult)
|
||||
NS_IMPL_CYCLE_COLLECTION_TRACE_JSVAL_MEMBER_CALLBACK(mCachedResult)
|
||||
NS_IMPL_CYCLE_COLLECTION_TRACE_END
|
||||
|
||||
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(AbstractResult)
|
||||
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
|
||||
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
|
||||
|
||||
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(AbstractResult)
|
||||
tmp->DropJSData();
|
||||
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
|
||||
|
||||
NS_IMETHODIMP
|
||||
AbstractResult::GetDispatchDurationMS(double *aDispatchDuration)
|
||||
{
|
||||
*aDispatchDuration = mDispatchDuration.ToMilliseconds();
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
NS_IMETHODIMP
|
||||
AbstractResult::GetExecutionDurationMS(double *aExecutionDuration)
|
||||
{
|
||||
*aExecutionDuration = mExecutionDuration.ToMilliseconds();
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
NS_IMETHODIMP
|
||||
AbstractResult::GetResult(JSContext *cx, JS::MutableHandleValue aResult)
|
||||
{
|
||||
if (mCachedResult.isUndefined()) {
|
||||
nsresult rv = GetCacheableResult(cx, aResult);
|
||||
if (NS_FAILED(rv)) {
|
||||
return rv;
|
||||
}
|
||||
mCachedResult = aResult;
|
||||
return NS_OK;
|
||||
}
|
||||
aResult.set(mCachedResult);
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a result as a string.
|
||||
*
|
||||
* In this implementation, attribute |result| is a string. Strings are
|
||||
* passed to JS without copy.
|
||||
*/
|
||||
class StringResult MOZ_FINAL : public AbstractResult
|
||||
{
|
||||
public:
|
||||
StringResult(TimeStamp aStartDate)
|
||||
: AbstractResult(aStartDate)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the object once the contents of the result as available.
|
||||
*
|
||||
* @param aContents The string to pass to JavaScript. Ownership of the
|
||||
* string and its contents is passed to StringResult. The string must
|
||||
* be valid UTF-16.
|
||||
*/
|
||||
void Init(TimeStamp aDispatchDate,
|
||||
TimeDuration aExecutionDuration,
|
||||
nsString& aContents) {
|
||||
AbstractResult::Init(aDispatchDate, aExecutionDuration);
|
||||
mContents = aContents;
|
||||
}
|
||||
|
||||
protected:
|
||||
nsresult GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult) MOZ_OVERRIDE;
|
||||
|
||||
private:
|
||||
nsString mContents;
|
||||
};
|
||||
|
||||
nsresult
|
||||
StringResult::GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult)
|
||||
{
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
MOZ_ASSERT(mContents.get());
|
||||
|
||||
// Convert mContents to a js string without copy. Note that this
|
||||
// may have the side-effect of stealing the contents of the string
|
||||
// from XPCOM and into JS.
|
||||
if (!xpc::StringToJsval(cx, mContents, aResult)) {
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return a result as a Uint8Array.
|
||||
*
|
||||
* In this implementation, attribute |result| is a Uint8Array. The array
|
||||
* is passed to JS without memory copy.
|
||||
*/
|
||||
class TypedArrayResult MOZ_FINAL : public AbstractResult
|
||||
{
|
||||
public:
|
||||
TypedArrayResult(TimeStamp aStartDate)
|
||||
: AbstractResult(aStartDate)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param aContents The contents to pass to JS. Calling this method.
|
||||
* transmits ownership of the ArrayBufferContents to the TypedArrayResult.
|
||||
* Do not reuse this value anywhere else.
|
||||
*/
|
||||
void Init(TimeStamp aDispatchDate,
|
||||
TimeDuration aExecutionDuration,
|
||||
ArrayBufferContents aContents) {
|
||||
AbstractResult::Init(aDispatchDate, aExecutionDuration);
|
||||
mContents = aContents;
|
||||
}
|
||||
|
||||
protected:
|
||||
nsresult GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult) MOZ_OVERRIDE;
|
||||
private:
|
||||
ScopedArrayBufferContents mContents;
|
||||
};
|
||||
|
||||
nsresult
|
||||
TypedArrayResult::GetCacheableResult(JSContext* cx, JS::MutableHandle<JS::Value> aResult)
|
||||
{
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
// We cannot simply construct a typed array using contents.header as
|
||||
// this would allow us to have several otherwise unrelated
|
||||
// ArrayBuffers with the same underlying C buffer. As this would be
|
||||
// very unsafe, we need to cache the result once we have it.
|
||||
|
||||
const ArrayBufferContents& contents = mContents.get();
|
||||
MOZ_ASSERT(contents.data);
|
||||
|
||||
JS::Rooted<JSObject*>
|
||||
arrayBuffer(cx, JS_NewArrayBufferWithContents(cx, contents.header));
|
||||
if (!arrayBuffer) {
|
||||
return NS_ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
|
||||
JS::Rooted<JSObject*>
|
||||
result(cx, JS_NewUint8ArrayWithBuffer(cx, arrayBuffer,
|
||||
0, contents.nbytes));
|
||||
if (!result) {
|
||||
return NS_ERROR_OUT_OF_MEMORY;
|
||||
}
|
||||
// The memory of contents has been allocated on a thread that
|
||||
// doesn't have a JSRuntime, hence without a context. Now that we
|
||||
// have a context, attach the memory to where it belongs.
|
||||
JS_updateMallocCounter(cx, contents.nbytes);
|
||||
mContents.forget();
|
||||
|
||||
aResult.setObject(*result);
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
//////// Callback events
|
||||
|
||||
/**
|
||||
* An event used to notify asynchronously of an error.
|
||||
*/
|
||||
class ErrorEvent MOZ_FINAL : public nsRunnable {
|
||||
public:
|
||||
/**
|
||||
* @param aOnSuccess The success callback.
|
||||
* @param aOnError The error callback.
|
||||
* @param aDiscardedResult The discarded result.
|
||||
* @param aOperation The name of the operation, used for error reporting.
|
||||
* @param aOSError The OS error of the operation, as returned by errno/
|
||||
* GetLastError().
|
||||
*
|
||||
* Note that we pass both the success callback and the error
|
||||
* callback, as well as the discarded result to ensure that they are
|
||||
* all released on the main thread, rather than on the IO thread
|
||||
* (which would hopefully segfault). Also, we pass the callbacks as
|
||||
* alread_AddRefed to ensure that we do not manipulate main-thread
|
||||
* only refcounters off the main thread.
|
||||
*/
|
||||
ErrorEvent(already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError,
|
||||
already_AddRefed<AbstractResult> aDiscardedResult,
|
||||
const nsACString& aOperation,
|
||||
int32_t aOSError)
|
||||
: mOnSuccess(aOnSuccess)
|
||||
, mOnError(aOnError)
|
||||
, mDiscardedResult(aDiscardedResult)
|
||||
, mOSError(aOSError)
|
||||
, mOperation(aOperation)
|
||||
{
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
}
|
||||
|
||||
NS_METHOD Run() {
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
(void)mOnError->Complete(mOperation, mOSError);
|
||||
|
||||
// Ensure that the callbacks are released on the main thread.
|
||||
mOnSuccess = nullptr;
|
||||
mOnError = nullptr;
|
||||
mDiscardedResult = nullptr;
|
||||
|
||||
return NS_OK;
|
||||
}
|
||||
private:
|
||||
// The callbacks. Maintained as nsRefPtr as they are generally
|
||||
// xpconnect values, which cannot be manipulated with nsCOMPtr off
|
||||
// the main thread. We store both the success callback and the
|
||||
// error callback to ensure that they are safely released on the
|
||||
// main thread.
|
||||
nsRefPtr<nsINativeOSFileSuccessCallback> mOnSuccess;
|
||||
nsRefPtr<nsINativeOSFileErrorCallback> mOnError;
|
||||
nsRefPtr<AbstractResult> mDiscardedResult;
|
||||
int32_t mOSError;
|
||||
nsCString mOperation;
|
||||
};
|
||||
|
||||
/**
|
||||
* An event used to notify of a success.
|
||||
*/
|
||||
class SuccessEvent MOZ_FINAL : public nsRunnable {
|
||||
public:
|
||||
/**
|
||||
* @param aOnSuccess The success callback.
|
||||
* @param aOnError The error callback.
|
||||
*
|
||||
* Note that we pass both the success callback and the error
|
||||
* callback to ensure that they are both released on the main
|
||||
* thread, rather than on the IO thread (which would hopefully
|
||||
* segfault). Also, we pass them as alread_AddRefed to ensure that
|
||||
* we do not manipulate xpconnect refcounters off the main thread
|
||||
* (which is illegal).
|
||||
*/
|
||||
SuccessEvent(already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError,
|
||||
already_AddRefed<nsINativeOSFileResult> aResult)
|
||||
: mOnSuccess(aOnSuccess)
|
||||
, mOnError(aOnError)
|
||||
, mResult(aResult)
|
||||
{
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
}
|
||||
|
||||
NS_METHOD Run() {
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
(void)mOnSuccess->Complete(mResult);
|
||||
|
||||
// Ensure that the callbacks are released on the main thread.
|
||||
mOnSuccess = nullptr;
|
||||
mOnError = nullptr;
|
||||
mResult = nullptr;
|
||||
|
||||
return NS_OK;
|
||||
}
|
||||
private:
|
||||
// The callbacks. Maintained as nsRefPtr as they are generally
|
||||
// xpconnect values, which cannot be manipulated with nsCOMPtr off
|
||||
// the main thread. We store both the success callback and the
|
||||
// error callback to ensure that they are safely released on the
|
||||
// main thread.
|
||||
nsRefPtr<nsINativeOSFileSuccessCallback> mOnSuccess;
|
||||
nsRefPtr<nsINativeOSFileErrorCallback> mOnError;
|
||||
nsRefPtr<nsINativeOSFileResult> mResult;
|
||||
};
|
||||
|
||||
|
||||
//////// Action events
|
||||
|
||||
/**
|
||||
* Base class shared by actions.
|
||||
*/
|
||||
class AbstractDoEvent: public nsRunnable {
|
||||
public:
|
||||
AbstractDoEvent(already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError)
|
||||
: mOnSuccess(aOnSuccess)
|
||||
, mOnError(aOnError)
|
||||
#if defined(DEBUG)
|
||||
, mResolved(false)
|
||||
#endif // defined(DEBUG)
|
||||
{
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail, asynchronously.
|
||||
*/
|
||||
void Fail(const nsACString& aOperation,
|
||||
already_AddRefed<AbstractResult> aDiscardedResult,
|
||||
int32_t aOSError = 0) {
|
||||
Resolve();
|
||||
nsRefPtr<ErrorEvent> event = new ErrorEvent(mOnSuccess.forget(),
|
||||
mOnError.forget(),
|
||||
aDiscardedResult,
|
||||
aOperation,
|
||||
aOSError);
|
||||
nsresult rv = NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
|
||||
if (NS_FAILED(rv)) {
|
||||
// Last ditch attempt to release on the main thread - some of
|
||||
// the members of event are not thread-safe, so letting the
|
||||
// pointer go out of scope would cause a crash.
|
||||
nsCOMPtr<nsIThread> main = do_GetMainThread();
|
||||
NS_ProxyRelease(main, event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Succeed, asynchronously.
|
||||
*/
|
||||
void Succeed(already_AddRefed<nsINativeOSFileResult> aResult) {
|
||||
Resolve();
|
||||
nsRefPtr<SuccessEvent> event = new SuccessEvent(mOnSuccess.forget(),
|
||||
mOnError.forget(),
|
||||
aResult);
|
||||
nsresult rv = NS_DispatchToMainThread(event, NS_DISPATCH_NORMAL);
|
||||
if (NS_FAILED(rv)) {
|
||||
// Last ditch attempt to release on the main thread - some of
|
||||
// the members of event are not thread-safe, so letting the
|
||||
// pointer go out of scope would cause a crash.
|
||||
nsCOMPtr<nsIThread> main = do_GetMainThread();
|
||||
NS_ProxyRelease(main, event);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Mark the event as complete, for debugging purposes.
|
||||
*/
|
||||
void Resolve() {
|
||||
#if defined(DEBUG)
|
||||
MOZ_ASSERT(!mResolved);
|
||||
mResolved = true;
|
||||
#endif // defined(DEBUG)
|
||||
}
|
||||
|
||||
private:
|
||||
nsRefPtr<nsINativeOSFileSuccessCallback> mOnSuccess;
|
||||
nsRefPtr<nsINativeOSFileErrorCallback> mOnError;
|
||||
#if defined(DEBUG)
|
||||
// |true| once the action is complete
|
||||
bool mResolved;
|
||||
#endif // defined(DEBUG)
|
||||
};
|
||||
|
||||
/**
|
||||
* An abstract event implementing reading from a file.
|
||||
*
|
||||
* Concrete subclasses are responsible for handling the
|
||||
* data obtained from the file and possibly post-processing it.
|
||||
*/
|
||||
class AbstractReadEvent: public AbstractDoEvent {
|
||||
public:
|
||||
/**
|
||||
* @param aPath The path of the file.
|
||||
*/
|
||||
AbstractReadEvent(const nsAString& aPath,
|
||||
const uint64_t aBytes,
|
||||
already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError)
|
||||
: AbstractDoEvent(aOnSuccess, aOnError)
|
||||
, mPath(aPath)
|
||||
, mBytes(aBytes)
|
||||
{
|
||||
MOZ_ASSERT(NS_IsMainThread());
|
||||
}
|
||||
|
||||
NS_METHOD Run() MOZ_OVERRIDE {
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
TimeStamp dispatchDate = TimeStamp::Now();
|
||||
|
||||
nsresult rv = BeforeRead();
|
||||
if (NS_FAILED(rv)) {
|
||||
// Error reporting is handled by BeforeRead();
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
ScopedArrayBufferContents buffer;
|
||||
rv = Read(buffer);
|
||||
if (NS_FAILED(rv)) {
|
||||
// Error reporting is handled by Read();
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
AfterRead(dispatchDate, buffer);
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* Read synchronously.
|
||||
*
|
||||
* Must be called off the main thread.
|
||||
*
|
||||
* @param aBuffer The destination buffer.
|
||||
*/
|
||||
nsresult Read(ScopedArrayBufferContents& aBuffer)
|
||||
{
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
|
||||
ScopedPRFileDesc file;
|
||||
#if defined(XP_WIN)
|
||||
// On Windows, we can't use PR_OpenFile because it doesn't
|
||||
// handle UTF-16 encoding, which is pretty bad. In addition,
|
||||
// PR_OpenFile opens files without sharing, which is not the
|
||||
// general semantics of OS.File.
|
||||
HANDLE handle =
|
||||
::CreateFileW(mPath.get(),
|
||||
GENERIC_READ,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
/*Security attributes*/nullptr,
|
||||
OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
|
||||
/*Template file*/ nullptr);
|
||||
|
||||
if (handle == INVALID_HANDLE_VALUE) {
|
||||
Fail(NS_LITERAL_CSTRING("open"), nullptr, ::GetLastError());
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
file = PR_ImportFile((PROsfd)handle);
|
||||
if (!file) {
|
||||
// |file| is closed by PR_ImportFile
|
||||
Fail(NS_LITERAL_CSTRING("ImportFile"), nullptr, PR_GetOSError());
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
#else
|
||||
// On other platforms, PR_OpenFile will do.
|
||||
NS_ConvertUTF16toUTF8 path(mPath);
|
||||
file = PR_OpenFile(path.get(), PR_RDONLY, 0);
|
||||
if (!file) {
|
||||
Fail(NS_LITERAL_CSTRING("open"), nullptr, PR_GetOSError());
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
#endif // defined(XP_XIN)
|
||||
|
||||
PRFileInfo64 stat;
|
||||
if (PR_GetOpenFileInfo64(file, &stat) != PR_SUCCESS) {
|
||||
Fail(NS_LITERAL_CSTRING("stat"), nullptr, PR_GetOSError());
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
uint64_t bytes = std::min((uint64_t)stat.size, mBytes);
|
||||
if (bytes > UINT32_MAX) {
|
||||
Fail(NS_LITERAL_CSTRING("Arithmetics"), nullptr, OS_ERROR_INVAL);
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
if (!aBuffer.Allocate(bytes)) {
|
||||
Fail(NS_LITERAL_CSTRING("allocate"), nullptr, OS_ERROR_NOMEM);
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
uint64_t total_read = 0;
|
||||
int32_t just_read = 0;
|
||||
char* dest_chars = reinterpret_cast<char*>(aBuffer.rwget().data);
|
||||
do {
|
||||
just_read = PR_Read(file, dest_chars + total_read,
|
||||
std::min(uint64_t(PR_INT32_MAX), bytes - total_read));
|
||||
if (just_read == -1) {
|
||||
Fail(NS_LITERAL_CSTRING("read"), nullptr, PR_GetOSError());
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
total_read += just_read;
|
||||
} while (just_read != 0 && total_read < bytes);
|
||||
if (total_read != bytes) {
|
||||
// We seem to have a race condition here.
|
||||
Fail(NS_LITERAL_CSTRING("read"), nullptr, OS_ERROR_RACE);
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Any steps that need to be taken before reading.
|
||||
*
|
||||
* In case of error, this method should call Fail() and return
|
||||
* a failure code.
|
||||
*/
|
||||
virtual
|
||||
nsresult BeforeRead() {
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Proceed after reading.
|
||||
*/
|
||||
virtual
|
||||
void AfterRead(TimeStamp aDispatchDate, ScopedArrayBufferContents& aBuffer) = 0;
|
||||
|
||||
protected:
|
||||
const nsString mPath;
|
||||
const uint64_t mBytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* An implementation of a Read event that provides the data
|
||||
* as a TypedArray.
|
||||
*/
|
||||
class DoReadToTypedArrayEvent MOZ_FINAL : public AbstractReadEvent {
|
||||
public:
|
||||
DoReadToTypedArrayEvent(const nsAString& aPath,
|
||||
const uint32_t aBytes,
|
||||
already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError)
|
||||
: AbstractReadEvent(aPath, aBytes,
|
||||
aOnSuccess, aOnError)
|
||||
, mResult(new TypedArrayResult(TimeStamp::Now()))
|
||||
{ }
|
||||
|
||||
~DoReadToTypedArrayEvent() {
|
||||
// If AbstractReadEvent::Run() has bailed out, we may need to cleanup
|
||||
// mResult, which is main-thread only data
|
||||
if (!mResult) {
|
||||
return;
|
||||
}
|
||||
nsCOMPtr<nsIThread> main = do_GetMainThread();
|
||||
(void)NS_ProxyRelease(main, mResult);
|
||||
}
|
||||
|
||||
protected:
|
||||
void AfterRead(TimeStamp aDispatchDate,
|
||||
ScopedArrayBufferContents& aBuffer) MOZ_OVERRIDE {
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
mResult->Init(aDispatchDate, TimeStamp::Now() - aDispatchDate, aBuffer.forget());
|
||||
Succeed(mResult.forget());
|
||||
}
|
||||
|
||||
private:
|
||||
nsRefPtr<TypedArrayResult> mResult;
|
||||
};
|
||||
|
||||
/**
|
||||
* An implementation of a Read event that provides the data
|
||||
* as a JavaScript string.
|
||||
*/
|
||||
class DoReadToStringEvent MOZ_FINAL : public AbstractReadEvent {
|
||||
public:
|
||||
DoReadToStringEvent(const nsAString& aPath,
|
||||
const nsACString& aEncoding,
|
||||
const uint32_t aBytes,
|
||||
already_AddRefed<nsINativeOSFileSuccessCallback> aOnSuccess,
|
||||
already_AddRefed<nsINativeOSFileErrorCallback> aOnError)
|
||||
: AbstractReadEvent(aPath, aBytes, aOnSuccess, aOnError)
|
||||
, mEncoding(aEncoding)
|
||||
, mResult(new StringResult(TimeStamp::Now()))
|
||||
{ }
|
||||
|
||||
~DoReadToStringEvent() {
|
||||
// If AbstraactReadEvent::Run() has bailed out, we may need to cleanup
|
||||
// mResult, which is main-thread only data
|
||||
if (!mResult) {
|
||||
return;
|
||||
}
|
||||
nsCOMPtr<nsIThread> main = do_GetMainThread();
|
||||
(void)NS_ProxyRelease(main, mResult);
|
||||
}
|
||||
|
||||
protected:
|
||||
nsresult BeforeRead() MOZ_OVERRIDE {
|
||||
// Obtain the decoder. We do this before reading to avoid doing
|
||||
// any unnecessary I/O in case the name of the encoding is incorrect.
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
nsAutoCString encodingName;
|
||||
if (!dom::EncodingUtils::FindEncodingForLabel(mEncoding, encodingName)) {
|
||||
Fail(NS_LITERAL_CSTRING("Decode"), mResult.forget(), OS_ERROR_INVAL);
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
mDecoder = dom::EncodingUtils::DecoderForEncoding(encodingName);
|
||||
if (!mDecoder) {
|
||||
Fail(NS_LITERAL_CSTRING("DecoderForEncoding"), mResult.forget(), OS_ERROR_INVAL);
|
||||
return NS_ERROR_FAILURE;
|
||||
}
|
||||
|
||||
return NS_OK;
|
||||
}
|
||||
|
||||
void AfterRead(TimeStamp aDispatchDate,
|
||||
ScopedArrayBufferContents& aBuffer) MOZ_OVERRIDE {
|
||||
MOZ_ASSERT(!NS_IsMainThread());
|
||||
|
||||
int32_t maxChars;
|
||||
const char* sourceChars = reinterpret_cast<const char*>(aBuffer.get().data);
|
||||
int32_t sourceBytes = aBuffer.get().nbytes;
|
||||
if (sourceBytes < 0) {
|
||||
Fail(NS_LITERAL_CSTRING("arithmetics"), mResult.forget(), OS_ERROR_TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
|
||||
nsresult rv = mDecoder->GetMaxLength(sourceChars, sourceBytes, &maxChars);
|
||||
if (NS_FAILED(rv)) {
|
||||
Fail(NS_LITERAL_CSTRING("GetMaxLength"), mResult.forget(), OS_ERROR_INVAL);
|
||||
return;
|
||||
}
|
||||
|
||||
if (maxChars < 0) {
|
||||
Fail(NS_LITERAL_CSTRING("arithmetics"), mResult.forget(), OS_ERROR_TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
|
||||
nsString resultString;
|
||||
resultString.SetLength(maxChars);
|
||||
if (resultString.Length() != (nsString::size_type)maxChars) {
|
||||
Fail(NS_LITERAL_CSTRING("allocation"), mResult.forget(), OS_ERROR_TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
rv = mDecoder->Convert(sourceChars, &sourceBytes,
|
||||
resultString.BeginWriting(), &maxChars);
|
||||
MOZ_ASSERT(NS_SUCCEEDED(rv));
|
||||
resultString.SetLength(maxChars);
|
||||
|
||||
mResult->Init(aDispatchDate, TimeStamp::Now() - aDispatchDate, resultString);
|
||||
Succeed(mResult.forget());
|
||||
}
|
||||
|
||||
private:
|
||||
nsCString mEncoding;
|
||||
nsCOMPtr<nsIUnicodeDecoder> mDecoder;
|
||||
nsRefPtr<StringResult> mResult;
|
||||
};
|
||||
|
||||
} // osfile
|
||||
|
||||
// The OS.File service
|
||||
|
||||
NS_IMPL_ISUPPORTS1(NativeOSFileInternalsService, nsINativeOSFileInternalsService);
|
||||
|
||||
NS_IMETHODIMP
|
||||
NativeOSFileInternalsService::Read(const nsAString& aPath,
|
||||
JS::HandleValue aOptions,
|
||||
nsINativeOSFileSuccessCallback *aOnSuccess,
|
||||
nsINativeOSFileErrorCallback *aOnError,
|
||||
JSContext* cx)
|
||||
{
|
||||
// Extract options
|
||||
nsCString encoding;
|
||||
uint64_t bytes = UINT64_MAX;
|
||||
|
||||
if (aOptions.isObject()) {
|
||||
dom::NativeOSFileReadOptions dict;
|
||||
if (!dict.Init(cx, aOptions)) {
|
||||
return NS_ERROR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (dict.mEncoding.WasPassed()) {
|
||||
CopyUTF16toUTF8(dict.mEncoding.Value(), encoding);
|
||||
}
|
||||
|
||||
if (dict.mBytes.WasPassed() && !dict.mBytes.Value().IsNull()) {
|
||||
bytes = dict.mBytes.Value().Value();
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare the off main thread event and dispatch it
|
||||
nsCOMPtr<nsINativeOSFileSuccessCallback> onSuccess(aOnSuccess);
|
||||
nsCOMPtr<nsINativeOSFileErrorCallback> onError(aOnError);
|
||||
|
||||
nsRefPtr<AbstractDoEvent> event;
|
||||
if (encoding.IsEmpty()) {
|
||||
event = new DoReadToTypedArrayEvent(aPath, bytes,
|
||||
onSuccess.forget(),
|
||||
onError.forget());
|
||||
} else {
|
||||
event = new DoReadToStringEvent(aPath, encoding, bytes,
|
||||
onSuccess.forget(),
|
||||
onError.forget());
|
||||
}
|
||||
|
||||
nsresult rv;
|
||||
nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
|
||||
|
||||
if (NS_FAILED(rv)) {
|
||||
return rv;
|
||||
}
|
||||
return target->Dispatch(event, NS_DISPATCH_NORMAL);
|
||||
}
|
||||
|
||||
} // namespace mozilla
|
||||
|
24
toolkit/components/osfile/NativeOSFileInternals.h
Normal file
24
toolkit/components/osfile/NativeOSFileInternals.h
Normal file
@ -0,0 +1,24 @@
|
||||
/* 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/. */
|
||||
|
||||
#ifndef mozilla_nativeosfileinternalservice_h__
|
||||
#define mozilla_nativeosfileinternalservice_h__
|
||||
|
||||
#include "nsINativeOSFileInternals.h"
|
||||
#include "mozilla/Attributes.h"
|
||||
|
||||
namespace mozilla {
|
||||
|
||||
class NativeOSFileInternalsService MOZ_FINAL : public nsINativeOSFileInternalsService {
|
||||
public:
|
||||
NS_DECL_ISUPPORTS
|
||||
NS_DECL_NSINATIVEOSFILEINTERNALSSERVICE
|
||||
private:
|
||||
// Avoid accidental use of built-in operator=
|
||||
void operator=(const NativeOSFileInternalsService& other) MOZ_DELETE;
|
||||
};
|
||||
|
||||
} // namespace mozilla
|
||||
|
||||
#endif // mozilla_finalizationwitnessservice_h__
|
@ -10,6 +10,7 @@ EXTRA_JS_MODULES += [
|
||||
'_PromiseWorker.jsm',
|
||||
'osfile_async_front.jsm',
|
||||
'osfile_async_worker.js',
|
||||
'osfile_native.jsm',
|
||||
'osfile_shared_allthreads.jsm',
|
||||
'osfile_shared_front.jsm',
|
||||
'osfile_unix_allthreads.jsm',
|
||||
|
@ -58,6 +58,7 @@ Cu.import("resource://gre/modules/osfile/_PromiseWorker.jsm", this);
|
||||
Cu.import("resource://gre/modules/Services.jsm", this);
|
||||
Cu.import("resource://gre/modules/TelemetryStopwatch.jsm", this);
|
||||
Cu.import("resource://gre/modules/AsyncShutdown.jsm", this);
|
||||
let Native = Cu.import("resource://gre/modules/osfile/osfile_native.jsm", {});
|
||||
|
||||
/**
|
||||
* Constructors for decoding standard exceptions
|
||||
@ -348,7 +349,7 @@ const PREF_OSFILE_LOG_REDIRECT = "toolkit.osfile.log.redirect";
|
||||
* @param bool oldPref
|
||||
* An optional value that the DEBUG flag was set to previously.
|
||||
*/
|
||||
let readDebugPref = function readDebugPref(prefName, oldPref = false) {
|
||||
function readDebugPref(prefName, oldPref = false) {
|
||||
let pref = oldPref;
|
||||
try {
|
||||
pref = Services.prefs.getBoolPref(prefName);
|
||||
@ -379,6 +380,19 @@ Services.prefs.addObserver(PREF_OSFILE_LOG_REDIRECT,
|
||||
}, false);
|
||||
SharedAll.Config.TEST = readDebugPref(PREF_OSFILE_LOG_REDIRECT, false);
|
||||
|
||||
|
||||
/**
|
||||
* If |true|, use the native implementaiton of OS.File methods
|
||||
* whenever possible. Otherwise, force the use of the JS version.
|
||||
*/
|
||||
let nativeWheneverAvailable = true;
|
||||
const PREF_OSFILE_NATIVE = "toolkit.osfile.native";
|
||||
Services.prefs.addObserver(PREF_OSFILE_NATIVE,
|
||||
function prefObserver(aSubject, aTopic, aData) {
|
||||
nativeWheneverAvailable = readDebugPref(PREF_OSFILE_NATIVE, nativeWheneverAvailable);
|
||||
}, false);
|
||||
|
||||
|
||||
// Update worker's DEBUG flag if it's true.
|
||||
// Don't start the worker just for this, though.
|
||||
if (SharedAll.Config.DEBUG && Scheduler.launched) {
|
||||
@ -913,12 +927,32 @@ File.makeDir = function makeDir(path, options) {
|
||||
* read from the file.
|
||||
*/
|
||||
File.read = function read(path, bytes, options = {}) {
|
||||
let promise = Scheduler.post("read",
|
||||
[Type.path.toMsg(path), bytes, options], path);
|
||||
return promise.then(
|
||||
function onSuccess(data) {
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
});
|
||||
if (typeof bytes == "object") {
|
||||
// Passing |bytes| as an argument is deprecated.
|
||||
// We should now be passing it as a field of |options|.
|
||||
options = bytes || {};
|
||||
} else {
|
||||
options = clone(options, ["outExecutionDuration"]);
|
||||
if (typeof bytes != "undefined") {
|
||||
options.bytes = bytes;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.compression || !nativeWheneverAvailable) {
|
||||
// We need to use the JS implementation.
|
||||
let promise = Scheduler.post("read",
|
||||
[Type.path.toMsg(path), bytes, options], path);
|
||||
return promise.then(
|
||||
function onSuccess(data) {
|
||||
if (typeof data == "string") {
|
||||
return data;
|
||||
}
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
});
|
||||
}
|
||||
|
||||
// Otherwise, use the native implementation.
|
||||
return Scheduler.push(() => Native.read(path, options));
|
||||
};
|
||||
|
||||
/**
|
||||
|
@ -362,6 +362,9 @@ const EXCEPTION_NAMES = {
|
||||
},
|
||||
read: function read(path, bytes, options) {
|
||||
let data = File.read(Type.path.fromMsg(path), bytes, options);
|
||||
if (typeof data == "string") {
|
||||
return data;
|
||||
}
|
||||
return new Meta({
|
||||
buffer: data.buffer,
|
||||
byteOffset: data.byteOffset,
|
||||
|
70
toolkit/components/osfile/modules/osfile_native.jsm
Normal file
70
toolkit/components/osfile/modules/osfile_native.jsm
Normal file
@ -0,0 +1,70 @@
|
||||
/* 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/. */
|
||||
|
||||
/**
|
||||
* Native (xpcom) implementation of key OS.File functions
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
this.EXPORTED_SYMBOLS = ["read"];
|
||||
|
||||
let {results: Cr, utils: Cu, interfaces: Ci} = Components;
|
||||
|
||||
let SharedAll = Cu.import("resource://gre/modules/osfile/osfile_shared_allthreads.jsm", {});
|
||||
|
||||
let SysAll = {};
|
||||
if (SharedAll.Constants.Win) {
|
||||
Cu.import("resource://gre/modules/osfile/osfile_win_allthreads.jsm", SysAll);
|
||||
} else if (SharedAll.Constants.libc) {
|
||||
Cu.import("resource://gre/modules/osfile/osfile_unix_allthreads.jsm", SysAll);
|
||||
} else {
|
||||
throw new Error("I am neither under Windows nor under a Posix system");
|
||||
}
|
||||
let {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
|
||||
let {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
|
||||
|
||||
/**
|
||||
* The native service holding the implementation of the functions.
|
||||
*/
|
||||
XPCOMUtils.defineLazyServiceGetter(this,
|
||||
"Internals",
|
||||
"@mozilla.org/toolkit/osfile/native-internals;1",
|
||||
"nsINativeOSFileInternalsService");
|
||||
|
||||
/**
|
||||
* Native implementation of OS.File.read
|
||||
*
|
||||
* This implementation does not handle option |compression|.
|
||||
*/
|
||||
this.read = function(path, options = {}) {
|
||||
// Sanity check on types of options
|
||||
if ("encoding" in options && typeof options.encoding != "string") {
|
||||
return Promise.reject(new TypeError("Invalid type for option encoding"));
|
||||
}
|
||||
if ("compression" in options && typeof options.compression != "string") {
|
||||
return Promise.reject(new TypeError("Invalid type for option compression"));
|
||||
}
|
||||
if ("bytes" in options && typeof options.bytes != "number") {
|
||||
return Promise.reject(new TypeError("Invalid type for option bytes"));
|
||||
}
|
||||
|
||||
let deferred = Promise.defer();
|
||||
Internals.read(path,
|
||||
options,
|
||||
function onSuccess(success) {
|
||||
success.QueryInterface(Ci.nsINativeOSFileResult);
|
||||
if ("outExecutionDuration" in options) {
|
||||
options.outExecutionDuration =
|
||||
success.executionDurationMS +
|
||||
(options.outExecutionDuration || 0);
|
||||
}
|
||||
deferred.resolve(success.result);
|
||||
},
|
||||
function onError(operation, oserror) {
|
||||
deferred.reject(new SysAll.Error(operation, oserror, path));
|
||||
}
|
||||
);
|
||||
return deferred.promise;
|
||||
};
|
@ -331,14 +331,35 @@ AbstractFile.read = function read(path, bytes, options = {}) {
|
||||
options = bytes;
|
||||
bytes = options.bytes || null;
|
||||
}
|
||||
if ("encoding" in options && typeof options.encoding != "string") {
|
||||
throw new TypeError("Invalid type for option encoding");
|
||||
}
|
||||
if ("compression" in options && typeof options.compression != "string") {
|
||||
throw new TypeError("Invalid type for option compression: " + options.compression);
|
||||
}
|
||||
if ("bytes" in options && typeof options.bytes != "number") {
|
||||
throw new TypeError("Invalid type for option bytes");
|
||||
}
|
||||
let file = exports.OS.File.open(path);
|
||||
try {
|
||||
let buffer = file.read(bytes, options);
|
||||
if ("compression" in options && options.compression == "lz4") {
|
||||
return Lz4.decompressFileContent(buffer, options);
|
||||
} else {
|
||||
if ("compression" in options) {
|
||||
if (options.compression == "lz4") {
|
||||
buffer = Lz4.decompressFileContent(buffer, options);
|
||||
} else {
|
||||
throw OS.File.Error.invalidArgument("Compression");
|
||||
}
|
||||
}
|
||||
if (!("encoding" in options)) {
|
||||
return buffer;
|
||||
}
|
||||
let decoder;
|
||||
try {
|
||||
decoder = new TextDecoder(options.encoding);
|
||||
} catch (ex if ex instanceof TypeError) {
|
||||
throw OS.File.Error.invalidArgument("Decode");
|
||||
}
|
||||
return decoder.decode(buffer);
|
||||
} finally {
|
||||
file.close();
|
||||
}
|
||||
|
@ -139,6 +139,15 @@ Object.defineProperty(OSError.prototype, "becauseAccessDenied", {
|
||||
return this.unixErrno == Const.EACCES;
|
||||
}
|
||||
});
|
||||
/**
|
||||
* |true| if the error was raised because some invalid argument was passed,
|
||||
* |false| otherwise.
|
||||
*/
|
||||
Object.defineProperty(OSError.prototype, "becauseInvalidArgument", {
|
||||
get: function becauseInvalidArgument() {
|
||||
return this.unixErrno == Const.EINVAL;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Serialize an instance of OSError to something that can be
|
||||
@ -331,6 +340,10 @@ OSError.noSuchFile = function noSuchFile(operation, path) {
|
||||
return new OSError(operation, Const.ENOENT, path);
|
||||
};
|
||||
|
||||
OSError.invalidArgument = function invalidArgument(operation) {
|
||||
return new OSError(operation, Const.EINVAL);
|
||||
};
|
||||
|
||||
let EXPORTED_SYMBOLS = [
|
||||
"declareFFI",
|
||||
"libc",
|
||||
|
@ -161,6 +161,16 @@ Object.defineProperty(OSError.prototype, "becauseAccessDenied", {
|
||||
return this.winLastError == Const.ERROR_ACCESS_DENIED;
|
||||
}
|
||||
});
|
||||
/**
|
||||
* |true| if the error was raised because some invalid argument was passed,
|
||||
* |false| otherwise.
|
||||
*/
|
||||
Object.defineProperty(OSError.prototype, "becauseInvalidArgument", {
|
||||
get: function becauseInvalidArgument() {
|
||||
return this.winLastError == Const.ERROR_NOT_SUPPORTED ||
|
||||
this.winLastError == Const.ERROR_BAD_ARGUMENTS;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Serialize an instance of OSError to something that can be
|
||||
@ -368,6 +378,10 @@ OSError.noSuchFile = function noSuchFile(operation, path) {
|
||||
return new OSError(operation, Const.ERROR_FILE_NOT_FOUND, path);
|
||||
};
|
||||
|
||||
OSError.invalidArgument = function invalidArgument(operation) {
|
||||
return new OSError(operation, Const.ERROR_NOT_SUPPORTED);
|
||||
};
|
||||
|
||||
let EXPORTED_SYMBOLS = [
|
||||
"declareFFI",
|
||||
"libc",
|
||||
|
@ -11,7 +11,22 @@ DIRS += [
|
||||
MOCHITEST_CHROME_MANIFESTS += ['tests/mochi/chrome.ini']
|
||||
XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell/xpcshell.ini']
|
||||
|
||||
SOURCES += [
|
||||
'NativeOSFileInternals.cpp',
|
||||
]
|
||||
|
||||
XPIDL_MODULE = 'toolkit_osfile'
|
||||
|
||||
XPIDL_SOURCES += [
|
||||
'nsINativeOSFileInternals.idl',
|
||||
]
|
||||
|
||||
EXPORTS.mozilla += [
|
||||
'NativeOSFileInternals.h',
|
||||
]
|
||||
|
||||
EXTRA_PP_JS_MODULES += [
|
||||
'osfile.jsm',
|
||||
]
|
||||
|
||||
FINAL_LIBRARY = 'toolkitcomps'
|
||||
|
93
toolkit/components/osfile/nsINativeOSFileInternals.idl
Normal file
93
toolkit/components/osfile/nsINativeOSFileInternals.idl
Normal file
@ -0,0 +1,93 @@
|
||||
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
|
||||
/* vim: set ts=2 et sw=2 tw=40: */
|
||||
/* 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/. */
|
||||
|
||||
#include "nsISupports.idl"
|
||||
|
||||
/**
|
||||
* The result of a successful asynchronous operation.
|
||||
*/
|
||||
[scriptable, builtinclass, uuid(08B4CF29-3D65-4E79-B522-A694C322ED07)]
|
||||
interface nsINativeOSFileResult: nsISupports
|
||||
{
|
||||
/**
|
||||
* The actual value produced by the operation.
|
||||
*
|
||||
* Actual type of this value depends on the options passed to the
|
||||
* operation.
|
||||
*/
|
||||
[implicit_jscontext]
|
||||
readonly attribute jsval result;
|
||||
|
||||
/**
|
||||
* Delay between when the operation was requested on the main thread and
|
||||
* when the operation was started off main thread.
|
||||
*/
|
||||
readonly attribute double dispatchDurationMS;
|
||||
|
||||
/**
|
||||
* Duration of the off main thread execution.
|
||||
*/
|
||||
readonly attribute double executionDurationMS;
|
||||
};
|
||||
|
||||
/**
|
||||
* A callback invoked in case of success.
|
||||
*/
|
||||
[scriptable, function, uuid(2C1922CA-CA1B-4099-8B61-EC23CFF49412)]
|
||||
interface nsINativeOSFileSuccessCallback: nsISupports
|
||||
{
|
||||
void complete(in nsINativeOSFileResult result);
|
||||
};
|
||||
|
||||
/**
|
||||
* A callback invoked in case of error.
|
||||
*/
|
||||
[scriptable, function, uuid(F612E0FC-6736-4D24-AA50-FD661B3B40B6)]
|
||||
interface nsINativeOSFileErrorCallback: nsISupports
|
||||
{
|
||||
/**
|
||||
* @param operation The name of the failed operation. Provided to aid
|
||||
* debugging only, may change without notice.
|
||||
* @param OSstatus The OS status of the operation (errno under Unix,
|
||||
* GetLastError under Windows).
|
||||
*/
|
||||
void complete(in ACString operation, in long OSstatus);
|
||||
};
|
||||
|
||||
/**
|
||||
* A service providing native implementations of some of the features
|
||||
* of OS.File.
|
||||
*/
|
||||
[scriptable, builtinclass, uuid(913362AD-1526-4623-9E6B-A2EB08AFBBB9)]
|
||||
interface nsINativeOSFileInternalsService: nsISupports
|
||||
{
|
||||
/**
|
||||
* Implementation of OS.File.read
|
||||
*
|
||||
* @param path The absolute path to the file to read.
|
||||
* @param options An object that may contain some of the following fields
|
||||
* - {number} bytes The maximal number of bytes to read.
|
||||
* - {string} encoding If provided, return the result as a string, decoded
|
||||
* using this encoding. Otherwise, pass the result as an ArrayBuffer.
|
||||
* Invalid encodings cause onError to be called with the platform-specific
|
||||
* "invalid argument" constant.
|
||||
* - {string} compression Unimplemented at the moment.
|
||||
* @param onSuccess The success callback.
|
||||
* @param onError The error callback.
|
||||
*/
|
||||
[implicit_jscontext]
|
||||
void read(in AString path, in jsval options,
|
||||
in nsINativeOSFileSuccessCallback onSuccess,
|
||||
in nsINativeOSFileErrorCallback onError);
|
||||
};
|
||||
|
||||
|
||||
%{ C++
|
||||
|
||||
#define NATIVE_OSFILE_INTERNALS_SERVICE_CID {0x63A69303,0x8A64,0x45A9,{0x84, 0x8C, 0xD4, 0xE2, 0x79, 0x27, 0x94, 0xE6}}
|
||||
#define NATIVE_OSFILE_INTERNALS_SERVICE_CONTRACTID "@mozilla.org/toolkit/osfile/native-internals;1"
|
||||
|
||||
%}
|
@ -155,7 +155,6 @@ let test = maketest("Main", function main(test) {
|
||||
yield test_debug();
|
||||
yield test_info_features_detect();
|
||||
yield test_read_write();
|
||||
yield test_read_write_all();
|
||||
yield test_position();
|
||||
yield test_iter();
|
||||
yield test_exists();
|
||||
@ -303,92 +302,6 @@ let test_read_write = maketest("read_write", function read_write(test) {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Test OS.File.writeAtomic
|
||||
*/
|
||||
let test_read_write_all = maketest("read_write_all", function read_write_all(test) {
|
||||
return Task.spawn(function() {
|
||||
let pathDest = OS.Path.join(OS.Constants.Path.tmpDir,
|
||||
"osfile async test read writeAtomic.tmp");
|
||||
let tmpPath = pathDest + ".tmp";
|
||||
|
||||
let test_with_options = function(options, suffix) {
|
||||
return Task.spawn(function() {
|
||||
let optionsBackup = JSON.parse(JSON.stringify(options));
|
||||
|
||||
// Check that read + writeAtomic performs a correct copy
|
||||
let currentDir = yield OS.File.getCurrentDirectory();
|
||||
let pathSource = OS.Path.join(currentDir, EXISTING_FILE);
|
||||
let contents = yield OS.File.read(pathSource);
|
||||
test.ok(contents, "Obtained contents");
|
||||
let bytesWritten = yield OS.File.writeAtomic(pathDest, contents, options);
|
||||
test.is(contents.byteLength, bytesWritten, "Wrote the correct number of bytes (" + suffix + ")");
|
||||
|
||||
// Check that options are not altered
|
||||
test.is(Object.keys(options).length, Object.keys(optionsBackup).length,
|
||||
"The number of options was not changed");
|
||||
for (let k in options) {
|
||||
test.is(options[k], optionsBackup[k], "Option was not changed (" + suffix + ")");
|
||||
}
|
||||
yield reference_compare_files(pathSource, pathDest, test);
|
||||
|
||||
// Check that temporary file was removed or doesn't exist
|
||||
test.info("Compare complete");
|
||||
test.ok(!(new FileUtils.File(tmpPath).exists()), "No temporary file at the end of the run (" + suffix + ")");
|
||||
|
||||
// Check that writeAtomic fails if noOverwrite is true and the destination
|
||||
// file already exists!
|
||||
let view = new Uint8Array(contents.buffer, 10, 200);
|
||||
try {
|
||||
let opt = JSON.parse(JSON.stringify(options));
|
||||
opt.noOverwrite = true;
|
||||
yield OS.File.writeAtomic(pathDest, view, opt);
|
||||
test.fail("With noOverwrite, writeAtomic should have refused to overwrite file (" + suffix + ")");
|
||||
} catch (err) {
|
||||
test.info("With noOverwrite, writeAtomic correctly failed (" + suffix + ")");
|
||||
test.ok(err instanceof OS.File.Error, "writeAtomic correctly failed with a file error (" + suffix + ")");
|
||||
test.ok(err.becauseExists, "writeAtomic file error confirmed that the file already exists (" + suffix + ")");
|
||||
}
|
||||
yield reference_compare_files(pathSource, pathDest, test);
|
||||
test.ok(!(new FileUtils.File(tmpPath).exists()), "Temporary file was removed");
|
||||
|
||||
// Now write a subset
|
||||
let START = 10;
|
||||
let LENGTH = 100;
|
||||
view = new Uint8Array(contents.buffer, START, LENGTH);
|
||||
bytesWritten = yield OS.File.writeAtomic(pathDest, view, options);
|
||||
test.is(bytesWritten, LENGTH, "Partial write wrote the correct number of bytes (" + suffix + ")");
|
||||
let array2 = yield OS.File.read(pathDest);
|
||||
let view1 = new Uint8Array(contents.buffer, START, LENGTH);
|
||||
test.is(view1.length, array2.length, "Re-read partial write with the correct number of bytes (" + suffix + ")");
|
||||
let decoder = new TextDecoder();
|
||||
test.is(decoder.decode(view1), decoder.decode(array2), "Comparing re-read of partial write (" + suffix + ")");
|
||||
|
||||
// Write strings, default encoding
|
||||
let ARBITRARY_STRING = "aeiouyâêîôûçß•";
|
||||
yield OS.File.writeAtomic(pathDest, ARBITRARY_STRING, options);
|
||||
let array = yield OS.File.read(pathDest);
|
||||
let IN_STRING = decoder.decode(array);
|
||||
test.is(ARBITRARY_STRING, IN_STRING, "String write + read with default encoding works (" + suffix + ")");
|
||||
|
||||
let opt16 = JSON.parse(JSON.stringify(options));
|
||||
opt16.encoding = "utf-16";
|
||||
yield OS.File.writeAtomic(pathDest, ARBITRARY_STRING, opt16);
|
||||
array = yield OS.File.read(pathDest);
|
||||
IN_STRING = (new TextDecoder("utf-16")).decode(array);
|
||||
test.is(ARBITRARY_STRING, IN_STRING, "String write + read with utf-16 encoding works (" + suffix + ")");
|
||||
|
||||
// Cleanup.
|
||||
OS.File.remove(pathDest);
|
||||
});
|
||||
};
|
||||
|
||||
yield test_with_options({tmpPath: tmpPath}, "Renaming, not flushing");
|
||||
yield test_with_options({tmpPath: tmpPath, flush: true}, "Renaming, flushing");
|
||||
yield test_with_options({}, "Not renaming, not flushing");
|
||||
yield test_with_options({flush: true}, "Not renaming, flushing");
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Test file.{getPosition, setPosition}
|
||||
|
86
toolkit/components/osfile/tests/xpcshell/head.js
Normal file
86
toolkit/components/osfile/tests/xpcshell/head.js
Normal file
@ -0,0 +1,86 @@
|
||||
/* Any copyright is dedicated to the Public Domain.
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/ */
|
||||
|
||||
"use strict";
|
||||
|
||||
let {utils: Cu, interfaces: Ci} = Components;
|
||||
|
||||
let {OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
|
||||
let {Services} = Cu.import("resource://gre/modules/Services.jsm", {});
|
||||
let {Promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
|
||||
let {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
|
||||
let {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", {});
|
||||
let {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm", {});
|
||||
|
||||
Services.prefs.setBoolPref("toolkit.osfile.log", true);
|
||||
|
||||
/**
|
||||
* As add_task, but execute the test both with native operations and
|
||||
* without.
|
||||
*/
|
||||
function add_test_pair(generator) {
|
||||
add_task(function*() {
|
||||
do_print("Executing test " + generator.name + " with native operations");
|
||||
Services.prefs.setBoolPref("toolkit.osfile.native", true);
|
||||
return Task.spawn(generator);
|
||||
});
|
||||
add_task(function*() {
|
||||
do_print("Executing test " + generator.name + " without native operations");
|
||||
Services.prefs.setBoolPref("toolkit.osfile.native", false);
|
||||
return Task.spawn(generator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch asynchronously the contents of a file using xpcom.
|
||||
*
|
||||
* Used for comparing xpcom-based results to os.file-based results.
|
||||
*
|
||||
* @param {string} path The _absolute_ path to the file.
|
||||
* @return {promise}
|
||||
* @resolves {string} The contents of the file.
|
||||
*/
|
||||
function reference_fetch_file(path, test) {
|
||||
do_print("Fetching file " + path);
|
||||
let deferred = Promise.defer();
|
||||
let file = new FileUtils.File(path);
|
||||
NetUtil.asyncFetch(file,
|
||||
function(stream, status) {
|
||||
if (!Components.isSuccessCode(status)) {
|
||||
deferred.reject(status);
|
||||
return;
|
||||
}
|
||||
let result, reject;
|
||||
try {
|
||||
result = NetUtil.readInputStreamToString(stream, stream.available());
|
||||
} catch (x) {
|
||||
reject = x;
|
||||
}
|
||||
stream.close();
|
||||
if (reject) {
|
||||
deferred.reject(reject);
|
||||
} else {
|
||||
deferred.resolve(result);
|
||||
}
|
||||
});
|
||||
return deferred.promise;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compare asynchronously the contents two files using xpcom.
|
||||
*
|
||||
* Used for comparing xpcom-based results to os.file-based results.
|
||||
*
|
||||
* @param {string} a The _absolute_ path to the first file.
|
||||
* @param {string} b The _absolute_ path to the second file.
|
||||
*
|
||||
* @resolves {null}
|
||||
*/
|
||||
function reference_compare_files(a, b, test) {
|
||||
return Task.spawn(function*() {
|
||||
do_print("Comparing files " + a + " and " + b);
|
||||
let a_contents = yield reference_fetch_file(a, test);
|
||||
let b_contents = yield reference_fetch_file(b, test);
|
||||
do_check_eq(a_contents, b_contents);
|
||||
});
|
||||
};
|
@ -1,13 +1,5 @@
|
||||
"use strict";
|
||||
|
||||
const Ci = Components.interfaces;
|
||||
const Cu = Components.utils;
|
||||
|
||||
Cu.import("resource://gre/modules/osfile.jsm");
|
||||
Cu.import("resource://gre/modules/Services.jsm");
|
||||
Cu.import("resource://gre/modules/Task.jsm");
|
||||
Cu.import("resource://gre/modules/commonjs/sdk/core/promise.js");
|
||||
|
||||
function run_test() {
|
||||
do_test_pending();
|
||||
run_next_test();
|
||||
|
@ -1,16 +1,18 @@
|
||||
/* Any copyright is dedicated to the Public Domain.
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/ */
|
||||
|
||||
/**
|
||||
* Test that functions throw the appropriate exceptions.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
Components.utils.import("resource://gre/modules/osfile.jsm");
|
||||
let EXISTING_FILE = do_get_file("xpcshell.ini").path;
|
||||
|
||||
function run_test() {
|
||||
do_test_pending();
|
||||
run_next_test();
|
||||
}
|
||||
|
||||
add_task(function test_typeerror() {
|
||||
// Tests on |open|
|
||||
|
||||
add_test_pair(function test_typeerror() {
|
||||
let exn;
|
||||
try {
|
||||
let fd = yield OS.File.open("/tmp", {no_such_key: 1});
|
||||
@ -22,6 +24,66 @@ add_task(function test_typeerror() {
|
||||
do_check_true(exn.constructor.name == "TypeError");
|
||||
});
|
||||
|
||||
add_task(function() {
|
||||
do_test_finished();
|
||||
// Tests on |read|
|
||||
|
||||
add_test_pair(function* test_bad_encoding() {
|
||||
do_print("Testing with a wrong encoding");
|
||||
try {
|
||||
yield OS.File.read(EXISTING_FILE, { encoding: "baby-speak-encoded" });
|
||||
do_throw("Should have thrown with an ex.becauseInvalidArgument");
|
||||
} catch (ex if ex.becauseInvalidArgument) {
|
||||
do_print("Wrong encoding caused the correct exception");
|
||||
}
|
||||
|
||||
try {
|
||||
yield OS.File.read(EXISTING_FILE, { encoding: 4 });
|
||||
do_throw("Should have thrown a TypeError");
|
||||
} catch (ex if ex.constructor.name == "TypeError") {
|
||||
// Note that TypeError doesn't carry across compartments
|
||||
do_print("Non-string encoding caused the correct exception");
|
||||
}
|
||||
});
|
||||
|
||||
add_test_pair(function* test_bad_compression() {
|
||||
do_print("Testing with a non-existing compression");
|
||||
try {
|
||||
yield OS.File.read(EXISTING_FILE, { compression: "mmmh-crunchy" });
|
||||
do_throw("Should have thrown with an ex.becauseInvalidArgument");
|
||||
} catch (ex if ex.becauseInvalidArgument) {
|
||||
do_print("Wrong encoding caused the correct exception");
|
||||
}
|
||||
|
||||
do_print("Testing with a bad type for option compression");
|
||||
try {
|
||||
yield OS.File.read(EXISTING_FILE, { compression: 5 });
|
||||
do_throw("Should have thrown a TypeError");
|
||||
} catch (ex if ex.constructor.name == "TypeError") {
|
||||
// Note that TypeError doesn't carry across compartments
|
||||
do_print("Non-string encoding caused the correct exception");
|
||||
}
|
||||
});
|
||||
|
||||
add_test_pair(function* test_bad_bytes() {
|
||||
do_print("Testing with a bad type for option bytes");
|
||||
try {
|
||||
yield OS.File.read(EXISTING_FILE, { bytes: "five" });
|
||||
do_throw("Should have thrown a TypeError");
|
||||
} catch (ex if ex.constructor.name == "TypeError") {
|
||||
// Note that TypeError doesn't carry across compartments
|
||||
do_print("Non-number bytes caused the correct exception");
|
||||
}
|
||||
});
|
||||
|
||||
add_test_pair(function* read_non_existent() {
|
||||
do_print("Testing with a non-existent file");
|
||||
try {
|
||||
yield OS.File.read("I/do/not/exist");
|
||||
do_throw("Should have thrown with an ex.becauseNoSuchFile");
|
||||
} catch (ex if ex.becauseNoSuchFile) {
|
||||
do_print("Correct exceptions");
|
||||
}
|
||||
});
|
||||
|
||||
function run_test() {
|
||||
run_next_test();
|
||||
}
|
||||
|
@ -6,7 +6,6 @@
|
||||
Components.utils.import("resource://gre/modules/osfile.jsm");
|
||||
|
||||
function run_test() {
|
||||
do_test_pending();
|
||||
run_next_test();
|
||||
}
|
||||
|
||||
@ -69,7 +68,3 @@ add_task(function test_error_attributes () {
|
||||
do_check_true(err.becauseNoSuchFile);
|
||||
}
|
||||
});
|
||||
|
||||
add_task(function() {
|
||||
do_test_finished();
|
||||
});
|
||||
|
@ -4,10 +4,6 @@
|
||||
|
||||
"use strict";
|
||||
|
||||
const Cu = Components.utils;
|
||||
|
||||
Cu.import("resource://gre/modules/osfile.jsm", this);
|
||||
Cu.import("resource://gre/modules/Services.jsm", this);
|
||||
Cu.import("resource://gre/modules/ctypes.jsm", this);
|
||||
Cu.import("resource://testing-common/AppData.jsm", this);
|
||||
|
||||
|
100
toolkit/components/osfile/tests/xpcshell/test_read_write.js
Normal file
100
toolkit/components/osfile/tests/xpcshell/test_read_write.js
Normal file
@ -0,0 +1,100 @@
|
||||
/* Any copyright is dedicated to the Public Domain.
|
||||
* http://creativecommons.org/publicdomain/zero/1.0/ */
|
||||
|
||||
"use strict";
|
||||
|
||||
let {utils: Cu} = Components;
|
||||
|
||||
let SHARED_PATH;
|
||||
|
||||
let EXISTING_FILE = do_get_file("xpcshell.ini").path;
|
||||
|
||||
add_task(function* init() {
|
||||
do_get_profile();
|
||||
SHARED_PATH = OS.Path.join(OS.Constants.Path.profileDir, "test_osfile_read.tmp");
|
||||
});
|
||||
|
||||
|
||||
// Check that OS.File.read() is executed after the previous operation
|
||||
add_test_pair(function* ordering() {
|
||||
let string1 = "Initial state " + Math.random();
|
||||
let string2 = "After writing " + Math.random();
|
||||
yield OS.File.writeAtomic(SHARED_PATH, string1);
|
||||
OS.File.writeAtomic(SHARED_PATH, string2);
|
||||
let string3 = yield OS.File.read(SHARED_PATH, { encoding: "utf-8" });
|
||||
do_check_eq(string3, string2);
|
||||
});
|
||||
|
||||
add_test_pair(function* read_write_all() {
|
||||
let DEST_PATH = SHARED_PATH + Math.random();
|
||||
let TMP_PATH = DEST_PATH + ".tmp";
|
||||
|
||||
let test_with_options = function(options, suffix) {
|
||||
return Task.spawn(function*() {
|
||||
do_print("Running test read_write_all with options " + JSON.stringify(options));
|
||||
let TEST = "read_write_all " + suffix;
|
||||
|
||||
let optionsBackup = JSON.parse(JSON.stringify(options));
|
||||
|
||||
// Check that read + writeAtomic performs a correct copy
|
||||
let currentDir = yield OS.File.getCurrentDirectory();
|
||||
let pathSource = OS.Path.join(currentDir, EXISTING_FILE);
|
||||
let contents = yield OS.File.read(pathSource);
|
||||
do_check_true(!!contents); // Content is not empty
|
||||
|
||||
let bytesWritten = yield OS.File.writeAtomic(DEST_PATH, contents, options);
|
||||
do_check_eq(contents.byteLength, bytesWritten); // Correct number of bytes written
|
||||
|
||||
// Check that options are not altered
|
||||
do_check_eq(JSON.stringify(options), JSON.stringify(optionsBackup));
|
||||
yield reference_compare_files(pathSource, DEST_PATH, TEST);
|
||||
|
||||
// Check that temporary file was removed or never created exist
|
||||
do_check_false(new FileUtils.File(TMP_PATH).exists());
|
||||
|
||||
// Check that writeAtomic fails if noOverwrite is true and the destination
|
||||
// file already exists!
|
||||
let view = new Uint8Array(contents.buffer, 10, 200);
|
||||
try {
|
||||
let opt = JSON.parse(JSON.stringify(options));
|
||||
opt.noOverwrite = true;
|
||||
yield OS.File.writeAtomic(DEST_PATH, view, opt);
|
||||
do_throw("With noOverwrite, writeAtomic should have refused to overwrite file (" + suffix + ")");
|
||||
} catch (err if err instanceof OS.File.Error && err.becauseExists) {
|
||||
do_print("With noOverwrite, writeAtomic correctly failed (" + suffix + ")");
|
||||
}
|
||||
yield reference_compare_files(pathSource, DEST_PATH, TEST);
|
||||
|
||||
// Check that temporary file was removed or never created
|
||||
do_check_false(new FileUtils.File(TMP_PATH).exists());
|
||||
|
||||
// Now write a subset
|
||||
let START = 10;
|
||||
let LENGTH = 100;
|
||||
view = new Uint8Array(contents.buffer, START, LENGTH);
|
||||
bytesWritten = yield OS.File.writeAtomic(DEST_PATH, view, options);
|
||||
do_check_eq(bytesWritten, LENGTH);
|
||||
|
||||
let array2 = yield OS.File.read(DEST_PATH);
|
||||
let view1 = new Uint8Array(contents.buffer, START, LENGTH);
|
||||
do_check_eq(view1.length, array2.length);
|
||||
let decoder = new TextDecoder();
|
||||
do_check_eq(decoder.decode(view1), decoder.decode(array2));
|
||||
|
||||
|
||||
// Cleanup.
|
||||
yield OS.File.remove(DEST_PATH);
|
||||
yield OS.File.remove(TMP_PATH);
|
||||
});
|
||||
};
|
||||
|
||||
yield test_with_options({tmpPath: TMP_PATH}, "Renaming, not flushing");
|
||||
yield test_with_options({tmpPath: TMP_PATH, flush: true}, "Renaming, flushing");
|
||||
yield test_with_options({}, "Not renaming, not flushing");
|
||||
yield test_with_options({flush: true}, "Not renaming, flushing");
|
||||
});
|
||||
|
||||
|
||||
function run_test() {
|
||||
run_next_test();
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
[DEFAULT]
|
||||
head =
|
||||
head = head.js
|
||||
tail =
|
||||
|
||||
[test_available_free_space.js]
|
||||
@ -25,6 +25,7 @@ tail =
|
||||
[test_open.js]
|
||||
[test_telemetry.js]
|
||||
[test_duration.js]
|
||||
[test_read_write.js]
|
||||
[test_compression.js]
|
||||
[test_osfile_writeAtomic_backupTo_option.js]
|
||||
[test_osfile_error.js]
|
||||
|
@ -40,6 +40,7 @@ function setup_osfile_crash_noerror() {
|
||||
|
||||
Services.prefs.setBoolPref("toolkit.osfile.debug.failshutdown", true);
|
||||
Services.prefs.setIntPref("toolkit.asyncshutdown.crash_timeout", 1);
|
||||
Services.prefs.setBoolPref("toolkit.osfile.native", false);
|
||||
|
||||
OS.File.getCurrentDirectory();
|
||||
Services.obs.notifyObservers(null, "profile-before-change", null);
|
||||
@ -68,6 +69,7 @@ function setup_osfile_crash_exn() {
|
||||
|
||||
Services.prefs.setBoolPref("toolkit.osfile.debug.failshutdown", true);
|
||||
Services.prefs.setIntPref("toolkit.asyncshutdown.crash_timeout", 1);
|
||||
Services.prefs.setBoolPref("toolkit.osfile.native", false);
|
||||
|
||||
OS.File.read("I do not exist");
|
||||
Services.obs.notifyObservers(null, "profile-before-change", null);
|
||||
@ -80,7 +82,6 @@ function after_osfile_crash_exn(mdump, extra) {
|
||||
let state = info.conditions[0].state;
|
||||
do_print("Keys: " + Object.keys(state).join(", "));
|
||||
do_check_eq(info.phase, "profile-before-change");
|
||||
do_check_true(state.launched);
|
||||
do_check_false(state.shutdown);
|
||||
do_check_true(state.worker);
|
||||
do_check_true(!!state.latestSent);
|
||||
|
@ -114,6 +114,7 @@ function testReload() {
|
||||
info("shouldBeEmptyFirst is empty now");
|
||||
}
|
||||
else if (!data.added || !Object.keys(data.added).length) {
|
||||
info(JSON.stringify(data));
|
||||
ok(false, "deleted object should have something if an added object " +
|
||||
"does not have anything");
|
||||
endTestReloaded();
|
||||
@ -159,6 +160,7 @@ function testAddIframe() {
|
||||
};
|
||||
|
||||
let onStoresUpdate = data => {
|
||||
info(JSON.stringify(data));
|
||||
info("checking if the hosts list is correct for this iframe addition");
|
||||
|
||||
markOutMatched(shouldBeEmpty, data.added);
|
||||
|
@ -592,7 +592,7 @@ struct PRFilePrivate {
|
||||
|
||||
// copied from nsprpub/pr/src/{io/prfile.c | md/windows/w95io.c} :
|
||||
// PR_Open and _PR_MD_OPEN
|
||||
static nsresult
|
||||
nsresult
|
||||
OpenFile(const nsAFlatString &name, int osflags, int mode,
|
||||
PRFileDesc **fd)
|
||||
{
|
||||
|
Loading…
Reference in New Issue
Block a user