Skip to content

Commit

Permalink
Merge pull request #259 from PSPDFKit/reinhard/configuration-prop
Browse files Browse the repository at this point in the history
Android improvements
  • Loading branch information
Reinhard Hafenscher authored Jul 25, 2019
2 parents 3c473ce + 414937d commit 77dd26d
Show file tree
Hide file tree
Showing 8 changed files with 209 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,15 @@ public void accept(List<Annotation> annotations) {
}
break;
case COMMAND_ADD_ANNOTATION:
if (args != null) {
annotationDisposables.add(root.addAnnotation(args.getMap(0)));
if (args != null && args.size() == 2) {
final int requestId = args.getInt(0);
annotationDisposables.add(root.addAnnotation(requestId, args.getMap(1)));
}
break;
case COMMAND_REMOVE_ANNOTATION:
if (args != null) {
annotationDisposables.add(root.removeAnnotation(args.getMap(0)));
if (args != null && args.size() == 2) {
final int requestId = args.getInt(0);
annotationDisposables.add(root.removeAnnotation(requestId, args.getMap(1)));
}
break;
case COMMAND_GET_ALL_UNSAVED_ANNOTATIONS:
Expand All @@ -211,8 +213,9 @@ public void accept(JSONObject jsonObject) {
}
break;
case COMMAND_ADD_ANNOTATIONS:
if (args != null && args.size() == 1) {
annotationDisposables.add(root.addAnnotations(args.getMap(0)));
if (args != null && args.size() == 2) {
final int requestId = args.getInt(0);
annotationDisposables.add(root.addAnnotations(requestId, args.getMap(1)));
}
break;
case COMMAND_GET_FORM_FIELD_VALUE:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ public PdfViewDataReturnedEvent(@IdRes int viewId, int requestId, @NonNull List<
payload = Arguments.makeNativeMap(map);
}

public PdfViewDataReturnedEvent(@IdRes int viewId, int requestId, boolean result) {
super(viewId);
this.requestId = requestId;
Map<String, Object> map = new HashMap<>();
map.put("requestId", requestId);
map.put("result", result);

payload = Arguments.makeNativeMap(map);
}

public PdfViewDataReturnedEvent(@IdRes int viewId, int requestId, @NonNull JSONObject jsonObject) {
super(viewId);
this.requestId = requestId;
Expand Down
102 changes: 61 additions & 41 deletions android/src/main/java/com/pspdfkit/views/PdfView.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Single;
Expand Down Expand Up @@ -171,47 +173,46 @@ public void setFragmentTag(String fragmentTag) {
}

public void setConfiguration(PdfActivityConfiguration configuration) {
if (configuration != null && !configuration.equals(this.configuration)) {
// The configuration changed, recreate the fragment.
// We set the current page index so the fragment is created at this location.
this.pageIndex = fragment != null ? fragment.getPageIndex() : this.pageIndex;
removeFragment(false);
}
this.configuration = configuration;
setupFragment();
}

public void setDocument(@Nullable String document) {
if (document == null) {
public void setDocument(@Nullable String documentPath) {
if (documentPath == null) {
this.document = null;
removeFragment(false);
return;
}

if (Uri.parse(document).getScheme() == null) {
if (Uri.parse(documentPath).getScheme() == null) {
// If there is no scheme it might be a raw path.
try {
File file = new File(document);
document = Uri.fromFile(file).toString();
File file = new File(documentPath);
documentPath = Uri.fromFile(file).toString();
} catch (Exception e) {
document = FILE_SCHEME + document;
documentPath = FILE_SCHEME + document;
}
}
if (documentOpeningDisposable != null) {
documentOpeningDisposable.dispose();
}
updateState();
documentOpeningDisposable = PdfDocumentLoader.openDocumentAsync(getContext(), Uri.parse(document))
documentOpeningDisposable = PdfDocumentLoader.openDocumentAsync(getContext(), Uri.parse(documentPath))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<PdfDocument>() {

@Override
public void accept(PdfDocument pdfDocument) throws Exception {
PdfView.this.document = pdfDocument;
setupFragment();
}

}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
PdfView.this.document = null;
setupFragment();
eventDispatcher.dispatchEvent(new PdfViewDocumentLoadFailedEvent(getId(), throwable.getMessage()));
}
.subscribe(pdfDocument -> {
PdfView.this.document = pdfDocument;
setupFragment();
}, throwable -> {
PdfView.this.document = null;
setupFragment();
eventDispatcher.dispatchEvent(new PdfViewDocumentLoadFailedEvent(getId(), throwable.getMessage()));
});
}

Expand Down Expand Up @@ -329,15 +330,17 @@ public void removeFragment(boolean makeInactive) {
PdfFragment pdfFragment = (PdfFragment) fragmentManager.findFragmentByTag(fragmentTag);
if (pdfFragment != null) {
fragmentManager.beginTransaction()
.remove(pdfFragment)
.commitAllowingStateLoss();
.remove(pdfFragment)
.commitNowAllowingStateLoss();
}
if (makeInactive) {
// Clear everything.
isActive = false;
document = null;
}

fragment = null;
document = null;

fragmentGetter.onComplete();
fragmentGetter = BehaviorSubject.create();
pendingFragmentActions.dispose();
Expand Down Expand Up @@ -492,17 +495,19 @@ private EnumSet<AnnotationType> getTypeFromString(@Nullable String type) {
return EnumSet.noneOf(AnnotationType.class);
}

public Disposable addAnnotation(ReadableMap annotation) {
public Disposable addAnnotation(final int requestId, ReadableMap annotation) {
return fragmentGetter.take(1).map(PdfFragment::getDocument).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(pdfDocument -> {
JSONObject json = new JSONObject(annotation.toHashMap());
pdfDocument.getAnnotationProvider().createAnnotationFromInstantJson(json.toString());
});

.map(pdfDocument -> {
JSONObject json = new JSONObject(annotation.toHashMap());
return pdfDocument.getAnnotationProvider().createAnnotationFromInstantJson(json.toString());
})
.map(Annotation::toInstantJson)
.observeOn(AndroidSchedulers.mainThread())
.subscribe((instantJson) -> eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, true)),
(throwable) -> eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, throwable)));
}

public Disposable removeAnnotation(ReadableMap annotation) {
public Disposable removeAnnotation(final int requestId, ReadableMap annotation) {
return fragmentGetter.take(1).map(PdfFragment::getDocument).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(pdfDocument -> {
Expand All @@ -515,10 +520,23 @@ public Disposable removeAnnotation(ReadableMap annotation) {
if (pageIndex == -1 || type == null || name == null) {
return Observable.empty();
}

return pdfDocument.getAnnotationProvider().getAllAnnotationsOfType(getTypeFromString(type), pageIndex, 1)
.filter(annotationToFilter -> name.equals(annotationToFilter.getName()))
.map(filteredAnnotation -> new Pair<>(filteredAnnotation, pdfDocument));
}).subscribe(pair -> pair.second.getAnnotationProvider().removeAnnotationFromPage(pair.first));
})
.firstOrError()
.flatMapCompletable(pair -> Completable.fromAction(() -> {
pair.second.getAnnotationProvider().removeAnnotationFromPage(pair.first);
}))
.subscribe(() -> eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, true)), (throwable -> {
if (throwable instanceof NoSuchElementException) {
// We didn't find an annotation so return false.
eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, false));
} else {
eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, throwable));
}
}));
}

public Single<JSONObject> getAllUnsavedAnnotations() {
Expand All @@ -535,14 +553,16 @@ public JSONObject call() throws Exception {
});
}

public Disposable addAnnotations(ReadableMap annotation) {
public Disposable addAnnotations(final int requestId, ReadableMap annotation) {
return fragmentGetter.take(1).map(PdfFragment::getDocument).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(pdfDocument -> {
JSONObject json = new JSONObject(annotation.toHashMap());
final DataProvider dataProvider = new DocumentJsonDataProvider(json);
DocumentJsonFormatter.importDocumentJson(pdfDocument, dataProvider);
});
.flatMapCompletable(currentDocument -> Completable.fromAction(() -> {
JSONObject json = new JSONObject(annotation.toHashMap());
final DataProvider dataProvider = new DocumentJsonDataProvider(json);
DocumentJsonFormatter.importDocumentJson(currentDocument, dataProvider);
}))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, true)),
(throwable) -> eventDispatcher.dispatchEvent(new PdfViewDataReturnedEvent(getId(), requestId, throwable)));
}

public Disposable getFormFieldValue(final int requestId, @NonNull String formElementName) {
Expand Down
42 changes: 39 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,26 @@ class PSPDFKitView extends React.Component {
* Adds a new annotation to the current document.
*
* @param annotation InstantJson of the annotation to add.
*
* Returns a promise resolving to true if the annotation was added. Otherwise, returns false if an error has occurred.
*/
addAnnotation = function(annotation) {
if (Platform.OS === "android") {
let requestId = this._nextRequestId++;
let requestMap = this._requestMap;

// We create a promise here that will be resolved once onDataReturned is called.
let promise = new Promise(function(resolve, reject) {
requestMap[requestId] = { resolve: resolve, reject: reject };
});

UIManager.dispatchViewManagerCommand(
findNodeHandle(this.refs.pdfView),
this._getViewManagerConfig("RCTPSPDFKitView").Commands.addAnnotation,
[annotation]
[requestId, annotation]
);

return promise;
} else if (Platform.OS === "ios") {
return NativeModules.PSPDFKitViewManager.addAnnotation(
annotation,
Expand All @@ -206,14 +218,26 @@ class PSPDFKitView extends React.Component {
* Removes an existing annotation from the current document.
*
* @param annotation InstantJson of the annotation to remove.
*
* Returns a promise resolving to true if the annotation was removed. Otherwise, returns false if the annotation couldn't be found.
*/
removeAnnotation = function(annotation) {
if (Platform.OS === "android") {
let requestId = this._nextRequestId++;
let requestMap = this._requestMap;

// We create a promise here that will be resolved once onDataReturned is called.
let promise = new Promise(function(resolve, reject) {
requestMap[requestId] = { resolve: resolve, reject: reject };
});

UIManager.dispatchViewManagerCommand(
findNodeHandle(this.refs.pdfView),
this._getViewManagerConfig("RCTPSPDFKitView").Commands.removeAnnotation,
[annotation]
[requestId, annotation]
);

return promise;
} else if (Platform.OS === "ios") {
return NativeModules.PSPDFKitViewManager.removeAnnotation(
annotation,
Expand Down Expand Up @@ -256,14 +280,26 @@ class PSPDFKitView extends React.Component {
* Applies the passed in document instant json.
*
* @param annotations The document instant json to apply.
*
* Returns a promise resolving to true if the annotation was added.
*/
addAnnotations = function(annotations) {
if (Platform.OS === "android") {
let requestId = this._nextRequestId++;
let requestMap = this._requestMap;

// We create a promise here that will be resolved once onDataReturned is called.
let promise = new Promise(function(resolve, reject) {
requestMap[requestId] = { resolve: resolve, reject: reject };
});

UIManager.dispatchViewManagerCommand(
findNodeHandle(this.refs.pdfView),
this._getViewManagerConfig("RCTPSPDFKitView").Commands.addAnnotations,
[annotations]
[requestId, annotations]
);

return promise;
} else if (Platform.OS === "ios") {
return NativeModules.PSPDFKitViewManager.addAnnotations(
annotations,
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-native-pspdfkit",
"version": "1.24.8",
"version": "1.24.9",
"description": "A React Native module for the PSPDFKit library.",
"keywords": [
"react native",
Expand Down
Loading

0 comments on commit 77dd26d

Please sign in to comment.