001/*
002 * #%L
003 * Errai Prototype
004 * %%
005 * Copyright (C) 2015 - 2017 Doltech
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 * 
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 * 
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package gwt.material.design.addins.client.camera;
021
022import com.google.gwt.core.client.GWT;
023import com.google.gwt.dom.client.Document;
024import com.google.gwt.dom.client.Element;
025import com.google.gwt.event.logical.shared.ValueChangeEvent;
026import gwt.material.design.client.base.AbstractValueWidget;
027import gwt.material.design.client.base.MaterialWidget;
028import gwt.material.design.jscore.client.api.file.File;
029import gwt.material.design.jscore.client.api.file.FileReader;
030
031import static gwt.material.design.jquery.client.api.JQuery.$;
032
033public class Html5Camera extends AbstractValueWidget<String> {
034
035
036    private String imageUrl;
037    private MaterialWidget imageFileInput = new MaterialWidget(Document.get().createFileInputElement());
038
039    public Html5Camera() {
040        super(Document.get().createDivElement());
041        setInitialClasses("camera-manual-upload");
042    }
043
044
045    @Override
046    protected void onLoad() {
047        super.onLoad();
048
049        add(imageFileInput);
050        imageFileInput.setDataAttribute("accept", "image/*");
051        imageFileInput.setDataAttribute("capture", "camera");
052
053
054        $(imageFileInput.getElement()).on("change", e -> {
055            captureToDataURL();
056            return true;
057        });
058
059        imageFileInput.setVisible(false);
060    }
061
062    public void load() {
063        $(imageFileInput.getElement()).click();
064    }
065
066    protected void captureToDataURL() {
067        File file =  toFile(imageFileInput.getElement());
068
069        FileReader reader = new FileReader();
070        $(reader).on("load", e -> {
071            imageUrl = reader.result;
072            ValueChangeEvent.fire(this, imageUrl);
073            return true;
074        });
075
076        if (file != null) {
077            reader.readAsDataURL(file);
078        } else {
079            GWT.log("Please provide a file before reading the file.", new NullPointerException());
080        }
081    }
082
083    protected native File toFile(Element inputElement) /*-{
084        return $wnd.jQuery(inputElement).prop('files')[0];
085    }-*/;
086
087    @Override
088    public String getValue() {
089        return imageUrl;
090    }
091}