diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..2a3d13fa --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Jugaad s.r.l. + Copyright 2018-2020 GEAR.it s.r.l. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/License.pdf b/License.pdf index 71070d46..d43c6996 100644 Binary files a/License.pdf and b/License.pdf differ diff --git a/README.md b/README.md index ea3dda12..e660a1ae 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ This plugin is released under the Apache 2.0 license **Only the plugin source code is under the license Apache 2.0, the library included in the plugin follow the license of his owner, please check it on:** http://www.radaeepdf.com/ecommerce/technical-specification -Jugaad s.r.l. and Radaee Studio distribute the plugin as-is for free. +Jugaad s.r.l. and Radaee Studio distribute the plugin as-is for free. Jugaad s.r.l. is the maintainer of the plug-in project. Jugaad s.r.l. is the maintainer of the plug-in project. If you, as user and developer need new features or fixes you shall submit them here on GitHub. @@ -30,7 +30,7 @@ If you, as user and developer need new features or fixes you shall submit them h 2. Add the android/iOS platform. `cd RadaeePDF-Cordova` - `cordova platform add android@latest --save` and/or `cordova platform add ios --save` + `cordova platform add android@8.0 --save` and/or `cordova platform add ios --save` 3. Add the plugin. `cordova plugin add https://github.com/RadaeePDF-Jugaad/RadaeePDF-Cordova.git --save` @@ -138,14 +138,12 @@ For more examples, check demo/js/index.js - iOS: CALayer based tiled rendering. RadaeePDF library version included: -- Android: v3.55 - 03/May/2021 -- iOS: v3.73 +- Android: v3.55 (native library 3.60) +- iOS: v4.5 Original development: -- Based on the original Xamarin module from GEAR.it. - This plugin was created based on [PaoloMessina/RadaeeCordova](https://github.com/PaoloMessina/RadaeeCordova) www.paolomessina.it, email: paolo.messina.it@gmail.com More information about RadaeePDF SDK on http://www.radaeepdf.com. For guide please check [Knowledge Base articles](http://www.radaeepdf.com/support/knowledge-base?view=kb&catid=4) - diff --git a/demo/js/index.js b/demo/js/index.js index 2ffe9f55..2861de1e 100644 --- a/demo/js/index.js +++ b/demo/js/index.js @@ -203,7 +203,7 @@ var app = { RadaeePDFPlugin.open( { - url: "https://www.radaeepdf.com/documentation/readeula/eula/eula.pdf", + url: "https://www.radaeepdf.com/documentation/readeula/eula/eula.pdf", password: "" //password if needed }, function(message) { diff --git a/package.json b/package.json index 434b7ca0..9750e505 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,19 @@ { "name": "com.radaee.cordova", - "version": "1.3.2", - "description": "RadaeePDF reader cordova plugin", + "version": "1.3.6", + "description": "RadaeePDF Classic Reader Cordova plugin", "cordova": { "platforms": [ - "android" + "android", + "ios" ] }, + "dependencies": { + "cordova-android": "^8.0.0" +}, "repository": { "type": "git", - "url": "https://github.com/gearit/RadaeePDF-Cordova.git" + "url": "https://github.com/RadaeePDF-Jugaad/RadaeePDF-Cordova.git" }, "keywords": [ "cordova", @@ -23,5 +27,5 @@ "version": ">=3.0.0" } ], - "author": "Gear.it S.R.L." + "author": "Jugaad S.R.L." } diff --git a/plugin.xml b/plugin.xml index ed0105b3..d7437878 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,13 +1,13 @@ + id="com.radaee.cordova" version="1.6.8"> RadaeePDF-Cordova - GEAR.it S.R.L. + Jugaad s.r.l. RadaeePDF SDK Plugin for Cordova. The best PDF rendering engine with annotation, form, page creation features. Support forum, java and objective-c sources are available on www.radaeepdf.com Apache pdf, open, inapppdf, radaee, cordova, radaeepdf, android, ios @@ -84,9 +84,13 @@ + + + + @@ -98,18 +102,13 @@ + + + - - - - - - - - - + @@ -155,6 +154,8 @@ + + @@ -165,9 +166,7 @@ - - - + @@ -187,42 +186,41 @@ + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + + + - - - - + + + + + @@ -248,53 +246,50 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + - - - - - - - + + + + + + + + + + + + + + + + + + @@ -465,142 +460,173 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + diff --git a/src/android/ViewLib/src/main/java/com/radaee/reader/GLView.java b/src/android/ViewLib/src/main/java/com/radaee/reader/GLView.java index ba7b2368..a4f18ef6 100755 --- a/src/android/ViewLib/src/main/java/com/radaee/reader/GLView.java +++ b/src/android/ViewLib/src/main/java/com/radaee/reader/GLView.java @@ -48,7 +48,7 @@ import com.radaee.view.GLPage; import com.radaee.view.ILayoutView; import com.radaee.view.VSel; -import com.radaee.viewlib.R; +import com.radaee.reader.R; import java.util.ArrayList; import java.util.List; @@ -2112,7 +2112,7 @@ public void PDFSetStamp(int code) { { m_status = STA_STAMP; if (m_dicon == null) { - m_icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.pdf_custom_stamp); + m_icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_custom_stamp); if (m_icon != null) { m_dicon = m_doc.NewImage(m_icon, true); } diff --git a/src/android/ViewLib/src/main/java/com/radaee/reader/PDFLayoutView.java b/src/android/ViewLib/src/main/java/com/radaee/reader/PDFLayoutView.java index a05c5a2e..72112a51 100755 --- a/src/android/ViewLib/src/main/java/com/radaee/reader/PDFLayoutView.java +++ b/src/android/ViewLib/src/main/java/com/radaee/reader/PDFLayoutView.java @@ -53,7 +53,7 @@ import com.radaee.view.PDFLayoutVert; import com.radaee.view.VPage; import com.radaee.view.VSel; -import com.radaee.viewlib.R; +import com.radaee.reader.R; import java.util.ArrayList; import java.util.List; @@ -1947,7 +1947,7 @@ public void PDFSetStamp(int code) { { m_status = STA_STAMP; //if(m_dicon == null) { - m_icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.pdf_custom_stamp); + m_icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_custom_stamp); if (m_icon != null) { m_dicon = m_doc.NewImage(m_icon, true); } diff --git a/src/android/ViewLib/src/main/java/com/radaee/util/FileBrowserAdt.java b/src/android/ViewLib/src/main/java/com/radaee/util/FileBrowserAdt.java index 56e12d9f..e6ea2b85 100644 --- a/src/android/ViewLib/src/main/java/com/radaee/util/FileBrowserAdt.java +++ b/src/android/ViewLib/src/main/java/com/radaee/util/FileBrowserAdt.java @@ -12,7 +12,7 @@ import android.widget.LinearLayout; import android.widget.TextView; -import com.radaee.viewlib.R; +import com.radaee.reader.R; import java.io.File; import java.util.Vector; @@ -32,13 +32,13 @@ public class FileGridItem extends LinearLayout { public FileGridItem(Context context, AttributeSet attrs) { super(context, attrs); if (m_def_file_icon == null) - m_def_file_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_file); + m_def_file_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_file); if (m_def_dir_icon == null) - m_def_dir_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_folder); + m_def_dir_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder0); if (m_def_up_icon == null) - m_def_up_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_go_up); + m_def_up_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder1); if (m_def_refresh_icon == null) - m_def_refresh_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_refresh); + m_def_refresh_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder2); this.setBackgroundColor(0); this.setOrientation(VERTICAL); } diff --git a/src/android/ViewLib/src/main/java/com/radaee/util/PDFGridItem.java b/src/android/ViewLib/src/main/java/com/radaee/util/PDFGridItem.java index 9816ef61..f79ace76 100755 --- a/src/android/ViewLib/src/main/java/com/radaee/util/PDFGridItem.java +++ b/src/android/ViewLib/src/main/java/com/radaee/util/PDFGridItem.java @@ -15,7 +15,7 @@ import com.radaee.pdf.Global; import com.radaee.pdf.Matrix; import com.radaee.pdf.Page; -import com.radaee.viewlib.R; +import com.radaee.reader.R; import java.io.File; @@ -36,13 +36,13 @@ public PDFGridItem(Context context, AttributeSet attrs) { super(context, attrs); if( m_def_pdf_icon == null ) - m_def_pdf_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.file03); + m_def_pdf_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_file); if( m_def_dir_icon == null ) - m_def_dir_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.folder0); + m_def_dir_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder0); if( m_def_up_icon == null ) - m_def_up_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.folder1); + m_def_up_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder1); if( m_def_refresh_icon == null ) - m_def_refresh_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.folder2); + m_def_refresh_icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_grid_folder2); this.setBackgroundColor(0); this.setOrientation(VERTICAL); unlock_file(); diff --git a/src/android/ViewLib/src/main/jniLibs/arm64-v8a/librdpdf.so b/src/android/ViewLib/src/main/jniLibs/arm64-v8a/librdpdf.so index 781e90da..1d9c4f30 100644 Binary files a/src/android/ViewLib/src/main/jniLibs/arm64-v8a/librdpdf.so and b/src/android/ViewLib/src/main/jniLibs/arm64-v8a/librdpdf.so differ diff --git a/src/android/ViewLib/src/main/jniLibs/armeabi-v7a/librdpdf.so b/src/android/ViewLib/src/main/jniLibs/armeabi-v7a/librdpdf.so index a515aeb8..9b3e5fd7 100644 Binary files a/src/android/ViewLib/src/main/jniLibs/armeabi-v7a/librdpdf.so and b/src/android/ViewLib/src/main/jniLibs/armeabi-v7a/librdpdf.so differ diff --git a/src/android/ViewLib/src/main/jniLibs/x86/librdpdf.so b/src/android/ViewLib/src/main/jniLibs/x86/librdpdf.so index b5256995..77c78c34 100644 Binary files a/src/android/ViewLib/src/main/jniLibs/x86/librdpdf.so and b/src/android/ViewLib/src/main/jniLibs/x86/librdpdf.so differ diff --git a/src/android/ViewLib/src/main/jniLibs/x86_64/librdpdf.so b/src/android/ViewLib/src/main/jniLibs/x86_64/librdpdf.so index a56e784c..609cbb8d 100644 Binary files a/src/android/ViewLib/src/main/jniLibs/x86_64/librdpdf.so and b/src/android/ViewLib/src/main/jniLibs/x86_64/librdpdf.so differ diff --git a/src/android/ViewLib/src/main/res/drawable/bar_back.png b/src/android/ViewLib/src/main/res/drawable/bg_background.png old mode 100755 new mode 100644 similarity index 100% rename from src/android/ViewLib/src/main/res/drawable/bar_back.png rename to src/android/ViewLib/src/main/res/drawable/bg_background.png diff --git a/src/android/ViewLib/src/main/res/drawable/menu_back.png b/src/android/ViewLib/src/main/res/drawable/bg_menu.png old mode 100755 new mode 100644 similarity index 100% rename from src/android/ViewLib/src/main/res/drawable/menu_back.png rename to src/android/ViewLib/src/main/res/drawable/bg_menu.png diff --git a/src/android/ViewLib/src/main/res/drawable/btn_add_bookmark.png b/src/android/ViewLib/src/main/res/drawable/btn_add_bookmark.png new file mode 100644 index 00000000..8a3d9450 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_add_bookmark.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_edit.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_edit.png deleted file mode 100644 index 83c79b86..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_edit.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_editbox.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_editbox.png new file mode 100644 index 00000000..bbb98f50 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_annot_editbox.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_ellipse.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_ellipse.png index 9703ad6c..044de3c0 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_ellipse.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_ellipse.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_ink.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_ink.png index d1a2a3a3..3e7bf569 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_ink.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_ink.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_line.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_line.png index 9a01fa32..2437ba78 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_line.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_line.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_note.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_note.png index 2b2ccad2..e9ebc021 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_note.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_note.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_polygon.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_polygon.png index ee0027f4..a08f2894 100644 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_polygon.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_polygon.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_polyline.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_polyline.png index 178fcbf6..cc7a7fd2 100644 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_polyline.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_polyline.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_rect.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_rect.png index 5009d0fe..556ecada 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_annot_rect.png and b/src/android/ViewLib/src/main/res/drawable/btn_annot_rect.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annot_stamp.png b/src/android/ViewLib/src/main/res/drawable/btn_annot_stamp.png new file mode 100644 index 00000000..c9ee6858 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_annot_stamp.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_annots.png b/src/android/ViewLib/src/main/res/drawable/btn_annots.png new file mode 100644 index 00000000..209c2368 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_annots.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_back.png b/src/android/ViewLib/src/main/res/drawable/btn_back.png index 2780e756..e457b3df 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_back.png and b/src/android/ViewLib/src/main/res/drawable/btn_back.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_done.png b/src/android/ViewLib/src/main/res/drawable/btn_done.png index ace4dbdb..aee4307b 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_done.png and b/src/android/ViewLib/src/main/res/drawable/btn_done.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_ink.png b/src/android/ViewLib/src/main/res/drawable/btn_ink.png deleted file mode 100755 index af498798..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_ink.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_left.png b/src/android/ViewLib/src/main/res/drawable/btn_left.png index 8db8349f..1404c9a0 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_left.png and b/src/android/ViewLib/src/main/res/drawable/btn_left.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_more.png b/src/android/ViewLib/src/main/res/drawable/btn_more.png new file mode 100644 index 00000000..f1d1d64f Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_more.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_outline.png b/src/android/ViewLib/src/main/res/drawable/btn_outline.png index 921b04a6..9465161e 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_outline.png and b/src/android/ViewLib/src/main/res/drawable/btn_outline.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_perform.png b/src/android/ViewLib/src/main/res/drawable/btn_perform.png index daba85eb..0ebefa2e 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_perform.png and b/src/android/ViewLib/src/main/res/drawable/btn_perform.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_print.png b/src/android/ViewLib/src/main/res/drawable/btn_print.png index b683b555..68583b8c 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_print.png and b/src/android/ViewLib/src/main/res/drawable/btn_print.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_redo.png b/src/android/ViewLib/src/main/res/drawable/btn_redo.png index 7ecdcc59..fb1c811d 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_redo.png and b/src/android/ViewLib/src/main/res/drawable/btn_redo.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_remove.png b/src/android/ViewLib/src/main/res/drawable/btn_remove.png index dda0e7e5..de7b3600 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_remove.png and b/src/android/ViewLib/src/main/res/drawable/btn_remove.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_right.png b/src/android/ViewLib/src/main/res/drawable/btn_right.png index d30041e1..d43110e7 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_right.png and b/src/android/ViewLib/src/main/res/drawable/btn_right.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_save.png b/src/android/ViewLib/src/main/res/drawable/btn_save.png new file mode 100644 index 00000000..fd1c4497 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_save.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_search.png b/src/android/ViewLib/src/main/res/drawable/btn_search.png index f0edfbdc..61c55753 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_search.png and b/src/android/ViewLib/src/main/res/drawable/btn_search.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_select.png b/src/android/ViewLib/src/main/res/drawable/btn_select.png index b2a04008..faa5042f 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_select.png and b/src/android/ViewLib/src/main/res/drawable/btn_select.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_settings.png b/src/android/ViewLib/src/main/res/drawable/btn_settings.png index b0453c1a..3c15e485 100644 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_settings.png and b/src/android/ViewLib/src/main/res/drawable/btn_settings.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_share.png b/src/android/ViewLib/src/main/res/drawable/btn_share.png new file mode 100644 index 00000000..def81632 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_share.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_show_bookmarks.png b/src/android/ViewLib/src/main/res/drawable/btn_show_bookmarks.png new file mode 100644 index 00000000..01bda28a Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/btn_show_bookmarks.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_undo.png b/src/android/ViewLib/src/main/res/drawable/btn_undo.png index dac5348a..7a34b101 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_undo.png and b/src/android/ViewLib/src/main/res/drawable/btn_undo.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_view.png b/src/android/ViewLib/src/main/res/drawable/btn_view.png index dac4259c..8b183ffc 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_view.png and b/src/android/ViewLib/src/main/res/drawable/btn_view.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_view_dual.png b/src/android/ViewLib/src/main/res/drawable/btn_view_dual.png index c377f749..2d366328 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_view_dual.png and b/src/android/ViewLib/src/main/res/drawable/btn_view_dual.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_view_horz.png b/src/android/ViewLib/src/main/res/drawable/btn_view_horz.png index 611a0ce4..a41dc6b5 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_view_horz.png and b/src/android/ViewLib/src/main/res/drawable/btn_view_horz.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_view_single.png b/src/android/ViewLib/src/main/res/drawable/btn_view_single.png index e7e7dcad..db6081f5 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_view_single.png and b/src/android/ViewLib/src/main/res/drawable/btn_view_single.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/btn_view_vert.png b/src/android/ViewLib/src/main/res/drawable/btn_view_vert.png index f03eb8bb..5598c298 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/btn_view_vert.png and b/src/android/ViewLib/src/main/res/drawable/btn_view_vert.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/file03.png b/src/android/ViewLib/src/main/res/drawable/file03.png deleted file mode 100755 index ceb44604..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/file03.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/folder0.png b/src/android/ViewLib/src/main/res/drawable/folder0.png deleted file mode 100755 index 9fa15d7d..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/folder0.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/folder1.png b/src/android/ViewLib/src/main/res/drawable/folder1.png deleted file mode 100755 index 14035181..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/folder1.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/folder2.png b/src/android/ViewLib/src/main/res/drawable/folder2.png deleted file mode 100755 index e925ea51..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/folder2.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_add.png b/src/android/ViewLib/src/main/res/drawable/ic_add.png deleted file mode 100755 index 16138737..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_add.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_bookmarks.png b/src/android/ViewLib/src/main/res/drawable/ic_bookmarks.png deleted file mode 100755 index ce2d3992..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_bookmarks.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_custom_stamp.png b/src/android/ViewLib/src/main/res/drawable/ic_custom_stamp.png new file mode 100644 index 00000000..5d80170a Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/ic_custom_stamp.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_file.png b/src/android/ViewLib/src/main/res/drawable/ic_file.png deleted file mode 100644 index 8c70c427..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_file.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_folder.png b/src/android/ViewLib/src/main/res/drawable/ic_folder.png deleted file mode 100644 index fb933c1d..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_folder.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_go_up.png b/src/android/ViewLib/src/main/res/drawable/ic_go_up.png deleted file mode 100644 index 81c9d2fc..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_go_up.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_grid_file.png b/src/android/ViewLib/src/main/res/drawable/ic_grid_file.png new file mode 100644 index 00000000..af5d5629 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/ic_grid_file.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_grid_folder0.png b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder0.png new file mode 100644 index 00000000..9b86423a Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder0.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_grid_folder1.png b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder1.png new file mode 100644 index 00000000..3deaae21 Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder1.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_grid_folder2.png b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder2.png new file mode 100644 index 00000000..658b840b Binary files /dev/null and b/src/android/ViewLib/src/main/res/drawable/ic_grid_folder2.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_more.png b/src/android/ViewLib/src/main/res/drawable/ic_more.png deleted file mode 100755 index eda93b09..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_more.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_refresh.png b/src/android/ViewLib/src/main/res/drawable/ic_refresh.png deleted file mode 100644 index 3578c526..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_refresh.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/ic_share.png b/src/android/ViewLib/src/main/res/drawable/ic_share.png deleted file mode 100644 index 9f135814..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/ic_share.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/pdf_custom_stamp.png b/src/android/ViewLib/src/main/res/drawable/pdf_custom_stamp.png deleted file mode 100755 index e8a70094..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/pdf_custom_stamp.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/drawable/pt_end.png b/src/android/ViewLib/src/main/res/drawable/pt_end.png index 3779b4b6..607dfba0 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/pt_end.png and b/src/android/ViewLib/src/main/res/drawable/pt_end.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/pt_start.png b/src/android/ViewLib/src/main/res/drawable/pt_start.png index 8ca84215..44298207 100755 Binary files a/src/android/ViewLib/src/main/res/drawable/pt_start.png and b/src/android/ViewLib/src/main/res/drawable/pt_start.png differ diff --git a/src/android/ViewLib/src/main/res/drawable/save.png b/src/android/ViewLib/src/main/res/drawable/save.png deleted file mode 100755 index d896d756..00000000 Binary files a/src/android/ViewLib/src/main/res/drawable/save.png and /dev/null differ diff --git a/src/android/ViewLib/src/main/res/layout/bar_act.xml b/src/android/ViewLib/src/main/res/layout/bar_act.xml index ea610f4d..ae77ef4a 100755 --- a/src/android/ViewLib/src/main/res/layout/bar_act.xml +++ b/src/android/ViewLib/src/main/res/layout/bar_act.xml @@ -2,7 +2,7 @@ + android:background="@drawable/bg_background" > + android:clickable="true" + android:src="@drawable/btn_annot_stamp" /> + android:src="@drawable/btn_annot_editbox" /> + android:clickable="true" + android:src="@drawable/btn_annots" /> + android:src="@drawable/btn_more" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFNav/PDFNavCtrl.h b/src/ios/PDFViewer/PDFNav/PDFNavCtrl.h new file mode 100755 index 00000000..b0297621 --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/PDFNavCtrl.h @@ -0,0 +1,17 @@ +// +// PDFNavCtrl.h +// RDPDFReader +// +// Created by Radaee on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// +#import "PDFNavThumb.h" +#import +@interface PDFNavCtrl : UIViewController +{ + __weak IBOutlet PDFNavThumb *mNav; + __weak IBOutlet UISegmentedControl *mTab; +} +- (IBAction)OnUpdate:(id)sender; +@end + diff --git a/src/ios/PDFViewer/PDFNav/PDFNavCtrl.m b/src/ios/PDFViewer/PDFNav/PDFNavCtrl.m new file mode 100755 index 00000000..5b5f9cd0 --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/PDFNavCtrl.m @@ -0,0 +1,126 @@ +// +// PDFNavCtrl.m +// RDPDFReader +// +// Created by Radaee on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import "PDFNavCtrl.h" +#import "UICellView.h" +#import "PDFReaderCtrl.h" + +@implementation PDFNavCtrl + +- (void)show_error:(NSString *)msg +{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Error", nil) message:msg preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + }]; + [alert addAction:conform]; + [self presentViewController:alert animated:YES completion:nil]; +} + +- (void)show_password :(UICellView *)cell +{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Password" message:NSLocalizedString(@"Need password to open the PDF file.", nil) preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + UITextField *txt = [alert textFields][0]; + [self process_open :cell :[txt text]]; + }]; + UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { + }]; + + [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { + textField.placeholder = @"Password"; + textField.secureTextEntry = YES; + }]; + [alert addAction:conform]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; +} + +- (void)process_delete:(UICellView *)cell +{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Delete" , nil) message:NSLocalizedString(@"Do you confirm to delete the PDF file?", nil) preferredStyle:UIAlertControllerStyleAlert]; + PDFNavThumb *vw = mNav; + UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + [cell UIDelete]; + [vw refresh]; + }]; + UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { + }]; + [alert addAction:conform]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; +} + +- (void)process_open:(UICellView *)cell :(NSString *)pswd +{ + int err = 0; + PDFReaderCtrl *reader; + RDPDFDoc *doc = [cell UIGetDoc:pswd :&err]; + switch(err) + { + case err_ok://goto reader page. + reader = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + [reader setDoc:doc]; + [self presentViewController:reader animated:YES completion:nil]; + break; + case err_open: + [self show_error:@"can't open file. file can't be readable."]; + doc = nil; + break; + case err_password: + [self show_password:cell]; + doc = nil; + break; + case err_encrypt: + [self show_error:@"unknown encryption."]; + doc = nil; + break; + case err_bad_file: + [self show_error:@"PDF file damaged."]; + doc = nil; + break; + default: + [self show_error:@"Unknown error."]; + doc = nil; + break; + } +} +- (void)viewDidAppear:(BOOL)animated +{ + [mNav refresh]; +} +- (void)viewDidLoad { + [super viewDidLoad]; + [mNav setCallback + :^(id cell) { + UICellView *view = (UICellView *)cell; + [self process_open:view :nil]; + } + :^(id cell){ + UICellView *view = (UICellView *)cell; + [self process_delete:view]; + }]; + NSString *folder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; + [mNav setDir:folder]; +} + + +- (IBAction)OnUpdate:(id)sender { + UISegmentedControl *seg = (UISegmentedControl *)sender; + int isel = (int)[seg selectedSegmentIndex]; + if(isel == 0) + { + NSString *folder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; + [mNav setDir:folder]; + } + else + { + NSString *folder = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + [mNav setDir:folder]; + } +} +@end diff --git a/src/ios/PDFViewer/PDFNav/PDFNavThumb.h b/src/ios/PDFViewer/PDFNav/PDFNavThumb.h new file mode 100755 index 00000000..c909de49 --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/PDFNavThumb.h @@ -0,0 +1,24 @@ +// +// PDFNavThumb.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// +#import "PDFObjc.h" +#import "UICellView.h" +typedef void(^func_nav)(id); +@interface PDFNavThumb : UIScrollView +{ + dispatch_queue_t m_queue; + Boolean m_cancel; + NSString *m_cur_dir; + func_nav OnPDFOpen; + func_delete OnPDFDelete; +} +-(id)initWithFrame:(CGRect)frame; +-(id)initWithCoder:(NSCoder *)aDecoder; +-(void)setCallback:(func_nav)pdf_open :(func_delete)pdf_delete; +-(void)setDir:(NSString *)dir; +-(void)refresh; +@end diff --git a/src/ios/PDFViewer/PDFNav/PDFNavThumb.m b/src/ios/PDFViewer/PDFNav/PDFNavThumb.m new file mode 100755 index 00000000..a487a463 --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/PDFNavThumb.m @@ -0,0 +1,178 @@ +// +// PDFNavThumb.m +// RDPDFReader +// +// Created by Radaee on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// +#import "PDFNavThumb.h" +#import "PDFObjc.h" +#import + +UIImage *g_nav_refresh; +UIImage *g_nav_def; + +@implementation PDFNavThumb +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + //self.autoresizesSubviews = YES; + //self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + [self setBackgroundColor:[UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1]]; + m_cancel = false; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + //self.autoresizesSubviews = YES; + //self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + [self setBackgroundColor:[UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1]]; + m_cancel = false; + } + return self; +} + +-(void)setFrame:(CGRect)frame +{ + [super setFrame:frame]; + [self refresh]; +} + +-(void)dealloc +{ + m_cancel = true; + if(m_queue) + { +#if !OS_OBJECT_USE_OBJC + dispatch_release(m_queue); +#endif + m_queue = nil; + } +} + +-(void)reset +{ + m_cancel = true; + if(m_queue) + { +#if !OS_OBJECT_USE_OBJC + dispatch_release(m_queue); +#endif + m_queue = nil; + } + m_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + for(UIView *view in self.subviews) + { + [view removeFromSuperview]; + } + m_cancel = false; +} + +#define CELL_WIDTH 128 +#define CELL_HEIGHT 142 +-(void)tapAction:(UITapGestureRecognizer *)tap +{ + if(OnPDFOpen) OnPDFOpen(tap.view); +} + +-(void)tapRefresh:(UITapGestureRecognizer *)tap +{ + [self refresh]; +} + +-(void)setCallback:(func_nav)pdf_open :(func_delete)pdf_delete +{ + OnPDFOpen = pdf_open; + OnPDFDelete = pdf_delete; +} + +-(void)setDir:(NSString *)dir +{ + [self reset]; + if(!dir || [dir length] == 0) return; + m_cur_dir = dir; + CGRect rect = self.bounds; + float w = rect.size.width; + int col_cnt = ((int)w) / CELL_WIDTH; + if(col_cnt < 1) col_cnt = 1; + float gap = (w - col_cnt * CELL_WIDTH) / col_cnt; + float step = gap + CELL_WIDTH; + + NSFileManager *fm = [NSFileManager defaultManager]; + NSArray *dirArray = [fm contentsOfDirectoryAtPath:dir error:nil]; + float x = gap * 0.5f; + float y = 4; + int col = 0; + Boolean *cancel = &m_cancel; + + if(!g_nav_refresh) g_nav_refresh = [UIImage imageNamed:@"nav_refresh"]; + if(!g_nav_def) g_nav_def = [UIImage imageNamed:@"nav_def"]; + + //add first refresh button. + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"UICellView" owner:self options:nil]; + UICellView *view = [views lastObject]; + [view UILoad:@"." :@"." :CGRectMake(x, y, CELL_WIDTH, CELL_HEIGHT) :g_nav_refresh]; + [view UISetDelete:nil]; + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRefresh:)]; + [view addGestureRecognizer:tap]; + [self addSubview:view]; + x += step; + col++; + if(col >= col_cnt) + { + x = gap * 0.5f; + y += CELL_HEIGHT + 4; + col = 0; + } + + for(NSString *fname in dirArray) + { + NSString *sExt = [fname substringFromIndex:[fname length] - 4]; + if(![sExt compare: @".pdf"]) + { + NSString *sFile = [dir stringByAppendingPathComponent:fname]; + views = [[NSBundle mainBundle] loadNibNamed:@"UICellView" owner:self options:nil]; + view = [views lastObject]; + [view UILoad:fname :sFile :CGRectMake(x, y, CELL_WIDTH, CELL_HEIGHT) :g_nav_def]; + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; + [view addGestureRecognizer:tap]; + [view UISetDelete:OnPDFDelete]; + + dispatch_async(m_queue, ^{ + if (*cancel) return; + [view BKRender];//render in backing thread. + dispatch_async(dispatch_get_main_queue(), ^{ + [view UIUpdate]; + }); + }); + + [self addSubview:view]; + x += step; + col++; + if(col >= col_cnt) + { + x = gap * 0.5f; + y += CELL_HEIGHT + 4; + col = 0; + } + } + } + if(col > 0) y += CELL_HEIGHT + 4; + if(y < rect.size.height) + y = rect.size.height; + self.contentSize = CGSizeMake(rect.size.width, y); +} + +-(void)refresh +{ + [self setDir:m_cur_dir]; +} +@end diff --git a/src/ios/PDFViewer/PDFNav/UICellView.h b/src/ios/PDFViewer/PDFNav/UICellView.h new file mode 100755 index 00000000..6b7c7bba --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/UICellView.h @@ -0,0 +1,23 @@ +// +// UICellView.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import "PDFObjc.h" + +typedef void(^func_delete)(id); +@interface UICellView : UIView + +-(id)initWithFrame:(CGRect)frame; +-(id)initWithCoder:(NSCoder *)aDecoder; +- (IBAction)OnDelete:(id)sender; +-(void)UILoad : (NSString *)fname :(NSString *)path :(CGRect)frame :(UIImage *)def; +-(void)UISetDelete:(func_delete)callback; +-(void)UIUpdate; +-(void)BKRender; +-(RDPDFDoc *)UIGetDoc : (NSString *)pswd :(int *)err; +-(void)UIDelete; +@end diff --git a/src/ios/PDFViewer/PDFNav/UICellView.m b/src/ios/PDFViewer/PDFNav/UICellView.m new file mode 100755 index 00000000..47cd0fd6 --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/UICellView.m @@ -0,0 +1,132 @@ +// +// UICellView.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/3. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "UICellView.h" +#import "RDVGlobal.h" + +@interface UICellView() { + __weak IBOutlet UIImageView *mImg; + __weak IBOutlet UILabel *mLabel; + __weak IBOutlet UIButton *mDelete; + NSString *m_path; + RDVLocker *m_locker; + + func_delete m_delete; + RDPDFDIB *m_dib;//rendered thumb + int m_dibw; + int m_dibh; +} + +@end + +@implementation UICellView +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + m_path = nil; + m_dib = nil; + m_locker = [[RDVLocker alloc] init]; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + m_path = nil; + m_dib = nil; + m_locker = [[RDVLocker alloc] init]; + } + return self; +} + +- (IBAction)OnDelete:(id)sender { + if(m_delete) m_delete(self); +} + +-(void)UILoad : (NSString *)fname :(NSString *)path :(CGRect)frame :(UIImage *)def +{ + self.frame = frame; + [mLabel setText:fname]; + m_path = path; + float pix = [[UIScreen mainScreen] scale]; + m_dibw = pix * frame.size.width; + m_dibh = pix * frame.size.width; + [self setBackgroundColor:[UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1]]; + [mImg setContentMode:UIViewContentModeScaleAspectFit]; + [mImg setImage:def]; +} + +-(void)UISetDelete:(func_delete)callback +{ + m_delete = callback; + if(!callback) mDelete.hidden = YES; +} +-(void)UIDelete +{ + [m_locker lock]; + unlink([m_path UTF8String]); + [m_locker unlock]; +} + +-(void)UIUpdate +{ + if(m_dib) + { + CGImageRef image = [m_dib image]; + [mImg setImage:[[UIImage alloc] initWithCGImage:image]]; + CGImageRelease(image); + //m_dib = nil; + } +} + +-(void)BKRender +{ + [m_locker lock]; + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + int err = [doc open:m_path :nil]; + if(!err) + { + RDPDFPage *page = [doc page:0]; + float pw = [doc pageWidth:0]; + float ph = [doc pageHeight:0]; + float scale0 = m_dibw / pw; + float scale1 = m_dibh / ph; + if(scale0 > scale1) scale0 = scale1; + pw *= scale0; + ph *= scale0; + int dibw = (int)(pw + 0.5f); + int dibh = (int)(ph + 0.5f); + m_dib = [[RDPDFDIB alloc] init: dibw :dibh]; + [page renderPrepare:m_dib]; + if(![page renderThumb:m_dib]) + { + RDPDFMatrix *mat = [[RDPDFMatrix alloc] init:scale0 :-scale0 :0 :dibh]; + [page render:m_dib :mat :2]; + mat = nil; + } + page = nil; + } + doc = nil; + [m_locker unlock]; +} + +-(RDPDFDoc *)UIGetDoc : (NSString *)pswd :(int *)err +{ + [m_locker lock]; + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + *err = [doc open:m_path :pswd]; + [m_locker unlock]; + return doc; +} + +@end diff --git a/src/ios/PDFViewer/PDFNav/UICellView.xib b/src/ios/PDFViewer/PDFNav/UICellView.xib new file mode 100755 index 00000000..52210e0a --- /dev/null +++ b/src/ios/PDFViewer/PDFNav/UICellView.xib @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.h b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.h new file mode 100755 index 00000000..0532e720 --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.h @@ -0,0 +1,24 @@ +// +// PDFPagesCtrl.h +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#pragma once +#import +#import "PDFPagesView.h" +@class RDPDFDoc; + +typedef void(^PagesDone)(const bool *pages_del, const int *pages_rot); + +@interface PDFPagesCtrl : UIViewController +{ + __weak IBOutlet PDFPagesView *mPages; + RDPDFDoc *m_doc; + PagesDone m_done; +} +- (void)setCallback:(RDPDFDoc *)doc :(PagesDone)done; +- (IBAction)OnBtnBack:(id)sender; +- (IBAction)OnBtnDone:(id)sender; +@end diff --git a/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.m b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.m new file mode 100755 index 00000000..81baf20d --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.m @@ -0,0 +1,52 @@ +// +// PDFPagesCtrl.m +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#import +#import "PDFPagesCtrl.h" +#import "PDFObjc.h" + +@implementation PDFPagesCtrl +-(void)setCallback:(RDPDFDoc *)doc :(PagesDone)done +{ + m_doc = doc; + m_done = done; +} + +- (void)viewDidLoad { + [super viewDidLoad]; +} + +-(void)viewWillAppear:(BOOL)animated +{ + if(self.navigationController) + self.navigationController.navigationBarHidden = YES; +} +- (void)viewDidAppear:(BOOL)animated +{ + [super viewDidAppear:animated]; + [mPages open:m_doc]; +} + +- (IBAction)OnBtnBack:(id)sender { + if(self.navigationController) [self.navigationController popViewControllerAnimated:YES]; + else [self dismissViewControllerAnimated:YES completion:nil]; +} + +- (IBAction)OnBtnDone:(id)sender { + if([mPages modified]) + { + int pcnt = [m_doc pageCount]; + int *rots = (int *)malloc((sizeof(int) + sizeof(bool)) * pcnt); + bool *dels = (bool *)(rots + pcnt); + [mPages getEditData:dels :rots]; + m_done(dels, rots); + free(rots); + } + if(self.navigationController) [self.navigationController popViewControllerAnimated:YES]; + else [self dismissViewControllerAnimated:YES completion:nil]; +} +@end diff --git a/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.storyboard b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.storyboard new file mode 100755 index 00000000..0609e61e --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/PDFPagesCtrl.storyboard @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFPages/PDFPagesView.h b/src/ios/PDFViewer/PDFPages/PDFPagesView.h new file mode 100755 index 00000000..206b7c13 --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/PDFPagesView.h @@ -0,0 +1,56 @@ +// +// PDFPagesView.h +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#pragma once +#import +#import "UIPageCellView.h" +@class RDPDFDoc; +@class RDPDFPage; +@class RDPDFDIB; + +@interface RDPDFPageCell : NSObject +{ + UIView *m_parent; + UIPageCellView *m_view; + RDPDFDoc *m_doc; + RDPDFPage *m_page; + int m_pageno; + RDPDFDIB *m_dib; + bool m_deleted; + int m_rotate; + int m_status; + CGFloat m_x; + CGFloat m_y; + CGFloat m_scale_pix; + onPageDelete m_del; +} +@property bool deleted; +@property int rotate; +-(id)init:(UIView *)parent :(RDPDFDoc *) doc :(int)pageno :(onPageDelete)del; +-(bool)updateRotate; +-(void)UISetPos:(CGFloat)x :(CGFloat)y; +-(void)UIRemove; +-(bool)UIRender:(dispatch_queue_t)queue; +-(bool)UICancel:(dispatch_queue_t)queue; +@end + +@interface PDFPagesView : UIScrollView +{ + dispatch_queue_t m_queue; + RDPDFDoc *m_doc; + int m_row_cnt; + int m_col_cnt; + int m_gap; + NSMutableArray *m_cells_org; + NSMutableArray *m_cells; +} +-(id)initWithFrame:(CGRect)frame; +-(id)initWithCoder:(NSCoder *)aDecoder; +-(void)open:(RDPDFDoc *)doc; +-(bool)modified; +-(void)getEditData:(bool *)dels :(int *)rots; +@end diff --git a/src/ios/PDFViewer/PDFPages/PDFPagesView.m b/src/ios/PDFViewer/PDFPages/PDFPagesView.m new file mode 100755 index 00000000..8d6b737b --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/PDFPagesView.m @@ -0,0 +1,350 @@ +// +// PDFPagesView.m +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#import +#import "PDFPagesView.h" +#import "PDFObjc.h" + +#define CELL_WIDTH 158 +#define CELL_HEIGHT 198 +#define CELL_SIZE 158 + +@implementation RDPDFPageCell +@synthesize deleted = m_deleted; +@synthesize rotate = m_rotate; +-(id)init:(UIView *)parent :(RDPDFDoc *) doc :(int)pageno :(onPageDelete)del +{ + self = [super init]; + if(self) + { + m_parent = parent; + m_doc = doc; + m_pageno = pageno; + m_scale_pix = [[UIScreen mainScreen] scale]; + m_del = del; + m_status = 0; + } + return self; +} + +-(bool)updateRotate +{ + int rot0 = m_rotate >> 16; + int rot1 = rot0 + [m_view getRotate]; + if(rot1 > 360) rot1 -= 360; + m_rotate = (rot0 << 16) | rot1; + return (rot0 != rot1); +} + +-(void)UISetPos:(CGFloat)x :(CGFloat)y +{ + m_x = x; + m_y = y + 8; + if(!m_view) + { + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"UIPageCellView" owner:self options:nil]; + m_view = [views lastObject]; + [m_view setPageNo:m_del :m_pageno]; + [m_parent addSubview:m_view]; + } + [m_view setFrame:CGRectMake(m_x, m_y, CELL_WIDTH, CELL_HEIGHT)]; +} + +-(void)UIRemove +{ + [m_view UIRemove]; +} + +-(bool)UIRender:(dispatch_queue_t)queue +{ + if(m_status != 0) return false; + m_status = 1; + dispatch_async(queue, ^{ + if (self->m_status < 0) return; + + float csize = CELL_SIZE * self->m_scale_pix; + RDPDFDoc *doc = self->m_doc; + int pageno = self->m_pageno; + RDPDFPage *page = [doc page:pageno]; + float pw = [doc pageWidth:pageno]; + float ph = [doc pageHeight:pageno]; + float scale1 = csize / pw; + float scale2 = csize / ph; + if(scale1 > scale2) scale1 = scale2; + int iw = pw * scale1; + int ih = ph * scale1; + + RDPDFDIB *dib = [[RDPDFDIB alloc] init:iw :ih]; + [dib erase:-1]; + RDPDFMatrix *mat = [[RDPDFMatrix alloc] init:scale1 :-scale1 :0 :ih]; + self->m_page = page; + [page render:dib :mat :2]; + mat = nil; + if (self->m_status < 0) + { + dib = nil; + page = nil; + } + else + { + self->m_status = 2; + self->m_dib = dib; + dispatch_async(dispatch_get_main_queue(), ^{ + [self->m_view UIUpdate: self->m_dib]; + }); + } + }); + return true; +} + +-(bool)UICancel:(dispatch_queue_t)queue +{ + if(m_status <= 0) return false; + m_status = -1; + dispatch_async(queue, ^{ + self->m_page = nil; + dispatch_async(dispatch_get_main_queue(), ^{ + [self->m_view UIUpdate: nil]; + self->m_dib = nil; + self->m_status = 0; + }); + }); + return true; +} + +@end + +@implementation PDFPagesView +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + //self.autoresizesSubviews = YES; + //self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + [self setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0]]; + + self.userInteractionEnabled = YES; + self.multipleTouchEnabled = NO; + self.alwaysBounceHorizontal = YES; + self.alwaysBounceVertical = NO; + self.delegate = self; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + //self.autoresizesSubviews = YES; + //self.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + [self setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0]]; + + self.userInteractionEnabled = YES; + self.multipleTouchEnabled = NO; + self.alwaysBounceHorizontal = YES; + self.alwaysBounceVertical = NO; + self.delegate = self; + } + return self; +} + +-(void)dealloc +{ + if(m_queue) + { +#if !OS_OBJECT_USE_OBJC + dispatch_release(m_queue); +#endif + m_queue = nil; + } +} + +-(void)onPagesUpdate +{ + int pcnt = (int)[m_cells_org count]; + m_cells = [[NSMutableArray alloc] init]; + float xstep = m_gap + CELL_WIDTH; + int pidx = 0; + for(int pcur = 0; pcur < pcnt; pcur++) + { + RDPDFPageCell *cell = [m_cells_org objectAtIndex:pcur]; + if(cell.deleted) + [cell UIRemove]; + else + { + [m_cells addObject:cell]; + [cell UISetPos:(pidx % m_col_cnt) * xstep + (m_gap >> 1) :CELL_HEIGHT * (pidx / m_col_cnt) + 2]; + pidx++; + } + } + + pcnt = (int)[m_cells count]; + m_row_cnt = (pcnt + m_col_cnt - 1) / m_col_cnt; + + self.contentSize = CGSizeMake(self.frame.size.width, m_row_cnt * CELL_HEIGHT + 4); +} + +-(void)onSizeChanged +{ + CGSize screen_sz = self.frame.size; + float w = screen_sz.width - 4; + m_col_cnt = ((int)w) / (CELL_WIDTH + 4); + if(m_col_cnt < 1) m_col_cnt = 1; + if(m_col_cnt < 2) m_gap = 4; + else m_gap = (w - m_col_cnt * (CELL_WIDTH + 4)) / m_col_cnt + 4; + //float step = m_gap + CELL_WIDTH; + + int pcnt = (int)[m_cells count]; + m_row_cnt = (pcnt + m_col_cnt - 1) / m_col_cnt; + + [self onPagesUpdate]; + self.contentOffset = CGPointZero; +} + +-(void)setFrame:(CGRect)frame +{ + [super setFrame:frame]; + if(m_doc) + { + [self onSizeChanged]; + [self scrollViewDidScroll:self]; + } +} + +-(bool)modified +{ + int pcnt = (int)m_cells_org.count; + for(int pcur = 0; pcur < pcnt; pcur++) + { + RDPDFPageCell *cell = [m_cells_org objectAtIndex:pcur]; + if (cell.deleted) return true; + else if ([cell updateRotate]) return true; + } + return false; +} + +-(void)getEditData:(bool *)dels :(int *)rots +{ + int pcnt = (int)m_cells_org.count; + for(int pcur = 0; pcur < pcnt; pcur++) + { + RDPDFPageCell *cell = [m_cells_org objectAtIndex:pcur]; + dels[pcur] = cell.deleted; + [cell updateRotate]; + rots[pcur] = cell.rotate; + } +} + +-(void)open:(RDPDFDoc *)doc +{ + m_doc = doc; + int pcnt = [m_doc pageCount]; + m_cells_org = [[NSMutableArray alloc] init]; + m_cells = [[NSMutableArray alloc] init]; + onPageDelete del = ^(int pageno) + { + RDPDFPageCell *cell = [self->m_cells_org objectAtIndex:pageno]; + [cell UICancel:self->m_queue]; + cell.deleted = true; + [self onPagesUpdate]; + [self scrollViewDidScroll:self]; + }; + + for(int pcur = 0; pcur < pcnt; pcur++) + { + RDPDFPageCell *cell = [[RDPDFPageCell alloc] init:self :m_doc :pcur :del]; + RDPDFPage *page = [m_doc page:pcur]; + int rot = [page getRotate]; + page = nil; + cell.rotate = (rot << 16) | rot; + [m_cells_org addObject:cell]; + } + [self onSizeChanged]; + [self scrollViewDidScroll:self]; +} + +-(BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView +{ + return YES; +} + +-(void)scrollViewDidScrollToTop:(UIScrollView *)scrollView +{ +} + +-(void)scrollViewDidScroll:(UIScrollView *)scrollView +{ + if(scrollView != self) return; + CGPoint screen_org = self.contentOffset; + CGSize screen_sz = self.frame.size; + int row0 = screen_org.y / CELL_HEIGHT; + int row1 = (screen_org.y + screen_sz.height) / CELL_HEIGHT; + int idx0 = row0 * m_col_cnt; + int idx1 = (row1 + 1) * m_col_cnt; + int pcnt = (int)[m_cells count]; + if(idx1 > pcnt) idx1 = pcnt; + int icur = 0; + while(icur < idx0) + { + RDPDFPageCell *cell = [m_cells objectAtIndex:icur]; + [cell UICancel:m_queue]; + icur++; + } + while(icur < idx1) + { + RDPDFPageCell *cell = [m_cells objectAtIndex:icur]; + [cell UIRender:m_queue]; + icur++; + } + while(icur < pcnt) + { + RDPDFPageCell *cell = [m_cells objectAtIndex:icur]; + [cell UICancel:m_queue]; + icur++; + } +} + +- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView +{ +} + +- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate +{ +} + +- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView +{ +} + +- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView +{ +} + + +- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView +{ + return NULL; +} + +- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view +{ +} + +- (void)scrollViewDidZoom:(UIScrollView *)scrollView +{ +} + +- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale +{ +} + + +@end diff --git a/src/ios/PDFViewer/PDFPages/UIPageCellView.h b/src/ios/PDFViewer/PDFPages/UIPageCellView.h new file mode 100755 index 00000000..0f3c6894 --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/UIPageCellView.h @@ -0,0 +1,27 @@ +// +// UIPageCellView.h +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#pragma once +#import +@class RDPDFDIB; + +typedef void(^onPageDelete)(int pageno); +@interface UIPageCellView : UIView +{ + __weak IBOutlet UIImageView *mImg; + __weak IBOutlet UIView *mTools; + int m_rotate; + int m_pageno; + onPageDelete m_del; +} +- (void)UIUpdate:(RDPDFDIB *)dib; +- (void)UIRemove; +- (void)setPageNo:(onPageDelete)del :(int)pageno; +- (int)getRotate; +- (IBAction)OnPageDelete:(id)sender; +- (IBAction)OnPageRotate:(id)sender; +@end diff --git a/src/ios/PDFViewer/PDFPages/UIPageCellView.m b/src/ios/PDFViewer/PDFPages/UIPageCellView.m new file mode 100755 index 00000000..a4e47fe0 --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/UIPageCellView.m @@ -0,0 +1,53 @@ +// +// UIPageCellView.m +// PDFViewer +// +// Created by Radaee Lou on 2020/8/13. +// + +#import +#import "UIPageCellView.h" +#import "PDFObjc.h" + +@implementation UIPageCellView + +- (void)setFrame:(CGRect)frame +{ + [super setFrame:frame]; + [mTools setFrame:CGRectMake(mTools.frame.origin.x, mTools.frame.origin.y, mImg.frame.size.width, mTools.frame.size.height)]; +} + +- (void)UIUpdate:(RDPDFDIB *)dib +{ + if(!dib) [mImg setImage:nil]; + else [mImg setImage:[UIImage imageWithCGImage:[dib image]]]; +} + +- (void)UIRemove +{ + [mImg setImage:nil]; + [self removeFromSuperview]; +} + +- (void)setPageNo:(onPageDelete)del :(int)pageno +{ + m_del = del; + m_pageno = pageno; +} + +- (int)getRotate +{ + return m_rotate; +} + +- (IBAction)OnPageDelete:(id)sender { + m_del(m_pageno); +} + +- (IBAction)OnPageRotate:(id)sender { + CGAffineTransform transform = CGAffineTransformRotate(mImg.transform, M_PI * 0.5); + mImg.transform = transform; + m_rotate += 90; + m_rotate %= 360; +} +@end diff --git a/src/ios/PDFViewer/PDFPages/UIPageCellView.xib b/src/ios/PDFViewer/PDFPages/UIPageCellView.xib new file mode 100755 index 00000000..df3ec2a8 --- /dev/null +++ b/src/ios/PDFViewer/PDFPages/UIPageCellView.xib @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.h b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.h old mode 100644 new mode 100755 similarity index 70% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.h rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.h index c236b718..60deebf3 --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.h +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.h @@ -10,24 +10,29 @@ #import #import "UILStyleView.h" #import "UIColorBtn.h" -@class PDFAnnot; -@interface DlgAnnotPropComm : UIView +#import "../UILShadowView.h" +@class RDPDFAnnot; +@interface DlgAnnotPropComm : UILShadowView { - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; UIViewController *m_vc; BOOL m_has_fill; __weak IBOutlet UITextField *mLWidth; + __weak IBOutlet UILabel *mLLWidth; __weak IBOutlet UILStyleBtn *mLStyle; + __weak IBOutlet UILabel *mLLStyle; __weak IBOutlet UIColorBtn *mLColor; + __weak IBOutlet UILabel *mLLColor; __weak IBOutlet UIColorBtn *mFColor; __weak IBOutlet UILabel *mLFColor; __weak IBOutlet UISlider *mAlpha; __weak IBOutlet UILabel *mLAlpha; __weak IBOutlet UIButton *mLocked; + __weak IBOutlet UILabel *mLLock; } -(id)initWithFrame:(CGRect)frame; -(id)initWithCoder:(NSCoder *)aDecoder; --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc; -(void)hasFill:(BOOL)has; -(void)updateAnnot; -(IBAction)OnAlphaChanged:(id)sender; diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.m b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.m old mode 100644 new mode 100755 similarity index 59% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.m rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.m index 542e1dd3..a0ca4e2e --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropComm.m +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.m @@ -7,8 +7,9 @@ // #import -#import "DlgAnnotPropComm.h" #import "PDFObjc.h" +#import "DlgAnnotPropComm.h" + @implementation DlgAnnotPropComm -(id)initWithFrame:(CGRect)frame @@ -39,19 +40,30 @@ -(IBAction)OnLock:(id)sender mLocked.selected = !mLocked.selected; } --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc { m_annot = annot; m_vc = vc; - mLWidth.text = [NSString stringWithFormat:@"%f",[m_annot getStrokeWidth]]; + mLWidth.text = [NSString stringWithFormat:@"%.2f",[m_annot getStrokeWidth]]; + mLWidth.font = [UIFont systemFontOfSize:15]; + mLWidth.textAlignment = NSTextAlignmentCenter; + [mLWidth addTarget:self action:@selector(dismissKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit]; [mLStyle setDash:NULL :0 :m_vc]; unsigned int lcolor = [m_annot getStrokeColor]; [mLColor setColor: lcolor:NO :m_vc]; + mFColor.tag = 1; if(m_has_fill) [mFColor setColor:[m_annot getFillColor] :YES :m_vc]; mAlpha.value = (lcolor >> 24) / 255.0f; mLAlpha.text = [NSString stringWithFormat:@"%d",(lcolor >> 24)]; mLocked.selected = [m_annot isLocked]; + mLLWidth.text = NSLocalizedString(@"Line width", nil); + mLLStyle.text = NSLocalizedString(@"Line style", nil); + mLLColor.text = NSLocalizedString(@"Line color", nil); + mLFColor.text = NSLocalizedString(@"Fill color", nil); + mLLock.text = NSLocalizedString(@"Lock", nil); + [mLocked setTitle:NSLocalizedString(@"Locked", nil) forState:UIControlStateNormal]; } + -(void)hasFill:(BOOL)has { m_has_fill = has; @@ -62,7 +74,7 @@ -(void)hasFill:(BOOL)has -(void)updateAnnot { unsigned int ia = 255 * mAlpha.value; - unsigned int color = (mLColor.color&0xFFFFFF)|(ia << 24); + unsigned int color = (mLColor.color&0xFFFFFFFF)|(ia << 24); CGFloat lw = [mLWidth.text floatValue]; const CGFloat *dash = mLStyle.dash; float dashf[4]; @@ -74,17 +86,22 @@ -(void)updateAnnot dashf[3] = dash[3]; } int dash_cnt = mLStyle.dashCnt; - [m_annot setLocked:mLocked.selected]; - if (![m_annot isLocked]) { - [m_annot setStrokeWidth:lw]; - [m_annot setStrokeDash:dashf :dash_cnt]; - [m_annot setStrokeColor:color]; - if(m_has_fill && mFColor.color >> 24) - { - color = (mFColor.color&0xFFFFFF)|(ia << 24); - [m_annot setFillColor:color]; - } + [m_annot setStrokeWidth:lw]; + [m_annot setStrokeDash:dashf :dash_cnt]; + [m_annot setStrokeColor:color]; + if(m_has_fill && mFColor.color >> 24) + { + color = (mFColor.color&0xFFFFFFFF)|(ia << 24); + [m_annot setFillColor:color]; } + [m_annot setLocked:mLocked.selected]; +} + +- (void)dismissKeyboard +{ + [mLWidth resignFirstResponder]; } + + @end diff --git a/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.xib b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.xib new file mode 100755 index 00000000..ba674805 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropComm.xib @@ -0,0 +1,219 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.h b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.h old mode 100644 new mode 100755 similarity index 64% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.h rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.h index 25f061a0..edfa65c3 --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.h +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.h @@ -10,19 +10,24 @@ #import #import "UIColorBtn.h" #import "UIIconView.h" -@class PDFAnnot; -@interface DlgAnnotPropIcon : UIView +#import "../UILShadowView.h" +@class RDPDFAnnot; +@interface DlgAnnotPropIcon : UILShadowView { - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; UIViewController *m_vc; __weak IBOutlet UIIconBtn *mIcon; + __weak IBOutlet UILabel *mLIcon; __weak IBOutlet UIColorBtn *mFColor; + __weak IBOutlet UILabel *mLFColor; __weak IBOutlet UISlider *mAlpha; + __weak IBOutlet UILabel *mLLock; __weak IBOutlet UIButton *mLocked; __weak IBOutlet UILabel *mLAlpha; } + -(IBAction)OnAlphaChanged:(id)sender; -(IBAction)OnLock:(id)sender; --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc; -(void)updateAnnot; @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.m b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.m old mode 100644 new mode 100755 similarity index 71% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.m rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.m index d1c1e5e9..ae450035 --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropIcon.m +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.m @@ -7,8 +7,9 @@ // #import -#import "DlgAnnotPropIcon.h" #import "PDFObjc.h" +#import "DlgAnnotPropIcon.h" + @implementation DlgAnnotPropIcon -(id)initWithFrame:(CGRect)frame @@ -37,28 +38,31 @@ -(IBAction)OnLock:(id)sender mLocked.selected = !mLocked.selected; } --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc { m_vc = vc; m_annot = annot; [mIcon setIcon:m_annot :m_vc]; unsigned int fcolor = [m_annot getFillColor]; + mFColor.tag = 1; [mFColor setColor:fcolor :YES :m_vc]; mAlpha.value = (fcolor >> 24) / 255.0f; mLAlpha.text = [NSString stringWithFormat:@"%d",(fcolor >> 24)]; mLocked.selected = [m_annot isLocked]; + mLIcon.text = NSLocalizedString(@"Icon", nil); + mLFColor.text = NSLocalizedString(@"Fill color", nil); + mLLock.text = NSLocalizedString(@"Lock", nil); + [mLocked setTitle:NSLocalizedString(@"Locked", nil) forState:UIControlStateNormal]; } -(void)updateAnnot { unsigned int ia = 255 * mAlpha.value; - unsigned int color = (mFColor.color&0xFFFFFF)|(ia << 24); + unsigned int color = (mFColor.color&0xFFFFFFFF)|(ia << 24); + [m_annot setFillColor:color]; [m_annot setLocked:mLocked.selected]; - if (![m_annot isLocked]) { - [m_annot setFillColor:color]; - [m_annot setIcon:[mIcon icon]]; - } + [m_annot setIcon:[mIcon icon]]; } @end diff --git a/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.xib b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.xib new file mode 100755 index 00000000..1a18f5ae --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropIcon.xib @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.h b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.h old mode 100644 new mode 100755 similarity index 64% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.h rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.h index 102147da..d7335990 --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.h +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.h @@ -11,24 +11,32 @@ #import "UILStyleView.h" #import "UILHeadView.h" #import "UIColorBtn.h" -@class PDFAnnot; -@interface DlgAnnotPropLine : UIView +#import "../UILShadowView.h" +@class RDPDFAnnot; +@interface DlgAnnotPropLine : UILShadowView { - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; UIViewController *m_vc; __weak IBOutlet UITextField *mLWidth; + __weak IBOutlet UILabel *mLLWidth; __weak IBOutlet UILStyleBtn *mLStyle; + __weak IBOutlet UILabel *mLLStyle; __weak IBOutlet UIColorBtn *mLColor; + __weak IBOutlet UILabel *mLLColor; __weak IBOutlet UIColorBtn *mFColor; + __weak IBOutlet UILabel *mLFColor; __weak IBOutlet UILHeadBtn *mLStart; + __weak IBOutlet UILabel *mLLStart; __weak IBOutlet UILHeadBtn *mLEnd; + __weak IBOutlet UILabel *mLLEnd; __weak IBOutlet UISlider *mAlpha; __weak IBOutlet UILabel *mLAlpha; + __weak IBOutlet UILabel *mLLock; __weak IBOutlet UIButton *mLocked; } -(id)initWithFrame:(CGRect)frame; -(id)initWithCoder:(NSCoder *)aDecoder; --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc; -(void)updateAnnot; -(IBAction)OnAlphaChanged:(id)sender; -(IBAction)OnLock:(id)sender; diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.m b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.m old mode 100644 new mode 100755 similarity index 55% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.m rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.m index de3490f3..c3ee4b0a --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropLine.m +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.m @@ -7,8 +7,9 @@ // #import -#import "DlgAnnotPropLine.h" #import "PDFObjc.h" +#import "DlgAnnotPropLine.h" + @implementation DlgAnnotPropLine -(id)initWithFrame:(CGRect)frame @@ -16,7 +17,6 @@ -(id)initWithFrame:(CGRect)frame self = [super initWithFrame:frame]; if(self) { - } return self; } @@ -39,14 +39,18 @@ -(IBAction)OnLock:(id)sender mLocked.selected = !mLocked.selected; } --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc { m_annot = annot; m_vc = vc; - mLWidth.text = [NSString stringWithFormat:@"%f",[m_annot getStrokeWidth]]; + mLWidth.text = [NSString stringWithFormat:@"%.2f",[m_annot getStrokeWidth]]; + mLWidth.font = [UIFont systemFontOfSize:15]; + mLWidth.textAlignment = NSTextAlignmentCenter; + [mLWidth addTarget:self action:@selector(dismissKeyboard) forControlEvents:UIControlEventEditingDidEndOnExit]; [mLStyle setDash:NULL :0 :m_vc]; unsigned int lcolor = [m_annot getStrokeColor]; [mLColor setColor: lcolor:NO :m_vc]; + mFColor.tag = 1; [mFColor setColor:[m_annot getFillColor] :YES :m_vc]; int lhead = [m_annot getLineStyle]; [mLStart setStyle:lhead & 0xffff :m_vc]; @@ -54,11 +58,20 @@ -(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc mAlpha.value = (lcolor >> 24) / 255.0f; mLAlpha.text = [NSString stringWithFormat:@"%d",(lcolor >> 24)]; mLocked.selected = [m_annot isLocked]; + mLLWidth.text = NSLocalizedString(@"Line width", nil); + mLLStyle.text = NSLocalizedString(@"Line style", nil); + mLLColor.text = NSLocalizedString(@"Line color", nil); + mLFColor.text = NSLocalizedString(@"Fill color", nil); + mLLStart.text = NSLocalizedString(@"Line start", nil); + mLLEnd.text = NSLocalizedString(@"Line end", nil); + mLLock.text = NSLocalizedString(@"Lock", nil); + [mLocked setTitle:NSLocalizedString(@"Locked", nil) forState:UIControlStateNormal]; } + -(void)updateAnnot { unsigned int ia = 255 * mAlpha.value; - unsigned int color = (mLColor.color&0xFFFFFF)|(ia << 24); + unsigned int color = (mLColor.color&0xFFFFFFFF)|(ia << 24); CGFloat lw = [mLWidth.text floatValue]; const CGFloat *dash = mLStyle.dash; float dashf[4]; @@ -70,18 +83,22 @@ -(void)updateAnnot dashf[3] = dash[3]; } int dash_cnt = mLStyle.dashCnt; - [m_annot setLocked:mLocked.selected]; - if (![m_annot isLocked]) { - [m_annot setStrokeWidth:lw]; - [m_annot setStrokeDash:dashf :dash_cnt]; - [m_annot setStrokeColor:color]; - if(mFColor.color >> 24) - { - color = (mFColor.color&0xFFFFFF)|(ia << 24); - [m_annot setFillColor:color]; - } - int lhead = mLStart.style | (mLEnd.style << 16); - [m_annot setLineStyle:lhead]; + [m_annot setStrokeWidth:lw]; + [m_annot setStrokeDash:dashf :dash_cnt]; + [m_annot setStrokeColor:color]; + if(mFColor.color >> 24) + { + color = (mFColor.color&0xFFFFFFFF)|(ia << 24); + [m_annot setFillColor:color]; } + int lhead = mLStart.style | (mLEnd.style << 16); + [m_annot setLineStyle:lhead]; + [m_annot setLocked:mLocked.selected]; +} + +- (void)dismissKeyboard +{ + [mLWidth resignFirstResponder]; } + @end diff --git a/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.xib b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.xib new file mode 100755 index 00000000..ae44b28f --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropLine.xib @@ -0,0 +1,271 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.h b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.h old mode 100644 new mode 100755 similarity index 66% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.h rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.h index e1b1d46d..88e1ded9 --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.h +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.h @@ -7,19 +7,22 @@ // #import "UIColorBtn.h" -@class PDFAnnot; -@interface DlgAnnotPropMarkup : UIView +#import "../UILShadowView.h" +@class RDPDFAnnot; +@interface DlgAnnotPropMarkup : UILShadowView { - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; UIViewController *m_vc; __weak IBOutlet UIColorBtn *mColor; + __weak IBOutlet UILabel *mLColor; __weak IBOutlet UISlider *mAlpha; + __weak IBOutlet UILabel *mLLock; __weak IBOutlet UIButton *mLocked; __weak IBOutlet UILabel *mLAlpha; } -(id)initWithFrame:(CGRect)frame; -(id)initWithCoder:(NSCoder *)aDecoder; --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc; -(void)updateAnnot; - (IBAction)OnAlpha:(id)sender; - (IBAction)OnLocked:(id)sender; diff --git a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.m b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.m old mode 100644 new mode 100755 similarity index 72% rename from src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.m rename to src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.m index 90d02d94..f854d1db --- a/src/ios/PDFViewer/Modules/AnnotProp/DlgAnnotPropMarkup.m +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.m @@ -7,15 +7,15 @@ // #import -#import "DlgAnnotPropMarkup.h" #import "PDFObjc.h" +#import "DlgAnnotPropMarkup.h" + @implementation DlgAnnotPropMarkup -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self) { - } return self; } @@ -29,7 +29,7 @@ -(id)initWithCoder:(NSCoder *)aDecoder return self; } --(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setAnnot:(RDPDFAnnot *)annot :(UIViewController *)vc; { m_annot = annot; m_vc = vc; @@ -38,22 +38,24 @@ -(void)setAnnot:(PDFAnnot *)annot :(UIViewController *)vc; color = [m_annot getFillColor]; else color = [m_annot getStrokeColor]; + mColor.tag = 1; [mColor setColor: color:NO :m_vc]; mAlpha.value = (color >> 24) / 255.0f; mLAlpha.text = [NSString stringWithFormat:@"%d",(color >> 24)]; mLocked.selected = [m_annot isLocked]; + mLColor.text = NSLocalizedString(@"Color", nil); + mLLock.text = NSLocalizedString(@"Lock", nil); + [mLocked setTitle:NSLocalizedString(@"Locked", nil) forState:UIControlStateNormal]; } -(void)updateAnnot { unsigned int ia = 255 * mAlpha.value; - unsigned int color = (mColor.color&0xFFFFFF)|(ia << 24); + unsigned int color = (mColor.color&0xFFFFFFFF)|(ia << 24); + if([m_annot type] == 9) + [m_annot setFillColor:color]; + else + [m_annot setStrokeColor:color]; [m_annot setLocked:mLocked.selected]; - if (![m_annot isLocked]) { - if([m_annot type] == 9) - [m_annot setFillColor:color]; - else - [m_annot setStrokeColor:color]; - } } - (IBAction)OnAlpha:(id)sender diff --git a/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.xib b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.xib new file mode 100755 index 00000000..00f2b3ca --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/DlgAnnotPropMarkup.xib @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFReader/MenuAnnot.h b/src/ios/PDFViewer/PDFReader/MenuAnnot.h new file mode 100755 index 00000000..454f8e59 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuAnnot.h @@ -0,0 +1,16 @@ +// +// MenuAnnot.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// +#pragma once +#import +#import "RDMenu.h" +@interface MenuAnnot : RDMenu + +- (id)init:(CGPoint)point :(RDBlock)callback; +- (void)updateIcons:(UIImage *)iInk; + +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuAnnot.m b/src/ios/PDFViewer/PDFReader/MenuAnnot.m new file mode 100755 index 00000000..f99a1db9 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuAnnot.m @@ -0,0 +1,41 @@ +// +// MenuAnnot.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "MenuAnnot.h" +@implementation MenuAnnot + +- (id)init:(CGPoint)point :(RDBlock)callback +{ + NSArray *items = @[ + @{NSLocalizedString(@"Ink", nil): [UIImage imageNamed:@"btn_annot_ink"]}, + @{NSLocalizedString(@"Line", nil): [UIImage imageNamed:@"btn_annot_line"]}, + @{NSLocalizedString(@"Note", nil): [UIImage imageNamed:@"btn_annot_note"]}, + @{NSLocalizedString(@"Rect", nil): [UIImage imageNamed:@"btn_annot_rect"]}, + @{NSLocalizedString(@"Ellipse", nil): [UIImage imageNamed:@"btn_annot_ellipse"]}, + @{NSLocalizedString(@"Stamp", nil): [UIImage imageNamed:@"btn_annot_stamp"]}, + @{NSLocalizedString(@"Editbox", nil): [UIImage imageNamed:@"btn_edit_box"]}, + @{NSLocalizedString(@"Polygon", nil): [UIImage imageNamed:@"btn_polygon"]}, + @{NSLocalizedString(@"Polyline", nil): [UIImage imageNamed:@"btn_polyline"]}, + ]; + + return [super init:point :callback :items]; +} + +- (void)updateIcons:(UIImage *)iInk +{ + UIImage *img; + if(img = iInk) + { + UIView *view = self.subviews[0]; + UIImageView *image = view.subviews[0]; + image.image = img; + } +} + +@end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/MenuAnnotOp.h b/src/ios/PDFViewer/PDFReader/MenuAnnotOp.h old mode 100644 new mode 100755 similarity index 64% rename from src/ios/PDFViewer/Modules/AnnotProp/MenuAnnotOp.h rename to src/ios/PDFViewer/PDFReader/MenuAnnotOp.h index 3bf17568..c4ed0bd3 --- a/src/ios/PDFViewer/Modules/AnnotProp/MenuAnnotOp.h +++ b/src/ios/PDFViewer/PDFReader/MenuAnnotOp.h @@ -12,13 +12,14 @@ typedef void(^func_annotop)(int); @interface MenuAnnotOp : UIView { - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; func_annotop m_callback; - Boolean m_has_pdfform; + Boolean m_has_perform; Boolean m_has_edit; Boolean m_has_remove; Boolean m_has_property; } --(id)init:(PDFAnnot *)annot :(CGPoint)position :(func_annotop)callback; --(PDFAnnot *)annot; +-(id)init:(RDPDFAnnot *)annot :(CGPoint)position :(func_annotop)callback; +-(RDPDFAnnot *)annot; +-(void)updateIcons:(UIImage *)iPerform :(UIImage *)iRemove; @end diff --git a/src/ios/PDFViewer/PDFReader/MenuAnnotOp.m b/src/ios/PDFViewer/PDFReader/MenuAnnotOp.m new file mode 100755 index 00000000..794b9424 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuAnnotOp.m @@ -0,0 +1,140 @@ +// +// MenuAnnotOp.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/7. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "MenuAnnotOp.h" +@implementation MenuAnnotOp +- (UIView *)createItem :(int)tag :(CGFloat)x :(CGFloat)w :(CGFloat)h :(UIImage *)img +{ + UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 5, w, h)]; + [button setImage:img forState:UIControlStateNormal]; + button.tag = tag; + [button setUserInteractionEnabled:YES]; + [button addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside]; + return button; +} + +-(void)tapAction:(UIButton *)tap +{ + if(m_callback) m_callback((int)tap.tag); +} + +-(id)init:(RDPDFAnnot *)annot :(CGPoint)position :(func_annotop)callback +{ + //todo: calcute area. + + self = [super init]; + if(self) + { + position.y -= 8; + m_annot = annot; + m_callback = callback; + int atype = [m_annot type]; + m_has_perform = (atype == 2 || atype == 17 || atype == 18 || atype == 19 || atype == 25 || atype == 26); + m_has_edit = (atype == 1 || atype == 4 || atype == 5 || atype == 6 || atype == 7 || atype == 8 || atype == 9 || atype == 10 || atype == 11 || atype == 12 || atype == 13 || atype == 15); + m_has_remove = (atype != 0); + m_has_property = (atype != 0 && atype != 2); + CGFloat iconSize = 40; + CGFloat width = 0; + UIView *view; + if(m_has_perform) + { + UIImage *img = [UIImage imageNamed:@"btn_perform"]; + view = [self createItem :0 :width :iconSize :iconSize :img]; + [self addSubview:view]; + width += iconSize; + } + if(m_has_edit) + { + UIImage *img = [UIImage imageNamed:@"btn_ink"]; + view = [self createItem :1 :width :iconSize :iconSize :img]; + [self addSubview:view]; + width += iconSize; + } + if(m_has_remove) + { + UIImage *img = [UIImage imageNamed:@"btn_remove"]; + view = [self createItem :2 :width :iconSize :iconSize :img]; + [self addSubview:view]; + width += iconSize; + } + if(m_has_property) + { + UIImage *img = [UIImage imageNamed:@"btn_prop"]; + view = [self createItem :3 :width :iconSize :iconSize :img]; + [self addSubview:view]; + width += iconSize; + } + + UIImage *img = (annot.isLocked) ? [UIImage imageNamed:@"btn_lock"] : [UIImage imageNamed:@"btn_unlock"]; + view = [self createItem :4 :width :iconSize :iconSize :img]; + [self addSubview:view]; + width += iconSize; + + if (@available(iOS 13.0, *)) { + [self setBackgroundColor:[UIColor systemGray6Color]]; + } else { + [self setBackgroundColor:[UIColor colorWithRed:0.9f green:0.9f blue:0.95f alpha:1.0f]]; + } + + self.layer.cornerRadius = 5.0f; + self.clipsToBounds = YES; + + CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width; + CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height; + CGFloat height = 50; + + //check if annot rect origin is equal to screen origin + if (position.x == 0 && position.y + 8 == 0) { + self.frame = CGRectMake(8, 8, width, height); + return self; + } + + //else manage menu annot position + position.y -= (height - iconSize); + + if (position.x + width > screenWidth && position.y - iconSize < 0) { + self.frame = CGRectMake(position.x - (position.x + width - screenWidth) - 8, 8, width, height); + } else if (position.x + width > screenWidth) { + self.frame = CGRectMake(position.x - (position.x + width - screenWidth) - 8, position.y - iconSize, width, height); + } else if (position.y > screenHeight) { + self.frame = CGRectMake(position.x, position.y - iconSize - (position.y - screenHeight) - 8, width, height); + } else if (position.x < 0 && position.y - iconSize > 0){ + self.frame = CGRectMake(8, position.y - iconSize, width, height); + } else if (position.y - iconSize < 0 && position.x > 0) { + self.frame = CGRectMake(position.x, 8, width, height); + } else if (position.x < 0 && position.y - iconSize < 0) { + self.frame = CGRectMake(8, 8, width, height); + } else { + self.frame = CGRectMake(position.x, position.y - iconSize, width, height); + } + + } + return self; +} +-(RDPDFAnnot *)annot +{ + return m_annot; +} +-(void)updateIcons:(UIImage *)iPerform :(UIImage *)iRemove +{ + if(m_has_perform && iPerform) + { + //item is UILabel, so, can't set icon + UILabel *view = self.subviews[0]; + } + if(m_has_remove && iRemove) + { + int idx = 0; + if(m_has_perform) idx++; + if(m_has_edit) idx++; + //item is UILabel, so, can't set icon + UILabel *view = self.subviews[idx]; + } +} +@end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/MenuCombo.h b/src/ios/PDFViewer/PDFReader/MenuCombo.h old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/Modules/AnnotProp/MenuCombo.h rename to src/ios/PDFViewer/PDFReader/MenuCombo.h diff --git a/src/ios/PDFViewer/Modules/AnnotProp/MenuCombo.m b/src/ios/PDFViewer/PDFReader/MenuCombo.m old mode 100644 new mode 100755 similarity index 89% rename from src/ios/PDFViewer/Modules/AnnotProp/MenuCombo.m rename to src/ios/PDFViewer/PDFReader/MenuCombo.m index f2a77b74..49ffc7b3 --- a/src/ios/PDFViewer/Modules/AnnotProp/MenuCombo.m +++ b/src/ios/PDFViewer/PDFReader/MenuCombo.m @@ -15,6 +15,7 @@ +(UIView *)createItem :(int)tag :(CGFloat)y :(CGFloat)w :(CGFloat )fsize :(NSStr UILabel *vlab = [[UILabel alloc] initWithFrame:CGRectMake(2, y, w - 2, fsize + 2)]; vlab.text = val; [vlab setFont:[UIFont systemFontOfSize:fsize]]; + vlab.textColor = [UIColor blackColor]; return vlab; } @@ -30,7 +31,7 @@ -(void)setPara:(CGFloat)w :(CGFloat) fsize :(NSArray *)data :(func_combo)callbac m_data = data; m_fsize = fsize; CGFloat item_h = fsize + 2; - self.backgroundColor = [UIColor colorWithRed:1 green:1 blue:0.8f alpha:1]; + self.backgroundColor = [UIColor colorWithRed:218.0f/255.0f green:227.0f/255.0f blue:255.0f/255.0f alpha:1]; UIView *view; CGFloat y = 0; diff --git a/src/ios/PDFViewer/PDFReader/MenuSearch.h b/src/ios/PDFViewer/PDFReader/MenuSearch.h new file mode 100755 index 00000000..51f2adbf --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuSearch.h @@ -0,0 +1,18 @@ +// +// MenuTool.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// + +#pragma once +#import +#import "RDMenu.h" +@interface MenuSearch : RDMenu + +@property (strong, nonatomic) UISwitch *caseSwitch; +@property (strong, nonatomic) UISwitch *wholeSwitch; +- (id)init:(CGPoint)point :(RDBlock)callback; + +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuSearch.m b/src/ios/PDFViewer/PDFReader/MenuSearch.m new file mode 100755 index 00000000..e3274a07 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuSearch.m @@ -0,0 +1,35 @@ +// +// MenuSearch.m +// PDFViewer +// +// Created by Federico Vellani on 25/06/2020. +// + +#import +#import "MenuSearch.h" +#import "RDVGlobal.h" + +@implementation MenuSearch + +- (id)init:(CGPoint)point :(RDBlock)callback +{ + _caseSwitch = [[UISwitch alloc] init]; + _wholeSwitch = [[UISwitch alloc] init]; + _caseSwitch.on = GLOBAL.g_case_sensitive; + _wholeSwitch.on = GLOBAL.g_match_whole_word; + [_caseSwitch addTarget:self action:@selector(changeSwitch) forControlEvents:UIControlEventValueChanged]; + [_wholeSwitch addTarget:self action:@selector(changeSwitch) forControlEvents:UIControlEventValueChanged]; + + NSMutableArray *items = [[NSMutableArray alloc] initWithObjects: + @{@"Case sensitive": _caseSwitch}, + @{@"Match whole word": _wholeSwitch}, nil]; + + return [super initWithSwitch:point :callback :items]; +} + +- (void)changeSwitch { + GLOBAL.g_case_sensitive = _caseSwitch.on; + GLOBAL.g_match_whole_word = _wholeSwitch.on; +} + +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuTool.h b/src/ios/PDFViewer/PDFReader/MenuTool.h new file mode 100755 index 00000000..5585d4ec --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuTool.h @@ -0,0 +1,18 @@ +// +// MenuTool.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// + +#pragma once +#import +#import "RDMenu.h" +@interface MenuTool : RDMenu + +- (id)init:(CGPoint)point :(RDBlock)callback; +- (void)updateIcons:(UIImage *)iUndo :(UIImage *)iRedo :(UIImage *)iSel; +- (void)updateVisible:(BOOL)hideUndo :(BOOL)hideRedo :(BOOL)hideSel; + +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuTool.m b/src/ios/PDFViewer/PDFReader/MenuTool.m new file mode 100755 index 00000000..0c3c9066 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuTool.m @@ -0,0 +1,104 @@ +// +// MenuTool.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "MenuTool.h" +#import "RDVGlobal.h" +@implementation MenuTool + +- (id)init:(CGPoint)point :(RDBlock)callback +{ + NSMutableArray *items = [[NSMutableArray alloc] initWithObjects: + @{NSLocalizedString(@"Undo", nil): [UIImage imageNamed:@"btn_undo"]}, + @{NSLocalizedString(@"Redo", nil): [UIImage imageNamed:@"btn_redo"]}, + @{NSLocalizedString(@"Selection", nil): [UIImage imageNamed:@"btn_select"]}, + @{NSLocalizedString(@"Meta", nil): [UIImage imageNamed:@"btn_meta"]}, + @{NSLocalizedString(@"Outlines", nil): [UIImage imageNamed:@"btn_outline"]}, + @{NSLocalizedString(@"Bookmarks", nil): [UIImage imageNamed:@"btn_bookmark"]}, + @{NSLocalizedString(@"Add Bookmark", nil): [UIImage imageNamed:@"btn_bookmark_add"]}, + @{NSLocalizedString(@"Slider", nil): [UIImage imageNamed:@"btn_slider"]}, + @{NSLocalizedString(@"Night mode", nil): [UIImage imageNamed:@"btn_night_mode"]}, + @{NSLocalizedString(@"Manage pages", nil): [UIImage imageNamed:@"btn_manage_page"]}, + nil]; + + if (!GLOBAL.g_navigation_mode) { + items[7] = @{NSLocalizedString(@"Thumbnail", nil): [UIImage imageNamed:@"btn_thumb"]}; + } + if (GLOBAL.g_dark_mode) { + items[8] = @{NSLocalizedString(@"Light mode", nil): [UIImage imageNamed:@"btn_light_mode"]}; + } + + return [super init:point :callback :items]; +} + +- (void)updateIcons:(UIImage *)iUndo :(UIImage *)iRedo :(UIImage *)iSel +{ + UIImage *icon; + if(icon = iUndo)//undo + { + UIView *view = self.subviews[0]; + UIImageView *img = view.subviews[0]; + img.image = icon; + } + if(icon = iRedo)//redo + { + UIView *view = self.subviews[1]; + UIImageView *img = view.subviews[0]; + img.image = icon; + } + if(icon = iSel)//select + { + UIView *view = self.subviews[2]; + UIImageView *img = view.subviews[0]; + img.image = icon; + } +} + +- (void)updateVisible:(BOOL)hideUndo :(BOOL)hideRedo :(BOOL)hideSel +{ + int hcnt = 0; + UIView *view = self.subviews[0]; + view.hidden = hideUndo; + if (hideUndo) { + hcnt++; + for (int c = 1; c != self.subviews.count; c++) { + CGRect rect = [(UIView *)[self.subviews objectAtIndex:c] frame]; + rect.origin.y -= rd_menu_height; + [(UIView *)[self.subviews objectAtIndex:c] setFrame:rect]; + } + } + + view = self.subviews[1]; + view.hidden = hideRedo; + + if (hideRedo) { + hcnt++; + for (int c = 2; c != self.subviews.count; c++) { + CGRect rect = [(UIView *)[self.subviews objectAtIndex:c] frame]; + rect.origin.y -= rd_menu_height; + [(UIView *)[self.subviews objectAtIndex:c] setFrame:rect]; + } + } + + view = self.subviews[2]; + view.hidden = hideSel; + if (hideSel) { + hcnt++; + for (int c = 3; c != self.subviews.count; c++) { + CGRect rect = [(UIView *)[self.subviews objectAtIndex:c] frame]; + rect.origin.y -= rd_menu_height; + [(UIView *)[self.subviews objectAtIndex:c] setFrame:rect]; + } + } + + CGRect rect = self.frame; + rect.origin.y += hcnt * rd_menu_height; + rect.size.height -= hcnt * rd_menu_height; + self.frame = rect; +} +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuVMode.h b/src/ios/PDFViewer/PDFReader/MenuVMode.h new file mode 100755 index 00000000..d1769c84 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuVMode.h @@ -0,0 +1,15 @@ +// +// MenuVMode.h +// RDPDFReader +// +// Created by Radaee on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// +#pragma once +#import +#import "RDMenu.h" +@interface MenuVMode : RDMenu + +- (id)init:(CGPoint)point :(RDBlock)callback; + +@end diff --git a/src/ios/PDFViewer/PDFReader/MenuVMode.m b/src/ios/PDFViewer/PDFReader/MenuVMode.m new file mode 100755 index 00000000..ca2bb633 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/MenuVMode.m @@ -0,0 +1,25 @@ +// +// MenuVMode.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/6. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "MenuVMode.h" +@implementation MenuVMode + +- (id)init:(CGPoint)point :(RDBlock)callback +{ + NSArray *items = @[ + @{NSLocalizedString(@"Vertical", nil): [UIImage imageNamed:@"btn_view_vert"]}, + @{NSLocalizedString(@"Horizontal", nil): [UIImage imageNamed:@"btn_view_horz"]}, + @{NSLocalizedString(@"Single Page", nil): [UIImage imageNamed:@"btn_view_single"]}, + @{NSLocalizedString(@"Double Page", nil): [UIImage imageNamed:@"btn_view_dual"]} + ]; + + return [super init:point :callback :items]; +} + +@end diff --git a/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.h b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.h new file mode 100755 index 00000000..34631874 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.h @@ -0,0 +1,164 @@ +// +// PDFReaderCtrl.h +// RDPDFReader +// +// Created by Radaee on 2020/5/5. +// Copyright © 2020 Radaee. All rights reserved. +// + +#pragma once +#import +#import "../PDFView/RDPDFView.h" +#import "../RDToolbar.h" +#import "SearchResultViewController.h" +#import "RDPopupTextViewController.h" +#import "../RDTreeTableViewController/RDTreeViewController.h" +//#import "PDFIOS.h" + +@class PDFLayoutView; +@class PDFThumbView; +@class RDPDFDoc; + +@protocol PDFReaderDelegate +// define protocol functions that can be used in any class using this delegate +- (void)willShowReader; +- (void)didShowReader; +- (void)willCloseReader; +- (void)didCloseReader; +- (void)didChangePage:(int)page; +- (void)didSearchTerm:(NSString *)term found:(BOOL)found; +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point; +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point; +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point; +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point; +@end; + + +@class PDFPopupCtrl; +@class MenuAnnotOp; +@interface PDFReaderCtrl : UIViewController +{ + PDFLayoutView *m_view; + PDFThumbView *m_thumb; + BOOL m_readonly; + int m_page_no; + int m_page_cnt; + RDPDFDoc *m_doc; + PDFPopupCtrl *m_popup; + MenuAnnotOp *m_menu_op; + UIMenuController *selectMenu; + int m_annot_type; + NSString *m_fstr; + BOOL m_whole; + BOOL m_case; + BOOL showingThumb; + BOOL findStart; + + UITapGestureRecognizer *searchTapNone; + UITapGestureRecognizer *searchTapField; +} +@property (nonatomic, assign) id delegate; +@property (strong, nonatomic) UIImage *closeImage; +@property (strong, nonatomic) UIImage *viewModeImage; +@property (strong, nonatomic) UIImage *searchImage; +@property (strong, nonatomic) UIImage *bookmarkImage; +@property (strong, nonatomic) UIImage *addBookmarkImage; +@property (strong, nonatomic) UIImage *outlineImage; +@property (strong, nonatomic) UIImage *lineImage; +@property (strong, nonatomic) UIImage *rowImage; +@property (strong, nonatomic) UIImage *rectImage; +@property (strong, nonatomic) UIImage *ellipseImage; +@property (strong, nonatomic) UIImage *bitmapImage; +@property (strong, nonatomic) UIImage *noteImage; +@property (strong, nonatomic) UIImage *signatureImage; +@property (strong, nonatomic) UIImage *printImage; +@property (strong, nonatomic) UIImage *shareImage; +@property (strong, nonatomic) UIImage *gridImage; +@property (strong, nonatomic) UIImage *deleteImage; +@property (strong, nonatomic) UIImage *doneImage; +@property (strong, nonatomic) UIImage *removeImage; +@property (strong, nonatomic) UIImage *prevImage; +@property (strong, nonatomic) UIImage *nextImage; +@property (strong, nonatomic) UIImage *undoImage; +@property (strong, nonatomic) UIImage *redoImage; +@property (strong, nonatomic) UIImage *performImage; +@property (strong, nonatomic) UIImage *moreImage; +@property (strong, nonatomic) UIImage *drawImage; +@property (strong, nonatomic) UIImage *selectImage; +@property (strong, nonatomic) UIImage *saveImage; +@property (strong, nonatomic) UIImage *metaImage; + +@property (nonatomic) BOOL hideSearchImage; +@property (nonatomic) BOOL hideDrawImage; +@property (nonatomic) BOOL hideViewImage; +@property (nonatomic) BOOL hideThumbImage; +@property (nonatomic) BOOL hideMoreImage; + +@property (strong, nonatomic) IBOutlet RDPDFView *mView; +@property (strong, nonatomic) IBOutlet RDPDFThumb *mThumb; +@property (strong, nonatomic) IBOutlet UIView *mSliderView; +@property (strong, nonatomic) IBOutlet UISlider *mSlider; +@property (strong, nonatomic) IBOutlet UILabel *mSliderLabel; +@property (strong, nonatomic) IBOutlet UIToolbar *mBarNoneTop; +@property (strong, nonatomic) IBOutlet RDToolbar *mBarNoneBottom; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBarThumbButton; +@property (strong, nonatomic) IBOutlet RDToolbar *mBarAnnot; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBarAnnotColorButton; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBarAnnotDoneButton; +@property (strong, nonatomic) IBOutlet UIToolbar *mBarSearchTop; +@property (strong, nonatomic) IBOutlet RDToolbar *mBarSearchBottom; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBarSearchResults; +@property (strong, nonatomic) IBOutlet UITextField *mSearchText; +@property (strong, nonatomic) IBOutlet UIButton *mSearchWhole; +@property (strong, nonatomic) IBOutlet UIButton *mSearchCase; +@property (strong, nonatomic) IBOutlet UILabel *fileName; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBtnBack; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBtnCancel; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBtnDone; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBtnPrev; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *mBtnNext; +@property (strong, nonatomic) IBOutlet NSLayoutConstraint *thumbHeightConstraint; +@property (strong, nonatomic) IBOutlet NSLayoutConstraint *mBarNoneBottomWidthConstraint; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *searchItem; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *annotItem; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *viewItem; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *thumbItem; +@property (strong, nonatomic) IBOutlet UIBarButtonItem *moreItem; + +- (void)setDoc:(RDPDFDoc *)doc; +- (void)setDoc:(RDPDFDoc *)doc :(BOOL)readonly; +- (void)setDoc:(RDPDFDoc *)doc :(int)pageno :(BOOL)readonly; +- (RDPDFDoc *)getDoc; +- (void)PDFGoto:(int)pageno; +- (int)PDFCurPage; +- (void)setImmersive:(BOOL)immersive; +- (void)setDoubleTapZoomMode:(int)mode; +- (void)setThumbnailBGColor:(int)color; +- (void)setReaderBGColor:(int)color; +- (BOOL)addAttachmentFromPath:(NSString *)path; +- (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size; ++ (bool)flatAnnotAtPage:(int)page doc:(RDPDFDoc *)doc; +- (bool)flatAnnots; +- (bool)saveDocumentToPath:(NSString *)path; +//- (void)updateAllPages; +- (void)updatePage:(int)pageno; +- (void)viewDidLoad; +- (void)closeView; +- (IBAction)back_pressed:(id)sender; +- (IBAction)mode_pressed:(id)sender; +- (IBAction)thumb_pressed:(id)sender; +- (IBAction)tool_pressed:(id)sender; +- (IBAction)annot_pressed:(id)sender; +- (IBAction)search_pressed:(id)sender; +- (IBAction)annot_ok:(id)sender; +- (IBAction)annot_cancel:(id)sender; +- (IBAction)annot_color:(id)sender; +- (IBAction)search_cancel:(id)sender; +- (IBAction)search_backward:(id)sender; +- (IBAction)search_forward:(id)sender; + +- (CGPoint)pdfPointsFromScreenPoints:(int)x :(int)y; +- (CGPoint)screenPointsFromPdfPoints:(float)x :(float)y :(int)pageNum; +- (NSArray *)pdfRectFromScreenRect:(CGRect)screenRect; +- (CGRect)screenRectFromPdfRect:(float)top :(float)left :(float)right :(float)bottom :(int)pageNum; +@end diff --git a/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.m b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.m new file mode 100755 index 00000000..f7429877 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.m @@ -0,0 +1,1792 @@ +// +// PDFReaderCtrl.m +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/5. +// Copyright © 2020 Radaee. All rights reserved. +// + +#import +#import "PDFPagesCtrl.h" +#import "PDFReaderCtrl.h" +#import "PDFPopupCtrl.h" +#import "PDFDialog.h" +#import "MenuVMode.h" +#import "MenuTool.h" +#import "MenuAnnot.h" +#import "MenuSearch.h" +#import "MenuAnnotOp.h" +#import "MenuCombo.h" +#import "DlgAnnotPropComm.h" +#import "DlgAnnotPropMarkup.h" +#import "DlgAnnotPropLine.h" +#import "DlgAnnotPropIcon.h" +#import "RDAnnotPickerViewController.h" +#import "RDExtendedSearch.h" +#import "RDMetaDataViewController.h" +#import "PDFLayoutView.h" +#import "PDFThumbView.h" +#import "SignatureViewController.h" +#import "RDBookmarkViewController.h" +#import "../PDFLayout/RDVFinder.h" + +@interface PDFReaderCtrl () +@end + +@implementation PDFReaderCtrl +- (void)showBaseAlert:(NSString *)msg +{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:msg preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *conform = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + }]; + [alert addAction:conform]; + [self presentViewController:alert animated:YES completion:nil]; +} + +- (RDPDFDoc *)getDoc +{ + return m_doc; +} + +- (void)loadPDF +{ + if(m_view) return; + m_view = [_mView view]; + [self thumbInit]; + [m_view PDFOpen:m_doc :4 :[_mView canvas] :self]; + [m_thumb PDFOpen:m_doc :2 :[_mThumb canvas] :self]; + if(GLOBAL.g_readonly) + { + m_readonly = YES; + } + if(m_readonly) + { + [m_view setReadOnly:YES]; + } + [self enter_none]; + UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleDarkContent; +} + +- (void)setDoc:(RDPDFDoc *)doc +{ + m_doc = doc; + [self loadPDF]; +} +- (void)setDoc:(RDPDFDoc *)doc :(BOOL)readonly +{ + m_doc = doc; + m_readonly = readonly; + [self loadPDF]; +} +- (void)setDoc:(RDPDFDoc *)doc :(int)pageno :(BOOL)readonly +{ + m_readonly = readonly; + m_page_cnt = [m_doc pageCount]; + [self setDoc:doc]; + [m_view setReadOnly:readonly]; + [self PDFGoto:pageno]; +} + +- (void)thumbInit +{ + m_thumb = (PDFThumbView *)[_mThumb view]; + + if (GLOBAL.g_thumbview_height) { + _thumbHeightConstraint.constant = GLOBAL.g_thumbview_height; + } + + if (!GLOBAL.g_navigation_mode) { + _mSlider.minimumValue = 1; + _mSlider.maximumValue = m_doc.pageCount; + _mSlider.value = self.PDFCurPage + 1; + _mSliderLabel.text = [NSString stringWithFormat:@"%i/%i", self.PDFCurPage, m_doc.pageCount]; + [_mSlider addTarget:self action:@selector(OnSliderValueChange:forEvent:) forControlEvents:UIControlEventValueChanged]; + } + + if (GLOBAL.g_navigation_mode) { + [self->_mBarThumbButton setImage:[UIImage imageNamed:@"btn_thumb"]]; + } else { + [self->_mBarThumbButton setImage:[UIImage imageNamed:@"btn_slider"]]; + } + +} + +- (void)PDFGoto:(int)pageno +{ + if (pageno < 0) pageno = 0; + if (pageno > m_doc.pageCount - 1) pageno = m_doc.pageCount - 1; + [m_view vGoto:pageno]; + [self thumbGoTo:pageno]; +} + +- (void)thumbGoTo:(int)pageno +{ + if (!GLOBAL.g_navigation_mode) { + _mSlider.value = pageno +1; + [self setSliderText:(int)_mSlider.value]; + } else { + [m_thumb vGoto:pageno]; + } +} + +- (int)PDFCurPage +{ + return m_page_no; +} + +- (void)showBars +{ + [self prefersStatusBarHidden]; + [self enter_none]; +} + +- (void)hideBars +{ + _mThumb.hidden = YES; + _mSliderView.hidden = YES; + [self enter_immersive]; +} + +- (void)setImmersive:(BOOL)immersive +{ + if (immersive) [self hideBars]; + else [self showBars]; +} + +- (void)setDoubleTapZoomMode:(int)mode +{ + [m_view setDoubleTapZoomMode:mode]; +} + +- (void)setThumbnailBGColor:(int)color +{ + [m_thumb PDFSetBGColor:color]; +} + +- (void)setReaderBGColor:(int)color +{ + [m_view PDFSetGBColor:color]; +} + +- (BOOL)addAttachmentFromPath:(NSString *)path +{ + return [m_view addAttachmentFromPath:path]; +} + +- (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size +{ + return [m_view saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:size]; +} + ++ (bool)flatAnnotAtPage:(int)page doc:(RDPDFDoc *)doc +{ + if (doc == nil) { + doc = [[RDPDFDoc alloc] init]; + [doc open:[GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name] :@""]; + } + if(page >= 0 && page < doc.pageCount) + { + RDPDFPage *ppage = [doc page:page]; + [ppage objsStart]; + if ([ppage flatAnnots]) { + return [doc save]; + } + } + return NO; +} + +- (bool)flatAnnots +{ + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + if (m_doc == nil) { + [doc open:[GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name] :@""]; + } else { + doc = m_doc; + } + for (int page = 0; page != [doc pageCount]; page++) { + [PDFReaderCtrl flatAnnotAtPage:page doc:doc]; + } + [m_view vUpdateRange];//update all pasges on screen. + return nil; +} + +- (bool)saveDocumentToPath:(NSString *)path +{ + if([path containsString:@"file://"]) + { + NSString *filePath = [path stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + return [m_doc saveAs:filePath: NO]; + } + } + return [m_doc saveAs:path: NO]; +} + +- (void)updateAllPages +{ + [m_view vUpdateRange]; +} +- (void)updatePage:(int)pageno +{ + [m_view vUpdatePage:pageno]; +} + +- (void)enter_none +{ + [_mBarNoneTop setHidden:NO]; + [_mBarNoneBottom setHidden:NO]; + [_mBarAnnot setHidden:YES]; + [_mBarSearchTop setHidden:YES]; + [_mBarSearchBottom setHidden:YES]; + if (!GLOBAL.g_navigation_mode) { + [_mThumb setHidden:YES]; + [_mSliderView setHidden:NO]; + } else { + [_mThumb setHidden:NO]; + [_mSliderView setHidden:YES]; + } +} + +- (void)enter_annot +{ + [_mBarNoneTop setHidden:YES]; + [_mBarNoneBottom setHidden:YES]; + [_mBarAnnot setHidden:NO]; + [_mBarSearchTop setHidden:YES]; + [_mBarSearchBottom setHidden:YES]; + [_mThumb setHidden:YES]; + _mBarAnnotDoneButton.enabled = YES; + if (m_annot_type == 2 || m_annot_type == 5) { + _mBarAnnotColorButton.enabled = NO; + } else { + _mBarAnnotColorButton.enabled = YES; + } +} + +- (void)enter_annot_edit +{ + [_mBarNoneTop setHidden:YES]; + [_mBarNoneBottom setHidden:YES]; + [_mBarAnnot setHidden:YES]; + [_mBarSearchTop setHidden:YES]; + [_mBarSearchBottom setHidden:YES]; + [_mThumb setHidden:YES]; +} + +- (void)enter_search +{ + CGRect rect = _mBarNoneTop.frame; + _mBarSearchTop.frame = rect; + [_mBarNoneTop setHidden:YES]; + [_mBarNoneBottom setHidden:YES]; + [_mBarAnnot setHidden:YES]; + [_mBarSearchTop setHidden:NO]; + [_mBarSearchBottom setHidden:NO]; + [_mThumb setHidden:YES]; + + [_mSearchText becomeFirstResponder]; + [_mSearchText addTarget:self action:@selector(search_forward:) forControlEvents:UIControlEventEditingDidEndOnExit]; + + _mSearchText.delegate = self; + + // This could be in an init method. + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSearchKeyboardFrameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSearchKeyboardHiding:) name:UIKeyboardWillHideNotification object:nil]; + + + searchTapNone = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; + [self.view addGestureRecognizer:searchTapNone]; + + searchTapField = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(enter_search)]; + [_mSearchText addGestureRecognizer:searchTapField]; +} + +-(void)dismissKeyboard +{ + [_mSearchText resignFirstResponder]; +} + +- (void)textFieldDidBeginEditing:(UITextField *)textField { + findStart = NO; +} + +- (void)onSearchKeyboardFrameChanged:(NSNotification*)notification +{ + NSDictionary* keyboardInfo = [notification userInfo]; + NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey]; + NSValue* keyboardFrameEnd = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey]; + CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue]; + CGRect keyboardFrameEndRect = [keyboardFrameEnd CGRectValue]; + + if ([_mSearchText isFirstResponder]) { + [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionTransitionCurlUp animations:^{ + if (keyboardFrameBeginRect.origin.y > keyboardFrameEndRect.origin.y) { + self->_mBarSearchBottom.transform = CGAffineTransformMakeTranslation(0, - keyboardFrameEndRect.size.height); + } else { + self->_mBarSearchBottom.transform = CGAffineTransformIdentity; + } + } completion:nil]; + } +} + +- (void)onSearchKeyboardHiding:(NSNotification*)notification { + [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionTransitionCurlUp animations:^{ + self->_mBarSearchBottom.transform = CGAffineTransformIdentity; + } completion:nil]; +} + +- (void)enter_select +{ + [_mBarNoneTop setHidden:YES]; + [_mBarNoneBottom setHidden:YES]; + [_mBarAnnot setHidden:NO]; + [_mBarSearchTop setHidden:YES]; + [_mBarSearchBottom setHidden:YES]; + [_mThumb setHidden:YES]; + _mBarAnnotDoneButton.enabled = NO; + _mBarAnnotColorButton.enabled = NO; + m_annot_type = 100; +} + +- (void)enter_immersive +{ + [_mBarNoneTop setHidden:YES]; + [_mBarNoneBottom setHidden:YES]; + [_mBarAnnot setHidden:YES]; + [_mBarSearchTop setHidden:YES]; + [_mBarSearchBottom setHidden:YES]; + if (!GLOBAL.g_navigation_mode) { + [_mSliderView setHidden:YES]; + } else { + [_mThumb setHidden:YES]; + } +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + [self loadPDF]; +} + +-(void)viewWillAppear:(BOOL)animated +{ + if(self.navigationController) + self.navigationController.navigationBarHidden = YES; + + if (_delegate && [_delegate respondsToSelector:@selector(willShowReader)]) { + [_delegate willShowReader]; + } + // Set images + if(_closeImage) + _mBtnBack.image = _closeImage; + if(_doneImage) + _mBtnDone.image = _doneImage; + if(_removeImage) + _mBtnCancel.image = _removeImage; + if(_prevImage) + _mBtnPrev.image = _prevImage; + if(_nextImage) + _mBtnNext.image = _nextImage; + + _fileName.text = [GLOBAL.g_pdf_name stringByDeletingPathExtension]; + _fileName.textColor = _mBarNoneTop.tintColor; + [self initialPopupView]; + + _mBarNoneBottomWidthConstraint.constant = 250; + + [self setBarButtonVisibility]; +} + +- (void)viewDidAppear:(BOOL)animated +{ + [super viewDidAppear:animated]; + + if (_delegate && [_delegate respondsToSelector:@selector(didShowReader)]) { + [_delegate didShowReader]; + } +} + +- (void)viewDidDisappear:(BOOL)animated +{ + [super viewDidDisappear:animated]; + + if (m_view == nil && _delegate && [_delegate respondsToSelector:@selector(didCloseReader)]) { + [_delegate didCloseReader]; + } +} + +- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator { + if ([m_popup isViewLoaded]) { + [self dismissViewControllerAnimated:NO completion:^{ + self->m_popup = nil; + }]; + } +} + +- (void)setBarButtonVisibility { + if (_hideSearchImage) { + NSMutableArray *noneToolbarItems = [_mBarNoneTop.items mutableCopy]; + [noneToolbarItems removeObject:_searchItem]; + [_mBarNoneTop setItems:noneToolbarItems]; + } + + if (_hideDrawImage) { + NSMutableArray *noneToolbarItems = [_mBarNoneBottom.toolbar.items mutableCopy]; + [noneToolbarItems removeObject:_annotItem]; + [_mBarNoneBottom.toolbar setItems:noneToolbarItems]; + _mBarNoneBottomWidthConstraint.constant -= _annotItem.image.size.width*2; + } + + if (_hideViewImage) { + NSMutableArray *noneToolbarItems = [_mBarNoneBottom.toolbar.items mutableCopy]; + [noneToolbarItems removeObject:_viewItem]; + [_mBarNoneBottom.toolbar setItems:noneToolbarItems]; + _mBarNoneBottomWidthConstraint.constant -= _viewItem.image.size.width*2; + } + + if (_hideThumbImage) { + NSMutableArray *noneToolbarItems = [_mBarNoneBottom.toolbar.items mutableCopy]; + [noneToolbarItems removeObject:_thumbItem]; + [_mBarNoneBottom.toolbar setItems:noneToolbarItems]; + _mBarNoneBottomWidthConstraint.constant -= _thumbItem.image.size.width*2; + } + + if (_hideMoreImage) { + NSMutableArray *noneToolbarItems = [_mBarNoneBottom.toolbar.items mutableCopy]; + [noneToolbarItems removeObject:_moreItem]; + [_mBarNoneBottom.toolbar setItems:noneToolbarItems]; + _mBarNoneBottomWidthConstraint.constant -= _moreItem.image.size.width*2; + } +} + +- (void)closeView +{ + self.navigationController.navigationBarHidden = NO; + [self.navigationController popViewControllerAnimated:YES]; + [self dismissViewControllerAnimated:YES completion:nil]; + [self PDFClose]; +} + +- (void)PDFClose +{ + if (_delegate && [_delegate respondsToSelector:@selector(willCloseReader)] && m_doc != nil) { + [_delegate willCloseReader]; + } + [m_view PDFClose]; + [m_thumb PDFClose]; + _fileName.text = @""; + m_view = nil; + m_thumb = nil; + if(self.navigationController) [self.navigationController popViewControllerAnimated:YES]; + else [self dismissViewControllerAnimated:YES completion:nil]; +} +- (IBAction)back_pressed:(id)sender +{ + UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleDefault; + if ([m_view isModified] && !GLOBAL.g_auto_save_doc && !GLOBAL.g_readonly && !m_readonly) { + + UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Exiting", nil) + message:NSLocalizedString(@"Document modified.\r\nDo you want to save it?", nil) + preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction* ok = [UIAlertAction + actionWithTitle:NSLocalizedString(@"Yes", nil) + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) + { + [self PDFClose]; + [self.navigationController setNavigationBarHidden:NO]; + [self.navigationController popViewControllerAnimated:YES]; + [self dismissViewControllerAnimated:YES completion:nil]; + [alert dismissViewControllerAnimated:YES completion:nil]; + }]; + UIAlertAction* cancel = [UIAlertAction + actionWithTitle:NSLocalizedString(@"No", nil) + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) + { + [self->m_view setModified:NO force:YES]; + [self PDFClose]; + [self.navigationController setNavigationBarHidden:NO]; + [self.navigationController popViewControllerAnimated:YES]; + [self dismissViewControllerAnimated:YES completion:nil]; + [alert dismissViewControllerAnimated:YES completion:nil]; + }]; + [alert addAction:ok]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; + } + else { + [self->m_view setModified:NO force:YES]; + [self PDFClose]; + self.navigationController.navigationBarHidden = NO; + [self.navigationController popViewControllerAnimated:YES]; + [self dismissViewControllerAnimated:YES completion:nil]; + } +} + +- (IBAction)mode_pressed:(id)sender +{ + PDFLayoutView *vw = m_view; + PDFReaderCtrl *thiz = self; + //CGRect from = [self buttonRect:sender]; + + if (showingThumb) { + [self thumb_pressed:nil]; + } + + MenuVMode *view = [[MenuVMode alloc] init:CGPointMake(self.view.center.x-125, _mBarNoneBottom.frame.origin.y) :^(int vmode){ + switch(vmode) + { + case 1: + [vw PDFSetVMode:1]; + break; + case 2: + [vw PDFSetVMode:3]; + break; + case 3: + [vw PDFSetVMode:7]; + break; + default: + [vw PDFSetVMode:0]; + break; + } + [thiz->m_popup dismiss]; + }]; + m_popup = [[PDFPopupCtrl alloc] init:view]; + [self presentViewController:m_popup animated:YES completion:nil]; +} + +-(void)OnMeta +{ + RDMetaDataViewController *metaViewController = [[RDMetaDataViewController alloc] initWithNibName:@"RDMetaDataViewController" bundle:nil]; + metaViewController.doc = m_doc; + metaViewController.autoSave = NO; + metaViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + metaViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:metaViewController animated:YES completion:nil]; + [m_view setModified:YES force:NO]; +} + +-(void)OnOutline +{ + if(!m_doc.rootOutline) + { + [self showBaseAlert:NSLocalizedString(@"This PDF file has no outlines!", nil)]; + return; + } + RDTreeViewController *treeViewController = [[RDTreeViewController alloc] initWithNibName:@"RDTreeViewController" bundle:nil]; + treeViewController.doc = m_doc; + treeViewController.delegate = self; + + treeViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + treeViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:treeViewController animated:YES completion:nil]; +} + +- (IBAction)search_pressed:(id)sender +{ + [self enter_search]; +} + +- (void)thumb_pressed:(id)sender +{ + int safeAreaBottom = 0; + if (@available(iOS 11.0, *)) + safeAreaBottom = UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom; + [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionTransitionCurlUp animations:^{ + if (self->showingThumb) { + self->_mSliderView.transform = CGAffineTransformIdentity; + self->_mThumb.transform = CGAffineTransformIdentity; + self->_mBarNoneBottom.transform = CGAffineTransformIdentity; + self->showingThumb = NO; + } else { + self->_mSliderView.transform = CGAffineTransformMakeTranslation(0, -self->_mSliderView.frame.size.height - safeAreaBottom); + self->_mBarNoneBottom.transform = CGAffineTransformMakeTranslation(0,-self->_mSliderView.frame.size.height - safeAreaBottom); + self->_mThumb.transform = CGAffineTransformMakeTranslation(0, -self->_mThumb.frame.size.height - safeAreaBottom); + self->_mBarNoneBottom.transform = CGAffineTransformMakeTranslation(0,-self->_mThumb.frame.size.height - safeAreaBottom); + self->showingThumb = YES; + } + } completion:nil]; +} + +- (IBAction)tool_pressed:(id)sender +{ + PDFLayoutView *vw = m_view; + PDFReaderCtrl *thiz = self; + //CGRect from = [self buttonRect:sender]; + + if (showingThumb) { + [self thumb_pressed:nil]; + } + + MenuTool *view = [[MenuTool alloc] init:CGPointMake(self.view.center.x-125, _mBarNoneBottom.frame.origin.y) :^(int tool){ + [thiz->m_popup dismiss]; + switch(tool) + { + case 0: + if(!self->m_readonly) + { + [vw vUndo]; + } + break; + case 1: + if(!self->m_readonly) + { + [vw vRedo]; + } + break; + case 2: + [thiz enter_select]; + [vw vSelStart]; + break; + case 3: + if(!self->m_readonly) + { + [thiz OnMeta]; + } + break; + case 4: + [thiz OnOutline]; + break; + case 5: + [thiz showBookmarksList]; + break; + case 6: + [thiz addBookmark]; + break; + case 7: + if (GLOBAL.g_navigation_mode) { + GLOBAL.g_navigation_mode = 0; + } else { + GLOBAL.g_navigation_mode = 1; + } + [self thumbInit]; + [self thumbGoTo:self.PDFCurPage]; + [self enter_none]; + break; + case 8: + if (GLOBAL.g_dark_mode) { + GLOBAL.g_dark_mode = false; + } else { + GLOBAL.g_dark_mode = true; + } + [self->m_view vUpdateRange]; + break; + case 9: + { + if(!self->m_readonly) + { + PDFPagesCtrl *pages = [[UIStoryboard storyboardWithName:@"PDFPagesCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfpages"]; + [pages setCallback:self->m_doc :^(const bool *pages_del, const int *pages_rot) + { + [self->m_view PDFSaveView]; + [self->m_thumb PDFSaveView]; + int pcnt = [self->m_doc pageCount]; + int pcur = pcnt; + while(pcur > 0) + { + pcur--; + if(pages_del[pcur]) [self->m_doc removePage:pcur]; + else if((pages_rot[pcur] >> 16) != (pages_rot[pcur] & 0xffff)) + { + int deg = (pages_rot[pcur] & 0xffff) - (pages_rot[pcur] >> 16); + if(deg < 0) deg += 360; + RDPDFPage *page = [self->m_doc page:pcur]; + int rotate = [page getRotate]; + [self->m_doc setPageRotate:pcur :rotate + deg]; + } + } + [self->m_thumb PDFRestoreView]; + [self->m_view PDFRestoreView]; + }]; + + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) + pages.modalPresentationStyle = UIModalPresentationFullScreen; + else + pages.modalPresentationStyle = UIModalPresentationFormSheet; + + [self presentViewController:pages animated:YES completion:nil]; + } + } + break; + default: + break; + } + }]; + [view updateIcons:_undoImage :_redoImage :_selectImage]; + if (![m_doc canSave]) { + //[view updateVisible:YES :YES :YES]; + } /* else { + [view updateVisible:_hideUndoImage :_hideRedoImage :_hideSelImage]; + } */ + + if (view.frame.size.height > (self.view.frame.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height - 50 - 50 - 10)) { + m_popup = [[PDFPopupCtrl alloc] init:[self getScrollViewWithMenu:view]]; + } else { + m_popup = [[PDFPopupCtrl alloc] init:view]; + } + [self presentViewController:m_popup animated:YES completion:nil]; +} + +- (IBAction)annot_pressed:(id)sender +{ + if ([m_view canSaveDocument]) { + //CGRect rect = _mBarNoneTop.frame; + PDFLayoutView *vw = m_view; + PDFReaderCtrl *thiz = self; + //CGRect from = [self buttonRect:sender]; + + if (showingThumb) { + [self thumb_pressed:nil]; + } + + MenuAnnot *view = [[MenuAnnot alloc] init:CGPointMake(self.view.center.x-125, _mBarNoneBottom.frame.origin.y) :^(int type){ + thiz->m_annot_type = type; + switch(type) + { + case 1://line + [vw vLineStart]; + break; + case 2://note + [vw vNoteStart]; + break; + case 3://erctangle + [vw vRectStart]; + break; + case 4://ellipse + [vw vEllipseStart]; + break; + case 5://stamp + [vw vImageStart]; + break; + case 6://editbox + [vw vEditboxStart]; + break; + case 7://polygon + [vw vPolygonStart]; + break; + case 8://polyline + [vw vPolylineStart]; + break; + case 100: + [vw vSelStart]; + break; + default://ink + [vw vInkStart]; + break; + } + [thiz->m_popup dismiss]; + [self enter_annot]; + }]; + [view updateIcons:_drawImage]; + + if (view.frame.size.height > (self.view.frame.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height - 50 - 50 - 10)) { + m_popup = [[PDFPopupCtrl alloc] init:[self getScrollViewWithMenu:view]]; + } else { + m_popup = [[PDFPopupCtrl alloc] init:view]; + } + [self presentViewController:m_popup animated:YES completion:nil]; + } +} + +- (void)OnEditboxOK +{ + [m_view vEditboxEnd]; + [self enter_none]; +} + +- (IBAction)annot_ok:(id)sender +{ + switch(m_annot_type) + { + case 1://line + [m_view vLineEnd]; + break; + case 2://note + [m_view vNoteEnd]; + break; + case 3://erctangle + [m_view vRectEnd]; + break; + case 4://ellipse + [m_view vEllipseEnd]; + break; + case 5://stamp + [m_view vImageEnd]; + break; + case 6://editbox + [m_view vEditboxEnd]; + break; + case 7://polygon + [m_view vPolygonEnd]; + break; + case 8://polyline + [m_view vPolylineEnd]; + break; + case 100: + [m_view vSelEnd]; + break; + default://ink + [m_view vInkEnd]; + break; + } + [self enter_none]; +} +- (IBAction)annot_cancel:(id)sender +{ + switch(m_annot_type) + { + case 1://line + [m_view vLineCancel]; + break; + case 2://note + [m_view vNoteCancel]; + break; + case 3://erctangle + [m_view vRectCancel]; + break; + case 4://ellipse + [m_view vEllipseCancel]; + break; + case 5://stamp + [m_view vImageCancel]; + break; + case 6://editbox + [m_view vEditboxCancel]; + break; + case 7://polygon + [m_view vPolygonCancel]; + break; + case 8://polyline + [m_view vPolylineCancel]; + break; + case 100: + [m_view vSelEnd]; + break; + default://ink + [m_view vInkCancel]; + break; + } + [self enter_none]; +} + +- (IBAction)annot_color:(id)sender +{ + RDAnnotPickerViewController *pickerViewController = [[RDAnnotPickerViewController alloc] initWithNibName:@"RDAnnotPickerViewController" bundle:nil]; + pickerViewController.annotType = m_annot_type; + pickerViewController.modalPresentationStyle = UIModalPresentationOverFullScreen; + pickerViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; + [self presentViewController:pickerViewController animated:YES completion:nil]; +} + +- (IBAction)search_result_pressed:(id)sender +{ + if (_mSearchText.text.length == 0) { + return; + } + + SearchResultViewController *viewController = [[SearchResultViewController alloc] initWithNibName:@"SearchResultViewController" bundle:nil]; + viewController.delegate = self; + viewController.searchedString = _mSearchText.text; + viewController.doc = m_doc; + viewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + viewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; + [self presentViewController:viewController animated:YES completion:nil]; +} + +- (IBAction)search_backward:(id)sender +{ + NSString *pat = _mSearchText.text; + if(!pat || pat.length <= 0) return; + [self searchProgress]; + BOOL mwhole = _mSearchWhole.state == UIControlStateSelected; + BOOL mcase = _mSearchCase.state == UIControlStateSelected; + GLOBAL.g_match_whole_word = mwhole; + GLOBAL.g_case_sensitive = mcase; + + [self startSearch:pat dir:-1 reset:NO]; +} + +- (IBAction)search_forward:(id)sender +{ + NSString *pat =_mSearchText.text; + if(!pat || pat.length <= 0) return; + [self searchProgress]; + BOOL mwhole =_mSearchWhole.state == UIControlStateSelected; + BOOL mcase =_mSearchCase.state == UIControlStateSelected; + GLOBAL.g_match_whole_word = mwhole; + GLOBAL.g_case_sensitive = mcase; + [self startSearch:pat dir:1 reset:NO]; +} + +- (IBAction)search_tool_pressed:(id)sender +{ + MenuSearch *view = [[MenuSearch alloc] init:CGPointMake(_mBarNoneBottom.frame.origin.x, _mBarNoneBottom.frame.origin.y) :nil]; + m_popup = [[PDFPopupCtrl alloc] init:view]; + [self presentViewController:m_popup animated:YES completion:nil]; +} + +- (IBAction)search_cancel:(id)sender +{ + [_mSearchText resignFirstResponder]; + _mSearchText.text = @""; + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [self.view removeGestureRecognizer:searchTapNone]; + [self.view removeGestureRecognizer:searchTapField]; + [[RDExtendedSearch sharedInstance] clearSearch]; + [m_view vFindEnd];//this already update the screen. + [self enter_none]; +} + +- (RDMenu *)getScrollViewWithMenu:(RDMenu *)menu +{ + CGFloat x = self.view.center.x - menu.frame.size.width / 2; + CGFloat y = [[UIApplication sharedApplication] statusBarFrame].size.height + 50 + 10; + CGFloat height = self.view.frame.size.height - y - (self.view.frame.size.height - _mBarNoneBottom.frame.origin.y) - 10; + + UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, menu.frame.size.width, height)]; + [menu setFrame:CGRectMake(0, 0, menu.frame.size.width, menu.frame.size.height)]; + [scrollView addSubview:menu]; + scrollView.layer.cornerRadius = 10.0f; + scrollView.contentSize = CGSizeMake(menu.frame.origin.x, menu.frame.size.height); + + RDMenu *rdMenu = [[RDMenu alloc] initWithFrame:CGRectMake(x, y, menu.frame.size.width, height)]; + rdMenu.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.0f]; + rdMenu.layer.cornerRadius = 10.0f; + rdMenu.layer.shadowRadius = 10.0f; + + [rdMenu addSubview:scrollView]; + + return rdMenu; +} + +#pragma mark - Bookmark + +- (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [self addBookMarks:pdfPath :@"" :[NSFileManager defaultManager] pdfName:[GLOBAL.g_pdf_name stringByDeletingPathExtension] withPath:withPath]; +} + +- (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager* )fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} + + +- (void)addBookmark +{ + NSString *pdfpath = [GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name]; + RDVPos pos; + [m_view vGetPos:&pos]; + int pageno = pos.pageno; + NSString *tempName = [[pdfpath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"_%d%@",pageno,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",pageno]; + NSString *BookMarkDir = [pdfpath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + [self showBaseAlert:NSLocalizedString(@"Cannot add bookmark.", nil)]; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + [self showBaseAlert:NSLocalizedString(@"Bookmark added!", nil)]; + } + else { + [self showBaseAlert:[NSString stringWithFormat:@"%@ %i",NSLocalizedString(@"Bookmark already exist at page", nil), pageno + 1]]; + } +} + +- (void)showBookmarksList +{ + NSArray *bookmarks = [self loadBookmarkForPdf:GLOBAL.g_pdf_path withPath:YES]; + if (bookmarks.count > 0) { + RDBookmarkViewController *bookmarkViewController = [[RDBookmarkViewController alloc] initWithNibName:@"RDBookmarkViewController" bundle:nil]; + bookmarkViewController.items = [self loadBookmarkForPdf:GLOBAL.g_pdf_path withPath:YES]; + bookmarkViewController.delegate = self; + bookmarkViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + bookmarkViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:bookmarkViewController animated:YES completion:nil]; + } else { + [self showBaseAlert:NSLocalizedString(@"No bookmark saved.", nil)]; + } +} + +- (void)didSelectBookmarkAtPage:(int)page { + [self PDFGoto:page]; +} + +#pragma mark - PDFThumbViewDelegate + +- (void)OnPageClicked :(int) pageno +{ + [m_view vGoto:pageno]; +} + +#pragma mark - Slider + +- (void)setSliderText:(int)value { + _mSliderLabel.text = [NSString stringWithFormat:@"%i/%i", value, m_doc.pageCount]; +} + +-(void)OnSliderValueChange:(UISlider*)slider forEvent:(UIEvent*)event +{ + [self updateSlider:slider.value goto:NO]; + UITouch *touchEvent = [[event allTouches] anyObject]; + if (touchEvent.phase == UITouchPhaseEnded) { + [self updateSlider:slider.value goto:YES]; + } +} + +- (void)updateSlider:(int)value goto:(BOOL)haveToGoTo { + int page = value; + if (page <= 0) { + page = 1; + } + if (page >= m_doc.pageCount) { + page = m_doc.pageCount; + } + + if (haveToGoTo) { + [self OnPageClicked:page - 1]; + } else { + [self setSliderText:page]; + } +} + +#pragma mark - MenuController + +- (BOOL)canBecomeFirstResponder +{ + return YES; +} + +-(void)initialPopupView +{ + if(!m_readonly) + { + UIMenuItem *underline = [[UIMenuItem alloc] initWithTitle:@"UDL" action:@selector(underline:)]; + UIMenuItem *highline = [[UIMenuItem alloc] initWithTitle:@"HGL" action:@selector(highlight:)]; + UIMenuItem *strike = [[UIMenuItem alloc] initWithTitle:@"STR" action:@selector(strikeOut:)]; + UIMenuItem *squiggly = [[UIMenuItem alloc] initWithTitle:@"SQG" action:@selector(squiggly:)]; + UIMenuItem *copyText; + if(!GLOBAL.g_disable_text_copy) + { + copyText = [[UIMenuItem alloc] initWithTitle:@"COPY" action:@selector(copyText:)]; + } + else + { + copyText = [[UIMenuItem alloc] initWithTitle:@"COPY" action:@selector(removeTarget:action:)]; + } + NSArray *itemsMC = [[NSArray alloc] initWithObjects:underline, highline, strike, squiggly, copyText, nil]; + selectMenu = [UIMenuController sharedMenuController]; + [selectMenu setMenuItems:itemsMC]; + } + else + { + UIMenuItem *copyText; + if(!GLOBAL.g_disable_text_copy) + { + copyText = [[UIMenuItem alloc] initWithTitle:@"COPY" action:@selector(copyText:)]; + + } + else + { + copyText = [[UIMenuItem alloc] initWithTitle:@"COPY" action:@selector(removeTarget:action:)]; + } + NSArray *itemsMC = [[NSArray alloc] initWithObjects:copyText, nil]; + selectMenu = [UIMenuController sharedMenuController]; + [selectMenu setMenuItems:itemsMC]; + } +} +-(void)copyText:(id)sender +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + NSString* s = [self->m_view vSelGetText]; + UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; + if(s != nil) + { + pasteboard.string = s; + } + [self endSelect]; + }); +} + +-(void)highlight:(id)sender +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + //0HighLight + [self->m_view vSelMarkup:0]; + [self endSelect]; + }); + +} +-(void)underline:(id)sender +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + //1UnderLine + [self->m_view vSelMarkup:1]; + [self endSelect]; + }); +} +-(void)strikeOut:(id)sender +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + //2strikethrough + [self->m_view vSelMarkup:2]; + [self endSelect]; + }); +} +-(void)squiggly:(id)sender +{ + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + //4squiggly + [self->m_view vSelMarkup:4]; + [self endSelect]; + }); +} + +- (void)endSelect +{ + [self enter_none]; + [m_view vSelEnd]; +} + + +#pragma mark - PDFLayoutDelegate + +- (void)OnPageChanged :(int)pageno +{ + if (_delegate && [_delegate respondsToSelector:@selector(didChangePage:)]) { + if (pageno != m_page_no) { + [_delegate didChangePage:pageno]; + } + } + m_page_no = pageno; + [self thumbGoTo:pageno]; +} +- (void)OnPageUpdated :(int)pageno +{ + [m_thumb PDFUpdatePage:pageno]; +} + +- (void)OnLongPressed:(float)x :(float)y +{ + if (_delegate && [_delegate respondsToSelector:@selector(didLongPressOnPage:atPoint:)]) { + RDVPos pos; + [m_view vGetPos:&pos x:x y:y]; + [_delegate didLongPressOnPage:pos.pageno atPoint:CGPointMake(x, y)]; + } +} + +- (void)OnSingleTapped:(float)x :(float)y +{ + if (_delegate && [_delegate respondsToSelector:@selector(didTapOnPage:atPoint:)]) { + RDVPos pos; + [m_view vGetPos:&pos x:x y:y]; + [_delegate didTapOnPage:pos.pageno atPoint:CGPointMake(x, y)]; + } + + if(_mBarNoneTop.hidden) + { + [self showBars]; + } + else + { + [self hideBars]; + } +} + +- (void)OnDoubleTapped:(float)x :(float)y +{ + if (_delegate && [_delegate respondsToSelector:@selector(didDoubleTapOnPage:atPoint:)]) { + RDVPos pos; + [m_view vGetPos:&pos x:x y:y]; + [_delegate didDoubleTapOnPage:pos.pageno atPoint:CGPointMake(x, y)]; + } +} + +- (void)OnFound:(bool)found +{ + if (_delegate && [_delegate respondsToSelector:@selector(didSearchTerm:found:)]) { + [_delegate didSearchTerm:_mSearchText.text found:found]; + } + + if(!found) + { + //[self showBaseAlert:@"No more found!"]; + } +} + +- (void)OnSelStart:(float)x :(float)y +{ +} + +- (void)OnSelEnd:(float)x1 :(float)y1 :(float)x2 :(float)y2 +{ + NSString *s = [m_view vSelGetText]; + NSLog(@"OnSelEnd select text = %@",s); + if(s) + { + //popup a menu + [selectMenu setTargetRect:CGRectMake(x2 * m_view.zoomScale, y2 * m_view.zoomScale, 0, 0) inView:m_view]; + [selectMenu setMenuVisible:YES animated:YES]; + } +} + +-(void)OnAnnotEdit:(RDPDFAnnot *)annot +{ + [self hideBars]; + RDPopupTextViewController *popupTextViewController = [[RDPopupTextViewController alloc] initWithNibName:@"RDPopupTextViewController" bundle:nil]; + popupTextViewController.annot = annot; + popupTextViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + popupTextViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:popupTextViewController animated:YES completion:nil]; +} +-(void)OnAnnotProp:(RDPDFAnnot *)annot +{ + int atype = [annot type]; + if(atype == 4 || atype == 8)//line and polyline + { + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropLine" owner:self options:nil]; + DlgAnnotPropLine *view = [views lastObject]; + + PDFLayoutView *vw = m_view; + PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 300, 410) :YES :^(BOOL is_ok){ + if (is_ok) + { + [view updateAnnot]; + [vw vAnnotEnd]; + [vw vUpdateAnnotPage]; + [vw setModified:YES force:NO]; + } + else + [vw vAnnotEnd]; + }]; + [view setAnnot:annot :dlg]; + [self presentViewController:dlg animated:NO completion:nil]; + } + else if(atype >= 9 && atype <= 12)//markup + { + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropMarkup" owner:self options:nil]; + DlgAnnotPropMarkup *view = [views lastObject]; + + PDFLayoutView *vw = m_view; + PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 300, 210) :YES :^(BOOL is_ok) + { + if (is_ok) + { + [view updateAnnot]; + [vw vAnnotEnd]; + [vw vUpdateAnnotPage]; + [vw setModified:YES force:NO]; + } + else + [vw vAnnotEnd]; + }]; + [view setAnnot:annot :dlg]; + [self presentViewController:dlg animated:NO completion:nil]; + } + else if(atype == 1 || atype == 17)//sticky note and file attachment. + { + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropIcon" owner:self options:nil]; + DlgAnnotPropIcon *view = [views lastObject]; + PDFLayoutView *vw = m_view; + PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 300, 210) :YES :^(BOOL is_ok){ + if (is_ok) + { + [view updateAnnot]; + [vw vAnnotEnd]; + [vw vUpdateAnnotPage]; + [vw setModified:YES force:NO]; + } + else + [vw vAnnotEnd]; + }]; + [view setAnnot:annot :dlg]; + [self presentViewController:dlg animated:NO completion:nil]; + } + else + { + NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropComm" owner:self options:nil]; + DlgAnnotPropComm *view = [views lastObject]; + [view hasFill:(atype != 15)]; + + PDFLayoutView *vw = m_view; + PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 300, 310) :YES :^(BOOL is_ok){ + if (is_ok) + { + [view updateAnnot]; + [vw vAnnotEnd]; + [vw vUpdateAnnotPage]; + [vw setModified:YES force:NO]; + } + else + [vw vAnnotEnd]; + }]; + [view setAnnot:annot :dlg]; + [self presentViewController:dlg animated:NO completion:nil]; + } +} + +- (void)OnAnnotClicked:(RDPDFAnnot *)annot :(CGRect)annotRect :(float)x :(float)y +{ + int atype = [annot type]; + PDFLayoutView *vw = m_view; + PDFReaderCtrl *thiz = self; + if(atype != 3 && atype != 20) + { + if (annotRect.size.width > [[UIScreen mainScreen] bounds].size.width && annotRect.origin.y < [[UIScreen mainScreen] bounds].origin.y) { + annotRect.origin = [[UIScreen mainScreen] bounds].origin; + } + m_menu_op = [[MenuAnnotOp alloc] init :annot :annotRect.origin :^(int opt){ + switch(opt) + { + case 0://perform + [vw vAnnotPerform]; + break; + case 1://edit + [thiz OnAnnotEdit:thiz->m_menu_op.annot]; + break; + case 2://remove + [vw vAnnotRemove]; + break; + case 3://property + [thiz OnAnnotProp:thiz->m_menu_op.annot]; + break; + case 4: //lock/unlock + [annot setLocked:![annot isLocked]]; + break; + } + if(thiz->m_menu_op) + { + [thiz->m_menu_op removeFromSuperview]; + thiz->m_menu_op = nil; + } + }]; + [m_menu_op updateIcons:_performImage :_deleteImage]; + [_mView addSubview:m_menu_op]; + } + [self enter_annot_edit]; +} +//notified when annotation status end. +- (void)OnAnnotEnd +{ + if(m_menu_op) + { + [m_menu_op removeFromSuperview]; + m_menu_op = nil; + } + [self showBars]; +} +//this mehod fired only when vAnnotPerform method invoked. +- (void)OnAnnotGoto:(int)pageno +{ + [m_view vGoto:pageno]; + [self thumbGoTo:pageno]; +} +//this mehod fired only when vAnnotPerform method invoked. +- (void)OnAnnotOpenURL:(NSString *)url +{ + //open URI + if( url ){ + UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") + message:[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Do you want to open:", @"Localizable"), url] + preferredStyle:UIAlertControllerStyleAlert]; + + UIAlertAction* ok = [UIAlertAction + actionWithTitle:NSLocalizedString(@"OK", nil) + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) + { + [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil]; + }]; + UIAlertAction* cancel = [UIAlertAction + actionWithTitle:NSLocalizedString(@"Cancel", nil) + style:UIAlertActionStyleDefault + handler:nil]; + + [alert addAction:ok]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; + } +} +//this mehod fired only when vAnnotPerform method invoked. +- (void)OnAnnotMovie:(NSString *)_fileName +{ + /* + [tempfiles addObject:_fileName]; + NSURL *urlPath = [NSURL fileURLWithPath:_fileName]; + if ([[NSFileManager defaultManager] fileExistsAtPath:_fileName]) { + AVPlayerViewController *avvc = [[AVPlayerViewController alloc] init]; + avvc.player = [AVPlayer playerWithURL:urlPath]; + avvc.view.frame = self.view.bounds; + avvc.modalPresentationStyle = UIModalPresentationFormSheet; + [self presentViewController:avvc animated:YES completion:nil]; + }else { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Error" + message:@"Couldn't find media file" + preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } + */ +} +//this mehod fired only when vAnnotPerform method invoked. +- (void)OnAnnotSound:(NSString *)_fileName +{ + //[tempfiles addObject:_fileName]; +} + +- (void)OnAnnotEditBox:(RDPDFAnnot *)annot :(CGRect)annotRect :(NSString *)editText :(float)textSize +{ + PDFPopupCtrl *pop; + if([annot getEditType] == 3)//multi-line + { + UITextView *text = [[UITextView alloc] init]; + pop = [[PDFPopupCtrl alloc] init:text]; + CGRect rect = [_mView convertRect:annotRect toView: pop.view]; + text.frame = rect; + text.text = editText; + text.backgroundColor = [UIColor whiteColor]; + text.textColor = [UIColor blackColor]; + text.font = [UIFont systemFontOfSize:textSize]; + PDFLayoutView *vw = m_view; + [pop setDismiss:^{ + [annot setEditText:text.text]; + [vw vUpdateAnnotPage]; + [vw vAnnotEnd]; + [vw setModified:YES force:NO]; + }]; + } + else + { + UITextField *text = [[UITextField alloc] init]; + pop = [[PDFPopupCtrl alloc] init:text]; + CGRect rect = [_mView convertRect:annotRect toView: pop.view]; + text.frame = rect; + text.text = editText; + text.backgroundColor = [UIColor whiteColor]; + text.textColor = [UIColor blackColor]; + text.font = [UIFont systemFontOfSize:textSize]; + PDFLayoutView *vw = m_view; + [pop setDismiss:^{ + [annot setEditText:text.text]; + [vw vUpdateAnnotPage]; + [vw vAnnotEnd]; + [vw setModified:YES force:NO]; + }]; + } + [self presentViewController:pop animated:NO completion:nil]; +} + +- (void)OnAnnotCommboBox:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selected:(int)index +{ + MenuCombo *view = [[MenuCombo alloc] init]; + PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; + [pop setDismiss:^{ + [self->m_view vAnnotEnd]; + }]; + + CGFloat fsize = vp.scale * 12 / [m_view vGetPixSize]; + CGRect rect = [_mView convertRect:annotRect toView: pop.view]; + int max_cnt = (dataArray.count > 5) ? 5 : (int)dataArray.count;//max 5 items height for scrollView + rect.origin.y += rect.size.height; + rect.size.height = (fsize + 2) * max_cnt; + + view.frame = rect; + PDFLayoutView *vw = m_view; + [view setPara:rect.size.width :fsize :dataArray :^(int idx){ + [annot setComboSel:idx]; + [vw vUpdateAnnotPage]; + [vw vAnnotEnd]; + [vw setModified:YES force:NO]; + [pop dismiss]; + }]; + [self presentViewController:pop animated:NO completion:nil]; +} + +- (void)OnAnnotList:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selectedIndexes:(NSArray *)indexes +{ + MenuCombo *view = [[MenuCombo alloc] init]; + PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; + [pop setDismiss:^{ + [self->m_view vAnnotEnd]; + }]; + + CGFloat fsize = vp.scale * 12 / [m_view vGetPixSize]; + CGRect rect = [_mView convertRect:annotRect toView: pop.view]; + + view.frame = rect; + PDFLayoutView *vw = m_view; + [view setPara:rect.size.width :fsize :dataArray :^(int idx){ + int sels[1] = {idx}; + [annot setListSels:sels :1]; + [vw vUpdateAnnotPage]; + [vw vAnnotEnd]; + [vw setModified:YES force:NO]; + [pop dismiss]; + }]; + [self presentViewController:pop animated:NO completion:nil]; +} + +- (void)OnAnnotTapped:(RDPDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point +{ + if (_delegate && [_delegate respondsToSelector:@selector(didTapOnAnnotationOfType:atPage:atPoint:)]) { + [_delegate didTapOnAnnotationOfType:annot.type atPage:page atPoint:point]; + } + NSLog(@"%@", [annot getEditText]); + if ([annot type]) { + + } +} + +#pragma mark - Signature + +- (void)OnAnnotSignature:(RDVPage *)vp :(RDPDFAnnot *)annot { + + NSString *annotImage = [m_view getImageFromAnnot:annot]; + NSString *emptyImage = [m_view emptyImageFromAnnot:annot]; + + NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:annotImage error:nil]; + NSDictionary *emptyAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:emptyImage error:nil]; + + if (attr.fileSize != emptyAttr.fileSize) { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") message:NSLocalizedString(@"Signature already exist. Do you want delete it?", nil) preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { + [self presentSignatureViewController:vp :annot]; + }]; + UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + [self->m_view vAnnotEnd]; + }]; + + [alert addAction:ok]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; + } else { + [self presentSignatureViewController:vp :annot]; + } +} + +- (void)presentSignatureViewController :(RDVPage *)vpage :(RDPDFAnnot *)annot +{ + SignatureViewController *sv = [[SignatureViewController alloc] init]; + sv.delegate = self; + sv.annotPage = vpage; + sv.annot = annot; + + if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { + sv.modalPresentationStyle = UIModalPresentationFormSheet; + } else { + sv.modalPresentationStyle = UIModalPresentationFullScreen; + } + + [self presentViewController:sv animated:YES completion:nil]; +} + +- (void)didSign:(RDVPage *)vp :(RDPDFAnnot *)annot +{ + [self dismissViewControllerAnimated:YES completion:^{ + if (![self->m_view PDFSignField:vp :annot]) + { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Error" + message:@"Couldn't Sign the field." + preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } + [self onDismissSignView]; + }]; +} + +- (void)onDismissSignView +{ + [m_view vAnnotEnd];//this function has already refreshed screen +} + +#pragma mark - Search list delegate +- (void)didSelectSelectSearchResult:(int)index +{ + [self dismissViewControllerAnimated:YES completion:^{ + [self goToSearchResult:index]; + }]; +} + +- (void)goToSearchResult:(int)index +{ + [self PDFGoto:index]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self startSearch:[[RDExtendedSearch sharedInstance] searchTxt] dir:1 reset:YES]; + }); +} + +- (void)startSearch:(NSString *)text dir:(int)dir reset:(BOOL)reset +{ + if (reset) { + [m_view vFindEnd]; + findStart = NO; + } + + if (!findStart) { + [m_view vFindStart:text :GLOBAL.g_case_sensitive :GLOBAL.g_match_whole_word]; + findStart = YES; + [m_view vFind:dir]; + } else if (text != nil && text.length > 0) { + [m_view vFind:dir]; + } +} + +- (void)searchProgress{ + RDVFinder *m_rdvfinder = [m_view getView]; + UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Searching", nil) message:@"" preferredStyle:UIAlertControllerStyleAlert]; + + UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + m_rdvfinder->is_cancel = true; + m_rdvfinder.cancelBlock(true); + }]; + + [alert addAction:cancel]; + UIView *alertView = alert.view; + UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; + progressBar.translatesAutoresizingMaskIntoConstraints = false; + progressBar.progress = 0; + [alertView addSubview:progressBar]; + + NSLayoutConstraint *bottomConstraint = [progressBar.bottomAnchor constraintEqualToAnchor:alertView.bottomAnchor]; + [bottomConstraint setActive:YES]; + bottomConstraint.constant = -45; + + [[progressBar.leftAnchor constraintEqualToAnchor:alertView.leftAnchor constant:10.0] setActive:YES]; + [[progressBar.rightAnchor constraintEqualToAnchor:alertView.rightAnchor constant:-10.0] setActive:YES]; + + [self presentViewController:alert animated:YES completion:nil]; + m_rdvfinder.updateBlock = ^(int index, int pcnt) + { + alert.message = [NSString stringWithFormat:@"%i/%i",index,pcnt]; + progressBar.progress = (float)index/(float)pcnt; + }; + m_rdvfinder.cancelBlock = ^(bool result){ + [self dismissViewControllerAnimated:NO completion:^{ + if(!result) + { + [self showBaseAlert:NSLocalizedString(@"No more found!", nil)]; + } + + }]; + }; + +} + +#pragma mark - Popup text delegate +- (void)onDismissPopupTextViewEdited:(BOOL)edited +{ + [m_view vAnnotEnd]; + [m_view vUpdateAnnotPage]; + if (edited) { + [m_view setModified:YES force:NO]; + } +} + +#pragma mark - RDTreeTableview delegate + +- (void)didSelectDest:(OUTLINE_ITEM *)item { + [self dismissViewControllerAnimated:YES completion:^{ + if ([item dest]) { + [self PDFGoto:[item dest]]; + } + }]; +} + +#pragma mark - Utils + +- (CGRect)buttonRect:(UIBarButtonItem *)item { + UIView *v = [item valueForKey:@"view"]; + CGRect fromRect = [_mBarNoneTop convertRect:v.frame toView:self.view]; + if (fromRect.origin.x + rd_menu_width > self.view.bounds.size.width) { + fromRect.origin.x = self.view.bounds.size.width - rd_menu_width - 8; + } + return fromRect; +} + +- (CGPoint)pdfPointsFromScreenPoints:(int)x :(int)y +{ + RDVPos pos; + [m_view vGetPos:&pos x:x y:y]; + CGPoint pdfPoints; + pdfPoints.x = pos.pdfx; + pdfPoints.y = pos.pdfy; + return pdfPoints; +} + +- (CGPoint)screenPointsFromPdfPoints:(float)x :(float)y :(int)pageNum +{ + return [m_view screenPointsFromPdfPoints:x :y :pageNum]; +} + +- (NSArray *)pdfRectFromScreenRect:(CGRect)screenRect +{ + PDF_RECT pdfrect = [m_view pdfRectFromScreenRect:screenRect]; + NSArray *rect = [NSArray arrayWithObjects:[NSNumber numberWithFloat:pdfrect.top],[NSNumber numberWithFloat:pdfrect.left],[NSNumber numberWithFloat:pdfrect.right],[NSNumber numberWithFloat:pdfrect.bottom], nil]; + return rect; +} + +- (CGRect)screenRectFromPdfRect:(float)top :(float)left :(float)right :(float)bottom :(int)pageNum +{ + return [m_view screenRectFromPdfRect:top :left :right :bottom :pageNum]; +} + + +@end diff --git a/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.storyboard b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.storyboard new file mode 100755 index 00000000..f78c2edb --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/PDFReaderCtrl.storyboard @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.h b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.h new file mode 100755 index 00000000..b61195cd --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.h @@ -0,0 +1,47 @@ +// +// RDAnnotPickerViewController.h +// PDFViewer +// +// Created by Federico Vellani on 24/06/2020. +// + +#import +#import "PDFObjc.h" +#import "UIColorBtn.h" +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + +@interface RDAnnotPickerViewController : UIViewController + +@property (nonatomic) int annotType; +@property (nonatomic) uint annotColor; +@property (strong, nonatomic) RDPDFAnnot *annot; + +@property (strong, nonatomic) IBOutlet UIView *pickerView; +@property (strong, nonatomic) IBOutlet UIView *paletteView; + +@property (strong, nonatomic) IBOutlet UISlider *redSlider; +@property (strong, nonatomic) IBOutlet UITextField *redTextField; + +@property (strong, nonatomic) IBOutlet UISlider *greenSlider; +@property (strong, nonatomic) IBOutlet UITextField *greenTextField; + +@property (strong, nonatomic) IBOutlet UISlider *blueSlider; +@property (strong, nonatomic) IBOutlet UITextField *blueTextField; + +@property (strong, nonatomic) IBOutlet UISlider *alphaSlider; +@property (strong, nonatomic) IBOutlet UITextField *alphaTextField; + +@property (strong, nonatomic) IBOutlet UIButton *dismissButton; +@property (weak, nonatomic) IBOutlet UIButton *cancelButton; + +@property (strong, nonatomic) UIColorBtn *colorBtn; + +- (IBAction)dismissPicker:(id)sender; +- (IBAction)cancelPicker:(id)sender; + +@end + diff --git a/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.m b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.m new file mode 100755 index 00000000..69b612df --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.m @@ -0,0 +1,199 @@ +// +// RDAnnotPickerViewController.m +// PDFViewer +// +// Created by Federico Vellani on 24/06/2020. +// + +#import "RDAnnotPickerViewController.h" +#import "RDVGlobal.h" +#import "RDUtils.h" + +@interface RDAnnotPickerViewController () + +@end + +@implementation RDAnnotPickerViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view from its nib. + + _paletteView.backgroundColor = (_colorBtn.tag == 1) ? [UIColorFromRGB([self getAnnotColor]) colorWithAlphaComponent:1.0f] : UIColorFromRGB([self getAnnotColor]); + + if (_colorBtn.tag == 1) { + _alphaSlider.userInteractionEnabled = NO; + _alphaTextField.userInteractionEnabled = NO; + } + + CGFloat red = 0; + CGFloat green = 0; + CGFloat blue = 0; + CGFloat alpha = 0; + [_paletteView.backgroundColor getRed:&red green:&green blue:&blue alpha:&alpha]; + + _redSlider.value = red * 255; + _greenSlider.value = green * 255; + _blueSlider.value = blue * 255; + _alphaSlider.value = alpha; + _redTextField.text = [NSString stringWithFormat:@"%i", (int)_redSlider.value]; + _greenTextField.text = [NSString stringWithFormat:@"%i", (int)_greenSlider.value]; + _blueTextField.text = [NSString stringWithFormat:@"%i", (int)_blueSlider.value]; + _alphaTextField.text = [NSString stringWithFormat:@"%.01f",_alphaSlider.value]; + [_cancelButton setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal]; + + [_redSlider addTarget:self action:@selector(onSliderValueChange:) forControlEvents:UIControlEventValueChanged]; + [_greenSlider addTarget:self action:@selector(onSliderValueChange:) forControlEvents:UIControlEventValueChanged]; + [_blueSlider addTarget:self action:@selector(onSliderValueChange:) forControlEvents:UIControlEventValueChanged]; + [_alphaSlider addTarget:self action:@selector(onSliderValueChange:) forControlEvents:UIControlEventValueChanged]; + + [_redTextField addTarget:self action:@selector(onTextFieldTextChanged:) forControlEvents:UIControlEventEditingDidEnd]; + [_greenTextField addTarget:self action:@selector(onTextFieldTextChanged:) forControlEvents:UIControlEventEditingDidEnd]; + [_blueTextField addTarget:self action:@selector(onTextFieldTextChanged:) forControlEvents:UIControlEventEditingDidEnd]; + [_alphaTextField addTarget:self action:@selector(onTextFieldTextChanged:) forControlEvents:UIControlEventEditingDidEnd]; + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; + [self.view addGestureRecognizer:tap]; + + if (_colorBtn) { + [[_pickerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES]; + [[_pickerView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES]; + } + + _paletteView.layer.shadowColor = [RDUtils radaeeBlackColor].CGColor; +} + +-(void)dismissKeyboard +{ + [_redTextField resignFirstResponder]; + [_greenTextField resignFirstResponder]; + [_blueTextField resignFirstResponder]; + [_alphaTextField resignFirstResponder]; +} + +-(void)onSliderValueChange:(UISlider*)slider +{ + [self updatePaletteViewColor]; + _redTextField.text = [NSString stringWithFormat:@"%i", (int)_redSlider.value]; + _greenTextField.text = [NSString stringWithFormat:@"%i", (int)_greenSlider.value]; + _blueTextField.text = [NSString stringWithFormat:@"%i", (int)_blueSlider.value]; + _alphaTextField.text = [NSString stringWithFormat:@"%.01f",_alphaSlider.value]; +} + +-(void)onTextFieldTextChanged:(UITextField *)textField +{ + NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet]; + NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:textField.text]; + if ([alphaNums isSupersetOfSet:inStringSet]) + { + if ([textField.text floatValue] <= 255.0 && textField != _alphaTextField) { + _redSlider.value = [_redTextField.text floatValue]; + _greenSlider.value = [_greenTextField.text floatValue]; + _blueSlider.value = [_blueTextField.text floatValue]; + } else if ([textField.text floatValue] <= 1.0 && textField == _alphaTextField) { + _alphaSlider.value = [_alphaTextField.text floatValue]; + } else { + _redSlider.value = (textField == _redTextField) ? 255 : [_redTextField.text floatValue]; + _greenSlider.value = (textField == _greenTextField) ? 255 : [_greenTextField.text floatValue]; + _blueSlider.value = (textField == _blueTextField) ? 255 : [_blueTextField.text floatValue]; + _alphaSlider.value = (textField == _alphaTextField) ? 1 : [_alphaTextField.text floatValue]; + textField.text = (textField == _alphaTextField) ? @"1.0" : @"255"; + } + [self updatePaletteViewColor]; + } +} + +- (void)updatePaletteViewColor +{ + _paletteView.backgroundColor = [UIColor colorWithRed:_redSlider.value/255 green:_greenSlider.value/255 blue:_blueSlider.value/255 alpha:_alphaSlider.value]; +} + +- (IBAction)dismissPicker:(id)sender +{ + unsigned int color; + color = [self hexFromColor:_paletteView.backgroundColor]; + + if (!_colorBtn) { + switch (_annotType) { + case 1: + GLOBAL.g_line_annot_color = color; + break; + case 3: + GLOBAL.g_rect_annot_color = color; + break; + case 4: + GLOBAL.g_oval_annot_color = color; + break; + case 7: + GLOBAL.g_line_annot_color = color; + break; + case 8: + GLOBAL.g_line_annot_color = color; + break; + default: + GLOBAL.g_ink_color = color; + break; + } + } else { + [_colorBtn setColor:color :YES]; + } + + [self dismissViewControllerAnimated:YES completion:nil]; +} + +- (IBAction)cancelPicker:(id)sender +{ + if (_colorBtn) { + [_colorBtn showViews]; + } + [self dismissViewControllerAnimated:YES completion:nil]; +} + +- (uint)getAnnotColor +{ + uint rgbValue; + if (!_colorBtn) { + switch (_annotType) { + case 1: + rgbValue = GLOBAL.g_line_annot_color; + break; + case 3: + rgbValue = GLOBAL.g_rect_annot_color; + break; + case 4: + rgbValue = GLOBAL.g_oval_annot_color; + break; + case 7: + rgbValue = GLOBAL.g_line_annot_color; + break; + case 8: + rgbValue = GLOBAL.g_line_annot_color; + break; + default: + rgbValue = GLOBAL.g_ink_color; + break; + } + } else { + rgbValue = _colorBtn.color; + } + return rgbValue; +} + +- (uint)hexFromColor:(UIColor *)color { + uint m_color = 0xFF000000|((int)_redSlider.value << 16)|((int)_greenSlider.value << 8)|(int)_blueSlider.value; + uint ia = 255 * _alphaSlider.value; + m_color = (m_color&0xFFFFFF)|(ia << 24); + return m_color; +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.xib b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.xib new file mode 100755 index 00000000..48a66e8c --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDAnnotPickerViewController.xib @@ -0,0 +1,353 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.h b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.h new file mode 100644 index 00000000..1a968a8f --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.h @@ -0,0 +1,25 @@ +// +// BookmarkTableViewController.h +// RDPDFViewLib +// +// Created by Emanuele Bortolami on 17/07/15. +// Copyright (c) 2015 gear.it. All rights reserved. +// + +#import + +@protocol BookmarkTableViewDelegate +- (void)didSelectBookmarkAtPage:(int)page; +@end + +@interface RDBookmarkViewController : UIViewController + +@property (strong, nonatomic) IBOutlet UITableView *tableView; +@property (strong, nonatomic) IBOutlet NSLayoutConstraint *tableViewHeight; +@property (strong, nonatomic) NSMutableArray *items; +@property (weak, nonatomic) id delegate; +@property (weak, nonatomic) IBOutlet UILabel *bookmarkTitle; + +- (IBAction)dismissView:(id)sender; + +@end diff --git a/src/ios/PDFViewer/BookmarkTableViewController.m b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.m similarity index 63% rename from src/ios/PDFViewer/BookmarkTableViewController.m rename to src/ios/PDFViewer/PDFReader/RDBookmarkViewController.m index 77c1c581..bc17a71c 100644 --- a/src/ios/PDFViewer/BookmarkTableViewController.m +++ b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.m @@ -6,26 +6,21 @@ // Copyright (c) 2015 gear.it. All rights reserved. // -#import "BookmarkTableViewController.h" +#import "RDBookmarkViewController.h" -@interface BookmarkTableViewController () +@interface RDBookmarkViewController () @end -@implementation BookmarkTableViewController +@implementation RDBookmarkViewController - (void)viewDidLoad { [super viewDidLoad]; - - // Uncomment the following line to preserve selection between presentations. - // self.clearsSelectionOnViewWillAppear = NO; - - // Uncomment the following line to display an Edit button in the navigation bar for this view controller. - // self.navigationItem.rightBarButtonItem = self.editButtonItem; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { - self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(closeView)]; - } + _tableViewHeight.constant = _items.count * 50; //items * number of cells + _tableView.translatesAutoresizingMaskIntoConstraints = NO; + _tableView.delegate = self; + _tableView.dataSource = self; + _bookmarkTitle.text = NSLocalizedString(@"Bookmarks", nil); } - (void)didReceiveMemoryWarning { @@ -50,6 +45,10 @@ - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger return _items.count; } +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return 50; +} + - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; @@ -64,7 +63,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N int pageno = [[arr objectAtIndex:0] intValue]; pageno++; - cell.textLabel.text = [NSString stringWithFormat:@"Page: %i", pageno]; + cell.textLabel.text = [NSString stringWithFormat:@"%@: %i",NSLocalizedString(@"Page", nil), pageno]; return cell; } @@ -74,7 +73,7 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath NSArray *arr = [_items objectAtIndex:indexPath.row]; int pageno = [[arr objectAtIndex:0] intValue]; - [_delegate didSelectItem:pageno]; + [_delegate didSelectBookmarkAtPage:pageno]; [self dismissViewControllerAnimated:YES completion:nil]; } @@ -105,28 +104,8 @@ - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEd } } -/* -// Override to support rearranging the table view. -- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { -} -*/ - -/* -// Override to support conditional rearranging of the table view. -- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { - // Return NO if you do not want the item to be re-orderable. - return YES; -} -*/ - -/* -#pragma mark - Navigation - -// In a storyboard-based application, you will often want to do a little preparation before navigation -- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { - // Get the new view controller using [segue destinationViewController]. - // Pass the selected object to the new view controller. +- (void)dismissView:(id)sende { + [self dismissViewControllerAnimated:YES completion:nil]; } -*/ @end diff --git a/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.xib b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.xib new file mode 100644 index 00000000..d298664d --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDBookmarkViewController.xib @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.h b/src/ios/PDFViewer/PDFReader/RDExtendedSearch.h old mode 100644 new mode 100755 similarity index 73% rename from src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.h rename to src/ios/PDFViewer/PDFReader/RDExtendedSearch.h index 4d5408e5..08147b63 --- a/src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.h +++ b/src/ios/PDFViewer/PDFReader/RDExtendedSearch.h @@ -12,7 +12,7 @@ #import "RDVGlobal.h" #import "RDVPage.h" -#define SEARCH_LIST 0 +#define SEARCH_LIST 1 @interface RDSearchResult : NSObject @@ -25,9 +25,9 @@ @interface RDExtendedSearch : NSObject { - PDFPage *m_page; - PDFDoc *m_doc; - PDFFinder *m_finder; + RDPDFPage *m_page; + RDPDFDoc *m_doc; + RDPDFFinder *m_finder; void(^finishBlock)(void); void(^progressBlock)(NSMutableArray *, NSMutableArray *); } @@ -39,9 +39,9 @@ + (RDExtendedSearch *)sharedInstance; -- (BOOL)searchInit:(PDFDoc *)doc; -- (void)searchText:(NSString *)text inDoc:(PDFDoc *)doc progress:(void (^)(NSMutableArray *occurrences, NSMutableArray *total))progress finish:(void (^)(void))finish; -- (void)addPageSearchResults:(PDFFinder *)finder forPage:(int)page progress:(void (^)(NSMutableArray *occurrences, NSMutableArray *total))progress; +- (BOOL)searchInit:(RDPDFDoc *)doc; +- (void)searchText:(NSString *)text inDoc:(RDPDFDoc *)doc progress:(void (^)(NSMutableArray *occurrences, NSMutableArray *total))progress finish:(void (^)(void))finish; +- (void)addPageSearchResults:(RDPDFFinder *)finder forPage:(int)page progress:(void (^)(NSMutableArray *occurrences, NSMutableArray *total))progress; - (BOOL)pageIsInSearchResults:(int)page; - (int)getNextPageFromCurrentPage:(int)page; - (int)getPrevPageFromCurrentPage:(int)page; diff --git a/src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.m b/src/ios/PDFViewer/PDFReader/RDExtendedSearch.m old mode 100644 new mode 100755 similarity index 94% rename from src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.m rename to src/ios/PDFViewer/PDFReader/RDExtendedSearch.m index 675fdeba..0323a97c --- a/src/ios/PDFViewer/Modules/SearchList/RDExtendedSearch.m +++ b/src/ios/PDFViewer/PDFReader/RDExtendedSearch.m @@ -34,7 +34,7 @@ + (RDExtendedSearch *)sharedInstance return sharedInstance; } -- (BOOL)searchInit:(PDFDoc *)doc +- (BOOL)searchInit:(RDPDFDoc *)doc { m_doc = doc; m_finder = NULL; @@ -42,7 +42,7 @@ - (BOOL)searchInit:(PDFDoc *)doc return YES; } -- (void)searchText:(NSString *)text inDoc:(PDFDoc *)doc progress:(void (^)(NSMutableArray *, NSMutableArray *))progress finish:(void (^)(void))finish +- (void)searchText:(NSString *)text inDoc:(RDPDFDoc *)doc progress:(void (^)(NSMutableArray *, NSMutableArray *))progress finish:(void (^)(void))finish { _searching = YES; self.searchResults = [[NSMutableArray alloc] init]; @@ -83,7 +83,7 @@ - (void)searchText:(NSString *)text inDoc:(PDFDoc *)doc progress:(void (^)(NSMut }); } -- (void)addPageSearchResults:(PDFFinder *)finder forPage:(int)page progress:(void (^)(NSMutableArray *, NSMutableArray *))progress +- (void)addPageSearchResults:(RDPDFFinder *)finder forPage:(int)page progress:(void (^)(NSMutableArray *, NSMutableArray *))progress { NSMutableArray *progressResult = [NSMutableArray array]; for (int i = 0; i < finder.count; i++) { diff --git a/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.h b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.h new file mode 100755 index 00000000..e1a5ec98 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.h @@ -0,0 +1,27 @@ +// +// RDMetaDataViewController.h +// PDFViewer +// +// Created by Federico Vellani on 26/06/2020. +// + +#import + +@class RDPDFDoc; +@interface RDMetaDataViewController : UIViewController + +@property (strong, nonatomic) RDPDFDoc *doc; +@property (nonatomic) BOOL autoSave; + +@property (strong, nonatomic) IBOutlet UITextField *titleTextField; +@property (strong, nonatomic) IBOutlet UITextField *authorTextField; +@property (strong, nonatomic) IBOutlet UITextField *subjectTextField; +@property (strong, nonatomic) IBOutlet UITextView *keyWordsTextView; +@property (weak, nonatomic) IBOutlet UILabel *titleLabel; +@property (weak, nonatomic) IBOutlet UILabel *authorLabel; +@property (weak, nonatomic) IBOutlet UILabel *subjectLabel; +@property (weak, nonatomic) IBOutlet UILabel *keywordLabel; + +- (IBAction)dismissView:(id)sender; + +@end diff --git a/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.m b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.m new file mode 100755 index 00000000..70c5a27e --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.m @@ -0,0 +1,69 @@ +// +// RDMetaDataViewController.m +// PDFViewer +// +// Created by Federico Vellani on 26/06/2020. +// + +#import "RDMetaDataViewController.h" +#import "PDFObjc.h" + +@interface RDMetaDataViewController () + +@end + +@implementation RDMetaDataViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view from its nib. + [_titleTextField setText:[_doc meta:@"Title"]]; + [_authorTextField setText:[_doc meta:@"Author"]]; + [_subjectTextField setText:[_doc meta:@"Subject"]]; + [_keyWordsTextView setText:[_doc meta:@"Keywords"]]; + _titleLabel.text = NSLocalizedString(@"Title", nil); + _authorLabel.text = NSLocalizedString(@"Author", nil); + _subjectLabel.text = NSLocalizedString(@"Subject", nil); + _keywordLabel.text = NSLocalizedString(@"Keywords", nil); + + if (@available(iOS 13.0, *)) { + _keyWordsTextView.layer.borderColor = [UIColor systemGray4Color].CGColor; + } else { + _keyWordsTextView.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1.0].CGColor; + } + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; + [self.view addGestureRecognizer:tap]; +} + +- (void)dismissKeyboard +{ + [_titleTextField resignFirstResponder]; + [_authorTextField resignFirstResponder]; + [_subjectTextField resignFirstResponder]; + [_keyWordsTextView resignFirstResponder]; +} + +- (IBAction)dismissView:(id)sender +{ + [_doc setMeta:@"Title" :_titleTextField.text]; + [_doc setMeta:@"Author" :_authorTextField.text]; + [_doc setMeta:@"Subject" :_subjectTextField.text]; + [_doc setMeta:@"Keywords" :_keyWordsTextView.text]; + if (_autoSave) { + [_doc save]; + } + [self dismissViewControllerAnimated:YES completion:nil]; +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.xib b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.xib new file mode 100755 index 00000000..af1dea9d --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDMetaDataViewController.xib @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDPDFReflowViewController.h b/src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.h old mode 100644 new mode 100755 similarity index 91% rename from src/ios/PDFViewer/RDPDFReflowViewController.h rename to src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.h index 24b4227d..4d7227b4 --- a/src/ios/PDFViewer/RDPDFReflowViewController.h +++ b/src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.h @@ -10,12 +10,13 @@ #import "PDFIOS.h" #import #import "PDFReflowView.h" +#import "PDFObjc.h" @interface RDPDFReflowViewController : UIViewController { PDFReflowView *m_view; - PDFDoc *m_doc; - PDFPage *m_page; + RDPDFDoc *m_doc; + RDPDFPage *m_page; CGImageRef m_img; int m_cur_page; UIImage *img; diff --git a/src/ios/PDFViewer/RDPDFReflowViewController.m b/src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.m old mode 100644 new mode 100755 similarity index 93% rename from src/ios/PDFViewer/RDPDFReflowViewController.m rename to src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.m index 4fbff65e..7dbd9117 --- a/src/ios/PDFViewer/RDPDFReflowViewController.m +++ b/src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.m @@ -47,7 +47,6 @@ -(void)viewWillDisappear:(BOOL)animated -(void)createToolbarItems { - toolBar.barStyle = UIBarStyleBlackOpaque; UIBarButtonItem *fontBigButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fontBig"] style:UIBarButtonItemStylePlain target:self action:@selector(fontBig)]; fontBigButton.width =29; UIBarButtonItem *fontSmallButton = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fontSmall"] style:UIBarButtonItemStylePlain target:self action:@selector(fontSmall)]; @@ -68,6 +67,20 @@ -(void)createToolbarItems -(int)PDFOpen:(NSString *)path :(NSString *)pswd { + m_doc = [[RDPDFDoc alloc] init]; + int err_code = [m_doc open:path :pswd]; + switch(err_code) + { + case err_ok: + break; + case err_password: + return 2; + break; + default: + return 0; + break; + } + CGRect rect = [UIScreen mainScreen].bounds; if([[[UIDevice currentDevice] systemVersion]integerValue]>=7) { @@ -82,8 +95,6 @@ -(int)PDFOpen:(NSString *)path :(NSString *)pswd offset.y = self.view.frame.size.height*0.5; [m_view setContentOffset:offset]; - m_doc = [[PDFDoc alloc] init]; - [m_doc open:path :pswd]; [m_view vOpen:m_doc :path]; // [m_view vOpen:m_doc :nil]; diff --git a/src/ios/PDFViewer/RDPDFReflowViewController.xib b/src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.xib old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/RDPDFReflowViewController.xib rename to src/ios/PDFViewer/PDFReader/RDPDFReflowViewController.xib diff --git a/src/ios/PDFViewer/RDPageView/RDPageViewController.h b/src/ios/PDFViewer/PDFReader/RDPageViewController.h old mode 100644 new mode 100755 similarity index 95% rename from src/ios/PDFViewer/RDPageView/RDPageViewController.h rename to src/ios/PDFViewer/PDFReader/RDPageViewController.h index 30619730..7974ecc4 --- a/src/ios/PDFViewer/RDPageView/RDPageViewController.h +++ b/src/ios/PDFViewer/PDFReader/RDPageViewController.h @@ -27,7 +27,7 @@ NS_ASSUME_NONNULL_BEGIN - (void)setImmersive:(BOOL)immersive; - (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size; - (BOOL)addAttachmentFromPath:(NSString *)path; -- (bool)flatAnnotAtPage:(int)page doc:(PDFDoc *)doc; +- (bool)flatAnnotAtPage:(int)page doc:(RDPDFDoc *)doc; - (bool)flatAnnots; - (bool)saveDocumentToPath:(NSString *)path; diff --git a/src/ios/PDFViewer/RDPageView/RDPageViewController.m b/src/ios/PDFViewer/PDFReader/RDPageViewController.m old mode 100644 new mode 100755 similarity index 86% rename from src/ios/PDFViewer/RDPageView/RDPageViewController.m rename to src/ios/PDFViewer/PDFReader/RDPageViewController.m index 7e7b8b17..de0db772 --- a/src/ios/PDFViewer/RDPageView/RDPageViewController.m +++ b/src/ios/PDFViewer/PDFReader/RDPageViewController.m @@ -8,10 +8,11 @@ #import "RDPageViewController.h" #import "RDSinglePageViewController.h" +#import "RDVGlobal.h" @interface RDPageViewController () { - PDFDoc *doc; + RDPDFDoc *doc; BOOL statusBarHidden; BOOL isImmersive; int pageno; @@ -32,16 +33,16 @@ - (void)viewDidLoad { - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; - + UIViewController *vc = [self viewControllerAtIndex:0]; [self setViewControllers:@[vc] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil]; - + self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_back"] style:UIBarButtonItemStyleDone target:self action:@selector(closeView)]; } - (int)PDFOpenAtPath:(NSString *)path withPwd:(NSString *)pwd { - doc = [[PDFDoc alloc] init]; + doc = [[RDPDFDoc alloc] init]; int err_code = [doc open:path :pwd]; switch(err_code) { @@ -63,8 +64,13 @@ - (UIViewController *)viewControllerAtIndex:(NSUInteger)index viewController.doc = doc; viewController.pageViewNo = index; pageno = (int)index+1; - if (bgColor) { - [viewController.pdfView setReaderBackgroundColor:bgColor]; + if (bgColor) + { + CGFloat r = ((bgColor >> 16)&255) / 255.0; + CGFloat g = ((bgColor >> 8)&255) / 255.0; + CGFloat b = (bgColor&255) / 255.0; + CGFloat a = ((bgColor >> 24)&255) / 255.0; + viewController.pdfView.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:a]; } return viewController; } @@ -80,7 +86,7 @@ - (NSInteger)presentationCountForPageViewController:(UIPageViewController *)page { return [doc pageCount]; } - + - (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController { return 0; @@ -89,23 +95,23 @@ - (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)page - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { NSUInteger index = ((RDSinglePageViewController*) viewController).pageViewNo; - + if ((index == 0) || (index == NSNotFound)) { return nil; } - + index--; return [self viewControllerAtIndex:index]; } - + - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { NSUInteger index = ((RDSinglePageViewController*) viewController).pageViewNo; - + if (index == NSNotFound) { return nil; } - + index++; if (index == doc.pageCount) { return nil; @@ -147,7 +153,7 @@ -(void)PDFClose [self closeViewController:v]; } } - + doc = NULL; } @@ -216,10 +222,6 @@ - (void)setThumbHeight:(float)height { } -- (void)setFirstPageCover:(BOOL)cover -{ -} - - (void)setDoubleTapZoomMode:(int)mode { } @@ -227,7 +229,7 @@ - (void)setDoubleTapZoomMode:(int)mode - (void)setImmersive:(BOOL)immersive { isImmersive = immersive; - + if (isImmersive) { [self hideBars]; } else { @@ -251,7 +253,7 @@ - (BOOL)addAttachmentFromPath:(NSString *)path #pragma mark - Flat annot -- (bool)flatAnnotAtPage:(int)page doc:(PDFDoc *)doc +- (bool)flatAnnotAtPage:(int)page doc:(RDPDFDoc *)doc { return NO; } @@ -265,10 +267,16 @@ - (bool)flatAnnots - (bool)saveDocumentToPath:(NSString *)path { - NSString *prefix = @"file://"; - if([path rangeOfString:prefix].location != NSNotFound) + if([path containsString:@"file://"]) { - path = [path substringFromIndex:prefix.length]; + NSString *filePath = [path stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + return [doc saveAs:filePath: NO]; + } } return [doc saveAs:path: NO]; } diff --git a/src/ios/PDFViewer/RDPageView/RDPageViewController.xib b/src/ios/PDFViewer/PDFReader/RDPageViewController.xib old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/RDPageView/RDPageViewController.xib rename to src/ios/PDFViewer/PDFReader/RDPageViewController.xib diff --git a/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.h b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.h new file mode 100755 index 00000000..32bd5a05 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.h @@ -0,0 +1,31 @@ +// +// RDTextAnnotViewController.h +// PDFViewer +// +// Created by Federico Vellani on 01/07/2020. +// + +#import +@class RDPDFAnnot; + +@protocol RDPopupTextViewControllerDelegate + +- (void)onDismissPopupTextViewEdited:(BOOL)edited; + +@end + +@interface RDPopupTextViewController : UIViewController + +@property (strong, nonatomic) RDPDFAnnot *annot; +@property (strong, nonatomic) id delegate; + +@property (strong, nonatomic) IBOutlet UITextField *subjectTextField; +@property (strong, nonatomic) IBOutlet UITextView *textView; +@property (strong, nonatomic) IBOutlet UIButton *dismissButton; +@property (weak, nonatomic) IBOutlet UILabel *subjectLabel; +@property (weak, nonatomic) IBOutlet UILabel *textLabel; + +- (IBAction)dismissView:(id)sender; + +@end + diff --git a/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.m b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.m new file mode 100755 index 00000000..d45b7763 --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.m @@ -0,0 +1,65 @@ +// +// RDTextAnnotViewController.m +// PDFViewer +// +// Created by Federico Vellani on 01/07/2020. +// + +#import "RDPopupTextViewController.h" +#import "PDFObjc.h" + +@interface RDPopupTextViewController () + +@end + +@implementation RDPopupTextViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view from its nib. + _subjectTextField.text = [_annot getPopupSubject]; + _textView.text = [_annot getPopupText]; + _subjectLabel.text = NSLocalizedString(@"Subject", nil); + _textLabel.text = NSLocalizedString(@"Text", nil); + _subjectTextField.userInteractionEnabled = _textView.userInteractionEnabled = ![_annot isAnnotReadOnly]; + + if (@available(iOS 13.0, *)) { + _textView.layer.borderColor = [UIColor systemGray4Color].CGColor; + } else { + _textView.layer.borderColor = [UIColor colorWithWhite:0.8 alpha:1.0].CGColor; + } + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; + [self.view addGestureRecognizer:tap]; +} + +- (void)dismissKeyboard +{ + [_subjectTextField resignFirstResponder]; + [_textView resignFirstResponder]; +} + +- (IBAction)dismissView:(id)sender +{ + BOOL edited = NO; + if (![_annot isAnnotReadOnly]) { + edited = (![[_annot getPopupSubject] isEqualToString:_subjectTextField.text] || ![[_annot getPopupText]isEqualToString:_textView.text]); + [_annot setPopupSubject:_subjectTextField.text]; + [_annot setPopupText:_textView.text]; + } + [self dismissViewControllerAnimated:YES completion:^{ + [self->_delegate onDismissPopupTextViewEdited:edited]; + }]; +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.xib b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.xib new file mode 100755 index 00000000..07d743bc --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDPopupTextViewController.xib @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDPageView/RDSinglePageViewController.h b/src/ios/PDFViewer/PDFReader/RDSinglePageViewController.h old mode 100644 new mode 100755 similarity index 81% rename from src/ios/PDFViewer/RDPageView/RDSinglePageViewController.h rename to src/ios/PDFViewer/PDFReader/RDSinglePageViewController.h index bb2f2a02..89465a4c --- a/src/ios/PDFViewer/RDPageView/RDSinglePageViewController.h +++ b/src/ios/PDFViewer/PDFReader/RDSinglePageViewController.h @@ -7,11 +7,14 @@ // #import +#import "RDPDFView.h" #import "PDFLayoutView.h" @interface RDSinglePageViewController : UIViewController - -@property (strong, nonatomic) PDFDoc *doc; +{ + RDPDFView *mView; +} +@property (strong, nonatomic) RDPDFDoc *doc; @property (strong, nonatomic) PDFLayoutView *pdfView; @property (nonatomic) NSUInteger pageViewNo; diff --git a/src/ios/PDFViewer/PDFReader/RDSinglePageViewController.m b/src/ios/PDFViewer/PDFReader/RDSinglePageViewController.m new file mode 100755 index 00000000..0efb733b --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/RDSinglePageViewController.m @@ -0,0 +1,160 @@ +// +// ViewController.m +// RDPageViewController +// +// Created by Federico Vellani on 06/02/2020. +// Copyright © 2020 Federico Vellani. All rights reserved. +// + +#import "RDSinglePageViewController.h" + +@interface RDSinglePageViewController () + +@end + +@implementation RDSinglePageViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. +} + +- (void)viewWillAppear:(BOOL)animated +{ + [super viewWillAppear:animated]; + mView = [[RDPDFView alloc] initWithFrame:self.view.frame]; + _pdfView = mView.view; + _pdfView.scrollEnabled = NO; + _pdfView.singleViewPageNo = _pageViewNo; + _pdfView.userInteractionEnabled = NO; +//-(BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(RDPDFCanvas *)canvas :(id) del; + BOOL success = [_pdfView PDFOpen:_doc :4 :mView.canvas :self]; + [self.view addSubview:_pdfView]; +} + +- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator +{ + [_pdfView setFrame:CGRectMake(0, 0, size.width, size.height)]; + [_pdfView sizeThatFits:size]; +} + +- (void)OnAnnotClicked:(RDPDFAnnot *)annot :(float)x :(float)y { + +} + +- (void)OnAnnotCommboBox:(RDVPage *)vp :(NSArray *)dataArray selected:(int)index { + +} + +- (void)OnAnnotEditBox:(CGRect)annotRect :(NSString *)editText :(float)textSize { + +} + +- (void)OnAnnotEnd { + +} + +- (void)OnAnnotGoto:(int)pageno { + +} + +- (void)OnAnnotList:(RDVPage *)vp :(RDPDFAnnot *)annot items:(NSArray *)dataArray selectedIndexes:(NSArray *)indexes { + +} + +- (void)OnAnnotMovie:(NSString *)fileName { + +} + +- (void)OnAnnotOpenURL:(NSString *)url { + +} + +- (void)OnAnnotPopup:(RDPDFAnnot *)annot { + +} + +- (void)OnAnnotSignature:(RDVPage *)vp :(RDPDFAnnot *)annot { + +} + +- (void)OnAnnotSound:(NSString *)fileName { + +} + +- (void)OnDoubleTapped:(float)x :(float)y { + +} + +- (void)OnFound:(bool)found { + +} + +- (void)OnLongPressed:(float)x :(float)y { + +} + +- (void)OnPageChanged:(int)pageno { + +} + +- (void)OnPageUpdated:(int)pageno { + +} + +- (void)OnSelEnd:(float)x1 :(float)y1 :(float)x2 :(float)y2 { + +} + +- (void)OnSelStart:(float)x :(float)y { + +} + +- (void)OnSingleTapped:(float)x :(float)y { + +} + +- (void)OnAnnotClicked:(RDPDFAnnot *)annot :(PDF_RECT)rect :(float)x :(float)y { +} + + +- (void)OnAnnotCommboBox:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selected:(int)index { +} + + +- (void)OnAnnotEditBox:(RDPDFAnnot *)annot :(CGRect)annotRect :(NSString *)editText :(float)textSize { +} + + +- (void)OnAnnotList:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selectedIndexes:(NSArray *)indexes { +} + + +- (void)OnAnnotTapped:(RDPDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point { +} + + +- (void)didTapAnnot:(RDPDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point { + +} + +- (void)encodeWithCoder:(nonnull NSCoder *)aCoder { +} + +- (void)traitCollectionDidChange:(nullable UITraitCollection *)previousTraitCollection { +} + +- (void)didUpdateFocusInContext:(nonnull UIFocusUpdateContext *)context withAnimationCoordinator:(nonnull UIFocusAnimationCoordinator *)coordinator { +} + +- (void)setNeedsFocusUpdate { +} + +- (BOOL)shouldUpdateFocusInContext:(nonnull UIFocusUpdateContext *)context { + return NO; +} + +- (void)updateFocusIfNeeded { +} + +@end diff --git a/src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.h b/src/ios/PDFViewer/PDFReader/SearchResultTableViewController.h old mode 100644 new mode 100755 similarity index 78% rename from src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.h rename to src/ios/PDFViewer/PDFReader/SearchResultTableViewController.h index c76e9afd..d554e290 --- a/src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.h +++ b/src/ios/PDFViewer/PDFReader/SearchResultTableViewController.h @@ -15,7 +15,7 @@ @end -@interface SearchResultTableViewController : UITableViewController +@interface SearchResultViewController : UIViewController { UILabel *footerLabel; UINib *cellLoader; @@ -25,5 +25,6 @@ @property (strong, nonatomic) NSString *searchedString; @property (strong, nonatomic) PDFDoc *doc; @property (nonatomic, weak) id delegate; +@property (strong, nonatomic) IBOutlet UITableView *tableView; @end diff --git a/src/ios/PDFViewer/PDFReader/SearchResultViewController.h b/src/ios/PDFViewer/PDFReader/SearchResultViewController.h new file mode 100755 index 00000000..818a3a2e --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/SearchResultViewController.h @@ -0,0 +1,33 @@ +// +// SearchResultTableViewController.h +// MobileReplica +// +// Created by Emanuele Bortolami on 05/08/14. +// Copyright (c) 2014 GEAR.it s.r.l. All rights reserved. +// + +#import +@class RDExtendedSearch; +@class RDPDFDoc; + +@protocol SearchResultViewControllerDelegate + +- (void)didSelectSelectSearchResult:(int)index; + +@end + +@interface SearchResultViewController : UIViewController +{ + UILabel *footerLabel; + UINib *cellLoader; + NSMutableArray *items; +} + +@property (strong, nonatomic) NSString *searchedString; +@property (strong, nonatomic) RDPDFDoc *doc; +@property (nonatomic, weak) id delegate; +@property (strong, nonatomic) IBOutlet UITableView *tableView; + +- (IBAction)dismissView:(id)sender; + +@end diff --git a/src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.m b/src/ios/PDFViewer/PDFReader/SearchResultViewController.m old mode 100644 new mode 100755 similarity index 93% rename from src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.m rename to src/ios/PDFViewer/PDFReader/SearchResultViewController.m index f2518e62..a171e40b --- a/src/ios/PDFViewer/Modules/SearchList/SearchResultTableViewController.m +++ b/src/ios/PDFViewer/PDFReader/SearchResultViewController.m @@ -6,10 +6,11 @@ // Copyright (c) 2014 GEAR.it s.r.l. All rights reserved. // -#import "SearchResultTableViewController.h" +#import "SearchResultViewController.h" +#import "RDExtendedSearch.h" #import "RDUtils.h" -@implementation SearchResultTableViewController +@implementation SearchResultViewController - (void)viewDidLoad { @@ -21,8 +22,11 @@ - (void)viewDidLoad // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; items = [NSMutableArray array]; - self.view.backgroundColor = [UIColor whiteColor]; - self.tableView.backgroundColor = [UIColor whiteColor]; + self.tableView.backgroundColor = [RDUtils radaeeWhiteColor]; + self.tableView.layer.cornerRadius = 10.0f; + + self.tableView.delegate = self; + self.tableView.dataSource = self; } - (void)viewWillAppear:(BOOL)animated @@ -106,7 +110,6 @@ - (void)didReceiveMemoryWarning - (void)updateFooterText { footerLabel.text = ([[RDExtendedSearch sharedInstance] searching]) ? [NSString stringWithFormat:NSLocalizedString(@"Searching... (%i)", nil), (int)items.count] : [NSString stringWithFormat:NSLocalizedString(@"%i occurrences", nil), (int)items.count]; - footerLabel.textColor = ([[RDExtendedSearch sharedInstance] searching]) ? [UIColor lightGrayColor] : [UIColor blackColor]; } #pragma mark - Table view data source @@ -151,8 +154,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; cell.textLabel.font = [UIFont systemFontOfSize:14]; - cell.textLabel.textColor = [UIColor blackColor]; - cell.backgroundColor = [UIColor whiteColor]; + cell.backgroundColor = [RDUtils radaeeWhiteColor]; } // PDF Search @@ -160,7 +162,6 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N pageLabel.text = [NSString stringWithFormat:@"%i", [(RDSearchResult *)[items objectAtIndex:indexPath.row] page]]; pageLabel.font = [UIFont boldSystemFontOfSize:17]; pageLabel.textAlignment = NSTextAlignmentRight; - pageLabel.textColor = [UIColor blackColor]; cell.textLabel.attributedText = [self boldSearchedString:[(RDSearchResult *)[items objectAtIndex:indexPath.row] stringResult]]; cell.textLabel.numberOfLines = 0; @@ -228,7 +229,12 @@ - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *) - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // PDF Search - [self.delegate didSelectSelectSearchResult:[(RDSearchResult *)[items objectAtIndex:indexPath.row] page] - 1]; + [self.delegate didSelectSelectSearchResult:[(RDSearchResult *)[items objectAtIndex:indexPath.row] page]-1]; +} + +- (IBAction)dismissView:(id)sender +{ + [self dismissViewControllerAnimated:YES completion:nil]; } @end diff --git a/src/ios/PDFViewer/PDFReader/SearchResultViewController.xib b/src/ios/PDFViewer/PDFReader/SearchResultViewController.xib new file mode 100755 index 00000000..a554960c --- /dev/null +++ b/src/ios/PDFViewer/PDFReader/SearchResultViewController.xib @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.h b/src/ios/PDFViewer/PDFReader/UIColorBtn.h old mode 100644 new mode 100755 similarity index 75% rename from src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.h rename to src/ios/PDFViewer/PDFReader/UIColorBtn.h index cc08e98d..1bb543c8 --- a/src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.h +++ b/src/ios/PDFViewer/PDFReader/UIColorBtn.h @@ -8,14 +8,18 @@ #pragma once #import -@interface UIColorBtn : UIView +#import "../UILElement.h" +@interface UIColorBtn : UILElement { unsigned int m_color; Boolean m_has_enable; UIViewController *m_vc; } + -(id)initWithCoder:(NSCoder *)aDecoder; -(id)initWithFrame:(CGRect)frame; -(void)setColor:(unsigned int)color :(Boolean)has_enable :(UIViewController *)vc; +-(void)setColor:(unsigned int)color :(Boolean)has_enable; +-(void)showViews; -(int)color; @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.m b/src/ios/PDFViewer/PDFReader/UIColorBtn.m old mode 100644 new mode 100755 similarity index 50% rename from src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.m rename to src/ios/PDFViewer/PDFReader/UIColorBtn.m index 4c0a8a39..4044042f --- a/src/ios/PDFViewer/Modules/AnnotProp/UIColorBtn.m +++ b/src/ios/PDFViewer/PDFReader/UIColorBtn.m @@ -8,8 +8,9 @@ #import #import "UIColorBtn.h" -#import "PopColor.h" #import "PDFPopupCtrl.h" +#import "RDAnnotPickerViewController.h" + @implementation UIColorBtn -(id)initWithCoder:(NSCoder *)aDecoder { @@ -34,36 +35,29 @@ -(id)initWithFrame:(CGRect)frame -(void)tapAction:(id)sendor { - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"PopColor" owner:self options:nil]; - PopColor *view = [views lastObject]; - CGRect frame = self.frame; - frame.origin.x = 0; - frame.origin.y = 0; - frame = [self convertRect:frame toView:m_vc.view]; - frame.origin.x += frame.size.width; - frame.size.width = 118; - frame.size.height = 168; - CGRect rect = m_vc.view.frame; - if(frame.origin.y + frame.size.height > rect.origin.y + rect.size.height) - frame.origin.y = rect.origin.y + rect.size.height - frame.size.height; - view.frame = frame; + RDAnnotPickerViewController *pickerViewController = [[RDAnnotPickerViewController alloc] initWithNibName:@"RDAnnotPickerViewController" bundle:nil]; + pickerViewController.colorBtn = self; + [pickerViewController.view setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.2f]]; + pickerViewController.modalPresentationStyle = UIModalPresentationOverFullScreen; + pickerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [m_vc presentViewController:pickerViewController animated:YES completion:nil]; + [self showViews]; +} + +- (void)showViews +{ + if ([m_vc.view isHidden]) { + [m_vc.view setHidden:NO]; + } else { + [m_vc.view setHidden:YES]; + } - PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; - unsigned int *tclr = &m_color; - [view setPara:m_color :m_has_enable :^(Boolean ok, unsigned int color) { - if(ok) - { - CGFloat clr[4]; - clr[0] = ((color >> 16) & 0xff) / 255.0f; - clr[1] = ((color >> 8) & 0xff) / 255.0f; - clr[2] = (color & 0xff) / 255.0f; - clr[3] = ((color >> 24) & 0xff) / 255.0f; - *tclr = color; - self.backgroundColor = [UIColor colorWithRed:clr[0] green:clr[1] blue:clr[2] alpha:1]; - } - [pop dismiss]; - }]; - [m_vc presentViewController:pop animated:NO completion:nil]; +} + +- (void)setColor:(unsigned int)color :(Boolean)has_enable +{ + [self showViews]; + [self setColor:color :has_enable :m_vc]; } -(void)setColor:(unsigned int)color :(Boolean)has_enable :(UIViewController *)vc @@ -76,7 +70,7 @@ -(void)setColor:(unsigned int)color :(Boolean)has_enable :(UIViewController *)vc clr[1] = ((color >> 8) & 0xff) / 255.0f; clr[2] = (color & 0xff) / 255.0f; clr[3] = ((m_color >> 24) & 0xff) / 255.0f; - self.backgroundColor = [UIColor colorWithRed:clr[0] green:clr[1] blue:clr[2] alpha:1]; + self.backgroundColor = [UIColor colorWithRed:clr[0] green:clr[1] blue:clr[2] alpha:clr[3]]; } -(int)color { diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UIIconView.h b/src/ios/PDFViewer/PDFReader/UIIconView.h old mode 100644 new mode 100755 similarity index 72% rename from src/ios/PDFViewer/Modules/AnnotProp/UIIconView.h rename to src/ios/PDFViewer/PDFReader/UIIconView.h index bb7968ae..74505d3f --- a/src/ios/PDFViewer/Modules/AnnotProp/UIIconView.h +++ b/src/ios/PDFViewer/PDFReader/UIIconView.h @@ -6,22 +6,23 @@ // Copyright © 2020 Radaee. All rights reserved. // #import -@class PDFDIB; +#import "../UILShadowView.h" typedef void(^func_icon)(int); @class PDFPopupCtrl; -@class PDFAnnot; +@class RDPDFAnnot; +@class RDPDFDIB; @interface UIIconBtn : UIImageView { int m_atype; int m_icon; UIViewController *m_vc; - PDFDIB *m_dib; + RDPDFDIB *m_dib; PDFPopupCtrl *m_popup; NSMutableArray *m_dibs; - UIView *m_view; + UIScrollView *m_view; } -(id)initWithCoder:(NSCoder *)aDecoder; -(id)initWithFrame:(CGRect)frame; --(void)setIcon:(PDFAnnot *)annot :(UIViewController *)vc; +-(void)setIcon:(RDPDFAnnot *)annot :(UIViewController *)vc; -(int)icon; @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UIIconView.m b/src/ios/PDFViewer/PDFReader/UIIconView.m old mode 100644 new mode 100755 similarity index 68% rename from src/ios/PDFViewer/Modules/AnnotProp/UIIconView.m rename to src/ios/PDFViewer/PDFReader/UIIconView.m index c2ba3257..1c9f269c --- a/src/ios/PDFViewer/Modules/AnnotProp/UIIconView.m +++ b/src/ios/PDFViewer/PDFReader/UIIconView.m @@ -7,9 +7,10 @@ // #import +#import "PDFObjc.h" #import "UIIconView.h" #import "PDFPopupCtrl.h" -#import "PDFObjc.h" +#import "PDFDialog.h" const char *g_note_icon_names[] = { @@ -72,13 +73,13 @@ -(id)initWithFrame:(CGRect)frame -(void)updateIcon:(int)icon { m_icon = icon; - m_dib = [[PDFDIB alloc] init:48 :48]; + m_dib = [[RDPDFDIB alloc] init:48 :48]; [m_dib erase:-1]; Global_drawAnnotIcon(m_atype, m_icon, [m_dib handle]); self.image = [[UIImage alloc] initWithCGImage:[m_dib image]]; } --(void)setIcon:(PDFAnnot *)annot :(UIViewController *)vc +-(void)setIcon:(RDPDFAnnot *)annot :(UIViewController *)vc { m_atype = [annot type]; m_vc = vc; @@ -90,8 +91,8 @@ -(int)icon return m_icon; } -#define ICON_WIDTH 120 -#define ICON_HEIGHT 20 +#define ICON_WIDTH 150 +#define ICON_HEIGHT 40 -(void)tapItem:(UITapGestureRecognizer *)tap { CGPoint pt = [tap locationInView:m_view]; @@ -102,11 +103,14 @@ -(void)tapItem:(UITapGestureRecognizer *)tap -(void)tapAction:(id)sendor { + UIView *container = [(PDFDialog *)m_vc popView]; + container.hidden = YES; + CGRect frame = self.frame; frame.origin.x = 0; frame.origin.y = 0; frame = [self convertRect:frame toView:m_vc.view]; - frame.origin.x += frame.size.width; + //frame.origin.x += frame.size.width; frame.size.width = ICON_WIDTH; int items_cnt = 0; if(m_atype == 1) @@ -116,32 +120,36 @@ -(void)tapAction:(id)sendor frame.size.height = items_cnt * ICON_HEIGHT; CGRect rect = m_vc.view.frame; if(frame.origin.y + frame.size.height > rect.origin.y + rect.size.height) - frame.origin.y = rect.origin.y + rect.size.height - frame.size.height; - UIView *view = [[UIView alloc] initWithFrame: frame]; + frame.origin.y = rect.origin.y + rect.size.height - frame.size.height - 20; + if(frame.origin.x + frame.size.width > rect.size.width) + frame.origin.x = frame.origin.x - ((frame.origin.x + frame.size.width) - rect.size.width); + UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, container.frame.size.width, container.frame.size.height)]; + view.contentSize = CGSizeMake(ICON_WIDTH, 16 + items_cnt * ICON_HEIGHT); + view.scrollEnabled = YES; + view.clipsToBounds = YES; + //UIView *view = [[UIView alloc] initWithFrame: frame]; m_view = view; - view.backgroundColor = [UIColor whiteColor]; - m_popup = [[PDFPopupCtrl alloc] init:view]; m_dibs = [[NSMutableArray alloc] init]; UIImageView *lv; UILabel *lab; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapItem:)]; - UIFont *font = [UIFont systemFontOfSize:12]; + UIFont *font = [UIFont systemFontOfSize:15]; [view addGestureRecognizer:tap]; if(m_atype == 1) { for(int cur = 0; cur < items_cnt; cur++) { - lv = [[UIImageView alloc] initWithFrame:CGRectMake(0, cur * ICON_HEIGHT, ICON_HEIGHT, ICON_HEIGHT)]; + lv = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8 + cur * ICON_HEIGHT, ICON_HEIGHT, ICON_HEIGHT)]; lv.tag = 0; - PDFDIB *dib = [[PDFDIB alloc] init:48 :48]; + RDPDFDIB *dib = [[RDPDFDIB alloc] init:48 :48]; [dib erase:-1]; Global_drawAnnotIcon(m_atype, cur, [dib handle]); [m_dibs addObject:dib]; lv.image = [[UIImage alloc] initWithCGImage:[dib image]]; [view addSubview:lv]; - lab = [[UILabel alloc] initWithFrame:CGRectMake(ICON_HEIGHT, cur * ICON_HEIGHT, ICON_WIDTH - ICON_HEIGHT, ICON_HEIGHT)]; + lab = [[UILabel alloc] initWithFrame:CGRectMake(16 + ICON_HEIGHT, 8 + cur * ICON_HEIGHT, ICON_WIDTH - ICON_HEIGHT, ICON_HEIGHT)]; lab.tag = 0; lab.text = [NSString stringWithUTF8String:g_note_icon_names[cur]]; [lab setFont:font]; @@ -152,23 +160,31 @@ -(void)tapAction:(id)sendor { for(int cur = 0; cur < items_cnt; cur++) { - lv = [[UIImageView alloc] initWithFrame:CGRectMake(0, cur * ICON_HEIGHT, ICON_HEIGHT, ICON_HEIGHT)]; + lv = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8 + cur * ICON_HEIGHT, ICON_HEIGHT, ICON_HEIGHT)]; lv.tag = 0; - PDFDIB *dib = [[PDFDIB alloc] init:48 :48]; + lv.clipsToBounds = YES; + RDPDFDIB *dib = [[RDPDFDIB alloc] init:48 :48]; [dib erase:-1]; Global_drawAnnotIcon(m_atype, cur, [dib handle]); [m_dibs addObject:dib]; lv.image = [[UIImage alloc] initWithCGImage:[dib image]]; [view addSubview:lv]; - lab = [[UILabel alloc] initWithFrame:CGRectMake(ICON_HEIGHT, cur * ICON_HEIGHT, ICON_WIDTH - ICON_HEIGHT, ICON_HEIGHT)]; + lab = [[UILabel alloc] initWithFrame:CGRectMake(16 + ICON_HEIGHT, 8 + cur * ICON_HEIGHT, ICON_WIDTH - ICON_HEIGHT, ICON_HEIGHT)]; lab.tag = 0; lab.text = [NSString stringWithUTF8String:g_attach_icon_names[cur]]; [lab setFont:font]; [view addSubview:lab]; } } - + + UILShadowView *bgView = [[UILShadowView alloc] initWithFrame:container.frame]; + [bgView addSubview:view]; + bgView.center = container.center; + m_popup = [[PDFPopupCtrl alloc] init:bgView]; + [m_popup setDismiss:^{ + container.hidden = NO; + }]; [m_vc presentViewController:m_popup animated:NO completion:nil]; } @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.h b/src/ios/PDFViewer/PDFReader/UILHeadView.h old mode 100644 new mode 100755 similarity index 82% rename from src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.h rename to src/ios/PDFViewer/PDFReader/UILHeadView.h index 6ae59567..be87d066 --- a/src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.h +++ b/src/ios/PDFViewer/PDFReader/UILHeadView.h @@ -8,6 +8,8 @@ #pragma once #import +#import "../UILElement.h" +#import "../PDFView/PDFPopupCtrl.h" typedef void(^func_lhead)(int); @interface UILHeadView : UIView { @@ -18,10 +20,11 @@ typedef void(^func_lhead)(int); -(void)setStyle:(int)style; @end -@interface UILHeadBtn : UIView +@interface UILHeadBtn : UILElement { int m_style; UIViewController *m_vc; + PDFPopupCtrl *pop; } -(id)initWithCoder:(NSCoder *)aDecoder; -(id)initWithFrame:(CGRect)frame; diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.m b/src/ios/PDFViewer/PDFReader/UILHeadView.m old mode 100644 new mode 100755 similarity index 72% rename from src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.m rename to src/ios/PDFViewer/PDFReader/UILHeadView.m index 1614ef9e..dc0ab338 --- a/src/ios/PDFViewer/Modules/AnnotProp/UILHeadView.m +++ b/src/ios/PDFViewer/PDFReader/UILHeadView.m @@ -8,7 +8,23 @@ #import #import "UILHeadView.h" -#import "PDFPopupCtrl.h" +#import "PDFDialog.h" +#import "UILShadowView.h" + +const char *arrowType[] = +{ + "None", + "Arrow", + "Closed", + "Square", + "Circle", + "Butt", + "Diamond", + "Reverted", + "Reverted Closed", + "Slash" +}; + @implementation UILHeadView -(id)init:(CGRect)frame :(func_lhead)callback { @@ -133,91 +149,117 @@ -(id)initWithFrame:(CGRect)frame } -(void)tapAction:(id)sendor { -#define LHEAD_HEIGHT 20 -#define LHEAD_WIDTH 60 +#define LHEAD_HEIGHT 40 +#define LHEAD_WIDTH 100 + UIView *container = [(PDFDialog *)m_vc popView]; + container.hidden = YES; + CGRect frame = self.frame; frame.origin.x = 0; frame.origin.y = 0; frame = [self convertRect:frame toView:m_vc.view]; - frame.origin.x += frame.size.width; + //frame.origin.x += frame.size.width; frame.size.width = LHEAD_WIDTH; frame.size.height = LHEAD_HEIGHT * 10; CGRect rect = m_vc.view.frame; if(frame.origin.y + frame.size.height > rect.origin.y + rect.size.height) - frame.origin.y = rect.origin.y + rect.size.height - frame.size.height; - UIView *view = [[UIView alloc] initWithFrame: frame]; - PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; + frame.origin.y = rect.origin.y + rect.size.height - frame.size.height - 20; + + UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, container.frame.size.width, container.frame.size.height)]; + view.contentSize = CGSizeMake(LHEAD_WIDTH, 16 + LHEAD_HEIGHT * 10); + view.scrollEnabled = YES; + UILShadowView *bgView = [[UILShadowView alloc] initWithFrame:container.frame]; + [bgView addSubview:view]; + bgView.center = container.center; + pop = [[PDFPopupCtrl alloc] init:bgView]; + [pop setDismiss:^{ + container.hidden = NO; + }]; + UILHeadView *lv; UILHeadBtn *thiz = self; - lv = [[UILHeadView alloc] init:CGRectMake(0, 0, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:0]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:1]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:1]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 2, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 2, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:2]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:2]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 3, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 3, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:3]; + [view addSubview:[self getLineLabelAtIdx:3]]; [view addSubview:lv]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 4, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 4, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:4]; + [view addSubview:[self getLineLabelAtIdx:4]]; [view addSubview:lv]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 5, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 5, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:5]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:5]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 6, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 6, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:6]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:6]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 7, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 7, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:7]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:7]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 8, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 8, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:8]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:8]]; - lv = [[UILHeadView alloc] init:CGRectMake(0, LHEAD_HEIGHT * 9, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { + lv = [[UILHeadView alloc] init:CGRectMake(8, 8 + LHEAD_HEIGHT * 9, LHEAD_WIDTH, LHEAD_HEIGHT) :^(int style) { [thiz updateStyle:style]; [pop dismiss]; }]; [lv setStyle:9]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:9]]; + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateStyleFromGesture:)]; + [view addGestureRecognizer:tap]; [m_vc presentViewController:pop animated:NO completion:nil]; } @@ -236,8 +278,8 @@ -(void)drawRect:(CGRect)rect CGRect rc = self.bounds; CGFloat midy = rc.size.height * 0.5f; - CGContextMoveToPoint(ctx, 10, midy); - CGContextAddLineToPoint(ctx, rc.size.width - 2, midy); + CGContextMoveToPoint(ctx, 8, midy); + CGContextAddLineToPoint(ctx, rc.size.width - 8, midy); switch(m_style) { @@ -305,4 +347,23 @@ -(int)style { return m_style; } + +- (UILabel *)getLineLabelAtIdx:(int)idx +{ + UIFont *font = [UIFont systemFontOfSize:15]; + UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16 + LHEAD_WIDTH, 8 + idx * LHEAD_HEIGHT, 120, LHEAD_HEIGHT)]; + lab.tag = idx; + lab.text = [NSString stringWithUTF8String:arrowType[idx]]; + [lab setFont:font]; + return lab; +} + +- (void)updateStyleFromGesture:(UITapGestureRecognizer *)tap +{ + CGPoint pt = [tap locationInView:[tap view]]; + [self updateStyle:pt.y / LHEAD_HEIGHT]; + [pop dismiss]; +} + + @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.h b/src/ios/PDFViewer/PDFReader/UILStyleView.h old mode 100644 new mode 100755 similarity index 83% rename from src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.h rename to src/ios/PDFViewer/PDFReader/UILStyleView.h index e39ea8f4..9fd414f2 --- a/src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.h +++ b/src/ios/PDFViewer/PDFReader/UILStyleView.h @@ -8,6 +8,8 @@ #pragma once #import +#import "../UILElement.h" +#import "../PDFView/PDFPopupCtrl.h" typedef void(^func_lstyle)(const CGFloat *, int); @interface UILStyleView : UIView @@ -20,14 +22,14 @@ typedef void(^func_lstyle)(const CGFloat *, int); -(void)setDash:(const CGFloat *)dash :(int)dash_cnt; @end -@interface UILStyleBtn : UIView +@interface UILStyleBtn : UILElement { CGFloat m_dashs[4]; int m_dashs_cnt; UIViewController *m_vc; + PDFPopupCtrl *pop; } --(id)initWithCoder:(NSCoder *)aDecoder; --(id)initWithFrame:(CGRect)frame; + -(void)setDash:(const CGFloat *)dash :(int)dash_cnt :(UIViewController *)vc; -(const CGFloat *)dash; -(int)dashCnt; diff --git a/src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.m b/src/ios/PDFViewer/PDFReader/UILStyleView.m old mode 100644 new mode 100755 similarity index 63% rename from src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.m rename to src/ios/PDFViewer/PDFReader/UILStyleView.m index ac1977b7..428a4156 --- a/src/ios/PDFViewer/Modules/AnnotProp/UILStyleView.m +++ b/src/ios/PDFViewer/PDFReader/UILStyleView.m @@ -9,6 +9,19 @@ #import #import "UILStyleView.h" #import "PDFPopupCtrl.h" +#import "PDFDialog.h" +#import "UILShadowView.h" + +const char *lineType[] = +{ + "Style 1", + "Style 2", + "Style 3", + "Style 4", + "Style 5", + "Style 6" +}; + @implementation UILStyleView -(id)init:(CGRect)frame :(func_lstyle)callback { @@ -96,8 +109,8 @@ -(void)drawRect:(CGRect)rect CGContextSetLineWidth(ctx, 1); CGRect rc = self.bounds; CGFloat midy = rc.size.height * 0.5f; - CGContextMoveToPoint(ctx, 2, midy); - CGContextAddLineToPoint(ctx, rc.size.width - 2, midy); + CGContextMoveToPoint(ctx, 8, midy); + CGContextAddLineToPoint(ctx, rc.size.width - 8, midy); CGContextDrawPath(ctx, kCGPathStroke); CGContextRestoreGState(ctx); @@ -129,32 +142,45 @@ -(void)update:(const CGFloat *)dash :(int)dash_cnt } -(void)tapAction:(id)sendor { -#define LSTYLE_HEIGHT 30 -#define LSTYLE_WIDTH 60 +#define LSTYLE_HEIGHT 40 +#define LSTYLE_WIDTH 100 + UIView *container = [(PDFDialog *)m_vc popView]; + container.hidden = YES; + CGRect frame = self.frame; frame.origin.x = 0; frame.origin.y = 0; frame = [self convertRect:frame toView:m_vc.view]; - frame.origin.x += frame.size.width; + //frame.origin.x += frame.size.width; frame.size.width = LSTYLE_WIDTH; frame.size.height = LSTYLE_HEIGHT * 6; CGRect rect = m_vc.view.frame; if(frame.origin.y + frame.size.height > rect.origin.y + rect.size.height) frame.origin.y = rect.origin.y + rect.size.height - frame.size.height; - UIView *view = [[UIView alloc] initWithFrame: frame]; - PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; + + UIScrollView *view = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, container.frame.size.width, LSTYLE_HEIGHT * 6 + 16)]; + view.contentSize = CGSizeMake(LSTYLE_WIDTH, 16 + LSTYLE_HEIGHT * 6); + view.scrollEnabled = YES; + UILShadowView *bgView = [[UILShadowView alloc] initWithFrame:CGRectMake(container.frame.origin.x, container.frame.origin.y, container.frame.size.width, LSTYLE_HEIGHT * 6 + 16)]; + [bgView addSubview:view]; + bgView.center = container.center; + pop = [[PDFPopupCtrl alloc] init:bgView]; + [pop setDismiss:^{ + container.hidden = NO; + }]; UILStyleView *lv; UILStyleBtn *thiz = self; CGFloat tdash[4]; - lv = [[UILStyleView alloc] init:CGRectMake(0, 0, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:0]]; - lv = [[UILStyleView alloc] init:CGRectMake(0, LSTYLE_HEIGHT, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8 + LSTYLE_HEIGHT, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; @@ -162,8 +188,9 @@ -(void)tapAction:(id)sendor tdash[1] = 1; [lv setDash:tdash :2]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:1]]; - lv = [[UILStyleView alloc] init:CGRectMake(0, LSTYLE_HEIGHT * 2, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8 + LSTYLE_HEIGHT * 2, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; @@ -171,8 +198,9 @@ -(void)tapAction:(id)sendor tdash[1] = 2; [lv setDash:tdash :2]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:2]]; - lv = [[UILStyleView alloc] init:CGRectMake(0, LSTYLE_HEIGHT * 3, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8 + LSTYLE_HEIGHT * 3, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; @@ -180,8 +208,9 @@ -(void)tapAction:(id)sendor tdash[1] = 4; [lv setDash:tdash :2]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:3]]; - lv = [[UILStyleView alloc] init:CGRectMake(0, LSTYLE_HEIGHT * 4, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8 + LSTYLE_HEIGHT * 4, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; @@ -191,8 +220,9 @@ -(void)tapAction:(id)sendor tdash[3] = 2; [lv setDash:tdash :4]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:4]]; - lv = [[UILStyleView alloc] init:CGRectMake(0, LSTYLE_HEIGHT * 5, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { + lv = [[UILStyleView alloc] init:CGRectMake(8, 8 + LSTYLE_HEIGHT * 5, LSTYLE_WIDTH, LSTYLE_HEIGHT) :^(const CGFloat *dash, int dash_cnt) { [thiz update:dash :dash_cnt]; [pop dismiss]; }]; @@ -202,8 +232,26 @@ -(void)tapAction:(id)sendor tdash[3] = 2; [lv setDash:tdash :4]; [view addSubview:lv]; + [view addSubview:[self getLineLabelAtIdx:5]]; + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateStyleFromGesture:)]; + [view addGestureRecognizer:tap]; [m_vc presentViewController:pop animated:NO completion:nil]; } +- (UILabel *)getLineLabelAtIdx:(int)idx +{ + UIFont *font = [UIFont systemFontOfSize:15]; + UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16 + LSTYLE_WIDTH, 8 + idx * LSTYLE_HEIGHT, 120, LSTYLE_HEIGHT)]; + lab.tag = 0; + lab.text = [NSString stringWithUTF8String:lineType[idx]]; + [lab setFont:font]; + return lab; +} + +- (void)updateStyleFromGesture:(UITapGestureRecognizer *)tap +{ +} + @end diff --git a/src/ios/PDFViewer/fdat/GUST e-foundry License.txt b/src/ios/PDFViewer/PDFRes/GUST e-foundry License.txt similarity index 100% rename from src/ios/PDFViewer/fdat/GUST e-foundry License.txt rename to src/ios/PDFViewer/PDFRes/GUST e-foundry License.txt diff --git a/src/ios/PDFViewer/cmaps/cmaps.dat b/src/ios/PDFViewer/PDFRes/cmaps/cmaps.dat similarity index 100% rename from src/ios/PDFViewer/cmaps/cmaps.dat rename to src/ios/PDFViewer/PDFRes/cmaps/cmaps.dat diff --git a/src/ios/PDFViewer/cmaps/cmyk_rgb.dat b/src/ios/PDFViewer/PDFRes/cmaps/cmyk_rgb.dat similarity index 100% rename from src/ios/PDFViewer/cmaps/cmyk_rgb.dat rename to src/ios/PDFViewer/PDFRes/cmaps/cmyk_rgb.dat diff --git a/src/ios/PDFViewer/cmaps/umaps.dat b/src/ios/PDFViewer/PDFRes/cmaps/umaps.dat similarity index 100% rename from src/ios/PDFViewer/cmaps/umaps.dat rename to src/ios/PDFViewer/PDFRes/cmaps/umaps.dat diff --git a/src/ios/PDFViewer/PDFRes/enc.pdf b/src/ios/PDFViewer/PDFRes/enc.pdf new file mode 100755 index 00000000..d4672fec Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/enc.pdf differ diff --git a/src/ios/PDFViewer/fdat/fld.pdf b/src/ios/PDFViewer/PDFRes/fld.pdf old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/fdat/fld.pdf rename to src/ios/PDFViewer/PDFRes/fld.pdf diff --git a/src/ios/PDFViewer/PDFRes/fonts/NotoSansCJK-Regular.ttc b/src/ios/PDFViewer/PDFRes/fonts/NotoSansCJK-Regular.ttc new file mode 100644 index 00000000..271526fb Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/fonts/NotoSansCJK-Regular.ttc differ diff --git a/src/ios/PDFViewer/PDFRes/fonts/Symbol Neu for Powerline.ttf b/src/ios/PDFViewer/PDFRes/fonts/Symbol Neu for Powerline.ttf new file mode 100644 index 00000000..85e95acf Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/fonts/Symbol Neu for Powerline.ttf differ diff --git a/src/ios/PDFViewer/fdat/stdFont/argbsn00lp.ttf b/src/ios/PDFViewer/PDFRes/fonts/argbsn00lp.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/argbsn00lp.ttf rename to src/ios/PDFViewer/PDFRes/fonts/argbsn00lp.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/arimo.ttf b/src/ios/PDFViewer/PDFRes/fonts/arimo.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/arimo.ttf rename to src/ios/PDFViewer/PDFRes/fonts/arimo.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/arimob.ttf b/src/ios/PDFViewer/PDFRes/fonts/arimob.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/arimob.ttf rename to src/ios/PDFViewer/PDFRes/fonts/arimob.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/arimobi.ttf b/src/ios/PDFViewer/PDFRes/fonts/arimobi.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/arimobi.ttf rename to src/ios/PDFViewer/PDFRes/fonts/arimobi.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/arimoi.ttf b/src/ios/PDFViewer/PDFRes/fonts/arimoi.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/arimoi.ttf rename to src/ios/PDFViewer/PDFRes/fonts/arimoi.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/cousine.ttf b/src/ios/PDFViewer/PDFRes/fonts/cousine.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/cousine.ttf rename to src/ios/PDFViewer/PDFRes/fonts/cousine.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/cousineb.ttf b/src/ios/PDFViewer/PDFRes/fonts/cousineb.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/cousineb.ttf rename to src/ios/PDFViewer/PDFRes/fonts/cousineb.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/cousinebi.ttf b/src/ios/PDFViewer/PDFRes/fonts/cousinebi.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/cousinebi.ttf rename to src/ios/PDFViewer/PDFRes/fonts/cousinebi.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/cousinei.ttf b/src/ios/PDFViewer/PDFRes/fonts/cousinei.ttf similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/cousinei.ttf rename to src/ios/PDFViewer/PDFRes/fonts/cousinei.ttf diff --git a/src/ios/PDFViewer/fdat/stdFont/rdf008.dat b/src/ios/PDFViewer/PDFRes/fonts/rdf008.dat similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/rdf008.dat rename to src/ios/PDFViewer/PDFRes/fonts/rdf008.dat diff --git a/src/ios/PDFViewer/fdat/stdFont/rdf013.dat b/src/ios/PDFViewer/PDFRes/fonts/rdf013.dat similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/rdf013.dat rename to src/ios/PDFViewer/PDFRes/fonts/rdf013.dat diff --git a/src/ios/PDFViewer/fdat/stdFont/texgyretermes-bold.otf b/src/ios/PDFViewer/PDFRes/fonts/texgyretermes-bold.otf old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/texgyretermes-bold.otf rename to src/ios/PDFViewer/PDFRes/fonts/texgyretermes-bold.otf diff --git a/src/ios/PDFViewer/fdat/stdFont/texgyretermes-bolditalic.otf b/src/ios/PDFViewer/PDFRes/fonts/texgyretermes-bolditalic.otf old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/texgyretermes-bolditalic.otf rename to src/ios/PDFViewer/PDFRes/fonts/texgyretermes-bolditalic.otf diff --git a/src/ios/PDFViewer/fdat/stdFont/texgyretermes-italic.otf b/src/ios/PDFViewer/PDFRes/fonts/texgyretermes-italic.otf old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/texgyretermes-italic.otf rename to src/ios/PDFViewer/PDFRes/fonts/texgyretermes-italic.otf diff --git a/src/ios/PDFViewer/fdat/stdFont/texgyretermes-regular.otf b/src/ios/PDFViewer/PDFRes/fonts/texgyretermes-regular.otf old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/fdat/stdFont/texgyretermes-regular.otf rename to src/ios/PDFViewer/PDFRes/fonts/texgyretermes-regular.otf diff --git a/src/ios/PDFViewer/fdat/help.pdf b/src/ios/PDFViewer/PDFRes/help.pdf similarity index 100% rename from src/ios/PDFViewer/fdat/help.pdf rename to src/ios/PDFViewer/PDFRes/help.pdf diff --git a/src/ios/PDFViewer/PDFRes/outlines.pdf b/src/ios/PDFViewer/PDFRes/outlines.pdf new file mode 100755 index 00000000..87895f19 Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/outlines.pdf differ diff --git a/src/ios/PDFViewer/PDFRes/test.pdf b/src/ios/PDFViewer/PDFRes/test.pdf new file mode 100755 index 00000000..e429557b Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/test.pdf differ diff --git a/src/ios/PDFViewer/PDFRes/test.pfx b/src/ios/PDFViewer/PDFRes/test.pfx new file mode 100644 index 00000000..10583879 Binary files /dev/null and b/src/ios/PDFViewer/PDFRes/test.pfx differ diff --git a/src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.h b/src/ios/PDFViewer/PDFView/ActionStackManager.h old mode 100644 new mode 100755 similarity index 82% rename from src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.h rename to src/ios/PDFViewer/PDFView/ActionStackManager.h index 8e702216..8c037621 --- a/src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.h +++ b/src/ios/PDFViewer/PDFView/ActionStackManager.h @@ -16,20 +16,20 @@ @property (nonatomic) PDF_OBJ_REF hand; - (instancetype)initWithPage:(int)pgno index:(int)idx; -- (void)undo:(PDFDoc *)doc; -- (void)redo:(PDFDoc *)doc; +- (void)undo:(RDPDFDoc *)doc; +- (void)redo:(RDPDFDoc *)doc; - (int)pageno:(int)idx; @end @interface ASDel : ASItem -- (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx; +- (instancetype)initWithPage:(int)pgno page:(RDPDFPage *)page index:(int)idx; @end @interface ASAdd : ASItem -- (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx; +- (instancetype)initWithPage:(int)pgno page:(RDPDFPage *)page index:(int)idx; @end @@ -53,7 +53,7 @@ } - (void)push:(ASItem *)item; - +- (void)clear; - (ASItem *)undo; - (ASItem *)redo; - (int)cur; diff --git a/src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.m b/src/ios/PDFViewer/PDFView/ActionStackManager.m old mode 100644 new mode 100755 similarity index 76% rename from src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.m rename to src/ios/PDFViewer/PDFView/ActionStackManager.m index 84277cd0..e5a0edc1 --- a/src/ios/PDFViewer/Modules/ActionStack/ActionStackManager.m +++ b/src/ios/PDFViewer/PDFView/ActionStackManager.m @@ -17,10 +17,10 @@ - (instancetype)initWithPage:(int)pgno index:(int)idx return self; } -- (void)undo:(PDFDoc *)doc +- (void)undo:(RDPDFDoc *)doc {} -- (void)redo:(PDFDoc *)doc +- (void)redo:(RDPDFDoc *)doc {} - (int)pageno:(int)idx { @@ -31,7 +31,7 @@ - (int)pageno:(int)idx @implementation ASDel -- (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx +- (instancetype)initWithPage:(int)pgno page:(RDPDFPage *)page index:(int)idx { self = [super initWithPage:pgno index:idx]; self.hand = [[page annotAtIndex:idx] getRef]; @@ -40,20 +40,20 @@ - (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx } #pragma mark - Override -- (void)undo:(PDFDoc *)doc +- (void)undo:(RDPDFDoc *)doc { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; self.m_idx = [page annotCount]; [page addAnnot:self.hand :self.m_idx]; page = nil; } -- (void)redo:(PDFDoc *)doc +- (void)redo:(RDPDFDoc *)doc { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; - PDFAnnot *annot = [page annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page annotAtIndex:self.m_idx]; [annot removeFromPage]; page = nil; } @@ -62,7 +62,7 @@ - (void)redo:(PDFDoc *)doc @implementation ASAdd -- (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx +- (instancetype)initWithPage:(int)pgno page:(RDPDFPage *)page index:(int)idx { self = [super initWithPage:pgno index:idx]; self.hand = [[page annotAtIndex:idx] getRef]; @@ -71,18 +71,18 @@ - (instancetype)initWithPage:(int)pgno page:(PDFPage *)page index:(int)idx } #pragma mark - Override -- (void)undo:(PDFDoc *)doc +- (void)undo:(RDPDFDoc *)doc { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; - PDFAnnot *annot = [page annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page annotAtIndex:self.m_idx]; [annot removeFromPage]; page = nil; } -- (void)redo:(PDFDoc *)doc +- (void)redo:(RDPDFDoc *)doc { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; self.m_idx = [page annotCount]; [page addAnnot:self.hand :self.m_idx]; @@ -108,22 +108,22 @@ - (instancetype)initWithPage:(int)src_pageno initRect:(PDF_RECT)src_rect destPag } #pragma mark - Override -- (void)undo:(PDFDoc *)doc +- (void)undo:(RDPDFDoc *)doc { self.reorder = false; self.m_pageno = self.m_pageno0; if (self.m_pageno == self.m_pageno1) { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; - PDFAnnot *annot = [page annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page annotAtIndex:self.m_idx]; [annot setRect:&m_rect0]; page = nil; } else { - PDFPage *page0 = [doc page:self.m_pageno0]; - PDFPage *page1 = [doc page:self.m_pageno1]; + RDPDFPage *page0 = [doc page:self.m_pageno0]; + RDPDFPage *page1 = [doc page:self.m_pageno1]; [page0 objsStart]; [page1 objsStart]; - PDFAnnot *annot = [page1 annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page1 annotAtIndex:self.m_idx]; [annot MoveToPage:page0 :&m_rect0]; self.m_idx = page0.annotCount - 1; self.reorder = true; @@ -132,22 +132,22 @@ - (void)undo:(PDFDoc *)doc } } -- (void)redo:(PDFDoc *)doc +- (void)redo:(RDPDFDoc *)doc { self.reorder = false; self.m_pageno = self.m_pageno1; if (self.m_pageno == self.m_pageno0) { - PDFPage *page = [doc page:self.m_pageno]; + RDPDFPage *page = [doc page:self.m_pageno]; [page objsStart]; - PDFAnnot *annot = [page annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page annotAtIndex:self.m_idx]; [annot setRect:&m_rect1]; page = nil; } else { - PDFPage *page0 = [doc page:self.m_pageno0]; - PDFPage *page1 = [doc page:self.m_pageno1]; + RDPDFPage *page0 = [doc page:self.m_pageno0]; + RDPDFPage *page1 = [doc page:self.m_pageno1]; [page0 objsStart]; [page1 objsStart]; - PDFAnnot *annot = [page0 annotAtIndex:self.m_idx]; + RDPDFAnnot *annot = [page0 annotAtIndex:self.m_idx]; [annot MoveToPage:page1 :&m_rect1]; self.m_idx = page1.annotCount - 1; self.reorder = true; @@ -239,6 +239,12 @@ - (ASItem *)redo return item; } +- (void)clear +{ + m_stack = [[NSMutableArray alloc] init]; + m_pos = -1; + busy = NO; +} - (int)cur { return m_pos; diff --git a/src/ios/PDFViewer/PDFView/PDFDelegate.h b/src/ios/PDFViewer/PDFView/PDFDelegate.h new file mode 100755 index 00000000..1fa47a6d --- /dev/null +++ b/src/ios/PDFViewer/PDFView/PDFDelegate.h @@ -0,0 +1,16 @@ +// +// PDFDelegate.h +// RDPDFReader +// +// Created by Radaee Lou on 2020/5/5. +// Copyright © 2020 Radaee. All rights reserved. +// + +#ifndef PDFDelegate_h +#define PDFDelegate_h + +@protocol PDFOffScreenDelegate +-(void)onDrawOffScreen :(CGContextRef)ctx; +@end + +#endif /* PDFDelegate_h */ diff --git a/src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.h b/src/ios/PDFViewer/PDFView/PDFDialog.h old mode 100644 new mode 100755 similarity index 89% rename from src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.h rename to src/ios/PDFViewer/PDFView/PDFDialog.h index 72d33628..86598913 --- a/src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.h +++ b/src/ios/PDFViewer/PDFView/PDFDialog.h @@ -7,7 +7,7 @@ // #pragma once - +#import "UILShadowView.h" #import @interface PDFDialogBG : UIView { @@ -21,8 +21,6 @@ typedef void(^func_cb)(BOOL); { UIView *m_back; UIView *m_view; - UIButton *btn_ok; - UIButton *btn_cancel; CGRect m_rect; BOOL m_ok; BOOL m_has_button; @@ -31,4 +29,6 @@ typedef void(^func_cb)(BOOL); @property BOOL ok_pressed; - (id)init:(UIView *)view :(CGRect)rect :(BOOL)has_button :(func_cb)dismiss; - (void)dismiss; +- (UIView *)popView; +- (UIView *)buttonView; @end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.m b/src/ios/PDFViewer/PDFView/PDFDialog.m old mode 100644 new mode 100755 similarity index 62% rename from src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.m rename to src/ios/PDFViewer/PDFView/PDFDialog.m index 639effae..dc991f77 --- a/src/ios/PDFViewer/Modules/AnnotProp/PDFDialog.m +++ b/src/ios/PDFViewer/PDFView/PDFDialog.m @@ -54,7 +54,7 @@ - (id)init:(UIView *)view :(CGRect)rect :(BOOL)has_button :(func_cb)dismiss return self; } -#define DLG_BUTTON_HEIGHT 30 +#define DLG_BUTTON_HEIGHT 40 - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; @@ -62,28 +62,14 @@ - (void)viewDidLayoutSubviews if(m_has_button) { m_rect.origin.x = (rect.size.width - m_rect.size.width) * 0.5f; - m_rect.origin.y = (rect.size.height - m_rect.size.height - DLG_BUTTON_HEIGHT) * 0.5f; + m_rect.origin.y = (rect.size.height - m_rect.size.height - 50) * 0.5f; [m_view setFrame:m_rect]; - [btn_ok setFrame:CGRectMake(m_rect.origin.x, m_rect.origin.y + m_rect.size.height, m_rect.size.width * 0.5f, DLG_BUTTON_HEIGHT)]; - [btn_cancel setFrame:CGRectMake(m_rect.origin.x + m_rect.size.width * 0.5f, m_rect.origin.y + m_rect.size.height, m_rect.size.width * 0.5f, DLG_BUTTON_HEIGHT)]; - [btn_ok.titleLabel setFont:[UIFont systemFontOfSize:12]]; - [btn_cancel.titleLabel setFont:[UIFont systemFontOfSize:12]]; - [btn_ok setTitle:@"OK" forState:UIControlStateNormal]; - [btn_cancel setTitle:@"Cancel" forState:UIControlStateNormal]; - btn_ok.backgroundColor = m_view.backgroundColor; - btn_cancel.backgroundColor = m_view.backgroundColor; - btn_ok.titleLabel.textColor = [UIColor blueColor]; - btn_cancel.titleLabel.textColor = [UIColor blueColor]; - btn_ok.hidden = NO; - btn_cancel.hidden = NO; } else { m_rect.origin.x = (rect.size.width - m_rect.size.width) * 0.5f; m_rect.origin.y = (rect.size.height - m_rect.size.height) * 0.5f; [m_view setFrame:m_rect]; - btn_ok.hidden = YES; - btn_cancel.hidden = YES; } } @@ -95,20 +81,24 @@ - (void)OnOK:(id)sender - (void)OnCancel:(id)sender { + [self dismiss]; } - (void)viewDidLoad { [super viewDidLoad]; + if ([m_view isKindOfClass:[UILShadowView class]]) { + [[(UILShadowView *)m_view buttonView] setHidden:!m_has_button]; + if (m_has_button) { + [[(UILShadowView *)m_view okButton] addTarget:self action:@selector(OnOK:) forControlEvents:UIControlEventTouchUpInside]; + [[(UILShadowView *)m_view cancelButton] addTarget:self action:@selector(OnCancel:) forControlEvents:UIControlEventTouchUpInside]; + } + } m_back = [[PDFDialogBG alloc] init:m_view]; self.view = m_back; - btn_ok = [[UIButton alloc] init]; - btn_cancel = [[UIButton alloc] init]; - [m_back addSubview:btn_ok]; - [m_back addSubview:btn_cancel]; - [btn_ok addTarget:self action:@selector(OnOK:) forControlEvents:UIControlEventTouchUpInside]; - [btn_cancel addTarget:self action:@selector(OnCancel:) forControlEvents:UIControlEventTouchUpInside]; + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnCancel:)]; + [self.view addGestureRecognizer:tap]; } - (void)dismiss @@ -117,4 +107,8 @@ - (void)dismiss if(m_dismiss) m_dismiss(m_ok); } +- (UIView *)popView { + return m_view; +} + @end diff --git a/src/ios/PDFViewer/PDFView/PDFGridView.h b/src/ios/PDFViewer/PDFView/PDFGridView.h old mode 100644 new mode 100755 index fac0799f..06450886 --- a/src/ios/PDFViewer/PDFView/PDFGridView.h +++ b/src/ios/PDFViewer/PDFView/PDFGridView.h @@ -16,7 +16,7 @@ int thumbBackgroundColor; } - (id)initWithFrame:(CGRect)frame; -- (BOOL)PDFOpen :(PDFDoc *)doc :(int)page_gap :(id)del; +- (BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(id)del; - (void)PDFUpdatePage:(int)pageno; - (void)setThumbBackgroundColor:(int)color; @end diff --git a/src/ios/PDFViewer/PDFView/PDFGridView.m b/src/ios/PDFViewer/PDFView/PDFGridView.m old mode 100644 new mode 100755 index 8f80869d..865983da --- a/src/ios/PDFViewer/PDFView/PDFGridView.m +++ b/src/ios/PDFViewer/PDFView/PDFGridView.m @@ -22,14 +22,18 @@ -(id)initWithFrame:(CGRect)frame } return self; } +-(void)ProOnTimer:(NSTimer *)sender +{ + [self setNeedsDisplay]; +} --(BOOL)PDFOpen :(PDFDoc *)doc :(int)page_gap :(id)del +-(BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(id)del { [self PDFClose]; m_zoom = 1; m_doc = doc; m_delegate = del; - self.m_del = nil; + m_del = nil; page_gap = 1; m_sel_pno = -1; m_layout = [[RDVLayoutGrid alloc] init:self :100 :5]; diff --git a/src/ios/PDFViewer/PDFView/PDFLayoutView.h b/src/ios/PDFViewer/PDFView/PDFLayoutView.h old mode 100644 new mode 100755 index 8111032a..761ed401 --- a/src/ios/PDFViewer/PDFView/PDFLayoutView.h +++ b/src/ios/PDFViewer/PDFView/PDFLayoutView.h @@ -9,7 +9,7 @@ #import "PDFObjc.h" #import "RDVLayout.h" #import "RDVFinder.h" -#import "PDFOffScreenView.h" +#import "PDFDelegate.h" #define UIColorFromRGB(rgbValue) \ [UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ @@ -27,29 +27,29 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] - (void)OnSelStart:(float)x :(float)y; - (void)OnSelEnd:(float)x1 :(float)y1 :(float)x2 :(float)y2; //enter annotation status. -- (void)OnAnnotClicked:(PDFAnnot *)annot :(CGRect)annotRect :(float)x :(float)y; +- (void)OnAnnotClicked:(RDPDFAnnot *)annot :(CGRect)annotRect :(float)x :(float)y; //notified when annotation status end. - (void)OnAnnotEnd; //this mehod fired only when vAnnotPerform method invoked. - (void)OnAnnotGoto:(int)pageno; //this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotPopup:(PDFAnnot *)annot; -//this mehod fired only when vAnnotPerform method invoked. - (void)OnAnnotOpenURL:(NSString *)url; //this mehod fired only when vAnnotPerform method invoked. - (void)OnAnnotMovie:(NSString *)fileName; //this mehod fired only when vAnnotPerform method invoked. - (void)OnAnnotSound:(NSString *)fileName; -- (void)OnAnnotEditBox:(PDFAnnot *)annot :(CGRect)annotRect :(NSString *)editText :(float)textSize; -- (void)OnAnnotCommboBox:(PDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selected:(int)index; -- (void)OnAnnotList:(PDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selectedIndexes:(NSArray *)indexes; -- (void)OnAnnotSignature:(PDFAnnot *)annot; -- (void)OnAnnotTapped:(PDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point; +- (void)OnAnnotEditBox:(RDPDFAnnot *)annot :(CGRect)annotRect :(NSString *)editText :(float)textSize; +- (void)OnAnnotCommboBox:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selected:(int)index; +- (void)OnAnnotList:(RDVPage *)vp :(RDPDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selectedIndexes:(NSArray *)indexes; +- (void)OnAnnotSignature:(RDVPage *)vp :(RDPDFAnnot *)annot; +- (void)OnAnnotTapped:(RDPDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point; +- (void)OnEditboxOK; @end -@interface PDFLayoutView : UIScrollView +@class RDPDFCanvas; +@interface PDFLayoutView : UIScrollView { - PDFDoc *m_doc; + RDPDFDoc *m_doc; RDVLayout *m_layout; NSTimer *m_timer; enum LAYOUT_STATUS @@ -63,15 +63,19 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] sta_rect, sta_ellipse, sta_line, - sta_image + sta_image, + sta_editbox, + sta_polygon, + sta_polyline, }; enum LAYOUT_STATUS m_status; float m_scale_pix; float m_zoom; RDVPos m_zoom_pos; CGPoint zoomPoint; - PDFOffScreenView *m_child; - + UIView *m_child; + RDPDFCanvas *m_canvas; + id m_del; bool m_modified; NSTimeInterval m_tstamp; NSTimeInterval m_tstamp_tap; @@ -88,10 +92,11 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] RDVSel *m_sel; RDVPos m_sel_pos; - PDFInk *m_ink; + RDPDFInk *m_ink; + RDPDFPath *m_polygon; int m_annot_idx; - PDFAnnot *m_annot; + RDPDFAnnot *m_annot; RDVPos m_annot_pos; PDF_RECT m_annot_rect; @@ -113,34 +118,45 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] bool m_ellipse_drawing; BOOL readOnlyEnabled; - BOOL doublePage; - UIImageView *imgAnnot; NSString *tmpImage; double lastAngle; BOOL isResizing; BOOL isRotating; - BOOL coverPage; + BOOL isDecelerating; + BOOL isAnimating; + BOOL singlePage; + BOOL doublePage; + BOOL firstPageSingle; - int doubleTapZoomMode; - int readerBackgroundColor; + CGPoint touchBeginPoint; + CGPoint touchPoint; + CGPoint touchEndPoint; + CGPoint animatePoint; - PDFPage *tappedPage; + NSTimeInterval m_doubleTapTime; + int m_doubleTapCount; - bool isDoubleTapping; -#ifdef FTS_ENABLED - FTSOccurrence *currentOccurrence; -#endif + NSDate *touchBeginTime; + NSDate *touchEndTime; + int begin_touch_page; + + int doubleTapZoomMode; + int readerBackgroundColor; + RDPDFPage *tappedPage; } -@property (nonatomic) NSUInteger pageViewNo; -@property (nonatomic, weak) id m_del; +@property (nonatomic) NSUInteger singleViewPageNo; -(id)initWithFrame:(CGRect)frame; --(BOOL)PDFOpen :(PDFDoc *)doc :(int)page_gap :(id)del; +- (id)initWithCoder:(NSCoder *)aDecoder; +-(BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(RDPDFCanvas *)canvas :(id) del; -(void)PDFClose; +-(int)PDFGetVMode; -(void)PDFSetVMode:(int)vmode; +-(void)PDFSaveView; +-(void)PDFRestoreView; //start find. -(bool)vFindStart:(NSString *)pat :(bool)match_case :(bool)whole_word; @@ -155,7 +171,7 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] //you should invoke this method in select mode. -(NSString *)vSelGetText; //you should invoke this method in select mode. --(BOOL)vSelMarkup:(int)color :(int)type; +-(BOOL)vSelMarkup :(int)type; //invoke this method to leave select mode -(void)vSelEnd; @@ -173,6 +189,20 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] //end ink annotation status, and add ink to page. -(void)vInkEnd; +//enter ink annotation status. +-(bool)vPolygonStart; +//end ink annotation status. +-(void)vPolygonCancel; +//end ink annotation status, and add ink to page. +-(void)vPolygonEnd; + +//enter ink annotation status. +-(bool)vPolylineStart; +//end ink annotation status. +-(void)vPolylineCancel; +//end ink annotation status, and add ink to page. +-(void)vPolylineEnd; + //enter line annotation status. -(bool)vLineStart; //end line annotation status. @@ -199,83 +229,55 @@ alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] - (void)vImageEnd; - (BOOL)useTempImage; +//enter editbox annotation status. +-(bool)vEditboxStart; +//end editbox annotation status. +-(void)vEditboxCancel; +//end editbox annotation status, and add rect to page. +-(void)vEditboxEnd; + + //perform annotation actions, and end annotation status. -(void)vAnnotPerform; //remove annotation, and end annotation status. -(void)vAnnotRemove; //end annotation status. -(void)vAnnotEnd; --(void)removeAnnot:(PDFAnnot *)annot; //TextAnnot -- (PDFAnnot *)vGetTextAnnot:(int)x :(int)y; +- (RDPDFAnnot *)vGetTextAnnot:(int)x :(int)y; - (void)vAddTextAnnot:(int)x :(int)y :(NSString *)text :(NSString *)subject; - (void)vGetPos:(RDVPos *)pos; - (void)vGetPos:(RDVPos *)pos x:(int)x y:(int)y; -/** - goto page - - @param pageno page number - */ -(void)vGoto:(int)pageno; - - (void)vUndo; - (void)vRedo; - -- (int)vGetCurrentPage; -- (void)resetZoomLevel; - -- (void)setCommboItem :(int)item; -- (void)setEditBoxWithText :(NSString *)text; - -- (void)setReaderBackgroundColor:(int)color; -- (void)setFirstPageCover:(BOOL)cover; +- (void)vClearOP; +- (void)PDFSetGBColor:(int)color; - (void)setDoubleTapZoomMode:(int)mode; - -/* -- (CGImageRef )vGetImageForPage:(int)pg withSize:(CGSize)size withBackground:(BOOL)hasBackground; -- (float)getViewWidth; -- (float)getViewHeight; -- (BOOL)isCurlEnabled; -*/ - -- (void)refreshCurrentPage; -- (void)refreshCachedPages; - (void)vUpdateAnnotPage; -- (CGFloat)vGetScale; +- (void)vUpdatePage:(int)pageno; +- (void)vUpdateRange; - (CGFloat)vGetPixSize; - (BOOL)isModified; - (void)setModified:(BOOL)modified force:(BOOL)force; -- (void)selectListBoxItems:(NSArray *)items; -- (BOOL)setSignatureImageAtIndex:(int)index atPage:(int)pageNum; - +//functions below is not standard behavious of PDFLayoutView. +- (BOOL)PDFSignField:(RDVPage *)vp :(RDPDFAnnot *)annot; - (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size; -- (NSString *)getImageFromAnnot:(PDFAnnot *)annot; -- (NSString *)emptyImageFromAnnot:(PDFAnnot *)annot; +- (NSString *)getImageFromAnnot:(RDPDFAnnot *)annot; +- (NSString *)emptyImageFromAnnot:(RDPDFAnnot *)annot; - (NSString *)emptyAnnotWithSize:(CGSize)size; - (BOOL)addAttachmentFromPath:(NSString *)path; -- (BOOL)forceSave; - - (BOOL)canSaveDocument; - (void)setReadOnly:(BOOL)enabled; - -#ifdef FTS_ENABLED -- (void)applyFTSOccurrence:(FTSOccurrence *)occurrence; -#endif - -- (BOOL)pagingAvailable; - -- (void)OnDoubleTapOnPoint:(CGPoint)point; - -- (NSString *)getImageFromRect:(int)top :(int)right :(int)left :(int)bottom :(int)pageNum; - (PDF_RECT)pdfRectFromScreenRect:(CGRect)screenRect; - (CGPoint)screenPointsFromPdfPoints:(float)x :(float)y :(int)pageNum; - (CGRect)screenRectFromPdfRect:(float)left :(float)top :(float)right :(float)bottom :(int)pageNum; - +- (RDVFinder *)getView; @end diff --git a/src/ios/PDFViewer/PDFView/PDFLayoutView.m b/src/ios/PDFViewer/PDFView/PDFLayoutView.m old mode 100644 new mode 100755 index 4ec70ae6..91cd7c77 --- a/src/ios/PDFViewer/PDFView/PDFLayoutView.m +++ b/src/ios/PDFViewer/PDFView/PDFLayoutView.m @@ -15,24 +15,23 @@ #import "RDVSel.h" #import "RDUtils.h" #import "ActionStackManager.h" - -/*#import "FTSManager.h"*/ -#import "ReaderHandler.h" +#import "RDPDFView.h" #define TEMP_SIGNATURE @"radaee_signature_temp.png" #define TEMP_SIGNATURE_EMPTY @"radaee_empty_signature_temp.png" @class RDVLayoutDual; @interface PDFLayoutView () { -#ifdef FTS_ENABLED - FTSOccurrence *currentOccurrence; -#endif ActionStackManager *actionManger; } @end @implementation PDFLayoutView +{ + RDVPos m_save_pos; + int m_save_vmode; +} -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; @@ -45,6 +44,42 @@ -(id)initWithFrame:(CGRect)frame m_status = sta_none; m_sel = nil; m_cur_page = -1; + m_save_vmode = 0; + m_doubleTapCount = 0; + self.userInteractionEnabled = YES; + self.multipleTouchEnabled = YES; + self.alwaysBounceHorizontal = NO; + self.alwaysBounceVertical = NO; + self.delegate = self; + m_zoom = 1; + self.minimumZoomScale = 1; + self.maximumZoomScale = GLOBAL.g_layout_zoom_level; + self.bouncesZoom = NO; + m_child = [[UIView alloc] initWithFrame + :CGRectMake(0, 0, frame.size.width, frame.size.height)]; + [self addSubview:m_child]; + [self resignFirstResponder]; + + if (@available(iOS 11.0, *)) { + self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; + } + } + return self; +} + +- (id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + m_doc = nil; + m_layout = nil; + m_timer = nil; + m_scale_pix = [[UIScreen mainScreen] scale]; + m_status = sta_none; + m_sel = nil; + m_cur_page = -1; + m_save_vmode = 0; self.userInteractionEnabled = YES; self.multipleTouchEnabled = YES; self.alwaysBounceHorizontal = NO; @@ -54,9 +89,9 @@ -(id)initWithFrame:(CGRect)frame self.minimumZoomScale = 1; self.maximumZoomScale = GLOBAL.g_layout_zoom_level; self.bouncesZoom = NO; - m_child = [[PDFOffScreenView alloc] initWithFrame + CGRect frame = self.frame; + m_child = [[UIView alloc] initWithFrame :CGRectMake(0, 0, frame.size.width, frame.size.height)]; - [m_child setDelegate :self]; [self addSubview:m_child]; [self resignFirstResponder]; @@ -68,6 +103,18 @@ -(id)initWithFrame:(CGRect)frame return self; } +-(void)setFrame:(CGRect)frame +{ + [super setFrame:frame]; + if (!m_layout) return; + self.zoomScale = m_zoom = 1; + [m_layout vResize:frame.size.width * m_scale_pix :frame.size.height * m_scale_pix]; + self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, [m_layout doch]/m_scale_pix); + [m_layout vGotoPage:m_cur_page]; + [self setContentOffset:CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix) animated:NO]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; +} + -(void)dealloc { [self PDFClose]; @@ -76,18 +123,16 @@ -(void)dealloc - (void)clean { [self PDFClose]; if (!m_child) { - m_child = [[PDFOffScreenView alloc] initWithFrame:self.frame]; - [m_child setDelegate :self]; + m_child = [[UIView alloc] initWithFrame:self.frame]; [self addSubview:m_child]; } } --(BOOL)PDFOpen:(PDFDoc *)doc :(int)page_gap :(id)del +-(BOOL)PDFOpen:(RDPDFDoc *)doc :(int)page_gap :(RDPDFCanvas *)canvas :(id) del { [self clean]; - - // Load global var - doublePage = GLOBAL.g_double_page_enabled; + m_canvas = canvas; + m_del = del; // Zoom action on double tap // 1: default zoom @@ -95,7 +140,6 @@ -(BOOL)PDFOpen:(PDFDoc *)doc :(int)page_gap :(id)del doubleTapZoomMode = 1; m_doc = doc; - self.m_del = del; m_page_gap = page_gap * m_scale_pix; // Set meta tag UUID with the pdf id @@ -103,17 +147,21 @@ -(BOOL)PDFOpen:(PDFDoc *)doc :(int)page_gap :(id)del actionManger = [[ActionStackManager alloc] init]; self.backgroundColor = (GLOBAL.g_readerview_bg_color != 0) ? UIColorFromRGB(GLOBAL.g_readerview_bg_color) : [UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1.0f]; - m_child.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; - [self PDFSetVMode:GLOBAL.g_render_mode]; + [self PDFSetVMode:GLOBAL.g_view_mode]; m_timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(ProOnTimer:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]addTimer:m_timer forMode:NSDefaultRunLoopMode]; return TRUE; } - +-(int)PDFGetVMode +{ + return m_save_vmode; +} -(void)PDFSetVMode:(int)vmode { + m_save_vmode = vmode; + bool center_page = false; RDVPos pos; pos.pageno = -1; pos.pdfx = 0; @@ -129,88 +177,210 @@ -(void)PDFSetVMode:(int)vmode m_status = sta_none; m_zoom = 1; self.zoomScale = 1; + firstPageSingle = NO; bool *horzs = (bool *)calloc( sizeof(bool), m_doc.pageCount ); - switch (vmode) { + switch (m_save_vmode) { case 1:// Horizontal LTOR + singlePage = NO; doublePage = NO; - GLOBAL.g_paging_enabled = NO; - m_layout = [[RDVLayoutHorz alloc] init:self :false]; + m_layout = [[RDVLayoutHorz alloc] init:self :GLOBAL.g_layout_rtol :GLOBAL.g_auto_scale]; break; - case 2:// PageView RTOL + case 2:// PageView + singlePage = NO; doublePage = NO; - GLOBAL.g_paging_enabled = NO; memset(horzs, 0, sizeof(bool)); - m_layout = [[RDVLayoutSingle alloc] init:self :true :(int)_pageViewNo]; + m_layout = [[RDVLayoutSingle alloc] init:self :GLOBAL.g_layout_rtol :(int)_singleViewPageNo]; break; case 3:// Single Page (LTOR, paging enabled) + singlePage = YES; doublePage = NO; - GLOBAL.g_paging_enabled = YES; memset(horzs, 0, sizeof(bool) * m_doc.pageCount); - m_layout = [[RDVLayoutDual alloc] init:self :false :NULL :0 :horzs :[m_doc pageCount]]; - break; - case 4: // Double Page first page single (paging enabled) - for (int i = 0; i < m_doc.pageCount; i++) { - if (i > 0) { - horzs[i] = true; - } - } - GLOBAL.g_paging_enabled = YES; - memset(horzs, 1, sizeof(bool) * m_doc.pageCount); - m_layout = [[RDVLayoutDual alloc] init:self :false :NULL :0 :horzs :[m_doc pageCount]]; + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; break; - case 5:// Double Page (RTOL, paging enabled) - GLOBAL.g_paging_enabled = YES; + case 4: //Double Page, and first page as single, when in landscape(paging enabled) + singlePage = NO; + doublePage = YES; + firstPageSingle = YES; memset(horzs, 1, sizeof(bool) * m_doc.pageCount); - m_layout = [[RDVLayoutDual alloc] init:self :true :NULL :0 :horzs :[m_doc pageCount]]; + horzs[0] = false; + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; break; case 6:// Double Page (LTOR, paging enabled) - GLOBAL.g_paging_enabled = YES; + singlePage = NO; + doublePage = YES; memset(horzs, 1, sizeof(bool) * m_doc.pageCount); - m_layout = [[RDVLayoutDual alloc] init:self :false :NULL :0 :horzs :[m_doc pageCount]]; + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; break; - case 7:// Horizontal RTOL + case 7://dual page with cover, same like Acrobat on Windows + singlePage = NO; doublePage = NO; - GLOBAL.g_paging_enabled = NO; - memset(horzs, 0, sizeof(bool) * m_doc.pageCount); - m_layout = [[RDVLayoutHorz alloc] init:self :true]; + m_layout = [[RDVLayoutDualV alloc] init:self :GLOBAL.g_layout_rtol :YES :NO]; + [((RDVLayoutDualV *)m_layout) vSetAlign:align_hcenter]; + break; + case 8://dual page without cover, same like Acrobat on Windows + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutDualV alloc] init:self :GLOBAL.g_layout_rtol :NO :NO]; + [((RDVLayoutDualV *)m_layout) vSetAlign:align_hcenter]; break; default:// 0: Vertical - GLOBAL.g_paging_enabled = NO; - m_layout = [[RDVLayoutVert alloc] init : self]; + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutVert alloc] init : self :GLOBAL.g_auto_scale]; + [((RDVLayoutVert *)m_layout) vSetAlign:align_vcenter]; break; } free( horzs ); - if ([self pagingAvailable]) { - self.pagingEnabled = GLOBAL.g_paging_enabled; + [m_layout vOpen :m_doc :m_page_gap :self.layer]; + m_status = sta_none; + m_zoom = 1; + self.zoomScale = 1; + CGRect rect = self.frame; + CGSize size = rect.size; + [m_layout vResize:size.width * m_scale_pix :size.height * m_scale_pix]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; + self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, [m_layout doch]/m_scale_pix); + if(pos.pageno >= 0) + { + if (center_page) + [m_layout vGotoPage:pos.pageno]; + else + [m_layout vSetPos:[m_layout vw] /2 :[m_layout vh] /2 :&pos]; + CGPoint pt; + pt.x = [m_layout docx] / m_scale_pix; + pt.y = [m_layout docy] / m_scale_pix; + self.contentOffset = pt; } - if (GLOBAL.g_render_mode == 2) { - [(RDVLayoutSingle *)m_layout vOpen :m_doc :m_page_gap :self.layer :(int)_pageViewNo]; - } else { - [m_layout vOpen :m_doc :m_page_gap :self.layer]; + [self setNeedsDisplay]; +} + +-(void)PDFSaveView +{ + m_save_pos.pageno = -1; + m_save_pos.pdfx = 0; + m_save_pos.pdfy = 0; + if(m_layout) + { + [m_layout vGetPos:[m_layout vw] /2 :[m_layout vh] /2 :&m_save_pos]; + [m_layout vClose]; + } + m_layout = nil; + m_sel = nil; + m_cur_page = -1; + m_status = sta_none; + m_zoom = 1; + self.zoomScale = 1; +} + +-(void)PDFRestoreView +{ + bool center_page = false; + m_modified = true; + actionManger = [[ActionStackManager alloc] init];//reset all undo/redo + firstPageSingle = NO; + + bool *horzs = (bool *)calloc( sizeof(bool), m_doc.pageCount ); + switch (m_save_vmode) { + case 1:// Horizontal LTOR + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutHorz alloc] init:self :GLOBAL.g_layout_rtol :GLOBAL.g_auto_scale]; + break; + case 2:// PageView + singlePage = NO; + doublePage = NO; + memset(horzs, 0, sizeof(bool)); + m_layout = [[RDVLayoutSingle alloc] init:self :GLOBAL.g_layout_rtol :(int)_singleViewPageNo]; + break; + case 3:// Single Page (LTOR, paging enabled) + singlePage = YES; + doublePage = NO; + memset(horzs, 0, sizeof(bool) * m_doc.pageCount); + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; + break; + case 4: //Double Page, and first page as single, when in landscape(paging enabled) + singlePage = NO; + doublePage = YES; + firstPageSingle = YES; + memset(horzs, 1, sizeof(bool) * m_doc.pageCount); + horzs[0] = false; + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; + break; + case 6:// Double Page (LTOR, paging enabled) + singlePage = NO; + doublePage = YES; + memset(horzs, 1, sizeof(bool) * m_doc.pageCount); + m_layout = [[RDVLayoutDual alloc] init:self :GLOBAL.g_layout_rtol :NULL :0 :horzs :[m_doc pageCount]]; + center_page = true; + //[((RDVLayoutDual *)m_layout) vSetAlign:align_top]; + if (GLOBAL.g_auto_scale) [((RDVLayoutDual *)m_layout) vSetScaleMode:SCALE_FIT]; + break; + case 7://dual page with cover, same like Acrobat on Windows + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutDualV alloc] init:self :GLOBAL.g_layout_rtol :YES :NO]; + [((RDVLayoutDualV *)m_layout) vSetAlign:align_hcenter]; + break; + case 8://dual page without cover, same like Acrobat on Windows + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutDualV alloc] init:self :GLOBAL.g_layout_rtol :NO :NO]; + [((RDVLayoutDualV *)m_layout) vSetAlign:align_hcenter]; + break; + default:// 0: Vertical + singlePage = NO; + doublePage = NO; + m_layout = [[RDVLayoutVert alloc] init : self :GLOBAL.g_auto_scale]; + [((RDVLayoutVert *)m_layout) vSetAlign:align_vcenter]; + break; } - [self bringSubviewToFront:m_child]; + free( horzs ); + [m_layout vOpen :m_doc :m_page_gap :self.layer]; m_status = sta_none; m_zoom = 1; self.zoomScale = 1; CGRect rect = self.frame; CGSize size = rect.size; [m_layout vResize:size.width * m_scale_pix :size.height * m_scale_pix]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, [m_layout doch]/m_scale_pix); - if(pos.pageno >= 0) + if(m_save_pos.pageno >= 0) { - [m_layout vSetPos:[m_layout vw] /2 :[m_layout vh] /2 :&pos]; + if (m_save_pos.pageno >= m_doc.pageCount) m_save_pos.pageno = m_doc.pageCount - 1; + if (center_page) + [m_layout vGotoPage:m_save_pos.pageno]; + else + [m_layout vSetPos:[m_layout vw] /2 :[m_layout vh] /2 :&m_save_pos]; CGPoint pt; pt.x = [m_layout docx] / m_scale_pix; pt.y = [m_layout docy] / m_scale_pix; self.contentOffset = pt; } + m_save_pos.pageno = -1; + m_save_pos.pdfx = 0; + m_save_pos.pdfy = 0; [self setNeedsDisplay]; } -(BOOL)isModified { - return m_modified; + return m_modified; } - (void)setModified:(BOOL)modified force:(BOOL)force @@ -229,21 +399,21 @@ - (void)setModified:(BOOL)modified force:(BOOL)force } } -- (void)updateLastAnnotInfoAtPage:(PDFPage *)page +- (void)updateLastAnnotInfoAtPage:(RDPDFPage *)page { - PDFAnnot *annot = [page annotAtIndex:(page.annotCount - 1)]; + RDPDFAnnot *annot = [page annotAtIndex:(page.annotCount - 1)]; if (annot) { [self setAuthorForAnnot:annot]; [self setModifyDateForAnnot:annot]; } } -- (void)setAuthorForAnnot:(PDFAnnot *)annot +- (void)setAuthorForAnnot:(RDPDFAnnot *)annot { - [annot setPopupLabel:GLOBAL.g_author]; + [annot setPopupLabel:GLOBAL.g_annot_def_author]; } -- (void)setModifyDateForAnnot:(PDFAnnot *)annot +- (void)setModifyDateForAnnot:(RDPDFAnnot *)annot { [annot setModDate:[RDUtils pdfDateFromDate:[NSDate date]]]; } @@ -263,8 +433,8 @@ - (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSStri if([[NSFileManager defaultManager] fileExistsAtPath:path]) [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; - PDFPage *page = [m_doc page:pageno]; - PDFAnnot *annot = [page annotAtIndex:index]; + RDPDFPage *page = [m_doc page:pageno]; + RDPDFAnnot *annot = [page annotAtIndex:index]; NSString *annotPath = [self getImageFromAnnot:annot]; UIImage *img = [UIImage imageWithContentsOfFile:annotPath]; @@ -290,13 +460,13 @@ - (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSStri return NO; } -- (NSString *)getImageFromAnnot:(PDFAnnot *)annot +- (NSString *)getImageFromAnnot:(RDPDFAnnot *)annot { PDF_RECT rect; [annot getRect:&rect]; int width = (rect.right - rect.left) * m_scale_pix; int height = (rect.bottom- rect.top) * m_scale_pix; - PDFDIB *dib = [[PDFDIB alloc] init:width : height]; + RDPDFDIB *dib = [[RDPDFDIB alloc] init:width : height]; Global_setAnnotTransparency(0x00000000); [annot render:dib :0xffffffff]; Global_setAnnotTransparency(0x200040FF); @@ -313,7 +483,7 @@ - (NSString *)getImageFromAnnot:(PDFAnnot *)annot return filePath; } -- (NSString *)emptyImageFromAnnot:(PDFAnnot *)annot { +- (NSString *)emptyImageFromAnnot:(RDPDFAnnot *)annot { PDF_RECT rect; [annot getRect:&rect]; int width = (rect.right - rect.left) * m_scale_pix; @@ -323,7 +493,7 @@ - (NSString *)emptyImageFromAnnot:(PDFAnnot *)annot { - (NSString *)emptyAnnotWithSize:(CGSize)size { - PDFDIB *emptyDib = [[PDFDIB alloc] init:size.width : size.height]; + RDPDFDIB *emptyDib = [[RDPDFDIB alloc] init:size.width : size.height]; [emptyDib erase:0xffffffff]; UIImage *emptyImg = [UIImage imageWithCGImage:[emptyDib image]]; @@ -351,7 +521,7 @@ - (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { - (void)imageFromPage:(int)index inPDFRect:(CGRect )rect withScale:(float)scale { // Get the page - PDFPage *page = [m_doc page:index]; + RDPDFPage *page = [m_doc page:index]; // Initialize the DIB with the annotation size float w = rect.size.width * scale; @@ -397,7 +567,7 @@ - (BOOL)addAttachmentAtPage:(int)pageno fromPath:(NSString *)path inRect:(PDF_RE if([[NSFileManager defaultManager] fileExistsAtPath:path]) { - PDFPage *page = [m_doc page:pageno]; + RDPDFPage *page = [m_doc page:pageno]; BOOL res = [page addAnnotAttachment:path :0 :&rect]; if(res) @@ -413,7 +583,7 @@ - (BOOL)addAttachmentAtPage:(int)pageno fromPath:(NSString *)path inRect:(PDF_RE } - (void)autoSave { - if(GLOBAL.g_save_doc && m_modified) + if(GLOBAL.g_auto_save_doc && m_modified) { [m_doc save]; m_modified = false; @@ -444,21 +614,17 @@ -(void)PDFClose self.zoomScale = 1; [m_child removeFromSuperview]; m_child = nil; - self.m_del = nil; + m_del = nil; } -(void)ProRedrawOS { - [self bringSubviewToFront:m_child]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } -(void)ProUpdatePage:(int) pageno { [m_layout vRenderSync:pageno]; - - if(self.m_del){ - [self.m_del OnPageUpdated:pageno]; - } + if(m_del) [m_del OnPageUpdated:pageno]; } - (void)RDVOnPageRendered:(int)pageno @@ -478,10 +644,10 @@ -(void)RDVOnFound :(RDVFinder *)finder [self refresh]; }); - if( self.m_del ) + if( m_del ) { int pageno = [finder find_get_page]; - [self.m_del OnFound: (pageno >= 0 && pageno < [m_doc pageCount])]; + [m_del OnFound: (pageno >= 0 && pageno < [m_doc pageCount])]; } } @@ -490,23 +656,6 @@ -(void)ProOnTimer:(NSTimer *)sender [self setNeedsDisplay]; } --(CGSize)sizeThatFits:(CGSize)size -{ - self.zoomScale = m_zoom = 1; - [m_layout vResize:size.width * m_scale_pix :size.height * m_scale_pix]; - self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, [m_layout doch]/m_scale_pix); - [m_layout vGotoPage:m_cur_page]; - [self setContentOffset:CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix) animated:NO]; - CGRect rect = CGRectMake( self.contentOffset.x, self.contentOffset.y, self.frame.size.width, self.frame.size.height ); - m_child.frame = rect; - - if (self.zoomScale <= 1 && [self pagingAvailable]) { - self.pagingEnabled = GLOBAL.g_paging_enabled; - } - - return size; -} - -(void)osDrawAnnot:(CGContextRef)context { if( m_status == sta_annot && GLOBAL.g_highlight_annotation) @@ -515,7 +664,7 @@ -(void)osDrawAnnot:(CGContextRef)context int dy = (m_ty - m_py) / m_scale_pix; CGContextSetLineWidth(context, 1); CGContextSetRGBStrokeColor(context, 0, 0, 0, 1); - float scale = 1.0f/(m_zoom * m_scale_pix); + float scale = 1.0f / m_scale_pix; CGRect rect1 = CGRectMake(m_annot_rect.left * scale + dx, m_annot_rect.top * scale + dy, (m_annot_rect.right - m_annot_rect.left) * scale, @@ -573,23 +722,152 @@ -(void)osDrawInk:(CGContextRef)context } } + +-(void)osDrawPolygon:(CGContextRef)context +{ + if( m_status == sta_polygon && m_polygon ) + { + int cnt = [m_polygon nodesCount]; + int cur; + float red; + float green; + float blue; + float alpha; + PDF_POINT pt; + if(cnt > 1)//can be stroked? + { + red = ((GLOBAL.g_line_annot_color>>16)&0xFF)/255.0f; + green = ((GLOBAL.g_line_annot_color>>8)&0xFF)/255.0f; + blue = (GLOBAL.g_line_annot_color&0xFF)/255.0f; + alpha = ((GLOBAL.g_line_annot_color>>24)&0xFF)/255.0f; + CGContextSetLineWidth(context, GLOBAL.g_line_annot_width); + CGContextSetRGBStrokeColor(context, red, green, blue, alpha); + CGContextBeginPath( context ); + for(cur = 0; cur < cnt; cur++) + { + switch([m_polygon node: cur: &pt]) + { + case 1: + CGContextAddLineToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + default: + CGContextMoveToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + } + } + CGContextStrokePath(context); + } + + red = ((GLOBAL.g_line_annot_fill_color>>16)&0xFF)/255.0f; + green = ((GLOBAL.g_line_annot_fill_color>>8)&0xFF)/255.0f; + blue = (GLOBAL.g_line_annot_fill_color&0xFF)/255.0f; + alpha = ((GLOBAL.g_line_annot_fill_color>>24)&0xFF)/255.0f; + CGContextSetRGBFillColor(context, red, green, blue, alpha); + if(cnt > 2)//can be filled? + { + CGContextBeginPath( context ); + for(cur = 0; cur < cnt; cur++) + { + switch([m_polygon node: cur: &pt]) + { + case 1: + CGContextAddLineToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + default: + CGContextMoveToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + } + } + CGContextClosePath(context); + CGContextFillPath(context); + } + + for(cur = 0; cur < cnt; cur++) + { + [m_polygon node: cur: &pt]; + CGContextFillEllipseInRect(context, CGRectMake(pt.x/m_scale_pix - 4, pt.y/m_scale_pix - 4, 8, 8)); + } + } +} + + +-(void)osDrawPolyline:(CGContextRef)context +{ + if( m_status == sta_polyline && m_polygon ) + { + int cnt = [m_polygon nodesCount]; + int cur; + float red; + float green; + float blue; + float alpha; + PDF_POINT pt; + if(cnt > 1)//can be stroked? + { + red = ((GLOBAL.g_line_annot_color>>16)&0xFF)/255.0f; + green = ((GLOBAL.g_line_annot_color>>8)&0xFF)/255.0f; + blue = (GLOBAL.g_line_annot_color&0xFF)/255.0f; + alpha = ((GLOBAL.g_line_annot_color>>24)&0xFF)/255.0f; + CGContextSetLineWidth(context, GLOBAL.g_line_annot_width); + CGContextSetRGBStrokeColor(context, red, green, blue, alpha); + CGContextBeginPath( context ); + for(cur = 0; cur < cnt; cur++) + { + switch([m_polygon node: cur: &pt]) + { + case 1: + CGContextAddLineToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + default: + CGContextMoveToPoint(context, + pt.x/m_scale_pix, + pt.y/m_scale_pix); + break; + } + } + CGContextStrokePath(context); + } + + red = ((GLOBAL.g_line_annot_fill_color>>16)&0xFF)/255.0f; + green = ((GLOBAL.g_line_annot_fill_color>>8)&0xFF)/255.0f; + blue = (GLOBAL.g_line_annot_fill_color&0xFF)/255.0f; + alpha = ((GLOBAL.g_line_annot_fill_color>>24)&0xFF)/255.0f; + CGContextSetRGBFillColor(context, red, green, blue, alpha); + for(cur = 0; cur < cnt; cur++) + { + [m_polygon node: cur: &pt]; + CGContextFillEllipseInRect(context, CGRectMake(pt.x/m_scale_pix - 4, pt.y/m_scale_pix - 4, 8, 8)); + } + } +} + -(void)osDrawLines:(CGContextRef)context { if( m_status == sta_line && (m_lines_cnt || m_lines_drawing) ) { - CGContextSetLineWidth(context, GLOBAL.g_line_width); - float red = ((GLOBAL.g_line_color>>16)&0xFF)/255.0f; - float green = ((GLOBAL.g_line_color>>8)&0xFF)/255.0f; - float blue = (GLOBAL.g_line_color&0xFF)/255.0f; - float alpha = ((GLOBAL.g_line_color>>24)&0xFF)/255.0f; + CGContextSetLineWidth(context, GLOBAL.g_line_annot_width); + float red = ((GLOBAL.g_line_annot_color>>16)&0xFF)/255.0f; + float green = ((GLOBAL.g_line_annot_color>>8)&0xFF)/255.0f; + float blue = (GLOBAL.g_line_annot_color&0xFF)/255.0f; + float alpha = ((GLOBAL.g_line_annot_color>>24)&0xFF)/255.0f; CGContextSetRGBFillColor(context, red, green, blue, alpha); PDF_POINT *pt_cur = m_lines; PDF_POINT *pt_end = m_lines + (m_lines_cnt<<1); if( m_lines_drawing ) pt_end += 2; while( pt_cur < pt_end ) { - CGPoint start = CGPointMake(self.contentOffset.x + pt_cur->x/m_scale_pix, self.contentOffset.y + pt_cur->y/m_scale_pix); - CGPoint end = CGPointMake(self.contentOffset.x + pt_cur[1].x/m_scale_pix, self.contentOffset.y + pt_cur[1].y/m_scale_pix); + CGPoint start = CGPointMake(pt_cur->x/m_scale_pix, pt_cur->y/m_scale_pix); + CGPoint end = CGPointMake(pt_cur[1].x/m_scale_pix, pt_cur[1].y/m_scale_pix); CGPoint points[2] = {start, end}; CGContextStrokeLineSegments(context, points, 2); pt_cur += 2; @@ -601,11 +879,11 @@ -(void)osDrawRects:(CGContextRef)context { if( m_status == sta_rect && (m_rects_cnt || m_rects_drawing) ) { - CGContextSetLineWidth(context, GLOBAL.g_rect_width); - float red = ((GLOBAL.g_rect_color>>16)&0xFF)/255.0f; - float green = ((GLOBAL.g_rect_color>>8)&0xFF)/255.0f; - float blue = (GLOBAL.g_rect_color&0xFF)/255.0f; - float alpha = ((GLOBAL.g_rect_color>>24)&0xFF)/255.0f; + CGContextSetLineWidth(context, GLOBAL.g_rect_annot_width); + float red = ((GLOBAL.g_rect_annot_color>>16)&0xFF)/255.0f; + float green = ((GLOBAL.g_rect_annot_color>>8)&0xFF)/255.0f; + float blue = (GLOBAL.g_rect_annot_color&0xFF)/255.0f; + float alpha = ((GLOBAL.g_rect_annot_color>>24)&0xFF)/255.0f; CGContextSetRGBStrokeColor(context, red, green, blue, alpha); PDF_POINT *pt_cur = m_rects; PDF_POINT *pt_end = m_rects + (m_rects_cnt<<1); @@ -647,11 +925,11 @@ -(void)osDrawEllipse:(CGContextRef)context { if( m_status == sta_ellipse && (m_ellipse_cnt || m_ellipse_drawing) ) { - CGContextSetLineWidth(context, GLOBAL.g_oval_width); - float red = ((GLOBAL.g_oval_color>>16)&0xFF)/255.0f; - float green = ((GLOBAL.g_oval_color>>8)&0xFF)/255.0f; - float blue = (GLOBAL.g_oval_color&0xFF)/255.0f; - float alpha = ((GLOBAL.g_oval_color>>24)&0xFF)/255.0f; + CGContextSetLineWidth(context, GLOBAL.g_oval_annot_width); + float red = ((GLOBAL.g_oval_annot_color>>16)&0xFF)/255.0f; + float green = ((GLOBAL.g_oval_annot_color>>8)&0xFF)/255.0f; + float blue = (GLOBAL.g_oval_annot_color&0xFF)/255.0f; + float alpha = ((GLOBAL.g_oval_annot_color>>24)&0xFF)/255.0f; CGContextSetRGBStrokeColor(context, red, green, blue, alpha); PDF_POINT *pt_cur = m_ellipse; PDF_POINT *pt_end = m_ellipse + (m_ellipse_cnt<<1); @@ -697,7 +975,7 @@ -(void)osDrawFind:(CGContextRef)context if(!finder) return; int pgno = [finder find_get_page]; if(pgno < [m_layout cur_pg1] || pgno >= [m_layout cur_pg2]) return; - [finder drawOffScreen :[[RDVCanvas alloc] init :context :m_scale_pix * m_zoom] + [finder drawOffScreen :[[RDVCanvas alloc] init :context :m_scale_pix] :[m_layout vGetPage:pgno] :[m_layout docx] :[m_layout docy]]; @@ -706,12 +984,58 @@ -(void)osDrawFind:(CGContextRef)context -(void)osDrawSel:(CGContextRef)context { if(m_status != sta_sel) return; - [m_sel drawOffScreen :[[RDVCanvas alloc] init :context :m_scale_pix * m_zoom] + [m_sel drawOffScreen :[[RDVCanvas alloc] init :context :m_scale_pix] :[m_layout vGetPage:[m_sel pageno]] :[m_layout docx] :[m_layout docy]]; } +-(void)osDrawEditbox:(CGContextRef)context +{ + if( m_status == sta_editbox && (m_rects_cnt || m_rects_drawing) ) + { + CGContextSetLineWidth(context, GLOBAL.g_rect_annot_width); + float red = ((GLOBAL.g_rect_annot_color>>16)&0xFF)/255.0f; + float green = ((GLOBAL.g_rect_annot_color>>8)&0xFF)/255.0f; + float blue = (GLOBAL.g_rect_annot_color&0xFF)/255.0f; + float alpha = ((GLOBAL.g_rect_annot_color>>24)&0xFF)/255.0f; + CGContextSetRGBStrokeColor(context, red, green, blue, alpha); + PDF_POINT *pt_cur = m_rects; + PDF_POINT *pt_end = m_rects + (m_rects_cnt<<1); + if( m_rects_drawing ) pt_end += 2; + while( pt_cur < pt_end ) + { + PDF_RECT rect; + if( pt_cur->x > pt_cur[1].x ) + { + rect.right = pt_cur->x; + rect.left = pt_cur[1].x; + } + else + { + rect.left = pt_cur->x; + rect.right = pt_cur[1].x; + } + if( pt_cur->y > pt_cur[1].y ) + { + rect.bottom = pt_cur->y; + rect.top = pt_cur[1].y; + } + else + { + rect.top = pt_cur->y; + rect.bottom = pt_cur[1].y; + } + CGRect rect1 = CGRectMake(rect.left/m_scale_pix, + rect.top/m_scale_pix, + (rect.right - rect.left)/m_scale_pix, + (rect.bottom - rect.top)/m_scale_pix); + CGContextStrokeRect(context, rect1); + pt_cur += 2; + } + } +} + -(void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); @@ -721,47 +1045,15 @@ -(void)drawRect:(CGRect)rect //check current page changed? RDVPos pos; - [m_layout vGetPos :((doublePage) ? [m_layout vw] >> 2 : [m_layout vw] >> 1) :[m_layout vh] >> 1 :&pos]; + [m_layout vGetPos :[m_layout vw] >> 2 :[m_layout vh] >> 2 :&pos]; if( m_cur_page != pos.pageno ) { m_cur_page = pos.pageno; - if( self.m_del ) - [self.m_del OnPageChanged:m_cur_page]; - } -} - -#ifdef FTS_ENABLED -- (void)drawSearchRect:(CGContextRef)context -{ - if (m_cur_page == currentOccurrence.page) { - PDF_RECT drawRect; - - RDVPage *vpage = [m_layout vGetPage:m_cur_page]; - - drawRect.left = [vpage GetX] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:currentOccurrence.rect_l]; - drawRect.right = [vpage GetX] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:currentOccurrence.rect_r]; - drawRect.top = [vpage GetY] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:currentOccurrence.rect_b]; - drawRect.bottom = [vpage GetY] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:currentOccurrence.rect_t]; - - int dx = m_tx - m_px; - int dy = m_ty - m_py; - - CGContextSetRGBFillColor(context, 0.5, 0.0, 0.93, 0.25); - - CGRect rect1 = CGRectMake(self.contentOffset.x + (drawRect.left+dx)/m_scale_pix, - self.contentOffset.y + (drawRect.top+dy)/m_scale_pix, - (drawRect.right - drawRect.left)/m_scale_pix, - (drawRect.bottom - drawRect.top)/m_scale_pix); - CGContextFillRect(context, rect1); + if( m_del ) + [m_del OnPageChanged:m_cur_page]; } } -- (void)applyFTSOccurrence:(FTSOccurrence *)occurrence -{ - currentOccurrence = occurrence; -} -#endif - -(void)onDrawOffScreen:(CGContextRef)ctx { //draw all other status. @@ -772,9 +1064,9 @@ -(void)onDrawOffScreen:(CGContextRef)ctx [self osDrawLines:ctx]; [self osDrawRects:ctx]; [self osDrawEllipse:ctx]; -#ifdef FTS_ENABLED - [self drawSearchRect:ctx]; -#endif + [self osDrawEditbox:ctx]; + [self osDrawPolygon:ctx]; + [self osDrawPolyline:ctx]; } -(BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView @@ -789,75 +1081,1243 @@ -(void)scrollViewDidScrollToTop:(UIScrollView *)scrollView -(void)scrollViewDidScroll:(UIScrollView *)scrollView { if(scrollView != self) return; - /* - if(GLOBAL.g_render_mode == 3 || GLOBAL.g_render_mode == 4) { - //Vertical block - if (self.contentOffset.y <= 0) - self.contentOffset = CGPointMake(self.contentOffset.x, 0); - if (self.contentOffset.y > 0 && self.contentOffset.y >= self.contentSize.height - self.frame.size.height) { - self.contentOffset = CGPointMake(self.contentOffset.x, self.contentSize.height - self.frame.size.height); - } - }*/ - - //NSLog(@"POS:%f,%f", self.contentOffset.x, self.contentOffset.y); if(m_status == sta_zoom) { self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); [self setNeedsDisplay]; + [m_layout vMoveTo:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; } else { - int xval = self.contentOffset.x * m_scale_pix; - int yval = self.contentOffset.y * m_scale_pix; - int xlay = [m_layout docx]; - int ylay = [m_layout docy]; - int vw = [m_layout vw]; - int vh = [m_layout vh]; - if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + if(singlePage && GLOBAL.g_paging_enabled) { - if(xval < 0) xval = 0; - if(yval < 0) yval = 0; - [m_layout vMoveTo:xval :yval]; - } - else self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); - [self setNeedsDisplay]; - //NSLog(@"ZPOS4:%f,%f", self.contentOffset.x, self.contentOffset.y); - } - - m_child.frame = CGRectMake( self.contentOffset.x, self.contentOffset.y, self.frame.size.width, self.frame.size.height ); - [self ProRedrawOS]; -} - -- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView -{ -} - -- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate -{ -} - -- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView -{ -} + if(m_zoom > 1) + { + CGFloat getstatusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height; -- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView + CGSize screenSize = [self getScreenFrameForCurrentOrientation]; + CGFloat screenWidth = screenSize.width; + CGFloat screenHeight = screenSize.height ; + //stop on boundaries = true + if(GLOBAL.g_zoomed_stop_on_boundaries) + { + //screen size < page size + if(screenWidth < [m_layout vGetPage:m_cur_page].GetWidth ) + { + //right + if ((self.contentOffset.x * m_scale_pix + screenWidth) > [m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth) + { + [self setContentOffset: CGPointMake(([m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y) animated:NO]; + } + //left + if (self.contentOffset.x * m_scale_pix < [m_layout vGetPage:m_cur_page].GetX) + { + [self setContentOffset:CGPointMake(([m_layout vGetPage:m_cur_page].GetX / m_scale_pix), self.contentOffset.y) animated:NO]; + } + } + //screen size > page size + else + { + //right + left + [self setContentOffset:CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y) animated:NO]; + } + } + if(isAnimating) + { + [self setContentOffset:animatePoint animated:YES]; + } + else + { + if(isDecelerating) + { + if(screenWidth < [m_layout vGetPage:m_cur_page].GetWidth) + { + //right + if (m_cur_page + 1 <= m_doc.pageCount && ( (self.contentOffset.x * m_scale_pix + screenWidth) > [m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth)) + { + [self setContentOffset: CGPointMake(([m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + //left + if (m_cur_page >= 0 && (self.contentOffset.x * m_scale_pix < [m_layout vGetPage:m_cur_page].GetX)) + { + [self setContentOffset:CGPointMake(([m_layout vGetPage:m_cur_page].GetX / m_scale_pix), self.contentOffset.y) animated:YES]; + } + } + else + { + //left + right + [self setContentOffset:CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + } + else + { + int xval = self.contentOffset.x * m_scale_pix; + int yval = self.contentOffset.y * m_scale_pix; + int xlay = [m_layout docx]; + int ylay = [m_layout docy]; + int vw = [m_layout vw]; + int vh = [m_layout vh]; + if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + { + if(xval < 0) xval = 0; + if(yval < 0) yval = 0; + [m_layout vMoveTo:xval :yval]; + } + } + if ((screenHeight) < [m_layout vGetPage:m_cur_page].GetHeight) + { + //top page + if(self.contentOffset.y * m_scale_pix < [m_layout vGetPage:m_cur_page].GetY) + { + self.contentOffset = CGPointMake(self.contentOffset.x, ([m_layout vGetPage:m_cur_page].GetY / m_scale_pix)); + } + //bottom page + if((self.contentOffset.y * m_scale_pix + screenHeight) > [m_layout vGetPage:m_cur_page].GetY + [m_layout vGetPage:m_cur_page].GetHeight + getstatusBarHeight * m_scale_pix) + { + self.contentOffset =CGPointMake(self.contentOffset.x, ([m_layout vGetPage:m_cur_page].GetY + [m_layout vGetPage:m_cur_page].GetHeight - screenHeight) / m_scale_pix + getstatusBarHeight); + } + } + } + [self setNeedsDisplay]; + [m_layout vMoveTo:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; + + } + else + { + int xval = self.contentOffset.x * m_scale_pix; + int yval = self.contentOffset.y * m_scale_pix; + int xlay = [m_layout docx]; + int ylay = [m_layout docy]; + int vw = [m_layout vw]; + int vh = [m_layout vh]; + if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + { + if(xval < 0) xval = 0; + if(yval < 0) yval = 0; + [m_layout vMoveTo:xval :yval]; + } + else self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); + [self setNeedsDisplay]; + } + } + else if(doublePage && GLOBAL.g_paging_enabled) + { + if(m_zoom > 1) + { + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + CGFloat getstatusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height; + CGSize screenSize = [self getScreenFrameForCurrentOrientation]; + CGFloat screenWidth = screenSize.width; + CGFloat screenHeight = screenSize.height ; + int doublePageX; + int doublePageY; + int doublePageWidth; + int doublePageHeight; + bool m_layout_rtol = GLOBAL.g_layout_rtol; + if(orientation == UIInterfaceOrientationPortrait) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + if(m_layout_rtol) + { + if(m_cur_page % 2 != 0) + { + if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + if([m_layout vGetPage:m_cur_page].GetY <= [m_layout vGetPage:m_cur_page - 1].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page - 1].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page - 1].GetWidth; + if([m_layout vGetPage:m_cur_page].GetHeight >= [m_layout vGetPage:m_cur_page - 1].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page - 1].GetHeight; + } + } + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page + 1].GetX; + if([m_layout vGetPage:m_cur_page + 1].GetY <= [m_layout vGetPage:m_cur_page].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page + 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + if([m_layout vGetPage:m_cur_page + 1].GetHeight >= [m_layout vGetPage:m_cur_page].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + else if(firstPageSingle) + { + if(m_cur_page == 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + if(m_cur_page % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + if([m_layout vGetPage:m_cur_page].GetY <= [m_layout vGetPage:m_cur_page + 1].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page + 1].GetWidth; + if([m_layout vGetPage:m_cur_page].GetHeight >= [m_layout vGetPage:m_cur_page + 1].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page - 1].GetX; + if([m_layout vGetPage:m_cur_page + 1].GetY <= [m_layout vGetPage:m_cur_page].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page - 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + if([m_layout vGetPage:m_cur_page + 1].GetHeight >= [m_layout vGetPage:m_cur_page].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + } + else + { + if(m_cur_page % 2 == 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + if([m_layout vGetPage:m_cur_page].GetY <= [m_layout vGetPage:m_cur_page + 1].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page + 1].GetWidth; + if([m_layout vGetPage:m_cur_page].GetHeight >= [m_layout vGetPage:m_cur_page + 1].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page - 1].GetX; + if([m_layout vGetPage:m_cur_page + 1].GetY <= [m_layout vGetPage:m_cur_page].GetY) + { + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + } + else + { + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + } + doublePageWidth = [m_layout vGetPage:m_cur_page - 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + if([m_layout vGetPage:m_cur_page + 1].GetHeight >= [m_layout vGetPage:m_cur_page].GetHeight) + { + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + else + { + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + } + + if(GLOBAL.g_zoomed_stop_on_boundaries) + { + if(screenWidth < doublePageWidth) + { + //right + if ((self.contentOffset.x * m_scale_pix + screenWidth) > doublePageX + doublePageWidth) + { + [self setContentOffset: CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y) animated:NO]; + } + //left + if (self.contentOffset.x * m_scale_pix < doublePageX) + { + [self setContentOffset:CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y) animated:NO]; + } + } + } + if(isAnimating) + { + [self setContentOffset:animatePoint animated:YES]; + } + else + { + if(isDecelerating) + { + if(m_layout_rtol) + { + if(screenWidth < doublePageWidth) + { + //right + if (m_cur_page > 0 && ( (self.contentOffset.x * m_scale_pix + screenWidth) > doublePageX + doublePageWidth)) + { + [self setContentOffset: CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + //left + if (m_cur_page + 1 < m_doc.pageCount && (self.contentOffset.x * m_scale_pix < doublePageX)) + { + [self setContentOffset:CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y) animated:YES]; + } + } + else + { + //left + right + [self setContentOffset:CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + } + else + { + if(screenWidth < doublePageWidth) + { + //right + if (m_cur_page + 1 < m_doc.pageCount && ( (self.contentOffset.x * m_scale_pix + screenWidth) > doublePageX + doublePageWidth)) + { + [self setContentOffset: CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + //left + if (m_cur_page > 0 && (self.contentOffset.x * m_scale_pix < doublePageX)) + { + [self setContentOffset:CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y) animated:YES]; + } + } + else + { + //left + right + [self setContentOffset:CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y) animated:YES]; + } + } + + } + else + { + int xval = self.contentOffset.x * m_scale_pix; + int yval = self.contentOffset.y * m_scale_pix; + int xlay = [m_layout docx]; + int ylay = [m_layout docy]; + int vw = [m_layout vw]; + int vh = [m_layout vh]; + if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + { + if(xval < 0) xval = 0; + if(yval < 0) yval = 0; + [m_layout vMoveTo:xval :yval]; + } + } + if ((screenHeight) < doublePageHeight) + { + //top page + if(self.contentOffset.y * m_scale_pix < doublePageY) + { + self.contentOffset = CGPointMake(self.contentOffset.x, (doublePageY / m_scale_pix)); + } + //bottom page + if((self.contentOffset.y * m_scale_pix + screenHeight) > doublePageY + doublePageHeight + getstatusBarHeight * m_scale_pix) + { + self.contentOffset =CGPointMake(self.contentOffset.x, (doublePageY + doublePageHeight - screenHeight) / m_scale_pix + getstatusBarHeight); + } + } + } + [self setNeedsDisplay]; + [m_layout vMoveTo:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; + } + else + { + int xval = self.contentOffset.x * m_scale_pix; + int yval = self.contentOffset.y * m_scale_pix; + int xlay = [m_layout docx]; + int ylay = [m_layout docy]; + int vw = [m_layout vw]; + int vh = [m_layout vh]; + if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + { + if(xval < 0) xval = 0; + if(yval < 0) yval = 0; + [m_layout vMoveTo:xval :yval]; + } + else self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); + [self setNeedsDisplay]; + } + } + else + { + int xval = self.contentOffset.x * m_scale_pix; + int yval = self.contentOffset.y * m_scale_pix; + int xlay = [m_layout docx]; + int ylay = [m_layout docy]; + int vw = [m_layout vw]; + int vh = [m_layout vh]; + if(xval > xlay - vw && xval < xlay + vw && yval > ylay - vh && yval < ylay + vh) + { + if(xval < 0) xval = 0; + if(yval < 0) yval = 0; + [m_layout vMoveTo:xval :yval]; + } + else self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); + [self setNeedsDisplay]; + } + + } + + [self ProRedrawOS]; +} + +- (CGSize)getScreenFrameForCurrentOrientation { + return [self getScreenFrameForOrientation:[UIApplication sharedApplication].statusBarOrientation]; +} + +- (CGSize)getScreenFrameForOrientation:(UIInterfaceOrientation)orientation { + + CGSize fullScreenRect = [UIScreen mainScreen].currentMode.size; + + if (UIInterfaceOrientationIsLandscape(orientation)) { + CGSize temp = CGSizeZero; + temp.width = fullScreenRect.height; + temp.height = fullScreenRect.width; + fullScreenRect = temp; + } + + return fullScreenRect; +} + +- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { + isDecelerating = false; + touchBeginPoint = [self convertPoint:touchPoint toView:nil]; + touchBeginTime = [NSDate date]; + begin_touch_page = m_cur_page; } +-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ + touchPoint = point; + return self; +} + +-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView +{ + isAnimating = false; +} + +- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate +{ + float speed; + float speed_to_change_page = 500; + UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; + bool m_layout_rtol = GLOBAL.g_layout_rtol; + if((singlePage || (doublePage && orientation == UIInterfaceOrientationPortrait)) && GLOBAL.g_paging_enabled) + { + isDecelerating = false; + touchEndPoint = [self convertPoint:touchPoint toView:nil]; + touchEndTime = [NSDate date]; + NSTimeInterval executionTime = [touchEndTime timeIntervalSinceDate:touchBeginTime]; + //speed = pixel/second + if(touchEndPoint.x > touchBeginPoint.x) + { + speed = (touchEndPoint.x - touchBeginPoint.x)/executionTime; + } + else + { + speed = (touchBeginPoint.x - touchEndPoint.x)/executionTime; + } + if(m_zoom > 1 && m_status != sta_zoom && !GLOBAL.g_zoomed_stop_on_boundaries ) + { + CGSize screenSize = [self getScreenFrameForCurrentOrientation]; + CGFloat screenWidth = screenSize.width; + if(m_layout_rtol) + { + if((screenWidth) < [m_layout vGetPage:m_cur_page].GetWidth) + { + //right + if(m_cur_page > 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth) + { + if(touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX / m_scale_pix), self.contentOffset.y); + + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page + 1 < m_doc.pageCount && (self.contentOffset.x * m_scale_pix < [m_layout vGetPage:m_cur_page].GetX)) + { + if(touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX + [m_layout vGetPage:begin_touch_page + 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX / m_scale_pix), self.contentOffset.y);; + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + else + { + //right + if(m_cur_page > 0 && touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page - 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page + 1 < m_doc.pageCount && touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //right + else if(m_cur_page > 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page - 1].GetWidth + ([m_layout vGetPage:m_cur_page].GetX / 2)) + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + } + else + { + if((screenWidth) < [m_layout vGetPage:m_cur_page].GetWidth) + { + //right + if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth) + { + if(touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX + [m_layout vGetPage:m_cur_page].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && (self.contentOffset.x * m_scale_pix < [m_layout vGetPage:m_cur_page].GetX)) + { + if(touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX / m_scale_pix), self.contentOffset.y);; + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + else + { + //right + if(m_cur_page + 1 < m_doc.pageCount && touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page - 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //right + else if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page - 1].GetWidth + ([m_layout vGetPage:m_cur_page].GetX / 2)) + { + animatePoint = CGPointMake(([m_layout vGetPage:m_cur_page].GetX - ((screenWidth - [m_layout vGetPage:m_cur_page].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + } + } + [m_layout vMoveTo:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; + [self ProRedrawOS]; + } + else if(doublePage && GLOBAL.g_paging_enabled) + { + int doublePageX; + int doublePageY; + int doublePageWidth; + int doublePageHeight; + if(firstPageSingle) + { + if((m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 == 0) || m_cur_page == 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + if(m_cur_page % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page + 1].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page - 1].GetX; + doublePageY = [m_layout vGetPage:m_cur_page - 1].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page - 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + else + { + if(m_layout_rtol) + { + if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + if(m_cur_page % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page - 1].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page - 1].GetHeight; + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page + 1].GetX; + doublePageY = [m_layout vGetPage:m_cur_page + 1].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page + 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + else + { + if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 != 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + else + { + if(m_cur_page % 2 == 0) + { + doublePageX = [m_layout vGetPage:m_cur_page].GetX; + doublePageY = [m_layout vGetPage:m_cur_page].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page].GetWidth + [m_layout vGetPage:m_cur_page + 1].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page + 1].GetHeight; + } + else + { + doublePageX = [m_layout vGetPage:m_cur_page - 1].GetX; + doublePageY = [m_layout vGetPage:m_cur_page - 1].GetY; + doublePageWidth = [m_layout vGetPage:m_cur_page - 1].GetWidth + [m_layout vGetPage:m_cur_page].GetWidth; + doublePageHeight = [m_layout vGetPage:m_cur_page].GetHeight; + } + } + } + } + isDecelerating = false; + touchEndPoint = [self convertPoint:touchPoint toView:nil]; + touchEndTime = [NSDate date]; + NSTimeInterval executionTime = [touchEndTime timeIntervalSinceDate:touchBeginTime]; + //speed = pixel/second + + if(touchEndPoint.x > touchBeginPoint.x) + { + speed = (touchEndPoint.x - touchBeginPoint.x)/executionTime; + } + else + { + speed = (touchBeginPoint.x - touchEndPoint.x)/executionTime; + } + + if(m_zoom > 1 && m_status != sta_zoom && !GLOBAL.g_zoomed_stop_on_boundaries) + { + CGSize screenSize = [self getScreenFrameForCurrentOrientation]; + CGFloat screenWidth = screenSize.width; + if(m_layout_rtol) + { + if((screenWidth) < doublePageWidth) + { + //right + if(m_cur_page > 1 && self.contentOffset.x * m_scale_pix + screenWidth > doublePageX + doublePageWidth) + { + if(touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 != 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX / m_scale_pix), self.contentOffset.y); + } + } + else + { + animatePoint = CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page + 1 < m_doc.pageCount && (self.contentOffset.x * m_scale_pix < doublePageX)) + { + if(touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(m_doc.pageCount == m_cur_page + 2 && m_doc.pageCount % 2 != 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 1].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX + [m_layout vGetPage:begin_touch_page + 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + + } + else if(m_doc.pageCount == m_cur_page + 3 && m_doc.pageCount % 2 != 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX + [m_layout vGetPage:begin_touch_page + 2].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 2].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(begin_touch_page % 2 != 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX + [m_layout vGetPage:begin_touch_page + 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX + [m_layout vGetPage:begin_touch_page + 2].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + } + } + else + { + animatePoint = CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y);; + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + else + { + //right + if(m_cur_page > 1 && touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 != 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(begin_touch_page % 2 == 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 2].GetWidth + [m_layout vGetPage:begin_touch_page - 3].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page + 1 < m_doc.pageCount && touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 == 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 2].GetWidth + [m_layout vGetPage:begin_touch_page + 3].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 2].GetWidth + [m_layout vGetPage:begin_touch_page + 1].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //right + else if(m_cur_page >= 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetWidth) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page + 1].GetWidth + ([m_layout vGetPage:m_cur_page].GetX / 2)) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + } + else if(firstPageSingle) + { + if((screenWidth) < doublePageWidth) + { + //right + if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > doublePageX + doublePageWidth) + { + if(touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 != 0) + { + if(begin_touch_page + 3 < m_doc.pageCount) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 2].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + } + else + { + if(begin_touch_page + 2 < m_doc.pageCount) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 1].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + } + } + else + { + animatePoint = CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && (self.contentOffset.x * m_scale_pix < doublePageX)) + { + if(touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page - 3 < 0) + { + if(begin_touch_page - 1 == 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 1].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX + [m_layout vGetPage:begin_touch_page - 2].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + } + else + { + if(begin_touch_page % 2 != 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX + [m_layout vGetPage:begin_touch_page - 2].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + } + } + else + { + animatePoint = CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y);; + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + else + { + //right + if(m_cur_page + 2 < m_doc.pageCount && touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(m_cur_page == 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 1].GetWidth + [m_layout vGetPage:begin_touch_page + 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 1].GetWidth + [m_layout vGetPage:begin_touch_page + 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(begin_touch_page % 2 != 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 2].GetWidth + [m_layout vGetPage:begin_touch_page + 3].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 1].GetWidth + [m_layout vGetPage:begin_touch_page + 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(m_cur_page - 1 == 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 1].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 == 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(begin_touch_page % 2 != 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 2].GetWidth + [m_layout vGetPage:begin_touch_page - 1].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 3].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 3].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //right + else if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetWidth) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page - 1].GetWidth + ([m_layout vGetPage:m_cur_page].GetX / 2)) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + } + else + { + if((screenWidth) < doublePageWidth) + { + //right + if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > doublePageX + doublePageWidth) + { + if(touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 == 0) + { + if(begin_touch_page + 3 < m_doc.pageCount) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + if(begin_touch_page + 2 != m_doc.pageCount) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 2].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + } + } + else + { + if(begin_touch_page + 2 < m_doc.pageCount) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + if(screenWidth < [m_layout vGetPage:begin_touch_page + 1].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX / m_scale_pix), self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - [m_layout vGetPage:begin_touch_page + 1].GetWidth) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + } + } + else + { + animatePoint = CGPointMake((doublePageX + doublePageWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page - 1 > 0 && (self.contentOffset.x * m_scale_pix < doublePageX)) + { + if(touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 == 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX + [m_layout vGetPage:begin_touch_page - 2].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + } + else + { + animatePoint = CGPointMake((doublePageX / m_scale_pix), self.contentOffset.y);; + } + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + else + { + //right + if(m_cur_page + 3 < m_doc.pageCount && touchEndPoint.x < touchBeginPoint.x && speed > speed_to_change_page) + { + if(begin_touch_page % 2 == 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 2].GetWidth + [m_layout vGetPage:begin_touch_page + 3].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page + 1].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page + 1].GetWidth + [m_layout vGetPage:begin_touch_page + 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 1 && touchEndPoint.x > touchBeginPoint.x && speed > speed_to_change_page) + { + if(m_doc.pageCount == m_cur_page + 1 && m_doc.pageCount % 2 != 0) + { + if(screenWidth < [m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 1].GetX + [m_layout vGetPage:begin_touch_page - 1].GetWidth - screenWidth) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 1].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + else + { + if(begin_touch_page % 2 == 0) + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 2].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 2].GetWidth + [m_layout vGetPage:begin_touch_page - 1].GetWidth) ) / 2)) / m_scale_pix , self.contentOffset.y); + } + else + { + animatePoint = CGPointMake(([m_layout vGetPage:begin_touch_page - 3].GetX - ((screenWidth - ([m_layout vGetPage:begin_touch_page - 3].GetWidth + [m_layout vGetPage:begin_touch_page - 2].GetWidth)) / 2)) / m_scale_pix , self.contentOffset.y); + } + } + + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //right + else if(m_cur_page + 1 < m_doc.pageCount && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page].GetWidth) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + //left + else if(m_cur_page > 0 && self.contentOffset.x * m_scale_pix + screenWidth > [m_layout vGetPage:m_cur_page - 1].GetWidth + ([m_layout vGetPage:m_cur_page].GetX / 2)) + { + animatePoint = CGPointMake((doublePageX - ((screenWidth - doublePageWidth) / 2)) / m_scale_pix , self.contentOffset.y); + [self setContentOffset:animatePoint animated:YES]; + isAnimating = true; + } + } + } + } + [m_layout vMoveTo:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; + [self ProRedrawOS]; + } +} + +- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView +{ + isDecelerating = true; +} + +- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView +{ + isDecelerating = false; + isAnimating = false; +} - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { if( m_status == sta_none || m_status == sta_zoom ) - return m_child; - else - return NULL; + return m_child; + else + return NULL; } - (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view { if( m_status != sta_none ) return; - self.pagingEnabled = NO; - CGPoint point = [scrollView.pinchGestureRecognizer locationInView:self.window]; + CGPoint point = [scrollView.pinchGestureRecognizer locationInView:m_canvas]; [m_layout vZoomStart]; m_status = sta_zoom; if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 && [[[UIDevice currentDevice] systemVersion] floatValue] > 6.0 && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) @@ -877,7 +2337,7 @@ - (void)scrollViewDidZoom:(UIScrollView *)scrollView { if( m_status != sta_zoom ) return; m_zoom = self.zoomScale; - CGPoint point = [scrollView.pinchGestureRecognizer locationInView:self.window]; + CGPoint point = [scrollView.pinchGestureRecognizer locationInView:m_canvas]; if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 && [[[UIDevice currentDevice] systemVersion] floatValue] > 6.0 && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { CGFloat buffer = point.y; @@ -890,6 +2350,7 @@ - (void)scrollViewDidZoom:(UIScrollView *)scrollView [m_layout vSetPos:(point.x - (zoomPoint.x * m_zoom)) * m_scale_pix :(point.y - (zoomPoint.y * m_zoom)) * m_scale_pix :&m_zoom_pos]; self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); [self refresh]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale @@ -904,14 +2365,7 @@ - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)vi m_status = sta_none; [self refresh]; - if (self.zoomScale <= 1 && m_status != sta_annot) - { - [self vGoto:m_cur_page]; - - if (self.zoomScale <= 1 && [self pagingAvailable]) { - self.pagingEnabled = GLOBAL.g_paging_enabled; - } - } + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; } - (void)zoomPageToScale:(CGFloat)scale atPoint:(CGPoint)point { @@ -928,7 +2382,8 @@ - (void)zoomPageToScale:(CGFloat)scale atPoint:(CGPoint)point { [m_layout vSetPos:pt.x :pt.y :&m_zoom_pos]; self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); [m_layout vZoomConfirm]; - + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; + m_status = sta_none; [self refresh]; @@ -936,9 +2391,7 @@ - (void)zoomPageToScale:(CGFloat)scale atPoint:(CGPoint)point { [self vGoto:m_cur_page]; } - //[self zoomStartAtPoint:point]; - //[self zoomToScale:scale atPoint:point]; - //[self zoomConfirmToScale:scale]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; } - (void)refresh @@ -950,7 +2403,7 @@ - (void)refresh - (void)centerPage { - if(GLOBAL.g_render_mode == 3 || GLOBAL.g_render_mode == 6) + if(m_save_vmode == 3 || m_save_vmode == 6) { //[self resetZoomLevel]; } @@ -963,16 +2416,25 @@ -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event if( cnt == 1 ) { UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; + CGPoint point=[touch locationInView:m_canvas]; if( [self OnSelTouchBegin:point] ) return; if( [self OnAnnotTouchBegin:point] ) return; if( [self OnNoteTouchBegin:point] ) return; if( [self OnInkTouchBegin:point] ) return; + if( [self OnPolygonTouchBegin:point] ) return; + if( [self OnPolylineTouchBegin:point] ) return; if( [self OnLineTouchBegin:point] ) return; if( [self OnRectTouchBegin:point] ) return; if( [self OnEllipseTouchBegin:point] ) return; if( [self OnImageTouchBegin:point] ) return; + if( [self OnEditboxTouchBegin:point] ) return; [self OnNoneTouchBegin:point:touch.timestamp]; + m_doubleTapCount++; + if (m_doubleTapCount == 1)//first tap of double tap + { + m_doubleTapTime = event.timestamp; + [self performSelector:@selector(OnDoubleTapCheckEnd:) withObject:self afterDelay:0.5]; + } } } @@ -984,314 +2446,285 @@ -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event if( cnt == 1 ) { UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; + CGPoint point=[touch locationInView:m_canvas]; if( [self OnSelTouchMove :point] ) return; if( [self OnAnnotTouchMove:point] ) return; if( [self OnNoteTouchMove:point] ) return; if( [self OnInkTouchMove:point] ) return; + if( [self OnPolygonTouchMove:point] ) return; + if( [self OnPolylineTouchMove:point] ) return; if( [self OnLineTouchMove:point] ) return; if( [self OnRectTouchMove:point] ) return; if( [self OnEllipseTouchMove:point] ) return; if( [self OnImageTouchMove:point] ) return; + if( [self OnEditboxTouchMove:point] ) return; [self OnNoneTouchMove:point:touch.timestamp]; } } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { - UITouch *touch = [touches anyObject]; - if (touch.tapCount == 2 && m_status == sta_none) { - //this is the double tap action - [self OnDoubleTap:touch]; - } - else + NSSet *allTouches = [event allTouches]; + NSUInteger cnt = [allTouches count]; + if( cnt == 1 ) { - NSSet *allTouches = [event allTouches]; - NSUInteger cnt = [allTouches count]; - if( cnt == 1 ) + UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; + CGPoint point=[touch locationInView:m_canvas]; + if( [self OnSelTouchEnd:[touch locationInView:self]] ) return; + if( [self OnAnnotTouchEnd:point] ) return; + if( [self OnNoteTouchEnd:point] ) return; + if( [self OnInkTouchEnd:point] ) return; + if( [self OnPolygonTouchEnd:point] ) return; + if( [self OnPolylineTouchEnd:point] ) return; + if( [self OnLineTouchEnd:point] ) return; + if( [self OnRectTouchEnd:point] ) return; + if( [self OnEllipseTouchEnd:point] ) return; + if( [self OnImageTouchEnd:point] ) return; + if( [self OnEditboxTouchEnd:point] ) return; + if (m_status == sta_none && m_doubleTapCount == 2) { - UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; - if( [self OnSelTouchEnd:point] ) return; - if( [self OnAnnotTouchEnd:point] ) return; - if( [self OnNoteTouchEnd:point] ) return; - if( [self OnInkTouchEnd:point] ) return; - if( [self OnLineTouchEnd:point] ) return; - if( [self OnRectTouchEnd:point] ) return; - if( [self OnEllipseTouchEnd:point] ) return; - if( [self OnImageTouchMove:point] ) return; - [self OnNoneTouchEnd:point:touch.timestamp]; - } - } -} - -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -{ - [self touchesEnded:touches withEvent:event]; -} - -- (void)OnDoubleTap:(UITouch *)touch { - [self OnDoubleTapOnPoint:[touch locationInView:self.window]]; -} - -- (void)OnDoubleTapOnPoint:(CGPoint)point -{ - isDoubleTapping = YES; - - NSLog(@"double tap"); - - if (doubleTapZoomMode > 0) { - if (m_zoom > GLOBAL.g_zoom_level){ - //if (m_zoom > 1){ - if ([self pagingAvailable]) { - self.pagingEnabled = GLOBAL.g_paging_enabled; - } - [self resetZoomLevel]; - } else { - self.pagingEnabled = NO; - - if (doubleTapZoomMode == 1) { - [self defaultZoom:point]; - } else { -#ifndef SMART_ZOOM - //[self defaultZoom:touch]; -#else - [self initZoomWithPoint:[touch locationInView:self.window]]; - RDVPos pos; - CGPoint p = [touch locationInView:self.window]; - - [m_layout vGetPos:p.x * m_scale_pix :p.y * m_scale_pix :&pos]; - PDF_RECT mZoomRect = [ReaderHandler handleAutomaticZoom:m_layout withPos:pos forDoc:m_doc containedInWidth:[m_layout vw]]; - - float mParagraphWidth = mZoomRect.right - mZoomRect.left; - - if ((int)mParagraphWidth == 0) { - [self defaultZoom:touch]; // Call defaultZoom as fallback - return; - } - - int scale = (int) ([m_layout vw] / mParagraphWidth); //screen width / paragraph width - - pos.pdfx = mZoomRect.right - (mParagraphWidth / 2); - - if (scale > 1) { - - self.zoomScale = (scale > GLOBAL.g_zoom_level) ? GLOBAL.g_zoom_level : scale; - m_zoom = scale; - - [m_layout vZoomStart]; - [m_layout vZooming:scale]; - [m_layout vSetPos:[m_layout vw] /2 :[m_layout vh] /2 :&pos]; - [m_layout vZoomConfirm]; - - CGSize sz; - sz.width = [m_layout docw]/m_scale_pix; - sz.height = [m_layout doch]/m_scale_pix; - self.contentSize = sz; - //[m_view vSetPos:&m_zoom_pos :(pos.x - (zoomPoint.x * scale)) * m_scale :(pos.y - (zoomPoint.y * scale)) * m_scale]; - self.contentOffset = CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix); - - [self refresh]; + float dx = point.x - m_tx / m_scale_pix; + float dy = point.y - m_ty / m_scale_pix; + bool double_tap = true; + if( dx > 5 || dx < -5 ) + double_tap = false; + if( dy > 5 || dy < -5 ) + double_tap = false; + //this is the double tap action + if (double_tap && event.timestamp - m_doubleTapTime < 0.5) + { + if (doubleTapZoomMode > 0) + { + if (m_zoom > GLOBAL.g_tap_zoom_level) + { + [self defaultZoom:touch]; + self.pagingEnabled = GLOBAL.g_paging_enabled && m_layout && [m_layout vCanPaging]; + } + else + { + self.pagingEnabled = NO; + if (doubleTapZoomMode == 1) [self defaultZoom:touch]; + } } -#endif + if (m_del) + [m_del OnDoubleTapped:[touch locationInView:self.window].x :[touch locationInView:m_canvas].y]; } + m_doubleTapCount = 0; } - } - - if (self.m_del) { - [self.m_del OnDoubleTapped:point.x :point.y]; - } - - [self performSelector:@selector(delayedDoubleTapping) withObject:nil afterDelay:0.5]; - -} - -- (void)delayedOnSingleTapping:(NSArray *)a -{ - if (!isDoubleTapping && a && self.m_del) { - CGPoint point = CGPointMake([[a objectAtIndex:0] floatValue], [[a objectAtIndex:1] floatValue]); - [self.m_del OnSingleTapped:point.x:point.y]; + else + [self OnNoneTouchEnd:point:touch.timestamp]; } } -- (void)delayedDoubleTapping +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { - isDoubleTapping = NO; + [self touchesEnded:touches withEvent:event]; } -- (void)resetZoomLevel +- (void)OnDoubleTapCheckEnd:(id)sendor { - enum LAYOUT_STATUS save_status = m_status; - [self zoomPageToScale:1.0 atPoint:CGPointMake([m_layout vw] / 2, [m_layout vh] / 2)]; + if (m_doubleTapCount == 0) return; + + m_doubleTapCount = 0; + [m_layout vGetPos :m_tx :m_ty :&m_annot_pos]; - if ([imgAnnot isDescendantOfView:self]) { - CGPoint center = self.center; - center.x += self.contentOffset.x; - center.y += self.contentOffset.y; - imgAnnot.center = center; - } - m_status = save_status; -} + CGFloat x = m_tx / m_scale_pix; + CGFloat y = m_ty / m_scale_pix; + if( m_annot_pos.pageno < 0 ) return; -- (void)defaultZoom:(CGPoint )point -{ - if (self.zoomScale == GLOBAL.g_zoom_level && GLOBAL.g_zoom_step > 0) { - GLOBAL.g_zoom_step *= -1; - } else if (self.zoomScale <= self.minimumZoomScale && GLOBAL.g_zoom_step) { - GLOBAL.g_zoom_step = 1; + RDVPage *vpage = [m_layout vGetPage:m_annot_pos.pageno]; + if( !vpage )//shall not happen + { + if (m_del) [m_del OnSingleTapped:x:y]; + return; } - if (self.zoomScale > GLOBAL.g_zoom_level) m_zoom = 1; - else m_zoom = (self.zoomScale + GLOBAL.g_zoom_step > GLOBAL.g_zoom_level) ? GLOBAL.g_zoom_level : self.zoomScale + GLOBAL.g_zoom_step; - [self zoomPageToScale:m_zoom atPoint:point]; -} - --(void)OnSingleTap:(float)x :(float)y -{ - [m_layout vGetPos :x * m_scale_pix * m_zoom :y * m_scale_pix * m_zoom :&m_annot_pos]; - - if( m_annot_pos.pageno >= 0 ) + RDPDFPage *page = [vpage GetPage]; + if( !page ) return; + m_annot = [page annotAtPoint:m_annot_pos.pdfx: m_annot_pos.pdfy]; + m_annot_idx = -1; + if( m_annot ) { - RDVPage *vpage = [m_layout vGetPage:m_annot_pos.pageno]; - if( !vpage )//shall not happen + + PDF_RECT rect; + [m_annot getRect:&rect]; + + /* + RDPDFPageContent *content = [[RDPDFPageContent alloc] init]; + [content gsSave]; + float width = (rect.right - rect.left); + float height = (rect.bottom - rect.top); + + float xTranslation = width / 2.0f; + float yTranslation = height / 2.0f; + + //set the matrix 20x20 + RDPDFMatrix *matrix = [[RDPDFMatrix alloc] init:width :height :xTranslation :yTranslation]; + [content gsCatMatrix:matrix]; + matrix = nil; + + [content drawText:@"Testo di prova" :0 :50.0]; + [content gsRestore]; + content = nil; + */ + + m_annot_idx = [m_annot getIndex]; + + if(m_del && [m_del respondsToSelector:@selector(OnAnnotTapped:atPage:atPoint:)]) { - if(self.m_del) [self.m_del OnSingleTapped:x:y]; + [m_del OnAnnotTapped:m_annot atPage:m_cur_page atPoint:CGPointMake(x, y)]; + } + + if (![self canSaveDocument] && m_annot.type != 1) { + if (m_del) [m_del OnSingleTapped:x:y]; return; - } - PDFPage *page = [vpage GetPage]; - if( !page ) return; - m_annot = [page annotAtPoint:m_annot_pos.pdfx: m_annot_pos.pdfy]; - m_annot_idx = -1; - if( m_annot ) - { - m_annot_idx = [m_annot getIndex]; - - if(self.m_del && [self.m_del respondsToSelector:@selector(OnAnnotTapped:atPage:atPoint:)]) - { - [self.m_del OnAnnotTapped:m_annot atPage:m_cur_page atPoint:CGPointMake(x, y)]; + } + + if ([m_annot isAnnotReadOnly] && !([self isReadOnlyAnnotEnabled:m_annot])) + return; + + self.scrollEnabled = false; + m_status = sta_annot; + [m_annot getRect:&m_annot_rect]; + m_annot_rect.left = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.left]; + m_annot_rect.right = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.right]; + float tmp = m_annot_rect.top; + m_annot_rect.top = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:m_annot_rect.bottom]; + m_annot_rect.bottom = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:tmp]; + [self ProRedrawOS]; + + int nu = [m_annot getCheckStatus]; + if (nu != -1) { + switch (nu) { + case 0: + [m_annot setCheckValue:YES]; + break; + case 1: + [m_annot setCheckValue:NO]; + default: + //case 2,3 set Radiobox + [m_annot setRadio]; + break; } - - if (![self canSaveDocument] && m_annot.type != 1) { - if( self.m_del ) - { - if (!isDoubleTapping) { - NSArray *a = [NSArray arrayWithObjects:[NSNumber numberWithFloat:x], [NSNumber numberWithFloat:y], nil]; - [self performSelector:@selector(delayedOnSingleTapping:) withObject:a afterDelay:0.3]; - } - } - return; + [self setModified:YES force:NO]; + //need refresh PDFView and save annot status + [self ProUpdatePage :m_annot_pos.pageno]; + [self vAnnotEnd]; + [self autoSave]; + return; + } + + nu = [m_annot getComboItemCount]; + if (nu != -1){ + //int j= [m_annot getComboSel]; + NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0]; + for (int i = 0; i < nu; i++) { + NSString *str = [m_annot getComboItem:i]; + [arr addObject:str]; } - if ([m_annot isAnnotReadOnly] && !([self isReadOnlyAnnotEnabled:m_annot])) - return; - - self.scrollEnabled = false; - m_status = sta_annot; - [m_annot getRect:&m_annot_rect]; - m_annot_rect.left = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.left]; - m_annot_rect.right = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.right]; - float tmp = m_annot_rect.top; - m_annot_rect.top = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:m_annot_rect.bottom]; - m_annot_rect.bottom = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:tmp]; - [self ProRedrawOS]; + [self executeAnnotJS]; - int nu = [m_annot getCheckStatus]; - if (nu != -1) { - switch (nu) { - case 0: - [m_annot setCheckValue:YES]; - break; - case 1: - [m_annot setCheckValue:NO]; - default: - //case 2,3 set Radiobox - [m_annot setRadio]; - break; - } - [self setModified:YES force:NO]; - //need refresh PDFView and save annot status - [self ProUpdatePage :m_annot_pos.pageno]; - [self vAnnotEnd]; - [self autoSave]; - return; + if (m_del){ + [m_del OnAnnotCommboBox :vpage :m_annot :[self annotRect] :arr selected:[m_annot getComboSel]]; } + return ; + } + + nu = [m_annot getListItemCount]; + if (nu != -1){ - nu = [m_annot getComboItemCount]; - if (nu != -1){ - //int j= [m_annot getComboSel]; - NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0]; - for (int i = 0; i < nu; i++) { - NSString *str = [m_annot getComboItem:i]; - [arr addObject:str]; - } - - [self executeAnnotJS]; - - if (self.m_del){ - [self.m_del OnAnnotCommboBox :m_annot :[self annotRect] :arr selected:[m_annot getComboSel]]; - } - return ; - } + //BOOL multi = [m_annot isMultiSel]; - nu = [m_annot getListItemCount]; - if (nu != -1){ - - //BOOL multi = [m_annot isMultiSel]; - - NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0]; - for (int i = 0; i < nu; i++) { - NSString *str = [m_annot getListItem:i]; - [arr addObject:str]; - } - - // GET SELECTED ITEMS - - int sels[16]; //custom this number of sels - int count = [m_annot getListSels:sels :16]; //count is how many cell had been selected - int *cur = sels; - int *end = sels + count; - NSMutableArray *selected_items = [NSMutableArray array]; - while(cur < end) - { - [selected_items addObject:[NSNumber numberWithInt:*cur]]; //selected cell index - cur++; - } - - if (self.m_del){ - [self.m_del OnAnnotList:m_annot :[self annotRect] :arr selectedIndexes:selected_items]; // Modified method - } - - return; + NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0]; + for (int i = 0; i < nu; i++) { + NSString *str = [m_annot getListItem:i]; + [arr addObject:str]; } - int type = [m_annot getEditType]; - if (type > 0) { - if (self.m_del) { - [self.m_del OnAnnotEditBox:m_annot :[self annotRect] :[m_annot getEditText] :([m_annot getEditTextSize] / m_scale_pix) * (m_zoom * [m_layout vGetScaleMin:m_cur_page])]; - } - return ; - } + // GET SELECTED ITEMS - NSString *nuri = [m_annot getURI]; - if(nuri)//open url + int sels[16]; //custom this number of sels + int count = [m_annot getListSels:sels :16]; //count is how many cell had been selected + int *cur = sels; + int *end = sels + count; + NSMutableArray *selected_items = [NSMutableArray array]; + while(cur < end) { - if( self.m_del && GLOBAL.g_auto_launch_link) - { - [self.m_del OnAnnotOpenURL:nuri]; - [self vAnnotEnd]; - return; - } + [selected_items addObject:[NSNumber numberWithInt:*cur]]; //selected cell index + cur++; } - if(self.m_del) [self.m_del OnAnnotClicked:m_annot :[self annotRect] :x :y]; + if (m_del){ + [m_del OnAnnotList :vpage :m_annot :[self annotRect] :arr selectedIndexes:selected_items];// Modified method + } + return; } - else + + int type = [m_annot getEditType]; + if (type > 0) { + if (m_del) { + [m_del OnAnnotEditBox:m_annot :[self annotRect] :[m_annot getEditText] :([m_annot getEditTextSize] / m_scale_pix) * vpage.scale]; + } + return ; + } + + NSString *nuri = [m_annot getURI]; + nuri = [m_annot getURI]; + if(nuri)//open url { - if(self.m_del) { - NSArray *a = [NSArray arrayWithObjects:[NSNumber numberWithFloat:x], [NSNumber numberWithFloat:y], nil]; - [self performSelector:@selector(delayedOnSingleTapping:) withObject:a afterDelay:0.3]; + if( GLOBAL.g_auto_launch_link) + { + if(m_del) [m_del OnAnnotOpenURL:nuri]; + [self vAnnotEnd]; + return; + } + } + + if ([self canSaveDocument] && m_annot.fieldType == 4 && m_annot.getSignStatus == 0){ + if (m_del && GLOBAL.g_hand_signature) { + [m_del OnAnnotSignature :vpage :m_annot]; } + return; } + + if(m_del) [m_del OnAnnotClicked:m_annot :[self annotRect] :x :y]; + } + else + { + if (m_del) [m_del OnSingleTapped:x:y]; + [self vAnnotEnd]; + m_annot_rect.left = 0; + m_annot_rect.top = 0; + m_annot_rect.right = 0; + m_annot_rect.bottom = 0; + m_status = sta_none; + } +} + +- (void)resetZoomLevel +{ + enum LAYOUT_STATUS save_status = m_status; + [self zoomPageToScale:1.0 atPoint:CGPointMake([m_layout vw] / (m_scale_pix * 2), [m_layout vh] / (m_scale_pix * 2))]; + + if ([imgAnnot isDescendantOfView:self]) { + CGPoint center = self.center; + center.x += self.contentOffset.x; + center.y += self.contentOffset.y; + imgAnnot.center = center; + } + m_status = save_status; +} + +- (void)defaultZoom:(UITouch *)touch +{ + if (self.zoomScale == GLOBAL.g_tap_zoom_level && GLOBAL.g_zoom_step > 0) { + GLOBAL.g_zoom_step *= -1; + } else if (self.zoomScale <= self.minimumZoomScale && GLOBAL.g_zoom_step) { + GLOBAL.g_zoom_step = 1; } + if (self.zoomScale > GLOBAL.g_tap_zoom_level) m_zoom = 1; + else m_zoom = (self.zoomScale + GLOBAL.g_zoom_step > GLOBAL.g_tap_zoom_level) ? GLOBAL.g_tap_zoom_level : self.zoomScale + GLOBAL.g_zoom_step; + [self zoomPageToScale:m_zoom atPoint:[touch locationInView:m_canvas]]; } -(bool)OnSelTouchBegin:(CGPoint)point @@ -1299,11 +2732,11 @@ -(bool)OnSelTouchBegin:(CGPoint)point if( m_status != sta_sel ) return false; m_tx = point.x * m_scale_pix; m_ty = point.y * m_scale_pix; - [m_layout vGetPos : m_tx * m_zoom: m_ty * m_zoom :&m_sel_pos]; + [m_layout vGetPos : m_tx: m_ty :&m_sel_pos]; m_sel = [[RDVSel alloc] init:[m_doc page :m_sel_pos.pageno] :m_sel_pos.pageno]; - if( self.m_del ) - [self.m_del OnSelStart:point.x: point.y]; + if( m_del ) + [m_del OnSelStart:point.x: point.y]; return true; } @@ -1311,8 +2744,8 @@ -(bool)OnSelTouchMove:(CGPoint)point { if( m_status != sta_sel ) return false; RDVPage *vp = [m_layout vGetPage:m_sel_pos.pageno]; - float pdfx = [vp GetPDFX :[m_layout docx] + point.x * m_scale_pix * m_zoom]; - float pdfy = [vp GetPDFY :[m_layout docy] + point.y * m_scale_pix * m_zoom]; + float pdfx = [vp GetPDFX :[m_layout docx] + point.x * m_scale_pix]; + float pdfy = [vp GetPDFY :[m_layout docy] + point.y * m_scale_pix]; [m_sel SetSel :m_sel_pos.pdfx :m_sel_pos.pdfy :pdfx :pdfy]; [self ProRedrawOS]; @@ -1322,42 +2755,10 @@ -(bool)OnSelTouchMove:(CGPoint)point -(bool)OnSelTouchEnd:(CGPoint)point { if( m_status != sta_sel ) return false; - - if( self.m_del ) - [self.m_del OnSelEnd :m_tx/m_scale_pix :m_ty/m_scale_pix :point.x :point.y]; - return true; -} -- (NSString *)getImageFromRect:(int)top :(int)right :(int)left :(int)bottom :(int) pageNum -{ - if (!m_doc) - return nil; - - // set dib size with the draw_rect - int width = right - left; - int height = bottom - top; - - // get the selected page - PDFPage *page = [m_doc page:pageNum]; - [page objsStart]; - PDFDIB *dib = [[PDFDIB alloc] init :width :height]; - - // set the matrix with the draw_rect (we need only a portion of the page) - PDFMatrix *mat = [[PDFMatrix alloc] init :1 :-1 :-left :bottom]; - [page renderPrepare :dib]; - [page render :dib :mat :2];//always render best. - mat = NULL; - - // get the UIImage - UIImage *img = [UIImage imageWithCGImage:[dib image]]; - - //save image in PNG - NSString *tempDir = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.png"]; - [UIImagePNGRepresentation(img) writeToFile:tempDir atomically:YES]; - - NSString *imageBase64 = [UIImagePNGRepresentation(img) base64EncodedStringWithOptions:(NSDataBase64Encoding64CharacterLineLength)]; - - return imageBase64; + if( m_del ) + [m_del OnSelEnd :m_tx/m_scale_pix :m_ty/m_scale_pix :point.x :point.y]; + return true; } -(bool)OnAnnotTouchBegin:(CGPoint)point @@ -1388,8 +2789,8 @@ -(bool)OnAnnotTouchEnd:(CGPoint)point { if (m_status != sta_annot) return false; if (m_annot.type == 20) { // EditText - if (self.m_del) { - [self.m_del OnAnnotEnd]; + if (m_del) { + [m_del OnAnnotEnd]; } } @@ -1403,18 +2804,18 @@ -(bool)OnAnnotTouchEnd:(CGPoint)point m_tx = point.x * m_scale_pix; m_ty = point.y * m_scale_pix; - m_annot_rect.left += (m_tx - m_px) * m_zoom; - m_annot_rect.top += (m_ty - m_py) * m_zoom; - m_annot_rect.right += (m_tx - m_px) * m_zoom; - m_annot_rect.bottom += (m_ty - m_py) * m_zoom; + m_annot_rect.left += (m_tx - m_px); + m_annot_rect.top += (m_ty - m_py); + m_annot_rect.right += (m_tx - m_px); + m_annot_rect.bottom += (m_ty - m_py); RDVPage *vpage = [m_layout vGetPage:m_annot_pos.pageno]; RDVPos pos; - [m_layout vGetPos :point.x * m_scale_pix * m_zoom :point.y * m_scale_pix *m_zoom :&pos]; - PDFPage *page = [vpage GetPage]; - PDFAnnot *annot = [page annotAtIndex:m_annot_idx]; + [m_layout vGetPos :point.x * m_scale_pix :point.y * m_scale_pix :&pos]; + RDPDFPage *page = [vpage GetPage]; + RDPDFAnnot *annot = [page annotAtIndex:m_annot_idx]; if( pos.pageno == m_annot_pos.pageno ) { - PDFMatrix *mat = [vpage CreateInvertMatrix + RDPDFMatrix *mat = [vpage CreateInvertMatrix :self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; [mat transformRect:&m_annot_rect]; @@ -1432,10 +2833,10 @@ -(bool)OnAnnotTouchEnd:(CGPoint)point else if (m_tx != m_px && m_ty != m_py) { RDVPage *vdest = [m_layout vGetPage:pos.pageno]; - PDFPage *dpage = [vdest GetPage]; + RDPDFPage *dpage = [vdest GetPage]; if( dpage ) { - PDFMatrix *mat = [vdest CreateInvertMatrix + RDPDFMatrix *mat = [vdest CreateInvertMatrix :self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; [mat transformRect :&m_annot_rect]; @@ -1445,12 +2846,11 @@ -(bool)OnAnnotTouchEnd:(CGPoint)point [m_annot getRect:&rect]; PDF_OBJ_REF ref = [m_annot getRef]; - - [annot MoveToPage :dpage :&m_annot_rect]; + [annot MoveToPage :dpage :&m_annot_rect]; [self ProUpdatePage :m_annot_pos.pageno]; [self ProUpdatePage :pos.pageno]; - + ASMove *item = [[ASMove alloc] initWithPage:m_annot_pos.pageno initRect:rect destPage:pos.pageno destRect:m_annot_rect index:([dpage annotCount] - 1) ref:ref]; [actionManger push:item]; item.m_pageno = item.m_pageno0; @@ -1486,11 +2886,11 @@ -(bool)OnNoteTouchEnd:(CGPoint)point { if( m_status != sta_note ) return false; RDVPos pos; - [m_layout vGetPos :point.x * m_scale_pix * m_zoom :point.y * m_scale_pix * m_zoom :&pos]; + [m_layout vGetPos :point.x * m_scale_pix :point.y * m_scale_pix :&pos]; RDVPage *vpage = [m_layout vGetPage:pos.pageno]; if( vpage ) { - PDFPage *page = [vpage GetPage]; + RDPDFPage *page = [vpage GetPage]; if( page ) { [self setModified:YES force:NO]; @@ -1521,7 +2921,7 @@ -(bool)OnInkTouchBegin:(CGPoint)point { m_tx = point.x * m_scale_pix; m_ty = point.y * m_scale_pix; - m_ink = [[PDFInk alloc] init :GLOBAL.g_ink_width * m_scale_pix: GLOBAL.g_ink_color]; + m_ink = [[RDPDFInk alloc] init :GLOBAL.g_ink_width * m_scale_pix: GLOBAL.g_ink_color]; } [m_ink onDown :point.x * m_scale_pix :point.y * m_scale_pix]; return true; @@ -1542,6 +2942,56 @@ -(bool)OnInkTouchEnd:(CGPoint)point return true; } +-(bool)OnPolygonTouchBegin:(CGPoint)point +{ + if( m_status != sta_polygon ) return false; + return true; +} +-(bool)OnPolygonTouchMove:(CGPoint)point +{ + if( m_status != sta_polygon ) return false; + return true; +} +-(bool)OnPolygonTouchEnd:(CGPoint)point +{ + if( m_status != sta_polygon ) return false; + if (!m_polygon) m_polygon = [[RDPDFPath alloc] init]; + if([m_polygon nodesCount] < 1) + { + m_tx = point.x * m_scale_pix; + m_ty = point.y * m_scale_pix; + [m_polygon moveTo:m_tx :m_ty]; + } + else [m_polygon lineTo:point.x * m_scale_pix :point.y * m_scale_pix]; + [self ProRedrawOS]; + return true; +} + +-(bool)OnPolylineTouchBegin:(CGPoint)point +{ + if( m_status != sta_polyline ) return false; + return true; +} +-(bool)OnPolylineTouchMove:(CGPoint)point +{ + if( m_status != sta_polyline ) return false; + return true; +} +-(bool)OnPolylineTouchEnd:(CGPoint)point +{ + if( m_status != sta_polyline ) return false; + if (!m_polygon) m_polygon = [[RDPDFPath alloc] init]; + if([m_polygon nodesCount] < 1) + { + m_tx = point.x * m_scale_pix; + m_ty = point.y * m_scale_pix; + [m_polygon moveTo:m_tx :m_ty]; + } + else [m_polygon lineTo:point.x * m_scale_pix :point.y * m_scale_pix]; + [self ProRedrawOS]; + return true; +} + -(bool)OnLineTouchBegin:(CGPoint)point { if( m_status != sta_line ) return false; @@ -1707,7 +3157,11 @@ -(bool)OnImageTouchMove:(CGPoint)point if (!isRotating) { float width = (deltaMoveX > deltaMoveY) ? self.contentOffset.x + point.x - origin.origin.x : (self.contentOffset.y + point.y - origin.origin.y) * prop; float height = (deltaMoveX < deltaMoveY) ? self.contentOffset.y + point.y - origin.origin.y : (self.contentOffset.x + point.x - origin.origin.x) / prop; - [imgAnnot setFrame:CGRectMake(origin.origin.x, origin.origin.y, width, height)]; + if(width > 0 && height > 0) + { + [imgAnnot setFrame:CGRectMake(origin.origin.x, origin.origin.y, width, height)]; + } + } else { double l1 = point.x - imgAnnot.center.x; double l2 = imgAnnot.center.y - point.y; @@ -1759,6 +3213,74 @@ - (NSData *)rotateImage:(UIImage *)img return UIImagePNGRepresentation(result) ; } +-(bool)OnEditboxTouchBegin:(CGPoint)point +{ + if( m_status != sta_editbox ) return false; + if( m_rects_cnt >= m_rects_max ) + { + m_rects_max += 8; + m_rects = (PDF_POINT *)realloc(m_rects, (m_rects_max<<1) * sizeof(PDF_POINT)); + } + m_tx = point.x * m_scale_pix; + m_ty = point.y * m_scale_pix; + PDF_POINT *pt_cur = &m_rects[m_rects_cnt<<1]; + pt_cur->x = m_tx; + pt_cur->y = m_ty; + pt_cur[1].x = m_tx; + pt_cur[1].y = m_ty; + m_rects_drawing = true; + return true; +} + +-(bool)OnEditboxTouchMove:(CGPoint)point +{ + if( m_status != sta_editbox ) return false; + PDF_POINT *pt_cur = &m_rects[m_rects_cnt<<1]; + pt_cur[1].x = point.x * m_scale_pix; + pt_cur[1].y = point.y * m_scale_pix; + [self ProRedrawOS]; + return true; +} + +-(bool)OnEditboxTouchEnd:(CGPoint)point +{ + if( m_status != sta_editbox ) return false; + PDF_POINT *pt_cur = &m_rects[m_rects_cnt<<1]; + pt_cur[1].x = point.x * m_scale_pix; + pt_cur[1].y = point.y * m_scale_pix; + m_rects_cnt++; + if( m_rects_drawing ) + { + m_rects_drawing = false; + [self ProRedrawOS]; + } + + [m_layout vGetPos :pt_cur[0].x :pt_cur[0].y :&m_annot_pos]; + if (m_del) [m_del OnEditboxOK]; + RDVPage *vpage = [m_layout vGetPage:m_annot_pos.pageno]; + if( !vpage ) return true;//shall not happen + RDPDFPage *page = [vpage GetPage]; + if( !page ) return true;//shall not happen + m_annot_idx = [page annotCount] - 1; + m_annot = [page annotAtIndex:m_annot_idx]; + m_status = sta_annot; + self.scrollEnabled = false; + m_status = sta_annot; + [m_annot getRect:&m_annot_rect]; + m_annot_rect.left = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.left]; + m_annot_rect.right = [vpage x] - self.contentOffset.x * m_scale_pix + [vpage ToDIBX:m_annot_rect.right]; + float tmp = m_annot_rect.top; + m_annot_rect.top = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:m_annot_rect.bottom]; + m_annot_rect.bottom = [vpage y] - self.contentOffset.y * m_scale_pix + [vpage ToDIBY:tmp]; + [self ProRedrawOS]; + + if (m_del) { + [m_del OnAnnotEditBox:m_annot :[self annotRect] :[m_annot getEditText] :([m_annot getEditTextSize] / m_scale_pix) * vpage.scale]; + } + + return true; +} + -(void)OnNoneTouchBegin:(CGPoint)point :(NSTimeInterval)timeStamp { m_tstamp = timeStamp; @@ -1791,8 +3313,8 @@ -(void)OnNoneTouchMove:(CGPoint)point :(NSTimeInterval)timeStamp if( dx < 10 && dx > -10 && dy < 10 && dy > -10 ) { m_status = sta_none; - if( self.m_del ) - [self.m_del OnLongPressed :point.x :point.y]; + if( m_del ) + [m_del OnLongPressed :point.x :point.y]; } } } @@ -1804,18 +3326,16 @@ -(void)OnNoneTouchEnd:(CGPoint)point :(NSTimeInterval)timeStamp { float dx = point.x - m_tx / m_scale_pix; float dy = point.y - m_ty / m_scale_pix; - if( timeStamp - m_tstamp_tap < 0.15 )//single tap + if( timeStamp - m_tstamp_tap < 0.20 )//single tap { bool single_tap = true; if( dx > 5 || dx < -5 ) single_tap = false; if( dy > 5 || dy < -5 ) single_tap = false; - if( single_tap ) - { - [self OnSingleTap :point.x :point.y]; - } + if (!single_tap) m_doubleTapCount = 0; } else { + m_doubleTapCount = 0; bool long_press = true; if( dx > 5 || dx < -5 ) long_press = false; @@ -1823,8 +3343,8 @@ -(void)OnNoneTouchEnd:(CGPoint)point :(NSTimeInterval)timeStamp long_press = false; if( long_press ) { - if( self.m_del ) - [self.m_del OnLongPressed:point.x :point.y]; + if( m_del ) + [m_del OnLongPressed:point.x :point.y]; } } } @@ -1832,12 +3352,12 @@ -(void)OnNoneTouchEnd:(CGPoint)point :(NSTimeInterval)timeStamp - (void)vAddTextAnnot:(int)x :(int)y :(NSString *)text :(NSString *)subject { RDVPos pos; - [m_layout vGetPos:x * m_scale_pix * m_zoom :y * m_scale_pix * m_zoom :&pos]; + [m_layout vGetPos:x * m_scale_pix :y * m_scale_pix :&pos]; if(pos.pageno>=0) { RDVPage *vpage = [m_layout vGetPage:pos.pageno]; if( !vpage ) return; - PDFPage *page = [vpage GetPage]; + RDPDFPage *page = [vpage GetPage]; if (!page) { return; } @@ -1851,26 +3371,26 @@ - (void)vAddTextAnnot:(int)x :(int)y :(NSString *)text :(NSString *)subject //Action Stack Manger [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; - PDFAnnot *annot = [page annotAtIndex: [page annotCount] - 1]; + RDPDFAnnot *annot = [page annotAtIndex: [page annotCount] - 1]; [annot setPopupSubject:subject]; [annot setPopupText:text]; // Set Author and Modify date [self updateLastAnnotInfoAtPage:page]; - [self refreshCurrentPage]; + [self ProUpdatePage:pos.pageno]; [self autoSave]; } } -- (PDFAnnot *)vGetTextAnnot:(int)x :(int)y +- (RDPDFAnnot *)vGetTextAnnot:(int)x :(int)y { - PDFAnnot *annot; + RDPDFAnnot *annot; RDVPos pos; - [m_layout vGetPos:x * m_scale_pix * m_zoom :y * m_scale_pix * m_zoom :&pos]; + [m_layout vGetPos:x * m_scale_pix :y * m_scale_pix :&pos]; if(pos.pageno>=0) { - PDFPage *page = [m_doc page:pos.pageno]; + RDPDFPage *page = [m_doc page:pos.pageno]; [page objsStart]; if( !page ) return NULL; annot = [page annotAtPoint:pos.pdfx: pos.pdfy]; @@ -1886,15 +3406,15 @@ - (void)vAddImageWithImage:(UIImage *)image withRect:(PDF_RECT)rect tp = [tp stringByAppendingPathComponent:@"cache.dat"]; [m_doc setCache:tp]; - // Create the PDFPage instance of the current page - PDFPage *page = [m_doc page:m_cur_page]; + // Create the RDPDFPage instance of the current page + RDPDFPage *page = [m_doc page:m_cur_page]; [page objsStart]; // Create the CGImageRef of the image CGImageRef ref = [image CGImage]; - // Get PDFDocImage instance from CGImageRef (keeping alpha channel) - PDFDocImage *i = [m_doc newImage:ref :YES]; + // Get RDPDFDocImage instance from CGImageRef (keeping alpha channel) + RDPDFDocImage *i = [m_doc newImage:ref :YES]; // Add the image [page addAnnotBitmap:i :&rect]; @@ -1914,64 +3434,23 @@ - (void)vAddImageWithImage:(UIImage *)image withRect:(PDF_RECT)rect [self autoSave]; } -- (void)selectListBoxItems:(NSArray *)items +- (BOOL)PDFSignField:(RDVPage *)vp :(RDPDFAnnot *)annot { - if (m_annot == nil || [m_annot getListItemCount] == -1) { // Check if it is a list box - return; - } - - // Items contains indexes to select - if (items.count > 1 && ![m_annot isMultiSel]) { - return; - } - - int select[items.count]; - - for (int i = 0; i < items.count; i++) { - select[i] = [[items objectAtIndex:i] intValue]; - } - - [m_annot setListSels:select :(int)items.count]; - - [self executeAnnotJS]; - - [self ProUpdatePage:m_cur_page]; - - [self setModified:YES force:NO]; - - [self vAnnotEnd]; - - [self autoSave]; -} + if (!vp) return false; -- (BOOL)setSignatureImageAtIndex:(int)index atPage:(int)pageNum { // Create path. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:TEMP_SIGNATURE]; + UIImage *image = [UIImage imageWithContentsOfFile:filePath]; - UIImage *image = [UIImage imageWithContentsOfFile:filePath]; - - //get the PDFVPage - RDVPage *vpage = [m_layout vGetPage:pageNum]; - if( !vpage ) return NO; - - //get the PDFPage - PDFPage *page = [vpage GetPage]; - if (!page) { - return NO; - } - - //get the annotation - PDFAnnot *annot = [page annotAtIndex:index]; - - //init PDFDocForm and PDFPageContent - PDFDocForm *form = [m_doc newForm]; - PDFPageContent *content = [[PDFPageContent alloc] init]; + //init RDPDFDocForm and RDPDFPageContent + RDPDFDocForm *form = [m_doc newForm]; + RDPDFPageContent *content = [[RDPDFPageContent alloc] init]; [content gsSave]; - //create PDFDocImage with CGImageRef + //create RDPDFDocImage with CGImageRef CGImageRef ref = [image CGImage]; - PDFDocImage *docImage = [m_doc newImage:ref :YES]; + RDPDFDocImage *docImage = [m_doc newImage:ref :YES]; PDF_PAGE_IMAGE rimg = [form addResImage:docImage]; PDF_RECT rect; @@ -1989,34 +3468,33 @@ - (BOOL)setSignatureImageAtIndex:(int)index atPage:(int)pageNum { float yTranslation = (height - originalHeight * scale) / 2.0f; //set the matrix 20x20 - PDFMatrix *matrix = [[PDFMatrix alloc] init:scale * originalWidth :scale * originalHeight :xTranslation :yTranslation]; + RDPDFMatrix *matrix = [[RDPDFMatrix alloc] init:scale * originalWidth :scale * originalHeight :xTranslation :yTranslation]; [content gsCatMatrix:matrix]; matrix = nil; - //draw the image on the PDFPageContent + //draw the image on the RDPDFPageContent [content drawImage:rimg]; [content gsRestore]; - - //set the content on the PDFDocForm + //set the content on the RDPDFDocForm [form setContent:0 :0 :width :height :content]; - - //set the custom icon - BOOL success = [annot setIcon2:@"myIcon" :form]; - //free objects content = nil; - page = nil; - - [self ProUpdatePage:pageNum]; - // Delete temp signature image [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; - - if (success) { - [self setModified:YES force:NO]; + + BOOL ret = false; + if (GLOBAL.g_fake_sign) + ret = [annot setIcon2:@"rdsign" :form]; + else + { + NSString *cert_path = [[[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil] stringByAppendingPathComponent:@"test.pfx"]; + ret = ([annot signField:form :cert_path :@"111111" :@"" :@"" :@"" :@""] == 0); } - return success; + [self vClearOP]; + [self setModified:NO force:YES]; + [self ProUpdatePage:vp.pageno]; + return ret; } /* -(void)vGetTextFromPoint:(CGPoint )point @@ -2076,73 +3554,24 @@ -(void)vGetTextFromPoint:(CGPoint )point } */ -- (void)setCommboItem:(int)item -{ - if ([m_annot getComboSel] != item) { - [self setModified:YES force:NO]; - } - [m_annot setComboSel:item]; - [self setModifyDateForAnnot:m_annot]; - [self ProUpdatePage:m_annot_pos.pageno]; - [self vAnnotEnd]; - - [self autoSave]; -} - -- (void)setEditBoxWithText:(NSString *)text +-(void)vUpdateAnnotPage { - if (m_status != sta_annot) return; - if (![[m_annot getEditText] isEqualToString:text]) { - [self setModified:YES force:NO]; - [self setModifyDateForAnnot:m_annot]; - } - [m_annot setEditText:text]; - - [self executeAnnotJS]; - [self ProUpdatePage:m_annot_pos.pageno]; - [self vAnnotEnd]; - - [self autoSave]; -} - - -- (void)refreshCurrentPage { - if (m_cur_page > 0) { - [self ProUpdatePage:m_cur_page - 1]; - } - if ((m_cur_page + 1) < [m_doc pageCount]) { - [self ProUpdatePage:m_cur_page + 1]; - } - - if (m_cur_page >= 0 && m_cur_page < [m_doc pageCount]) { - [self ProUpdatePage:m_cur_page]; - } - [self setNeedsDisplay]; - [m_child setNeedsDisplay]; -} - -- (void)refreshCachedPages { - int start = m_layout.cur_pg1; - int end = m_layout.cur_pg2; - - while (start < end) { - [self ProUpdatePage:start]; - start++; - } + [m_canvas setNeedsDisplay]; } - -- (void)vUpdateAnnotPage +- (void)vUpdatePage:(int)pageno { - [self ProUpdatePage:m_annot_pos.pageno]; + [self ProUpdatePage:pageno]; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } -- (CGFloat)vGetScale +-(void)vUpdateRange { - return [[m_layout vGetPage:m_cur_page] scale]; + [m_layout vRenderRange]; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } - (CGFloat)vGetPixSize @@ -2150,11 +3579,6 @@ - (CGFloat)vGetPixSize return m_scale_pix; } -- (BOOL)pagingAvailable -{ - return (GLOBAL.g_render_mode == 3 || GLOBAL.g_render_mode == 4 || GLOBAL.g_render_mode == 6); -} - - (BOOL)canSaveDocument { return ([m_doc canSave] && !readOnlyEnabled); @@ -2165,20 +3589,13 @@ - (void)setReadOnly:(BOOL)enabled readOnlyEnabled = enabled; } -- (void)setReaderBackgroundColor:(int)color +- (void)PDFSetGBColor:(int)color { - GLOBAL.g_readerview_bg_color = color; - - if (GLOBAL.g_readerview_bg_color != 0) { + if (color != 0) { self.backgroundColor = UIColorFromRGB(color); } } -- (void)setFirstPageCover:(BOOL)cover -{ - coverPage = cover; -} - - (void)setDoubleTapZoomMode:(int)mode { doubleTapZoomMode = mode; @@ -2203,7 +3620,7 @@ - (BOOL)useTempImage return NO; } -- (BOOL)isReadOnlyAnnotEnabled:(PDFAnnot *)annot +- (BOOL)isReadOnlyAnnotEnabled:(RDPDFAnnot *)annot { int pageno = [m_annot getDest]; if( pageno >= 0 ) //is goto annot @@ -2227,16 +3644,6 @@ - (BOOL)isReadOnlyAnnotEnabled:(PDFAnnot *)annot return NO; } -- (BOOL)forceSave -{ - if ([m_doc save]) { - [self setModified:NO force:YES]; - return YES; - } - - return NO; -} - #pragma mark - VFind -(bool)vFindStart:(NSString *)pat :(bool)match_case :(bool)whole_word @@ -2251,7 +3658,7 @@ -(void)vFind:(int)dir { if( [m_layout vFind:dir] < 0 )//no more found. { - if( self.m_del ) [self.m_del OnFound:false]; + if( m_del ) [m_del OnFound:false]; } [self ProRedrawOS]; @@ -2260,6 +3667,7 @@ -(void)vFindEnd { [m_layout vFindEnd]; [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } @@ -2279,7 +3687,7 @@ -(void)vSelEnd self.scrollEnabled = true; m_status = sta_none; m_sel = nil; - [self refreshCurrentPage]; + [self ProRedrawOS]; } } @@ -2289,12 +3697,12 @@ -(NSString *)vSelGetText return [m_sel GetSelString]; } --(BOOL)vSelMarkup:(int)color :(int)type +-(BOOL)vSelMarkup :(int)type { if( m_status != sta_sel || !m_sel ) return false; [self setModified:[m_sel SetSelMarkup:type] force:NO]; - [actionManger push:[[ASAdd alloc] initWithPage:m_sel.pageno page:m_sel.pdfpage index:(m_sel.pdfpage.annotCount - 1)]]; + [actionManger push:[[ASAdd alloc] initWithPage:m_sel.pageno page:m_sel.page index:(m_sel.page.annotCount - 1)]]; [self autoSave]; [self ProUpdatePage :m_sel_pos.pageno]; @@ -2313,16 +3721,14 @@ -(void)vAnnotPerform int pageno = [m_annot getDest]; if( pageno >= 0 )//goto page { - if(self.m_del) - [self.m_del OnAnnotGoto:pageno]; + if(m_del) [m_del OnAnnotGoto:pageno]; [self vAnnotEnd]; return; } NSString *nuri = [m_annot getURI]; if(nuri)//open url { - if(self.m_del) - [self.m_del OnAnnotOpenURL:nuri]; + if(m_del) [m_del OnAnnotOpenURL:nuri]; [self vAnnotEnd]; return; } @@ -2331,8 +3737,7 @@ -(void)vAnnotPerform { nuri = [[NSTemporaryDirectory() stringByAppendingString:@"/"] stringByAppendingString:nuri]; [m_annot getMovieData:nuri]; - if(self.m_del) - [self.m_del OnAnnotMovie:nuri]; + if(m_del) [m_del OnAnnotMovie:nuri]; [self vAnnotEnd]; return; } @@ -2342,27 +3747,15 @@ -(void)vAnnotPerform int spara[4]; nuri = [[NSTemporaryDirectory() stringByAppendingString:@"/"] stringByAppendingString:nuri]; [m_annot getSoundData:spara :nuri]; - if(self.m_del) - [self.m_del OnAnnotSound:nuri]; - [self vAnnotEnd]; - return; - } - nuri = [m_annot getPopupText]; - if( nuri ) - { - //popup dialog to show text and subject. - //nuri is text content. - //subj is subject string. - if(self.m_del && (![m_annot isAnnotReadOnly] || m_annot.type == 1)) - [self.m_del OnAnnotPopup:m_annot]; + if(m_del) [m_del OnAnnotSound:nuri]; [self vAnnotEnd]; return; } /* // Signature fields suck - most of the time th pop up simply doesn't show. if ([self canSaveDocument] && m_annot.fieldType == 4 && m_annot.getSignStatus == 0){ - if (self.m_del && [self.m_del respondsToSelector:@selector(OnAnnotSignature:)] && GLOBAL.g_enable_graphical_signature) { - [self.m_del OnAnnotSignature:m_annot]; + if (m_del && GLOBAL.g_hand_signature) { + [m_del OnAnnotSignature :[m_layout vGetPage:m_annot_pos.pageno] :m_annot]; } return; } @@ -2384,26 +3777,19 @@ -(void)vAnnotRemove [self setModified:YES force:NO]; //Action Stack Manger - PDFPage *page = [m_doc page:m_annot_pos.pageno]; + RDPDFPage *page = [m_doc page:m_annot_pos.pageno]; [actionManger push:[[ASDel alloc] initWithPage:m_annot_pos.pageno page:page index:m_annot_idx]]; - PDFAnnot *annot = [page annotAtIndex:m_annot_idx]; + RDPDFAnnot *annot = [page annotAtIndex:m_annot_idx]; [annot removeFromPage]; [self vAnnotEnd]; [self ProUpdatePage :m_annot_pos.pageno]; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; [self autoSave]; } --(void)removeAnnot :(PDFAnnot *)annot -{ - [annot removeFromPage]; - [self setNeedsDisplay]; - [m_child setNeedsDisplay]; - [m_doc save]; -} -(void)vAnnotEnd { @@ -2413,9 +3799,8 @@ -(void)vAnnotEnd m_annot_idx = -1; m_annot = nil; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; - if(self.m_del) - [self.m_del OnAnnotEnd]; + [m_canvas setNeedsDisplay]; + if(m_del) [m_del OnAnnotEnd]; } -(bool)vNoteStart @@ -2498,7 +3883,7 @@ -(void)vInkCancel m_status = sta_none; m_ink = NULL; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } } @@ -2507,15 +3892,13 @@ -(void)vInkEnd if( !m_ink ) m_status = sta_none; if( m_status != sta_ink ) return; RDVPos pos; - [m_layout vGetPos :m_tx * m_zoom :m_ty * m_zoom :&pos]; + [m_layout vGetPos :m_tx :m_ty :&pos]; if(pos.pageno >= 0) { RDVPage *vpage = [m_layout vGetPage:pos.pageno]; - PDFMatrix *mats = [[PDFMatrix alloc] init :m_zoom :m_zoom :0 :0]; - [mats transformInk:m_ink]; - PDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; - PDFPage *page = [vpage GetPage]; + RDPDFPage *page = [vpage GetPage]; [mat transformInk:m_ink]; [page addAnnotInk:m_ink]; // Set Author and Modify date @@ -2530,7 +3913,120 @@ -(void)vInkEnd m_status = sta_none; m_ink = nil; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + [self autoSave]; + self.scrollEnabled = true; +} +//enter ink annotation status. +-(bool)vPolygonStart +{ + if(![self canSaveDocument]) return false; + if( m_status == sta_none ) + { + self.scrollEnabled = false; + m_polygon = NULL; + m_status = sta_polygon; + return true; + } + return false; +} +//end ink annotation status. +-(void)vPolygonCancel +{ + if( m_status == sta_polygon ) + { + [self enableScroll]; + m_status = sta_none; + m_polygon = NULL; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + } +} +//end ink annotation status, and add ink to page. +-(void)vPolygonEnd +{ + if( !m_polygon ) m_status = sta_none; + if( m_status != sta_polygon ) return; + RDVPos pos; + [m_layout vGetPos :m_tx :m_ty :&pos]; + if(pos.pageno >= 0) + { + RDVPage *vpage = [m_layout vGetPage:pos.pageno]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + :self.contentOffset.y * m_scale_pix]; + RDPDFPage *page = [vpage GetPage]; + [mat transformPath:m_polygon]; + [page addAnnotPolygon:m_polygon :GLOBAL.g_line_annot_color :GLOBAL.g_line_annot_fill_color :GLOBAL.g_line_annot_width * m_scale_pix / [vpage scale]]; + // Set Author and Modify date + [self updateLastAnnotInfoAtPage:page]; + + //Action Stack Manger + [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; + + [self ProUpdatePage :pos.pageno]; + [self setModified:YES force:NO]; + } + m_status = sta_none; + m_polygon = nil; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + [self autoSave]; + self.scrollEnabled = true; +} + +//enter ink annotation status. +-(bool)vPolylineStart +{ + if(![self canSaveDocument]) return false; + if( m_status == sta_none ) + { + self.scrollEnabled = false; + m_polygon = NULL; + m_status = sta_polyline; + return true; + } + return false; +} +//end ink annotation status. +-(void)vPolylineCancel +{ + if( m_status == sta_polyline ) + { + [self enableScroll]; + m_status = sta_none; + m_polygon = NULL; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + } +} +//end ink annotation status, and add ink to page. +-(void)vPolylineEnd +{ + if( !m_polygon ) m_status = sta_none; + if( m_status != sta_polyline ) return; + RDVPos pos; + [m_layout vGetPos :m_tx :m_ty :&pos]; + if(pos.pageno >= 0) + { + RDVPage *vpage = [m_layout vGetPage:pos.pageno]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + :self.contentOffset.y * m_scale_pix]; + RDPDFPage *page = [vpage GetPage]; + [mat transformPath:m_polygon]; + [page addAnnotPolyline:m_polygon :0 :0 :GLOBAL.g_line_annot_color :GLOBAL.g_line_annot_fill_color :GLOBAL.g_line_annot_width * m_scale_pix / [vpage scale]]; + // Set Author and Modify date + [self updateLastAnnotInfoAtPage:page]; + + //Action Stack Manger + [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; + + [self ProUpdatePage :pos.pageno]; + [self setModified:YES force:NO]; + } + m_status = sta_none; + m_polygon = nil; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; [self autoSave]; self.scrollEnabled = true; } @@ -2609,11 +4105,11 @@ -(void)vLineEnd rect.top = pt_cur->y; rect.bottom = pt_cur[1].y; } - PDFPage *page = [vpage GetPage]; - PDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; + RDPDFPage *page = [vpage GetPage]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; [mat transformPoint:pt_cur]; [mat transformPoint:&pt_cur[1]]; - [page addAnnotLine:pt_cur :&pt_cur[1] :GLOBAL.g_line_width :GLOBAL.g_line_annot_style1 :GLOBAL.g_line_annot_style2 :GLOBAL.g_line_color :GLOBAL.g_line_annot_fill_color]; + [page addAnnotLine:pt_cur :&pt_cur[1] :GLOBAL.g_line_annot_width :GLOBAL.g_line_annot_style1 :GLOBAL.g_line_annot_style2 :GLOBAL.g_line_annot_color :GLOBAL.g_line_annot_fill_color]; //Action Stack Manger [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; @@ -2663,7 +4159,7 @@ -(void)vRectCancel m_rects_drawing = false; m_status = sta_none; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } } -(void)vRectEnd @@ -2679,7 +4175,7 @@ -(void)vRectEnd { PDF_RECT rect; RDVPos pos; - [m_layout vGetPos :pt_cur->x * m_zoom :pt_cur->y * m_zoom :&pos]; + [m_layout vGetPos :pt_cur->x :pt_cur->y :&pos]; if( pos.pageno >= 0 ) { RDVPage *vpage = [m_layout vGetPage:pos.pageno]; @@ -2697,29 +4193,29 @@ -(void)vRectEnd } if( pt_cur->x > pt_cur[1].x ) { - rect.right = pt_cur->x * m_zoom; - rect.left = pt_cur[1].x * m_zoom; + rect.right = pt_cur->x; + rect.left = pt_cur[1].x; } else { - rect.left = pt_cur->x * m_zoom; - rect.right = pt_cur[1].x * m_zoom; + rect.left = pt_cur->x; + rect.right = pt_cur[1].x; } if( pt_cur->y > pt_cur[1].y ) { - rect.bottom = pt_cur->y * m_zoom; - rect.top = pt_cur[1].y * m_zoom; + rect.bottom = pt_cur->y; + rect.top = pt_cur[1].y; } else { - rect.top = pt_cur->y * m_zoom; - rect.bottom = pt_cur[1].y * m_zoom; + rect.top = pt_cur->y; + rect.bottom = pt_cur[1].y; } - PDFPage *page = [vpage GetPage]; - PDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + RDPDFPage *page = [vpage GetPage]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; [mat transformRect:&rect]; - [page addAnnotRect:&rect: GLOBAL.g_rect_width * m_scale_pix / [vpage scale]: GLOBAL.g_rect_color: GLOBAL.g_rect_annot_fill_color]; + [page addAnnotRect:&rect: GLOBAL.g_rect_annot_width * m_scale_pix / [vpage scale]: GLOBAL.g_rect_annot_color: GLOBAL.g_rect_annot_fill_color]; //Action Stack Manger [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; @@ -2739,7 +4235,7 @@ -(void)vRectEnd cur++; } [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; [self autoSave]; self.scrollEnabled = true; @@ -2766,7 +4262,7 @@ -(void)vEllipseCancel m_ellipse_drawing = false; m_status = sta_none; [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; } } @@ -2783,7 +4279,7 @@ -(void)vEllipseEnd { PDF_RECT rect; RDVPos pos; - [m_layout vGetPos :pt_cur->x * m_zoom :pt_cur->y * m_zoom :&pos]; + [m_layout vGetPos :pt_cur->x :pt_cur->y :&pos]; if( pos.pageno >= 0 ) { RDVPage *vpage = [m_layout vGetPage:pos.pageno]; @@ -2801,29 +4297,29 @@ -(void)vEllipseEnd } if( pt_cur->x > pt_cur[1].x ) { - rect.right = pt_cur->x * m_zoom; - rect.left = pt_cur[1].x * m_zoom; + rect.right = pt_cur->x; + rect.left = pt_cur[1].x; } else { - rect.left = pt_cur->x * m_zoom; - rect.right = pt_cur[1].x * m_zoom; + rect.left = pt_cur->x; + rect.right = pt_cur[1].x; } if( pt_cur->y > pt_cur[1].y ) { - rect.bottom = pt_cur->y * m_zoom; - rect.top = pt_cur[1].y * m_zoom; + rect.bottom = pt_cur->y; + rect.top = pt_cur[1].y; } else { - rect.top = pt_cur->y * m_zoom; - rect.bottom = pt_cur[1].y * m_zoom; + rect.top = pt_cur->y; + rect.bottom = pt_cur[1].y; } - PDFPage *page = [vpage GetPage]; - PDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + RDPDFPage *page = [vpage GetPage]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix :self.contentOffset.y * m_scale_pix]; [mat transformRect:&rect]; - [page addAnnotEllipse:&rect:GLOBAL.g_oval_width * m_scale_pix / [vpage scale] :GLOBAL.g_oval_color:GLOBAL.g_ellipse_annot_fill_color]; + [page addAnnotEllipse:&rect:GLOBAL.g_oval_annot_width * m_scale_pix / [vpage scale] :GLOBAL.g_oval_annot_color:GLOBAL.g_oval_annot_fill_color]; //Action Stack Manger [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; @@ -2843,7 +4339,7 @@ -(void)vEllipseEnd cur++; } [self setNeedsDisplay]; - [m_child setNeedsDisplay]; + [m_canvas setNeedsDisplay]; self.scrollEnabled = true; [self autoSave]; } @@ -2857,7 +4353,7 @@ - (BOOL)vImageStart m_status = sta_image; if(!imgAnnot) - imgAnnot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pdf_custom_stamp"]]; + imgAnnot = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_annot_stamp"]]; if (![imgAnnot isDescendantOfView:self]) { @@ -2910,8 +4406,8 @@ - (void)vImageEnd RDVPos pos1; RDVPos pos2; - [m_layout vGetPos:(imgAnnot.frame.origin.x - self.contentOffset.x) * m_scale_pix * m_zoom :(imgAnnot.frame.origin.y - self.contentOffset.y) * m_scale_pix * m_zoom: &pos1]; - [m_layout vGetPos:(imgAnnot.frame.origin.x - self.contentOffset.x + imgAnnot.frame.size.width) * m_scale_pix * m_zoom :(imgAnnot.frame.origin.y - self.contentOffset.y + imgAnnot.frame.size.height) * m_scale_pix * m_zoom :&pos2]; + [m_layout vGetPos:(imgAnnot.frame.origin.x - self.contentOffset.x) * m_scale_pix :(imgAnnot.frame.origin.y - self.contentOffset.y) * m_scale_pix: &pos1]; + [m_layout vGetPos:(imgAnnot.frame.origin.x - self.contentOffset.x + imgAnnot.frame.size.width) * m_scale_pix :(imgAnnot.frame.origin.y - self.contentOffset.y + imgAnnot.frame.size.height) * m_scale_pix :&pos2]; PDF_RECT rect; @@ -2931,6 +4427,112 @@ - (void)vImageEnd } } + +-(bool)vEditboxStart +{ + if(![self canSaveDocument]) return false; + if( m_status == sta_none ) + { + self.scrollEnabled = false; + m_status = sta_editbox; + m_rects_drawing = false; + return true; + } + return false; +} +-(void)vEditboxCancel +{ + if( m_status == sta_editbox ) + { + [self enableScroll]; + m_rects_cnt = 0; + m_rects_drawing = false; + m_status = sta_none; + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + } +} +-(void)vEditboxEnd +{ + if( m_status != sta_editbox ) return; + RDVPage *pages[128]; + int cur; + int end; + int pages_cnt = 0; + PDF_POINT *pt_cur = m_rects; + PDF_POINT *pt_end = pt_cur + (m_rects_cnt<<1); + while( pt_cur < pt_end ) + { + PDF_RECT rect; + RDVPos pos; + [m_layout vGetPos :pt_cur->x :pt_cur->y :&pos]; + if( pos.pageno >= 0 ) + { + RDVPage *vpage = [m_layout vGetPage:pos.pageno]; + cur = 0; + end = pages_cnt; + while( cur < end ) + { + if( pages[cur] == vpage ) break; + cur++; + } + if( cur >= end ) + { + pages[cur] = vpage; + pages_cnt++; + } + if( pt_cur->x > pt_cur[1].x ) + { + rect.right = pt_cur->x; + rect.left = pt_cur[1].x; + } + else + { + rect.left = pt_cur->x; + rect.right = pt_cur[1].x; + } + if( pt_cur->y > pt_cur[1].y ) + { + rect.bottom = pt_cur->y; + rect.top = pt_cur[1].y; + } + else + { + rect.top = pt_cur->y; + rect.bottom = pt_cur[1].y; + } + RDPDFPage *page = [vpage GetPage]; + RDPDFMatrix *mat = [vpage CreateInvertMatrix:self.contentOffset.x * m_scale_pix + :self.contentOffset.y * m_scale_pix]; + [mat transformRect:&rect]; + if (rect.right - rect.left < 80) rect.right = rect.left + 80; + if (rect.bottom - rect.top < 16) rect.top = rect.bottom - 16; + [page addAnnotEditText:&rect]; + + //Action Stack Manger + [actionManger push:[[ASAdd alloc] initWithPage:pos.pageno page:page index:(page.annotCount - 1)]]; + } + pt_cur += 2; + } + [self setModified:(m_rects_cnt != 0) force:NO]; + m_rects_cnt = 0; + m_rects_drawing = false; + m_status = sta_none; + + cur = 0; + end = pages_cnt; + while( cur < end ) + { + [self ProUpdatePage :[pages[cur] pageno]]; + cur++; + } + [self setNeedsDisplay]; + [m_canvas setNeedsDisplay]; + + [self autoSave]; + self.scrollEnabled = true; +} + - (void)enableScroll { self.scrollEnabled = true; @@ -2940,6 +4542,10 @@ - (void)enableScroll */ } +-(RDVFinder *)getView{ + return [m_layout finder]; +} + #pragma mark view Method -(void)vGetPos:(RDVPos *)pos { @@ -2948,7 +4554,7 @@ -(void)vGetPos:(RDVPos *)pos - (void)vGetPos:(RDVPos *)pos x:(int)x y:(int)y { - [m_layout vGetPos:x * m_scale_pix * m_zoom :y * m_scale_pix * m_zoom :pos]; + [m_layout vGetPos:x * m_scale_pix :y * m_scale_pix :pos]; } -(void)vGoto:(int)pageno @@ -2962,11 +4568,6 @@ -(void)vGoto:(int)pageno [self setNeedsDisplay]; } -- (int)vGetCurrentPage -{ - return m_cur_page; -} - - (void)vUndo { ASItem *item = [actionManger undo]; @@ -2988,23 +4589,22 @@ - (void)vUndo } [actionManger orderIndexes:item]; - //[self refreshCurrentPage]; // call update delegate method if(pg0 == pg1) { [self ProUpdatePage:pg0]; - if(self.m_del) - [self.m_del OnPageUpdated:pg0]; + if(m_del) + [m_del OnPageUpdated:pg0]; } else { [self ProUpdatePage:pg1]; [self ProUpdatePage:pg0]; - if(self.m_del) + if(m_del) { - [self.m_del OnPageUpdated:pg1]; - [self.m_del OnPageUpdated:pg0]; + [m_del OnPageUpdated:pg1]; + [m_del OnPageUpdated:pg0]; } } } @@ -3032,36 +4632,40 @@ - (void)vRedo } [actionManger orderIndexes:item]; - //[self refreshCurrentPage]; // call update delegate method if(pg0 == pg1) { [self ProUpdatePage:pg0]; - if(self.m_del) - [self.m_del OnPageUpdated:pg0]; + if(m_del) + [m_del OnPageUpdated:pg0]; } else { [self ProUpdatePage:pg0]; [self ProUpdatePage:pg1]; - if(self.m_del) + if(m_del) { - [self.m_del OnPageUpdated:pg0]; - [self.m_del OnPageUpdated:pg1]; + [m_del OnPageUpdated:pg0]; + [m_del OnPageUpdated:pg1]; } } } +- (void)vClearOP +{ + [actionManger clear]; +} + #pragma mark - PDFJSDelegate Methods - (void)executeAnnotJS { [self executeAnnotJS:m_annot]; } -- (void)executeAnnotJS:(PDFAnnot *)annot +- (void)executeAnnotJS:(RDPDFAnnot *)annot { - if (!annot || ! GLOBAL.g_execute_annot_JS) { + if (!annot || ! GLOBAL.g_exec_js) { return; } diff --git a/src/ios/PDFViewer/PDFView/PDFOffScreenView.h b/src/ios/PDFViewer/PDFView/PDFOffScreenView.h deleted file mode 100644 index e6aee0af..00000000 --- a/src/ios/PDFViewer/PDFView/PDFOffScreenView.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// PDFOffScreenView.h -// PDFViewer -// -// Created by Radaee on 2016/12/6. -// -// -#pragma once -#import "PDFObjc.h" -#import "RDVLayout.h" -#import "RDVSel.h" -#import "RDVFinder.h" - -@protocol PDFOffScreenDelegate --(void)onDrawOffScreen :(CGContextRef)ctx; -@end - -@interface PDFOffScreenView : UIView -{ - id m_del; -} --(id)initWithFrame:(CGRect)frame; --(void)setDelegate :(id)del; -@end diff --git a/src/ios/PDFViewer/PDFView/PDFOffScreenView.m b/src/ios/PDFViewer/PDFView/PDFOffScreenView.m deleted file mode 100644 index 884bf5ce..00000000 --- a/src/ios/PDFViewer/PDFView/PDFOffScreenView.m +++ /dev/null @@ -1,37 +0,0 @@ -// -// PDFOffScreenView.m -// PDFViewer -// -// Created by Radaee on 2016/12/6. -// -// - -#import -#import "PDFOffScreenView.h" -#import "RDVGlobal.h" - - -@implementation PDFOffScreenView --(id)initWithFrame:(CGRect)frame -{ - self = [super initWithFrame:frame]; - if(self) - { - m_del = nil; - } - return self; -} - --(void)setDelegate :(id)del; -{ - m_del = del; -} - --(void)drawRect:(CGRect)rect -{ - CGContextRef ctx = UIGraphicsGetCurrentContext(); - if(m_del) - [m_del onDrawOffScreen:ctx]; -} - -@end diff --git a/src/ios/PDFViewer/Modules/AnnotProp/PDFPopupCtrl.h b/src/ios/PDFViewer/PDFView/PDFPopupCtrl.h old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/Modules/AnnotProp/PDFPopupCtrl.h rename to src/ios/PDFViewer/PDFView/PDFPopupCtrl.h diff --git a/src/ios/PDFViewer/Modules/AnnotProp/PDFPopupCtrl.m b/src/ios/PDFViewer/PDFView/PDFPopupCtrl.m old mode 100644 new mode 100755 similarity index 97% rename from src/ios/PDFViewer/Modules/AnnotProp/PDFPopupCtrl.m rename to src/ios/PDFViewer/PDFView/PDFPopupCtrl.m index 9e3db18d..00c1e761 --- a/src/ios/PDFViewer/Modules/AnnotProp/PDFPopupCtrl.m +++ b/src/ios/PDFViewer/PDFView/PDFPopupCtrl.m @@ -67,7 +67,7 @@ - (id)init:(UIView *)view m_rect = m_view.frame; m_dismiss = nil; self.modalPresentationStyle = UIModalPresentationOverFullScreen; - self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + self.modalTransitionStyle = UIModalTransitionStyleCoverVertical; } return self; } diff --git a/src/ios/PDFViewer/PDFReflowView.h b/src/ios/PDFViewer/PDFView/PDFReflowView.h old mode 100644 new mode 100755 similarity index 67% rename from src/ios/PDFViewer/PDFReflowView.h rename to src/ios/PDFViewer/PDFView/PDFReflowView.h index ec31da90..51f099b5 --- a/src/ios/PDFViewer/PDFReflowView.h +++ b/src/ios/PDFViewer/PDFView/PDFReflowView.h @@ -7,12 +7,13 @@ // #import -#import "RDLoPDFViewController.h" +#import "PDFReaderCtrl.h" +#import "PDFObjc.h" @interface PDFReflowView : UIScrollView { - PDFDoc *m_doc; - PDFPage *m_page; + RDPDFDoc *m_doc; + RDPDFPage *m_page; CGImageRef m_img; UIImageView *imageView; UIImage *m_image; @@ -23,13 +24,13 @@ int m_w; int m_h; int m_cur_page; - PDFDIB *dib; + RDPDFDIB *m_dib; } @property (copy) UIImage *m_image; --(void)vOpen:(PDFDoc *)doc :(NSString *)docPath; -//-(void)vOpenPage:(PDFDoc *)doc :(int)pageno :(float)x :(float)y; +-(void)vOpen:(RDPDFDoc *)doc :(NSString *)docPath; +//-(void)vOpenPage:(RDPDFDoc *)doc :(int)pageno :(float)x :(float)y; //-(void)vGoto:(int)pageno; -(void)vClose; -(void)render :(int)PageNo :(float)ratio; diff --git a/src/ios/PDFViewer/PDFReflowView.m b/src/ios/PDFViewer/PDFView/PDFReflowView.m old mode 100644 new mode 100755 similarity index 63% rename from src/ios/PDFViewer/PDFReflowView.m rename to src/ios/PDFViewer/PDFView/PDFReflowView.m index 3828b57c..f7bb737b --- a/src/ios/PDFViewer/PDFReflowView.m +++ b/src/ios/PDFViewer/PDFView/PDFReflowView.m @@ -30,7 +30,7 @@ - (id)initWithFrame:(CGRect)frame return self; } --(void)vOpen:(PDFDoc *)doc :(NSString *)docPath +-(void)vOpen:(RDPDFDoc *)doc :(NSString *)docPath { [self vClose]; if(m_cur_page){ @@ -49,26 +49,16 @@ -(void)render :(int)PageNo :(float)ratio m_w = self.frame.size.width*scale; m_h = [m_page reflowPrepare:m_w - gap * 2:scale*ratio] + gap * 2; + if (m_h > 4000) m_h = 4000;//to avoid out of memory. CGSize size = CGRectMake(0, 0, m_w/scale, m_h/scale+44).size; [self setContentSize:size]; [imageView setFrame:CGRectMake(0, 0, m_w/scale, m_h/scale)]; - - dib = [[PDFDIB alloc] init:m_w :m_h]; - - - BOOL b = [m_page reflow:dib :gap:gap]; - - void *data = [dib data]; - CGDataProviderRef provider = CGDataProviderCreateWithData( NULL, data, m_w * m_h * 4, NULL ); - CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); - m_img = CGImageCreate( m_w, m_h, 8, 32, m_w<<2, cs, kCGBitmapByteOrder32Big|kCGImageAlphaNoneSkipLast, provider, NULL, FALSE, kCGRenderingIntentDefault ); - //CGColorSpaceRelease(cs); - //CGDataProviderRelease( provider ); - //imageView.image = nil; - - m_image = [UIImage imageWithCGImage:m_img]; - NSString *filePath = @"/Users/lujinrong/Downloads/image.png"; - BOOL result =[UIImagePNGRepresentation(m_image)writeToFile:filePath atomically:YES]; // + + m_dib = [[RDPDFDIB alloc] init:m_w :m_h]; + BOOL b = [m_page reflow:m_dib :gap:gap]; + m_image = [[UIImage alloc] initWithCGImage: [m_dib image]]; + //NSString *filePath = @"/Users/lujinrong/Downloads/image.png"; + //BOOL result =[UIImagePNGRepresentation(m_image)writeToFile:filePath atomically:YES]; // [imageView setImage:m_image]; //CGImageRelease(m_img); [self setNeedsDisplay]; diff --git a/src/ios/PDFViewer/PDFView/PDFThumbView.h b/src/ios/PDFViewer/PDFView/PDFThumbView.h old mode 100644 new mode 100755 index a0c2889f..37237fce --- a/src/ios/PDFViewer/PDFView/PDFThumbView.h +++ b/src/ios/PDFViewer/PDFView/PDFThumbView.h @@ -12,13 +12,20 @@ - (void)OnPageClicked :(int) pageno; @end +@class RDPDFThumb; @interface PDFThumbView : PDFLayoutView { id m_delegate; int m_sel_pno; + UIFont *m_font; + UIColor *m_color; + NSMutableParagraphStyle *m_pstyle; } - (id)initWithFrame:(CGRect)frame; -- (BOOL)PDFOpen :(PDFDoc *)doc :(int)page_gap :(id)del; +- (id)initWithCoder:(NSCoder *)aDecoder; +- (BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(RDPDFCanvas *)canvas :(id)del; - (void)PDFUpdatePage:(int)pageno; -- (void)setThumbBackgroundColor:(int)color; +- (void)PDFSetBGColor:(int)color; +- (void)PDFSaveView; +- (void)PDFRestoreView; @end diff --git a/src/ios/PDFViewer/PDFView/PDFThumbView.m b/src/ios/PDFViewer/PDFView/PDFThumbView.m old mode 100644 new mode 100755 index 4f85388e..9cfa39fb --- a/src/ios/PDFViewer/PDFView/PDFThumbView.m +++ b/src/ios/PDFViewer/PDFView/PDFThumbView.m @@ -7,16 +7,33 @@ // #import "PDFThumbView.h" +#import "RDPDFView.h" #import "RDVPage.h" #import "RDVCanvas.h" +#import "RDVGlobal.h" @implementation PDFThumbView +{ + int m_save_gap; +} -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self) { - m_child.backgroundColor = [UIColor colorWithWhite:0 alpha:0]; + m_scale_pix = [[UIScreen mainScreen] scale]; + self.maximumZoomScale = 1; + self.minimumZoomScale = 1; + self.pagingEnabled = NO; + } + return self; +} +- (id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + m_scale_pix = [[UIScreen mainScreen] scale]; self.maximumZoomScale = 1; self.minimumZoomScale = 1; self.pagingEnabled = NO; @@ -24,28 +41,80 @@ -(id)initWithFrame:(CGRect)frame return self; } --(BOOL)PDFOpen :(PDFDoc *)doc :(int)page_gap :(id)del +-(void)setFrame:(CGRect)frame { + [super setFrame:frame]; + if (!m_layout) return; + [m_layout vResize:frame.size.width * m_scale_pix :frame.size.height * m_scale_pix]; + self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, [m_layout doch]/m_scale_pix); + [m_layout vGotoPage:m_cur_page]; + [self setContentOffset:CGPointMake([m_layout docx]/m_scale_pix, [m_layout docy]/m_scale_pix) animated:NO]; +} + +- (BOOL)pagingAvailable { + return NO; +} +-(void)ProOnTimer:(NSTimer *)sender +{ + [self setNeedsDisplay]; +} + +-(BOOL)PDFOpen :(RDPDFDoc *)doc :(int)page_gap :(RDPDFCanvas *)canvas :(id)del +{ + [self PDFClose]; m_zoom = 1; m_doc = doc; m_delegate = del; - self.m_del = nil; - page_gap = 1; + m_del = nil; + //page_gap = 1; m_sel_pno = -1; - m_layout = [[RDVLayoutThumb alloc] init :self :(GLOBAL.g_render_mode == 7)]; + m_canvas = canvas; + m_layout = [[RDVLayoutThumb alloc] init :self :(GLOBAL.g_view_mode == 7)]; + m_save_gap = page_gap; [m_layout vOpen:m_doc :page_gap * m_scale_pix :self.layer]; [self bringSubviewToFront:m_child]; m_status = sta_none; - [m_layout vResize:self.frame.size.width * m_scale_pix :self.frame.size.height * m_scale_pix]; + CGRect rect = self.frame; + [m_layout vResize:rect.size.width * m_scale_pix :rect.size.height * m_scale_pix]; self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, 0); - self.backgroundColor = (GLOBAL.g_thumbview_bg_color != 0) ? UIColorFromRGB(GLOBAL.g_thumbview_bg_color) : [UIColor colorWithRed:0.7f green:0.7f blue:0.7f alpha:1.0f]; + self.backgroundColor = (GLOBAL.g_thumbview_bg_color) ? UIColorFromRGB(GLOBAL.g_thumbview_bg_color) : [UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:0.5f]; + [self setNeedsDisplay]; m_timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(ProOnTimer:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop]addTimer:m_timer forMode:NSDefaultRunLoopMode]; + + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; + [self addGestureRecognizer:tap]; return TRUE; } -- (BOOL)pagingAvailable { - return NO; +- (void)PDFSaveView +{ + [super PDFSaveView]; + m_sel_pno = -1; +} +- (void)PDFRestoreView +{ + m_layout = [[RDVLayoutThumb alloc] init :self :(GLOBAL.g_view_mode == 7)]; + [m_layout vOpen:m_doc :m_save_gap * m_scale_pix :self.layer]; + [self bringSubviewToFront:m_child]; + m_status = sta_none; + CGRect rect = self.frame; + [m_layout vResize:rect.size.width * m_scale_pix :rect.size.height * m_scale_pix]; + self.contentSize = CGSizeMake([m_layout docw]/m_scale_pix, 0); + [self setNeedsDisplay]; +} + +-(void)tapAction:(UITapGestureRecognizer *)tap +{ + RDVPos pos; + CGPoint pt = [tap locationOfTouch:0 inView:m_canvas]; + [m_layout vGetPos:pt.x * m_scale_pix :pt.y * m_scale_pix :&pos]; + if( pos.pageno >= 0 && pos.pageno != m_sel_pno ) + { + [self vGoto :pos.pageno]; + if( m_delegate ) + [m_delegate OnPageClicked: pos.pageno]; + } } -(void)vGoto:(int)pageno @@ -55,18 +124,17 @@ -(void)vGoto:(int)pageno pos.pdfx = 0; pos.pdfy = [m_doc pageHeight:pageno]; pos.pageno = pageno; - float xpos = self.frame.size.width * [[UIScreen mainScreen] scale]; + float xpos = self.frame.size.width * m_scale_pix; [m_layout vSetPos:(xpos - vp.w) / 2 :0 :&pos]; m_sel_pno = pageno; - - [self bringSubviewToFront:m_child]; - + CGPoint pt; pt.x = m_layout.docx / m_scale_pix; pt.y = m_layout.docy / m_scale_pix; - self.contentOffset = pt; - [m_child setNeedsDisplay]; + [self setContentOffset:pt animated:YES]; + [m_canvas setNeedsDisplay]; } + -(void)PDFUpdatePage:(int)pageno { [m_layout vRenderAsync:pageno]; @@ -79,129 +147,50 @@ -(void)PDFClose m_delegate = nil; } -#pragma mark delegate --(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -{ - NSSet *allTouches = [event allTouches]; - int cnt = (int)[allTouches count]; - if( cnt == 1 ) - { - UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; - //if( m_status == sta_none ) - { - m_tstamp = touch.timestamp; - m_tstamp_tap = m_tstamp; - m_tx = point.x * m_scale_pix; - m_ty = point.y * m_scale_pix; - m_px = m_tx; - m_py = m_ty; - // m_status = sta_hold; - } - } -} - --(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -{ - NSSet *allTouches = [event allTouches]; - int cnt = (int)[allTouches count]; - - if( cnt == 1 ) - { - UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; - //if( m_status == sta_hold ) - { - m_px = point.x * m_scale_pix; - m_py = point.y * m_scale_pix; - } - } -} - --(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -{ - NSSet *allTouches = [event allTouches]; - int cnt = (int)[allTouches count]; - if( cnt == 1 ) - { - UITouch *touch = [[allTouches allObjects] objectAtIndex:0]; - CGPoint point=[touch locationInView:[touch view]]; - //if(m_status == sta_hold) - //{ - m_status = sta_none; - //NSTimeInterval del = touch.timestamp - m_tstamp; - float dx = point.x * m_scale_pix - m_tx; - float dy = point.y * m_scale_pix - m_ty; - if( touch.timestamp - m_tstamp_tap < 0.15 )//single tap - { - bool single_tap = true; - if( dx > 5 || dx < -5 ) - single_tap = false; - if( dy > 5 || dy < -5 ) - single_tap = false; - if( single_tap ) - [self OnSingleTap:point.x * m_scale_pix :point.y * m_scale_pix]; - } - //} - } -} --(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -{ - [self touchesEnded:touches withEvent:event]; -} - --(void)OnSingleTap:(float)x :(float)y -{ - RDVPos pos; - [m_layout vGetPos:x :y :&pos]; - if( pos.pageno >= 0 && pos.pageno != m_sel_pno ) - { - [self vGoto :pos.pageno]; - [m_child setNeedsDisplay]; - if( m_delegate ) - [m_delegate OnPageClicked: pos.pageno]; - } -} - -(void)onDrawOffScreen:(CGContextRef)ctx { - if(m_sel_pno >= 0) + int start = m_layout.cur_pg1; + int end = m_layout.cur_pg2; + if (start < 0 && end < 0) return; + if(m_sel_pno >= 0 && m_sel_pno >= start && m_sel_pno <= end) { RDVPage *vpage = [m_layout vGetPage:m_sel_pno]; - CGContextRef ctx = UIGraphicsGetCurrentContext(); float scale = 1.0f/(m_zoom * m_scale_pix); float left = (float)vpage.x - self.contentOffset.x * m_scale_pix; float top = (float)vpage.y - self.contentOffset.y * m_scale_pix; CGRect rect = CGRectMake(scale * left, scale * top, scale * vpage.w, scale * vpage.h); + //CGRect rect = CGRectMake(0, 0, scale * vpage.w, scale * vpage.h); CGFloat clr[4] = {0, 0, 1, 0.25}; CGContextSetFillColor(ctx, clr); CGContextFillRect(ctx, rect); } - - int start = m_layout.cur_pg1; - int end = m_layout.cur_pg2; - while (start <= end) { - + + while (start <= end) + { RDVPage *vpage = [m_layout vGetPage:start]; - float scale = 1.0f/(m_zoom * m_scale_pix); + float scale = 1.0f / (m_zoom * m_scale_pix); float left = (float)vpage.x - self.contentOffset.x * m_scale_pix; CGRect rect = CGRectMake(scale * left, scale * (vpage.h/2 - vpage.h/5), scale * vpage.w, scale * (vpage.h/5)); // Add the page number - NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; - [paragraphStyle setAlignment:NSTextAlignmentCenter]; - [[NSString stringWithFormat:@"%i", start+1] drawInRect:rect withAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:scale * (vpage.h/5)], NSForegroundColorAttributeName: UIColorFromRGB(GLOBAL.g_thumbview_label_color), NSParagraphStyleAttributeName: paragraphStyle}]; - - start++; + if (!m_font) m_font = [UIFont systemFontOfSize:scale * vpage.h / 5]; + if (!m_color) m_color = UIColorFromRGB(GLOBAL.g_thumbview_label_color); + if (!m_pstyle) + { + m_pstyle = [[NSMutableParagraphStyle alloc] init]; + [m_pstyle setAlignment:NSTextAlignmentCenter]; + } + NSString *sdraw = [NSString stringWithFormat:@"%i", ++start]; + [sdraw drawInRect:rect withAttributes:@{NSFontAttributeName: m_font, NSForegroundColorAttributeName: m_color, NSParagraphStyleAttributeName: m_pstyle}]; } } -- (void)setThumbBackgroundColor:(int)color + +- (void)PDFSetBGColor:(int)color { GLOBAL.g_thumbview_bg_color = color; - + if (GLOBAL.g_thumbview_bg_color != 0) { self.backgroundColor = UIColorFromRGB(GLOBAL.g_thumbview_bg_color); } } - @end diff --git a/src/ios/PDFViewer/PDFView/RDPDFView.h b/src/ios/PDFViewer/PDFView/RDPDFView.h new file mode 100755 index 00000000..609eef44 --- /dev/null +++ b/src/ios/PDFViewer/PDFView/RDPDFView.h @@ -0,0 +1,37 @@ +// +// PDFOffScreenView.h +// PDFViewer +// +// Created by Radaee on 2016/12/6. +// +// +#pragma once +#import "PDFDelegate.h" + +@class RDVLayout; +@class RDVSel; +@class RDVFinder; + +@class PDFLayoutView; +@interface RDPDFCanvas : UIView +{ + PDFLayoutView *m_view; +} +-(void)setView :(PDFLayoutView *)view; +@end + +@interface RDPDFView : UIView +{ + PDFLayoutView *m_view; + RDPDFCanvas *m_canvas; +} +-(id)initWithFrame:(CGRect)frame; +-(id)initWithCoder:(NSCoder *)aDecoder; +-(PDFLayoutView *)view; +-(RDPDFCanvas *)canvas; +@end + +@interface RDPDFThumb :RDPDFView +{ +} +@end diff --git a/src/ios/PDFViewer/PDFView/RDPDFView.m b/src/ios/PDFViewer/PDFView/RDPDFView.m new file mode 100755 index 00000000..67a1adfc --- /dev/null +++ b/src/ios/PDFViewer/PDFView/RDPDFView.m @@ -0,0 +1,121 @@ +// +// PDFOffScreenView.m +// PDFViewer +// +// Created by Radaee on 2016/12/6. +// +// + +#import +#import "PDFObjc.h" +#import "RDVLayout.h" +#import "RDVSel.h" +#import "RDVFinder.h" +#import "RDPDFView.h" +#import "RDVGlobal.h" +#import "PDFLayoutView.h" +#import "PDFThumbView.h" + + +@implementation RDPDFCanvas +-(void)setView :(PDFLayoutView *)view +{ + m_view = view; + [self setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0]]; + [self setUserInteractionEnabled:NO]; +} + +-(void)drawRect:(CGRect)rect +{ + CGContextRef ctx = UIGraphicsGetCurrentContext(); + [m_view onDrawOffScreen:ctx]; +} + +@end + +@implementation RDPDFView +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + m_canvas = [[RDPDFCanvas alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + [m_canvas setView:m_view]; + m_canvas.autoresizesSubviews = YES; + m_canvas.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_view.autoresizesSubviews = YES; + m_view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self addSubview:m_view]; + [self addSubview:m_canvas]; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + CGRect frame = self.frame; + m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + m_canvas = [[RDPDFCanvas alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + [m_canvas setView:m_view]; + m_canvas.autoresizesSubviews = YES; + m_canvas.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_view.autoresizesSubviews = YES; + m_view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self addSubview:m_view]; + [self addSubview:m_canvas]; + } + return self; +} + +-(PDFLayoutView *)view +{ + return m_view; +} +-(RDPDFCanvas *)canvas +{ + return m_canvas; +} +@end + +@implementation RDPDFThumb +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + m_view = [[PDFThumbView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + m_canvas = [[RDPDFCanvas alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + [m_canvas setView:m_view]; + m_canvas.autoresizesSubviews = YES; + m_canvas.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_view.autoresizesSubviews = YES; + m_view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self addSubview:m_view]; + [self addSubview:m_canvas]; + [self setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]]; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + CGRect frame = self.frame; + m_view = [[PDFThumbView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + m_canvas = [[RDPDFCanvas alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; + [m_canvas setView:m_view]; + m_canvas.autoresizesSubviews = YES; + m_canvas.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + m_view.autoresizesSubviews = YES; + m_view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self addSubview:m_view]; + [self addSubview:m_canvas]; + [self setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]]; + } + return self; +} +@end diff --git a/src/ios/PDFViewer/PDFViewer-Info.plist b/src/ios/PDFViewer/PDFViewer-Info.plist index a04ee701..d3f92241 100755 --- a/src/ios/PDFViewer/PDFViewer-Info.plist +++ b/src/ios/PDFViewer/PDFViewer-Info.plist @@ -41,11 +41,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 4.0 + $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion - 4.0.1 + $(CURRENT_PROJECT_VERSION) LSApplicationCategoryType LSRequiresIPhoneOS @@ -75,6 +75,8 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + UIViewControllerBasedStatusBarAppearance + UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait diff --git a/src/ios/PDFViewer/PDFViewer-Prefix.pch b/src/ios/PDFViewer/PDFViewer-Prefix.pch index f7833495..edb23c24 100755 --- a/src/ios/PDFViewer/PDFViewer-Prefix.pch +++ b/src/ios/PDFViewer/PDFViewer-Prefix.pch @@ -13,3 +13,4 @@ #import #import "UINavigationController+autoRotate.h" #endif +#import "RDUtils.h" diff --git a/src/ios/PDFViewer/RDAppDelegate.h b/src/ios/PDFViewer/RDAppDelegate.h index c1b00199..aa107859 100755 --- a/src/ios/PDFViewer/RDAppDelegate.h +++ b/src/ios/PDFViewer/RDAppDelegate.h @@ -7,9 +7,9 @@ // #import -#import "RDFileTableController.h" +#import "RDFileCollectionViewController.h" #import "MoreViewController.h" -//#import "PDFVGlobal.h" + @class RDFileTableController; @interface RDAppDelegate : UIResponder @@ -17,7 +17,7 @@ @property (strong, nonatomic) UINavigationController *navController; @property (strong, nonatomic) UITabBarController *tabBarController; -@property (strong, nonatomic) RDFileTableController *viewController; +@property (strong, nonatomic) RDFileCollectionViewController *viewController; - (BOOL)isPortrait; @end diff --git a/src/ios/PDFViewer/RDAppDelegate.m b/src/ios/PDFViewer/RDAppDelegate.m index d52bae91..877f207d 100755 --- a/src/ios/PDFViewer/RDAppDelegate.m +++ b/src/ios/PDFViewer/RDAppDelegate.m @@ -19,16 +19,18 @@ @implementation RDAppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; - [[NSUserDefaults standardUserDefaults] setObject:@"Radaee" forKey:@"actCompany"]; - [[NSUserDefaults standardUserDefaults] setObject:@"radaee_com@yahoo.cn" forKey:@"actEmail"]; - [[NSUserDefaults standardUserDefaults] setObject:@"89WG9I-HCL62K-H3CRUZ-WAJQ9H-FADG6Z-XEBCAO" forKey:@"actSerial"]; - [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:2] forKey:@"actActivationType"]; - - [[NSUserDefaults standardUserDefaults] synchronize]; - + [[UIBarButtonItem appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UIButton appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UIButton appearance] setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal]; + [[UIImageView appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UITableViewCell appearance] setTintColor:[RDUtils radaeeIconColor]]; + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = @"radaee"; + g_mail = @"radaeepdf@gmail.com"; + g_serial = @"OBT5ZN-9SJHWQ-9ZOU9E-OQ31K2-5R5V9L-KM0Y1L"; [RDVGlobal Init]; - + self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; if ([self isPortrait]) { NSLog(@"portrait"); @@ -38,20 +40,17 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( NSLog(@"landscape"); } // Override point for customization after application launch. - self.window.backgroundColor = [UIColor whiteColor]; + self.window.backgroundColor = [RDUtils radaeeWhiteColor]; NSMutableArray *localControllesArray = [[NSMutableArray alloc]initWithCapacity:4]; - RDFileTableController *ctl = [[RDFileTableController alloc] initWithNibName:@"RDFileTableController" bundle:nil]; + RDFileCollectionViewController *ctl = [[RDFileCollectionViewController alloc] initWithNibName:@"RDFileCollectionViewController" bundle:nil]; navController = [[UINavigationController alloc] initWithRootViewController:ctl]; - navController.navigationBar.barStyle = UIBarStyleBlackOpaque; [localControllesArray addObject:navController]; NSString *title4 =[[NSString alloc]initWithFormat:NSLocalizedString(@"More", @"Localizable")]; // Do any additional setup after loading the view from its nib. - MoreViewController *moreCtl = [[MoreViewController alloc]initWithNibName:@"MoreViewController" bundle:nil]; - navController = [[UINavigationController alloc]initWithRootViewController:moreCtl]; - navController.navigationBar.barStyle = UIBarStyleBlackOpaque; - UITabBarItem *item3 = [[UITabBarItem alloc]initWithTitle:title4 image:[UIImage imageNamed:@"view_about.png"] tag:3 ]; + navController = [[UINavigationController alloc] initWithRootViewController:moreCtl]; + UITabBarItem *item3 = [[UITabBarItem alloc] initWithTitle:title4 image:[UIImage imageNamed:@"btn_info"] tag:3 ]; moreCtl.tabBarItem = item3; [localControllesArray addObject:navController]; @@ -74,9 +73,10 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( - (void)customizeAppearance { - [[UINavigationBar appearance] setTintColor:[UIColor orangeColor]]; - [[UITabBar appearance] setTintColor:[UIColor orangeColor]]; - [[UIToolbar appearance] setTintColor:[UIColor orangeColor]]; + [[UINavigationBar appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UITabBar appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UIToolbar appearance] setTintColor:[RDUtils radaeeIconColor]]; + [[UISwitch appearance] setTintColor:[RDUtils radaeeIconColor]]; } - (void)applicationWillResignActive:(UIApplication *)application diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.h b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.h new file mode 100755 index 00000000..a449829f --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.h @@ -0,0 +1,26 @@ +// +// RDCollectionViewCell.h +// PDFViewer +// +// Created by Federico Vellani on 19/06/2020. +// + +#import + +@protocol RDFileCollectionViewCellDelegate +- (void)showInfosAtIndexPath:(NSIndexPath *)indexPath; +@end + +@interface RDFileCollectionViewCell : UICollectionViewCell + +@property (strong, nonatomic) IBOutlet UIImageView *imgPreview; +@property (strong, nonatomic) IBOutlet UILabel *fileName; +@property (strong, nonatomic) IBOutlet UIButton *moreButton; +@property (strong, nonatomic) NSIndexPath *indexPath; +@property (nonatomic) id delegate; + +- (IBAction)moreButtonTapped:(id)sender; + +- (void)setShadow; + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.m b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.m new file mode 100755 index 00000000..799e106c --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.m @@ -0,0 +1,49 @@ +// +// RDCollectionViewCell.m +// PDFViewer +// +// Created by Federico Vellani on 19/06/2020. +// + +#import "RDFileCollectionViewCell.h" + +@implementation RDFileCollectionViewCell + +- (void)awakeFromNib { + [super awakeFromNib]; + // Initialization code +} + +- (void)setShadow +{ + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { + self.layer.cornerRadius = 15.0f; + self.contentView.layer.masksToBounds = YES; + + self.layer.shadowColor = [UIColor blackColor].CGColor; + self.layer.shadowOffset = CGSizeMake(0, 0.0f); + self.layer.shadowRadius = 15.0f; + self.layer.shadowOpacity = 0.25f; + self.layer.masksToBounds = NO; + self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.contentView.layer.cornerRadius].CGPath; + } + else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) + { + self.layer.cornerRadius = 10.0f; + self.contentView.layer.masksToBounds = YES; + + self.layer.shadowColor = [UIColor blackColor].CGColor; + self.layer.shadowOffset = CGSizeMake(0, 0.0f); + self.layer.shadowRadius = 10.0f; + self.layer.shadowOpacity = 0.25f; + self.layer.masksToBounds = NO; + self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.contentView.layer.cornerRadius].CGPath; + } +} + +- (IBAction)moreButtonTapped:(id)sender +{ + [_delegate showInfosAtIndexPath:_indexPath]; +} + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.xib b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.xib new file mode 100755 index 00000000..d2c18670 --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewCell.xib @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.h b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.h new file mode 100755 index 00000000..9a90541f --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.h @@ -0,0 +1,29 @@ +// +// RDFileCollectionViewController.h +// PDFViewer +// +// Created by Federico Vellani on 18/06/2020. +// + +#import +#import "sys/utsname.h" +#import "PDFHttpStream.h" +#import "PDFReaderCtrl.h" +#import "RDPDFReflowViewController.h" +#import "RDPageViewController.h" +#import "RDVGlobal.h" +#import "PDFHttpStream.h" +#import "RDFileCollectionViewCell.h" +#import "RDFileDetailViewController.h" +#import "RDMetaDataViewController.h" + +@interface RDFileCollectionViewController : UICollectionViewController +{ + NSMutableArray *m_files; + PDFReaderCtrl *m_pdf; + RDPDFReflowViewController *m_pdfR; + RDPageViewController *m_pdfP; + PDFHttpStream *httpStream; +} + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.m b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.m new file mode 100755 index 00000000..b65cbea6 --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.m @@ -0,0 +1,466 @@ +// +// RDFileCollectionViewController.m +// PDFViewer +// +// Created by Federico Vellani on 18/06/2020. +// + +#import "RDFileCollectionViewController.h" +#import "RDUtils.h" + +@interface RDFileCollectionViewController () + +@end + +@implementation RDFileCollectionViewController + +static NSString * const reuseIdentifier = @"Cell"; + +- (void)viewDidLoad { + [super viewDidLoad]; + + // Uncomment the following line to preserve selection between presentations + // self.clearsSelectionOnViewWillAppear = NO; + + // Register cell classes + [self.collectionView registerNib:[UINib nibWithNibName:@"RDFileCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"Cell"]; + + // Do any additional setup after loading the view. + [self refreshDouments]; + NSString *title = [[NSString alloc] initWithFormat:NSLocalizedString(@"All Files", @"Localizable")]; + self.title = title; + UITabBarItem *item = [[UITabBarItem alloc]initWithTitle:title image:[UIImage imageNamed:@"btn_files"] tag:0]; + + self.tabBarItem = item; + UIBarButtonItem *link = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_link"] style:UIBarButtonItemStylePlain target:self action:@selector(showOpenFromUrlAlert)]; + UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_refresh"] style:UIBarButtonItemStylePlain target:self action:@selector(refreshCollectionOnEdit)]; + self.navigationItem.leftBarButtonItem = link; + self.navigationItem.rightBarButtonItem = refresh; + + +} + +- (void)refreshDouments +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSFileManager *fm = [NSFileManager defaultManager]; + m_files = [[NSMutableArray alloc] init]; + [self addPDFs:dpath :@"" :fm :0]; + [self copyDocumentsFromAssets:dpath]; +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +#pragma mark + +- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { + return 1; +} + + +- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { + return [m_files count]; +} + +- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { + RDFileCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; + + // Configure the cell + RDFileItem *item = [m_files objectAtIndex:indexPath.row]; + cell.fileName.text = item.help; + cell.indexPath = indexPath; + cell.delegate = self; + [cell.imgPreview setImage:[self setImageForCellAtIndexPath:indexPath]]; + if (!cell.imgPreview.image && [item.help hasSuffix:@".pdf"]) { + cell.imgPreview.image = [UIImage imageNamed:@"encrypt"]; + } + [cell setShadow]; + return cell; +} + +- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath +{ + RDFileItem *item = [m_files objectAtIndex:indexPath.row]; + if (GLOBAL.g_view_mode == 2) + [self pdf_open_path_page:item :nil]; + else if(GLOBAL.g_view_mode == 5) + [self pdf_open_path_reflow:item :nil]; + else + [self pdf_open_path:item :nil]; +} + +#pragma mark + +- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath +{ + if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { + if ([[UIScreen mainScreen] bounds].size.width <= 375) { + return CGSizeMake(130, 150); + } + return CGSizeMake(160, 180); + } + return CGSizeMake(180, 200); +} +/* +// Uncomment this method to specify if the specified item should be highlighted during tracking +- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath { + return YES; +} +*/ + +/* +// Uncomment this method to specify if the specified item should be selected +- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath { + return YES; +} +*/ + +/* +// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item +- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath { + return NO; +} + +- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { + return NO; +} + +- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender { + +} +*/ + +#pragma mark - Files +- (void)addPDFs:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm :(int)level +{ + NSString *path = [dpath stringByAppendingFormat:@"/%@", subdir]; + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:path]; + NSString *fName; + while(fName = [fenum nextObject]) + { + BOOL dir; + NSString *dst = [path stringByAppendingFormat:@"%@",fName]; + if( [fm fileExistsAtPath:dst isDirectory:&dir] ) + { + if( dir ) + { + [self addPDFs:dpath :dst :fm :level+1]; + } + else if( [dst hasSuffix:@".pdf"] ) + { + NSString *dis = [subdir stringByAppendingFormat:@"%@",fName];//display name + RDFileItem *item = [[RDFileItem alloc] init:dis :dst :level]; + [m_files addObject:item]; + } + } + } +} + +- (void)copyDocumentsFromAssets :(NSString *)dpath +{ + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) { + + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + RDFileItem *item = [[RDFileItem alloc] init:[fpath stringByDeletingPathExtension] :destPath :0]; + [m_files addObject:item]; + } + } + } +} + +- (UIImage *)setImageForCellAtIndexPath:(NSIndexPath *)indexPath +{ + RDFileItem *item = [m_files objectAtIndex:indexPath.row]; + NSString *path = item.path; + CGImageRef img_ref = nil; + + const char *cpath = [path UTF8String]; + [item.locker lock]; + PDF_ERR err; + Document_setOpenFlag(3); + PDF_DOC m_docThumb = Document_open(cpath,nil, &err); + Document_setOpenFlag(1); + int result = 1; + if( m_docThumb == NULL ) + { + switch( err ) + { + case err_password: + result = 2; + break; + default: + result = 0; + break; + } + } + else + { + PDF_PAGE page = Document_getPage(m_docThumb, 0); + float w = Document_getPageWidth(m_docThumb,0); + float h = Document_getPageHeight(m_docThumb,0); + PDF_DIB m_dib = NULL; + int iw = 200; + int ih = 200; + if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) + { + ih = 200; + iw = 200; + } + PDF_DIB bmp = Global_dibGet(m_dib, iw, ih); + float ratiox = iw/w; + float ratioy = ih/h; + if( ratiox > ratioy ) ratiox = ratioy; + PDF_MATRIX mat = Matrix_createScale(ratiox, -ratiox, 0, h * ratioy); + Page_renderPrepare( page, bmp ); + Page_render(page, bmp, mat,false,1); + Matrix_destroy(mat); + Page_close(page); + Document_close(m_docThumb); + void *data = Global_dibGetData(bmp); + CGDataProviderRef provider = CGDataProviderCreateWithData( NULL, data, iw * ih * 4, NULL ); + CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); + img_ref = CGImageCreate( iw, ih, 8, 32, iw<<2, cs, kCGBitmapByteOrder32Little|kCGImageAlphaNoneSkipFirst, provider, NULL, FALSE, kCGRenderingIntentDefault ); + CGColorSpaceRelease(cs); + CGDataProviderRelease( provider ); + } + + [item.locker unlock]; + if(!img_ref) return nil; + return [UIImage imageWithCGImage:img_ref]; +} + +- (void)pdf_open_path:(RDFileItem *)item :(NSString *)pswd +{ + //Open PDF file + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [item.locker lock]; + int result = [doc open:item.path :pswd]; + [item.locker unlock]; + if(result == 0)//succeeded + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + [m_pdf setDoc:doc]; + m_pdf.hidesBottomBarWhenPushed = YES; + GLOBAL.g_pdf_path = [item.path stringByDeletingLastPathComponent]; + GLOBAL.g_pdf_name = [NSMutableString stringWithString:[item.path lastPathComponent]]; + [self.navigationController pushViewController:m_pdf animated:YES]; + } + else if(result == 2)//require password + { + [self pdf_show_pwd_error:^(NSString *pwd) { + [self pdf_open_path:item :pwd]; + }]; + } + else//error + { + NSString *str1 = NSLocalizedString(@"Alert", @"Localizable"); + NSString *str2 = NSLocalizedString(@"Error Document,Can't open", @"Localizable"); + NSString *str3 = NSLocalizedString(@"OK", @"Localizable"); + UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 message:str2 preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } +} + +- (void)pdf_open_path_page:(RDFileItem *)item :(NSString *)pswd +{ + //Open PDF file + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + [item.locker lock]; + int result = [m_pdfP PDFOpenAtPath:item.path withPwd:pswd]; + [item.locker unlock]; + if(result == 1)//succeeded + { + m_pdfP.hidesBottomBarWhenPushed = YES; + [self.navigationController pushViewController:m_pdfP animated:YES]; + } + else if(result == 2)//require password + { + [self pdf_show_pwd_error:^(NSString *pwd) { + [self pdf_open_path_page:item :pwd]; + }]; + } + else//error + { + NSString *str1 = NSLocalizedString(@"Alert", @"Localizable"); + NSString *str2 = NSLocalizedString(@"Error Document,Can't open", @"Localizable"); + NSString *str3 = NSLocalizedString(@"OK", @"Localizable"); + UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 + message:str2 + preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } +} + +- (void)pdf_open_path_reflow:(RDFileItem *)item :(NSString *)pswd +{ + //Open PDF file + m_pdfR = [[RDPDFReflowViewController alloc] initWithNibName:@"RDPDFReflowViewController" bundle:nil]; + [item.locker lock]; + int result = [m_pdfR PDFOpen:item.path :pswd]; + [item.locker unlock]; + if(result == 1)//succeeded + { + m_pdfR.hidesBottomBarWhenPushed = YES; + [self.navigationController pushViewController:m_pdfR animated:YES]; + } + else if(result == 2)//require password + { + [self pdf_show_pwd_error:^(NSString *pwd) { + [self pdf_open_path_reflow:item :pwd]; + }]; + } + else//error + { + NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); + NSString *str2=NSLocalizedString(@"Error Document,Can't open", @"Localizable"); + NSString *str3=NSLocalizedString(@"OK", @"Localizable"); + UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 message:str2 preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } +} + +- (void)pdf_show_pwd_error:(void (^)(NSString *pwd))success +{ + NSString *title = NSLocalizedString(@"Please Enter PassWord", @"Localizable"); + UIAlertController *pwdAlert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert]; + [pwdAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) + { + textField.placeholder = NSLocalizedString(@"PassWord", @"Localizable"); + textField.secureTextEntry = YES; + }]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { + UITextField *password = pwdAlert.textFields.firstObject; + success(password.text); + }]; + UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Localizable") style:UIAlertActionStyleCancel handler:nil]; + + [pwdAlert addAction:okAction]; + [pwdAlert addAction:cancel]; + [self presentViewController:pwdAlert animated:YES completion:nil]; +} + +#pragma mark - Url + +- (void)showOpenFromUrlAlert +{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Open from URL" message:@"Please insert URL" preferredStyle:UIAlertControllerStyleAlert]; + [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) + { + textField.placeholder = @"Insert PDF URL here"; + }]; + UIAlertAction *demo = [UIAlertAction actionWithTitle:@"Demo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + [self openPDFWithUrl:testUrlPath]; + }]; + UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]; + UIAlertAction *open = [UIAlertAction actionWithTitle:@"Open" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + UITextField *urlTextField = alert.textFields.firstObject; + [self openPDFWithUrl:urlTextField.text]; + [alert dismissViewControllerAnimated:YES completion:nil]; + }]; + [alert addAction:open]; + [alert addAction:demo]; + [alert addAction:cancel]; + [self presentViewController:alert animated:YES completion:nil]; +} + +- (void)openPDFWithUrl:(NSString *)url { + + if( m_pdf == nil ) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } + + // OPENHTTP + NSString *testfile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cache.pdf"]; + httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :testfile]; + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int error = [doc openStream:httpStream :@""]; + + switch(error) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc :YES]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + m_pdf.hidesBottomBarWhenPushed = YES; + [self.navigationController pushViewController:m_pdf animated:YES]; + } + break; + default: { + NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); + NSString *str2=NSLocalizedString(@"Error Document,Can't open", @"Localizable"); + NSString *str3=NSLocalizedString(@"OK", @"Localizable"); + UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 message:str2 preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; + [alert addAction:okAction]; + [self presentViewController:alert animated:YES completion:nil]; + } + break; + } +} + +#pragma mark - RDCollectionViewCell delegate + +- (void)showInfosAtIndexPath:(NSIndexPath *)indexPath +{ + RDFileItem *item = [m_files objectAtIndex:indexPath.row]; + RDFileDetailViewController *fileDetail = [[RDFileDetailViewController alloc]initWithNibName:@"RDFileDetailViewController" bundle:nil]; + fileDetail.coverImage = [self setImageForCellAtIndexPath:indexPath]; + fileDetail.pdfPath = item.path; + fileDetail.delegate = self; + fileDetail.modalPresentationStyle = UIModalPresentationOverCurrentContext; + fileDetail.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:fileDetail animated:YES completion:nil]; +} + +#pragma mark - RDFileDetailViewController delegate + +- (void)showSelectedFileMeta:(NSString *)pdfPath +{ + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + __block BOOL error = [doc open:pdfPath :@""]; + if (error) { + [self pdf_show_pwd_error:^(NSString *pwd) { + error = [doc open:pdfPath :pwd]; + }]; + } + + RDMetaDataViewController *metaViewController = [[RDMetaDataViewController alloc] initWithNibName:@"RDMetaDataViewController" bundle:nil]; + metaViewController.doc = doc; + metaViewController.autoSave = YES; + metaViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; + metaViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; + [self presentViewController:metaViewController animated:YES completion:nil]; + +} + +- (void)refreshCollectionOnEdit +{ + [self refreshDouments]; + [self.collectionView reloadData]; +} + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.xib b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.xib new file mode 100755 index 00000000..54735acd --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileCollectionViewController.xib @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.h b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.h new file mode 100755 index 00000000..57ef5d3c --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.h @@ -0,0 +1,40 @@ +// +// RDFileDetailViewController.h +// PDFViewer +// +// Created by Federico Vellani on 26/06/2020. +// + +#import + +@protocol RDFileDetailViewControllerDelegate + +- (void)showSelectedFileMeta:(NSString *)pdfPath; +- (void)refreshCollectionOnEdit; + +@end + +@interface RDFileDetailViewController : UIViewController + +@property (strong, nonatomic) IBOutlet UIImageView *cover; +@property (strong, nonatomic) IBOutlet UITextField *nameField; +@property (strong, nonatomic) IBOutlet UILabel *sizeLabel; +@property (strong, nonatomic) IBOutlet UILabel *lastModifiedLabel; +@property (strong, nonatomic) IBOutlet UIButton *metaButton; +@property (strong, nonatomic) IBOutlet UIButton *renameButton; +@property (strong, nonatomic) IBOutlet UIButton *shareButton; +@property (strong, nonatomic) IBOutlet UIButton *deleteButton; +@property (strong, nonatomic) IBOutlet UIButton *dismissButton; + +@property (strong, nonatomic) UIImage *coverImage; +@property (strong, nonatomic) NSString *pdfPath; + +@property (weak, nonatomic) id delegate; + +- (IBAction)dismissView:(id)sender; +- (IBAction)metaButtonTapped:(id)sender; +- (IBAction)renameButtonTapped:(id)sender; +- (IBAction)shareButtonTapped:(id)sender; +- (IBAction)deleteButtonTapped:(id)sender; + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.m b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.m new file mode 100755 index 00000000..af1e5041 --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.m @@ -0,0 +1,138 @@ +// +// RDFileDetailViewController.m +// PDFViewer +// +// Created by Federico Vellani on 26/06/2020. +// + +#import "RDFileDetailViewController.h" + +@interface RDFileDetailViewController () + +@end + +@implementation RDFileDetailViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view from its nib. + + [_cover setImage:_coverImage]; + + NSString *pdfName = [[_pdfPath lastPathComponent] stringByDeletingPathExtension]; + [_nameField setText:pdfName]; + + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:_pdfPath error:nil]; + NSString *fileSize = [NSByteCountFormatter stringFromByteCount:[attributes fileSize] countStyle:NSByteCountFormatterCountStyleFile]; + NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; + [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm"]; + NSString *modificationDate = [dateFormatter stringFromDate:[attributes objectForKey:NSFileModificationDate]]; + NSString *lastModifiedString = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Last modified", nil), modificationDate]; + + [_sizeLabel setText:fileSize]; + [_lastModifiedLabel setText:lastModifiedString]; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissKeyboard) name:UIKeyboardWillHideNotification object:nil]; + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]; + [self.view addGestureRecognizer:tap]; + + [_metaButton setTitleColor:[RDUtils radaeeBlackColor] forState:UIControlStateNormal]; + [_renameButton setTitleColor:[RDUtils radaeeBlackColor] forState:UIControlStateNormal]; + [_shareButton setTitleColor:[RDUtils radaeeBlackColor] forState:UIControlStateNormal]; + [_deleteButton setTitleColor:[RDUtils radaeeBlackColor] forState:UIControlStateNormal]; + [_metaButton setTitle:NSLocalizedString(@"Meta", nil) forState:UIControlStateNormal]; + [_renameButton setTitle:NSLocalizedString(@"Rename", nil) forState:UIControlStateNormal]; + [_shareButton setTitle:NSLocalizedString(@"Share", nil) forState:UIControlStateNormal]; + [_deleteButton setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal]; +} + +- (IBAction)dismissView:(id)sender +{ + [_delegate refreshCollectionOnEdit]; + [self dismissViewControllerAnimated:YES completion:nil]; +} + +- (IBAction)metaButtonTapped:(id)sender +{ + [self dismissViewControllerAnimated:YES completion:^{ + [self->_delegate showSelectedFileMeta:self->_pdfPath]; + }]; +} + +- (IBAction)renameButtonTapped:(id)sender +{ + if (!_nameField.userInteractionEnabled) { + [_nameField setUserInteractionEnabled:YES]; + [_nameField becomeFirstResponder]; + [_renameButton setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal]; + } else { + NSError * err = NULL; + NSFileManager * fm = [[NSFileManager alloc] init]; + NSString *newPath = [[_pdfPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[_nameField.text stringByAppendingPathExtension:@"pdf"]]; + if (![_pdfPath isEqualToString:newPath] && [fm fileExistsAtPath:newPath]) { + NSString *message = [NSString stringWithFormat:@"%@ %@",[newPath lastPathComponent],NSLocalizedString(@"already exist", nil)]; + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:message preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]; + [alertController addAction:cancelAction]; + [self presentViewController:alertController animated:YES completion:^{ + [self->_nameField setText:[[self->_pdfPath lastPathComponent] stringByDeletingPathExtension]]; + }]; + return; + } + BOOL result = [fm moveItemAtPath:_pdfPath toPath:newPath error:&err]; + if(!result) + NSLog(@"Error: %@", err); + _pdfPath = newPath; + [_renameButton setTitle:NSLocalizedString(@"Rename", nil) forState:UIControlStateNormal]; + [_nameField resignFirstResponder]; + [_nameField setUserInteractionEnabled:NO]; + } +} + +- (IBAction)shareButtonTapped:(id)sender +{ + NSURL *fileUrl = [NSURL fileURLWithPath:_pdfPath]; + UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[fileUrl] + applicationActivities:nil]; + if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) + { + [self presentViewController:activityViewController animated:YES completion:nil]; + } + else + { + UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activityViewController]; + [popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 0, 0) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; + } +} + +- (IBAction)deleteButtonTapped:(id)sender +{ + UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) message:NSLocalizedString(@"Are you sure you want to delete this file?", nil) preferredStyle:UIAlertControllerStyleAlert]; + UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + NSFileManager *fm = [NSFileManager defaultManager]; + [fm removeItemAtPath:self->_pdfPath error:nil]; + [self dismissView:nil]; + }]; + UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:nil]; + [alertController addAction:okAction]; + [alertController addAction:cancelAction]; + + [self presentViewController:alertController animated:YES completion:nil]; +} + +- (void)dismissKeyboard +{ + [self renameButtonTapped:nil]; +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.xib b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.xib new file mode 100755 index 00000000..bc3f00ff --- /dev/null +++ b/src/ios/PDFViewer/RDFileCollection/RDFileDetailViewController.xib @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDFileTableController.h b/src/ios/PDFViewer/RDFileTableController.h deleted file mode 100755 index bf6143ed..00000000 --- a/src/ios/PDFViewer/RDFileTableController.h +++ /dev/null @@ -1,52 +0,0 @@ -// -// RDFileTableController.h -// PDFViewer -// -// Created by Radaee on 12-10-29. -// Copyright (c) 2012年 __Radaee__. All rights reserved. - - -#import -#import "sys/utsname.h" -#import "PDFHttpStream.h" -#import "RDLoPDFViewController.h" -#import "RDPDFReflowViewController.h" -#import "RDPageViewController.h" -#import "RDVGlobal.h" -#import "PDFHttpStream.h" - -@interface PDFFileStream : NSObject -{ - FILE *m_file; - bool m_writable; -} --(bool)writeable; --(int)read: (void *)buf :(int)len; --(int)write:(const void *)buf :(int)len; --(unsigned long long)position; --(unsigned long long)length; --(bool)seek:(unsigned long long)pos; -@end - -@interface RDFileItem : NSObject --(id)init:(NSString *)help :(NSString *)path :(int)level; -@property NSString *help; -@property NSString *path; -@property int level; -@property RDVLocker *locker; -@end - -@interface RDFileTableController : UITableViewController -{ - RDLoPDFViewController *m_pdf; - RDPDFReflowViewController *m_pdfR; - RDPageViewController *m_pdfP; - NSMutableArray *m_files; - void *buffer; - PDFHttpStream *httpStream; -} -@end - - - - diff --git a/src/ios/PDFViewer/RDFileTableController.m b/src/ios/PDFViewer/RDFileTableController.m deleted file mode 100755 index e95d2bcc..00000000 --- a/src/ios/PDFViewer/RDFileTableController.m +++ /dev/null @@ -1,603 +0,0 @@ -// -// RDFileTableController.m -// PDFViewer -// -// Created by Radaee on 12-10-29. -// Copyright (c) 2012年 Radaee. All rights reserved. -// - -#import "RDFileTableController.h" -#define testUrlPath @"https://www.radaeepdf.com/documentation/MRBrochoure.pdf" - -//NSMutableString *pdfName; -//NSMutableString *pdfPath; - -@interface RDFileTableController () - -@end - -//Open pdf file from filestream -@implementation PDFFileStream - --(void)open :(NSString *)filePath -{ - //fileHandle = [NSFileHandle fileHandleForReadingAtPath:testfile]; - const char *path = [filePath UTF8String]; - if((m_file = fopen(path, "rb+"))){ - m_writable = true; - } - else { - m_file = fopen(path,"rb"); - m_writable = false; - } -} --(bool)writeable -{ - return m_writable; -} --(void)close :(NSString *)filePath -{ - if( m_file ) - fclose(m_file); - m_file = NULL; -} --(int)read: (void *)buf : (int)len -{ - if( !m_file ) return 0; - int read = (int)fread(buf, 1, len,m_file); - return read; -} --(int)write:(const void *)buf :(int)len -{ - if( !m_file ) return 0; - return (int)fwrite(buf, 1, len, m_file); -} - --(unsigned long long)position -{ - if( !m_file ) return 0; - int pos = (int)ftell(m_file); - return pos; -} - --(unsigned long long)length -{ - if( !m_file ) return 0; - int pos = (int)ftell(m_file); - fseek(m_file, 0, SEEK_END); - int filesize = (int)ftell(m_file); - fseek(m_file, pos, SEEK_SET); - return filesize; -} - --(bool)seek:(unsigned long long)pos -{ - if( !m_file ) return false; - fseek(m_file, (int)pos , SEEK_SET); - return true; -} -@end - -@implementation RDFileItem --(id)init:(NSString *)help :(NSString *)path :(int)level -{ - self = [super init]; - if(self) - { - _help = help; - _path = path; - _level = level; - _locker = [[RDVLocker alloc] init]; - } - return self; -} -@end - -@implementation RDFileTableController - -- (id)initWithStyle:(UITableViewStyle)style -{ - self = [super initWithStyle:style]; - if (self) - { - - } - return self; -} -#pragma mark -addFiles -- (void)addPDFs:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm :(int)level -{ - NSString *path = [dpath stringByAppendingFormat:@"/%@", subdir]; - NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:path]; - NSString *fName; - while(fName = [fenum nextObject]) - { - BOOL dir; - NSString *dst = [path stringByAppendingFormat:@"%@",fName]; - if( [fm fileExistsAtPath:dst isDirectory:&dir] ) - { - if( dir ) - { - [self addPDFs:dpath :dst :fm :level+1]; - } - else if( [dst hasSuffix:@".pdf"] ) - { - NSString *dis = [subdir stringByAppendingFormat:@"%@",fName];//display name - RDFileItem *item = [[RDFileItem alloc] init:dis :dst :level]; - [m_files addObject:item]; - } - } - } -} - -- (void)delPDFs:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm :(int)level -{ - NSString *path = [dpath stringByAppendingFormat:@"/%@", subdir]; - NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:path]; - NSString *fName; - while(fName = [fenum nextObject]) - { - BOOL dir; - NSString *dst = [path stringByAppendingFormat:@"/%@",fName]; - if( [fm fileExistsAtPath:dst isDirectory:&dir] ) - { - if( dir ) - { - [self addPDFs:dpath :dst :fm :level+1]; - } - else if( [dst hasSuffix:@".pdf"] ) - { - NSString *dis = [subdir stringByAppendingFormat:@"%@",fName];//display name - RDFileItem *item = [[RDFileItem alloc] init:dis :dst :level]; - [m_files addObject:item]; - } - } - } -} -- (void)viewDidLoad -{ - [super viewDidLoad]; - - if([[[UIDevice currentDevice]systemVersion] floatValue]>=7.0) - { - UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init]; - temporaryBarButtonItem.title = @""; - self.navigationItem.backBarButtonItem = temporaryBarButtonItem; - } - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *dpath = [paths objectAtIndex:0]; - NSFileManager *fm = [NSFileManager defaultManager]; - m_files = [[NSMutableArray alloc] init]; - [self addPDFs:dpath :@"" :fm :0]; - - NSString *title = [[NSString alloc] initWithFormat:NSLocalizedString(@"All Files", @"Localizable")]; - self.title = title; - UITabBarItem *item = [[UITabBarItem alloc]initWithTitle:title image:[UIImage imageNamed:@"btn_outline"] tag:0]; - - self.tabBarItem =item; - self.navigationItem.leftBarButtonItem = self.editButtonItem; - - [self copyDocumentsFromAssets:dpath]; - - //test demo for PDFMemOpen or PDFStreamOpen or HTTPPDFStream,click right button - UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Url" style:UIBarButtonItemStylePlain target:self action:@selector(selectRightAction)]; - self.navigationItem.rightBarButtonItem = rightButton; -} --(void)selectRightAction -{ - NSLog(@"click right"); - if( m_pdf == nil ) - { - m_pdf = [[RDLoPDFViewController alloc] init]; - } - - // OPENHTTP - [self openPDFWithUrl]; - - // OPENMEM - //[self openPDFWithMem]; - - m_pdf.hidesBottomBarWhenPushed = YES; - [self.navigationController pushViewController:m_pdf animated:YES]; -} - -- (void)openPDFWithUrl { - NSString *testfile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cache.pdf"]; - - httpStream = [[PDFHttpStream alloc] init]; - [httpStream open:testUrlPath :testfile]; - [m_pdf PDFOpenStream:httpStream :@""]; -} - -- (void)openPDFWithMem { - NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *dpath=[paths objectAtIndex:0]; - - NSString *hf = [[NSBundle mainBundle]pathForResource:@"help" ofType:@"pdf" inDirectory:@"fdat"]; - NSString *helpfile = [hf substringFromIndex:hf.length-8]; - NSString *documentPath = [dpath stringByAppendingString: [NSString stringWithFormat:@"/%@",helpfile]]; - - [[NSFileManager defaultManager] copyItemAtPath:hf toPath:documentPath error:nil]; - - - NSString *testfile1 = documentPath; - - char *path1 = (char *)[testfile1 UTF8String]; - FILE *file1 = fopen(path1, "rb"); - fseek(file1, 0, SEEK_END); - int filesize1 = (int)ftell(file1); - fseek(file1, 0, SEEK_SET); - buffer = malloc((filesize1)*sizeof(char)); - fread(buffer, filesize1, 1, file1); - fclose(file1); - - [m_pdf PDFOpenMem: buffer :filesize1 :nil]; -} - -- (BOOL)shouldAutorotate -{ - return YES; -} - - -#pragma mark - Table view data source - -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView -{ - return 1; -} - -- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath -{ - return 60; -} - -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section -{ - return m_files.count; -} - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath -{ - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FileCell"]; - UILabel *label = nil; - if(!cell) - { - CGRect rc = self.view.frame; - CGRect rect = CGRectMake(0, 0, rc.size.width, 25); - cell = [[UITableViewCell alloc] initWithFrame:rect]; - //get ios version - if([[[UIDevice currentDevice]systemVersion] floatValue]>=7.0) - { - //above ios7 - rect.origin.x += 70; - rect.origin.y += 15; - rect.size.width -= 4; - rect.size.height -= 4; - } - else - { - rect.origin.x += 60; - rect.origin.y += 15; - rect.size.width -= 4; - rect.size.height -= 4; - } - label = [[UILabel alloc] initWithFrame:rect]; - label.tag = 1; - label.font = [UIFont systemFontOfSize:rect.size.height - 4]; - [cell.contentView addSubview:label]; - cell.accessoryType = UITableViewCellAccessoryNone; - cell.backgroundColor = [[UIColor alloc] initWithWhite:1 alpha:0]; - } - else label = (UILabel *)[cell.contentView viewWithTag:1]; - NSUInteger row = [indexPath row]; - RDFileItem *item = [m_files objectAtIndex:row]; - cell.textLabel.numberOfLines = 0; - UIImage *image = [UIImage imageNamed:@"encrypt"]; - cell.imageView.image = image; - label.text = item.help; - return cell; -} - -// Override to support conditional editing of the table view. -- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath -{ - // Return NO if you do not want the specified item to be editable. - return YES; -} - - -// Override to support editing the table view. -- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath -{ - NSUInteger row = [indexPath row]; - - if( m_pdf == nil ) - { - m_pdf = [[RDLoPDFViewController alloc] initWithNibName:@"RDLoPDFViewController" bundle:nil]; - } - - RDFileItem *item = [m_files objectAtIndex:indexPath.row]; - NSString *path = item.path; - [item.locker lock]; - NSFileManager *fm = [NSFileManager defaultManager]; - [fm removeItemAtPath:path error:nil]; - [m_files removeObjectAtIndex:row]; - [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; - [item.locker unlock]; -} - -- (void)pdf_open_path:(RDFileItem *)item :(NSString *)pswd -{ - if( m_pdf == nil ) - { - m_pdf = [[RDLoPDFViewController alloc] initWithNibName:@"RDLoPDFViewController" bundle:nil]; - m_pdf.view.frame = self.view.frame; - } - - NSLock *theLock = [[NSLock alloc] init]; - - if ([theLock tryLock]) - { - //Open PDF file - int result = [m_pdf PDFOpen:item.path :pswd]; - - if(result == 1) - { - m_pdf.hidesBottomBarWhenPushed = YES; - [self.navigationController pushViewController:m_pdf animated:YES]; - } - //return value is encryption document - else if(result == 2) - { - NSString *title = NSLocalizedString(@"Please Enter PassWord", @"Localizable"); - UIAlertController *pwdAlert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert]; - [pwdAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) { - textField.placeholder = NSLocalizedString(@"PassWord", @"Localizable"); - textField.secureTextEntry = YES; - }]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { - UITextField *password = pwdAlert.textFields.firstObject; - if (![password.text isEqualToString:@""]) { - int result = [self->m_pdf PDFOpen:item.path :password.text]; - if(result == 1) - { - UINavigationController *nav = self.navigationController; - self->m_pdf.hidesBottomBarWhenPushed = YES; - nav.hidesBottomBarWhenPushed =NO; - [nav pushViewController:self->m_pdf animated:YES]; - } - else if(result == 2) - { - NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2=NSLocalizedString(@"Error PassWord", @"Localizable"); - [self presentPwdAlertControllerWithTitle:str1 message:str2]; - } - } - else - { - [self presentViewController:pwdAlert animated:YES completion:nil]; - } - }]; - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Localizable") style:UIAlertActionStyleCancel handler:nil]; - - [pwdAlert addAction:okAction]; - [pwdAlert addAction:cancel]; - [self presentViewController:pwdAlert animated:YES completion:nil]; - } - else if (result == 0) - { - NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2=NSLocalizedString(@"Error Document,Can't open", @"Localizable"); - NSString *str3=NSLocalizedString(@"OK", @"Localizable"); - UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 - message:str2 - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } - [theLock unlock]; - } -} - -- (void)openPageMode:(RDFileItem *)item :(NSString *)pswd -{ - //Open PDF file - m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; - [item.locker lock]; - int result = [m_pdfP PDFOpenAtPath:item.path withPwd:pswd]; - [item.locker unlock]; - if(result == 1)//succeeded - { - m_pdfP.hidesBottomBarWhenPushed = YES; - [self.navigationController pushViewController:m_pdfP animated:YES]; - } - else if(result == 2)//require password - { - NSString *title = NSLocalizedString(@"Please Enter PassWord", @"Localizable"); - UIAlertController *pwdAlert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert]; - [pwdAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) - { - textField.placeholder = NSLocalizedString(@"PassWord", @"Localizable"); - textField.secureTextEntry = YES; - }]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { - UITextField *password = pwdAlert.textFields.firstObject; - [self openPageMode:item :password.text]; - }]; - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Localizable") style:UIAlertActionStyleCancel handler:nil]; - - [pwdAlert addAction:okAction]; - [pwdAlert addAction:cancel]; - [self presentViewController:pwdAlert animated:YES completion:nil]; - } - else//error - { - NSString *str1 = NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2 = NSLocalizedString(@"Error Document,Can't open", @"Localizable"); - NSString *str3 = NSLocalizedString(@"OK", @"Localizable"); - UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 - message:str2 - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } -} - -- (void)openReflowMode:(RDFileItem *)item :(NSString *)pswd -{ - //Open PDF file - m_pdfR = [[RDPDFReflowViewController alloc] initWithNibName:@"RDPDFReflowViewController" bundle:nil]; - [item.locker lock]; - int result = [m_pdfR PDFOpen:item.path :pswd]; - [item.locker unlock]; - if(result == 1)//succeeded - { - m_pdfR.hidesBottomBarWhenPushed = YES; - [self.navigationController pushViewController:m_pdfR animated:YES]; - } - else if(result == 2)//require password - { - NSString *title = NSLocalizedString(@"Please Enter PassWord", @"Localizable"); - UIAlertController *pwdAlert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert]; - [pwdAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) - { - textField.placeholder = NSLocalizedString(@"PassWord", @"Localizable"); - textField.secureTextEntry = YES; - }]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { - UITextField *password = pwdAlert.textFields.firstObject; - [self openReflowMode:item :password.text]; - }]; - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Localizable") style:UIAlertActionStyleCancel handler:nil]; - - [pwdAlert addAction:okAction]; - [pwdAlert addAction:cancel]; - [self presentViewController:pwdAlert animated:YES completion:nil]; - } - else//error - { - NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2=NSLocalizedString(@"Error Document,Can't open", @"Localizable"); - NSString *str3=NSLocalizedString(@"OK", @"Localizable"); - UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 message:str2 preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } -} - -#pragma mark - Table view delegate -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath -{ - RDFileItem *item = [m_files objectAtIndex:indexPath.row]; - if (GLOBAL.g_render_mode == 2) - [self openPageMode:item :nil]; - else if(GLOBAL.g_render_mode == 5) - [self openReflowMode:item :nil]; - else - [self pdf_open_path:item :nil]; -} - -- (void)presentPwdAlertControllerWithTitle:(NSString *)title message:(NSString *)message -{ - -} - -- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath -{ -} - -- (void)copyDocumentsFromAssets:(NSString *)dpath -{ - NSString *hf = [[NSBundle mainBundle] pathForResource:@"fdat" ofType:nil]; - for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { - if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) { - - NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; - NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; - - if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { - [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; - RDFileItem *item = [[RDFileItem alloc] init:[fpath stringByDeletingPathExtension] :destPath :0]; - [m_files addObject:item]; - } - } - } -} - -- (BOOL)isPortrait -{ - return ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || - [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown); -} -- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath -{ - [NSThread detachNewThreadSelector:@selector(updateImageForCellAtIndexPath:) toTarget:self withObject:indexPath]; -} - -- (void)updateImageForCellAtIndexPath:(NSIndexPath *)indexPath -{ - RDFileItem *item = [m_files objectAtIndex:indexPath.row]; - NSString *path = item.path; - CGImageRef img_ref = nil; - - const char *cpath = [path UTF8String]; - [item.locker lock]; - PDF_ERR err; - PDF_DOC m_docThumb = Document_open(cpath,nil, &err); - int result = 1; - if( m_docThumb == NULL ) - { - switch( err ) - { - case err_password: - result = 2; - break; - default: - result = 0; - break; - } - } - else - { - PDF_PAGE page = Document_getPage(m_docThumb, 0); - float w = Document_getPageWidth(m_docThumb,0); - float h = Document_getPageHeight(m_docThumb,0); - PDF_DIB m_dib = NULL; - int iw = 89; - int ih = 111; - if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) - { - ih = 105; - iw = 80; - } - PDF_DIB bmp = Global_dibGet(m_dib, iw, ih); - float ratiox = iw/w; - float ratioy = ih/h; - if( ratiox > ratioy ) ratiox = ratioy; - PDF_MATRIX mat = Matrix_createScale(ratiox, -ratiox, 0, h * ratioy); - Page_renderPrepare( page, bmp ); - Page_render(page, bmp, mat,false,1); - Matrix_destroy(mat); - Page_close(page); - Document_close(m_docThumb); - void *data = Global_dibGetData(bmp); - CGDataProviderRef provider = CGDataProviderCreateWithData( NULL, data, iw * ih * 4, NULL ); - CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); - img_ref = CGImageCreate( iw, ih, 8, 32, iw<<2, cs, kCGBitmapByteOrder32Little|kCGImageAlphaNoneSkipFirst, provider, NULL, FALSE, kCGRenderingIntentDefault ); - CGColorSpaceRelease(cs); - CGDataProviderRelease( provider ); - } - [item.locker unlock]; - if(!img_ref) return; - UIImage *img= [UIImage imageWithCGImage:img_ref]; - dispatch_async(dispatch_get_main_queue(), ^{ - UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; - [cell.imageView performSelectorOnMainThread:@selector(setImage:) withObject:img waitUntilDone:NO]; - }); -} - -@end diff --git a/src/ios/PDFViewer/RDLoPDFViewController.h b/src/ios/PDFViewer/RDLoPDFViewController.h deleted file mode 100755 index 80c2869b..00000000 --- a/src/ios/PDFViewer/RDLoPDFViewController.h +++ /dev/null @@ -1,137 +0,0 @@ -// -// ViewController.h -// RDPDFReader -// -// Created by Radaee on 16/11/19. -// Copyright © 2016年 radaee. All rights reserved. -// - -#import -#import "PDFLayoutView.h" -#import -#import -#import "PDFThumbView.h" -#import "PDFGridView.h" - -// define the protocol for the delegate -@protocol RDPDFViewControllerDelegate -// define protocol functions that can be used in any class using this delegate -- (void)willShowReader; -- (void)didShowReader; -- (void)willCloseReader; -- (void)didCloseReader; -- (void)didChangePage:(int)page; -- (void)didSearchTerm:(NSString *)term found:(BOOL)found; -- (void)didTapOnPage:(int)page atPoint:(CGPoint)point; -- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point; -- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point; -- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point; -@end; - -@class TextAnnotViewController; -@class OutLineViewController; -@interface RDLoPDFViewController : UIViewController -{ - PDFLayoutView *m_view; - PDFThumbView *m_Thumbview; - UISlider *m_slider; - //PDFGridView *m_Gridview; - PDFDoc *m_doc; - - BOOL firstPageCover; - BOOL isImmersive; - BOOL readOnly; - - TextAnnotViewController *textAnnotVC; - OutLineViewController *outlineView; -} - -@property(nonatomic,strong) UILabel *pageNumLabel; - -#pragma mark - lib properties - -@property (strong, nonatomic) UIImage *closeImage; -@property (strong, nonatomic) UIImage *viewModeImage; -@property (strong, nonatomic) UIImage *searchImage; -@property (strong, nonatomic) UIImage *bookmarkImage; -@property (strong, nonatomic) UIImage *addBookmarkImage; -@property (strong, nonatomic) UIImage *outlineImage; -@property (strong, nonatomic) UIImage *lineImage; -@property (strong, nonatomic) UIImage *rowImage; -@property (strong, nonatomic) UIImage *rectImage; -@property (strong, nonatomic) UIImage *ellipseImage; -@property (strong, nonatomic) UIImage *bitmapImage; -@property (strong, nonatomic) UIImage *noteImage; -@property (strong, nonatomic) UIImage *signatureImage; -@property (strong, nonatomic) UIImage *printImage; -@property (strong, nonatomic) UIImage *shareImage; -@property (strong, nonatomic) UIImage *gridImage; -@property (strong, nonatomic) UIImage *deleteImage; -@property (strong, nonatomic) UIImage *doneImage; -@property (strong, nonatomic) UIImage *removeImage; -@property (strong, nonatomic) UIImage *prevImage; -@property (strong, nonatomic) UIImage *nextImage; -@property (strong, nonatomic) UIImage *undoImage; -@property (strong, nonatomic) UIImage *redoImage; -@property (strong, nonatomic) UIImage *performImage; -@property (strong, nonatomic) UIImage *moreImage; -@property (strong, nonatomic) UIImage *drawImage; -@property (strong, nonatomic) UIImage *selectImage; -@property (strong, nonatomic) UIImage *saveImage; -@property (strong, nonatomic) UIImage *metaImage; - -@property (nonatomic) BOOL hideSearchImage; -@property (nonatomic) BOOL hideDrawImage; -@property (nonatomic) BOOL hideSelImage; -@property (nonatomic) BOOL hideUndoImage; -@property (nonatomic) BOOL hideRedoImage; -@property (nonatomic) BOOL hideMoreImage; -@property (nonatomic) BOOL hideGridImage; - -// define delegate property -@property (nonatomic, assign) id delegate; - -- (int)PDFOpen:(NSString *)path : (NSString *)pwd; -- (int)PDFOpen:(NSString *)path : (NSString *)pwd atPage:(int)page readOnly:(BOOL)readOnlyEnabled autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose author:(NSString *)author; -- (int)PDFOpenStream:(id)stream :(NSString *)password; -- (int)PDFOpenMem:(void *)data :(int)data_size :(NSString *)pwd; -- (void)PDFGoto:(int)pageno; -- (void)closeView; -- (void)closeView:(BOOL)isFromCordova; - -#pragma mark - lib methods - -- (id)getDoc; -- (int)getCurrentPage; -- (CGImageRef)imageForPage:(int)pg; -- (void)setThumbnailBGColor:(int)color; -- (void)setThumbGridBGColor:(int)color; -- (void)setThumbGridElementHeight:(float)height; -- (void)setThumbGridGap:(float)gap; -- (void)setThumbGridViewMode:(int)mode; -- (void)setReaderBGColor:(int)color; -- (void)setToolbarColor:(int)color; -- (void)setToolbarTintColor:(int)color; -- (void)setThumbHeight:(float)height; -- (void)setFirstPageCover:(BOOL)cover; -- (void)setDoubleTapZoomMode:(int)mode; -- (void)setImmersive:(BOOL)immersive; -- (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size; -- (BOOL)addAttachmentFromPath:(NSString *)path; -- (void)refreshCurrentPage; - -- (bool)flatAnnotAtPage:(int)page doc:(PDFDoc *)doc; -- (bool)flatAnnots; -- (bool)saveDocumentToPath:(NSString *)path; - -// Form Manager - -- (NSString *)getJSONFormFields; -- (NSString *)getJSONFormFieldsAtPage:(int)page; -- (NSString *)setFormFieldWithJSON:(NSString *)json; - -- (CGPoint)pdfPointsFromScreenPoints:(int)x :(int)y; -- (CGPoint)screenPointsFromPdfPoints:(float)x :(float)y :(int)pageNum; -- (PDF_RECT)pdfRectFromScreenRect:(CGRect)screenRect; -- (CGRect)screenRectFromPdfRect:(float)top :(float)left :(float)right :(float)bottom :(int)pageNum; -@end diff --git a/src/ios/PDFViewer/RDLoPDFViewController.m b/src/ios/PDFViewer/RDLoPDFViewController.m deleted file mode 100644 index a249d871..00000000 --- a/src/ios/PDFViewer/RDLoPDFViewController.m +++ /dev/null @@ -1,2987 +0,0 @@ -// -// ViewController.m -// RDPDFReader -// -// Created by Radaee on 16/11/19. -// Copyright © 2016年 radaee. All rights reserved. -// - -#import "RDLoPDFViewController.h" -#import "OutLineViewController.h" -#import "RDToolBar.h" -#import "RDVGlobal.h" - -#import "TextAnnotViewController.h" -#import -#import "DrawModeTableViewController.h" -#import "RDMoreTableViewController.h" -#import "BookmarkTableViewController.h" -#import "RDAnnotListViewController.h" -#import "SignatureViewController.h" -#import "ViewModeTableViewController.h" -#import "RDFormManager.h" -#import "RDExtendedSearch.h" -#import "SearchResultTableViewController.h" - -#import "MenuAnnotOp.h" -#import "MenuCombo.h" -#import "PDFPopupCtrl.h" -#import "PDFDialog.h" -#import "DlgMeta.h" -#import "DlgAnnotPopText.h" -#import "DlgAnnotPropComm.h" -#import "DlgAnnotPropMarkup.h" -#import "DlgAnnotPropLine.h" -#import "DlgAnnotPropIcon.h" - -#define SYS_VERSION [[[UIDevice currentDevice]systemVersion] floatValue] -#define THUMB_HEIGHT 99 - -@interface RDLoPDFViewController () -{ - NSString *findString; - RDToolBar *toolBar; - UIToolbar *drawToolbar; - UISearchBar* m_searchBar; - UISlider *sliderBar; - UILabel *pageNumLabel; - BOOL b_findStart; - BOOL m_bSel; - BOOL statusBarHidden; - BOOL isPrint; - BOOL b_outline; - BOOL b_noteAnnot; - int pagecount; - int pagenow; - NSMutableArray *tempfiles; - - AVPlayerViewController *avvc; - UIPickerView *pickerView; - NSArray *pickViewArr; - UIButton *confirmPickerBtn; - UITextField *textFd; - - UIMenuController *selectMenu; - int selectItem; - UIAlertController *moreItemsContainer; - RDMoreTableViewController *moreTVContainer; - BookmarkTableViewController *b; - //UIPopoverController *bookmarkPopover; - CGPoint annotTapped; - RDAnnotListViewController *annotListTV; - UIMenuController *selectMC; - BOOL alreadySelected; - - PDFAnnot *cachedAnnot; - int posx; - int posy; - - int gridBackgroundColor; - int gridElementHeight; - int gridGap; - int gridMode; - int doubleTapZoomMode; - - int statusBarHeight; - - UIColor *toolbarColor; - UIColor *toolbarTintColor; - - UILabel *sliderLabel; - - PDFAnnot *selectedAnnot; - - MenuAnnotOp *m_menu_op; -} -@end - - -@implementation RDLoPDFViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - - [self initialPopupView]; - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshToolbarPosition) name:UIDeviceOrientationDidChangeNotification object:nil]; - - if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) { - self.automaticallyAdjustsScrollViewInsets = NO; - } - - isPrint = NO; - m_bSel = false; - float width = [UIScreen mainScreen].bounds.size.width; - pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 160, width, 60)]; - pickerView.delegate = self; - pickerView.dataSource = self; - pickerView.backgroundColor = [UIColor lightGrayColor]; - [self.view addSubview:pickerView]; - [self.view bringSubviewToFront:pickerView]; - - confirmPickerBtn = [UIButton buttonWithType:UIButtonTypeCustom]; - confirmPickerBtn.frame = CGRectMake(width - 60, pickerView.frame.origin.y - 40, 60, 40); - [confirmPickerBtn setTitle:@"OK" forState:UIControlStateNormal]; - confirmPickerBtn.hidden = YES; - [confirmPickerBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; - confirmPickerBtn.backgroundColor = [UIColor clearColor]; - [confirmPickerBtn addTarget:self action:@selector(setComboselect) forControlEvents:UIControlEventTouchUpInside]; - [self.view addSubview:confirmPickerBtn]; - - textFd = [[UITextField alloc] init]; - textFd.delegate = self; - [self.view addSubview:textFd]; - textFd.hidden = YES; -} --(void)viewWillAppear:(BOOL)animated -{ - if (_delegate && [_delegate respondsToSelector:@selector(willShowReader)]) { - [_delegate willShowReader]; - } - - - [toolBar removeFromSuperview]; - [self createToolbarItems]; - [toolBar sizeToFit]; - b_findStart = NO; - isPrint = NO; - b_outline = NO; - - self.navigationController.navigationBarHidden = YES; - - [self refreshToolbarPosition]; - - [self.view addSubview:toolBar]; - - toolBar.hidden = NO; - - [self toolBarStyle]; -} - -- (void)viewDidAppear:(BOOL)animated -{ - [super viewDidAppear:animated]; - - if (_delegate && [_delegate respondsToSelector:@selector(didShowReader)]) { - [_delegate didShowReader]; - } - - [self pageNumLabelInit:pagenow]; - [self refreshPdfViewPosition]; -} - --(void)viewWillDisappear:(BOOL)animated -{ - if(!b_outline && !isPrint){ - [m_Thumbview PDFClose]; - [m_view PDFClose]; - m_doc = nil; - } - - //delete temp files - [self clearTempFiles]; -} - -- (void)viewDidDisappear:(BOOL)animated -{ - [super viewDidDisappear:animated]; - - if(!b_outline) - { - if (_delegate && [_delegate respondsToSelector:@selector(didCloseReader)]) { - [_delegate didCloseReader]; - } - } -} - -- (BOOL)shouldAutorotate -{ - return YES; -} - -- (UIStatusBarStyle)preferredStatusBarStyle -{ - return UIStatusBarStyleLightContent; -} - -- (void)pageNumLabelInit:(int)pageno -{ - if (pageNumLabel) { - [pageNumLabel removeFromSuperview]; - } - - pageNumLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, [self barHeightDistance], 65, 30)]; - pagenow = pageno; - pageNumLabel.backgroundColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:0.4]; - pageNumLabel.textColor = [UIColor whiteColor]; - pageNumLabel.adjustsFontSizeToFitWidth = YES; - pageNumLabel.textAlignment= NSTextAlignmentCenter; - pageNumLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters; - pageNumLabel.layer.cornerRadius = 10; - pageNumLabel.font = [UIFont boldSystemFontOfSize:16]; - [self updatePageNumLabel:pageno+1]; - [self.view addSubview:pageNumLabel]; - - [pageNumLabel setHidden:toolBar.hidden]; -} - -- (void)updatePageNumLabel:(int)page -{ - NSString *pagestr = [[NSString alloc]initWithFormat:@"%d/",page]; - pagestr = [pagestr stringByAppendingFormat:@"%d",pagecount]; - pageNumLabel.text = pagestr; - pagenow = (page - 1); -} - -- (void)refreshPageNumLabelPosition { - pageNumLabel.frame = CGRectMake(0, [self barHeightDistance], 65, 30); -} - --(void)PDFGoto:(int)pageno -{ - if (pageno < 0) { - [self PDFGoto:0]; - return; - } - - if (pageno > m_doc.pageCount - 1) { - [self PDFGoto:m_doc.pageCount - 1]; - return; - } - - [m_view resetZoomLevel]; - [m_view vGoto:pageno]; - [m_Thumbview vGoto:pageno]; - [self updatePageNumLabel:(pageno + 1)]; -} - --(UIInterfaceOrientationMask)supportedInterfaceOrientations -{ - return UIInterfaceOrientationMaskAllButUpsideDown; -} -- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator -{ - [m_view setFrame:CGRectMake(0, 0, size.width, size.height)]; - [m_view sizeThatFits:size]; - m_Thumbview.frame = CGRectMake(0, size.height - GLOBAL.g_thumbview_height, size.width, GLOBAL.g_thumbview_height); - m_slider.frame = CGRectMake(0, size.height - GLOBAL.g_thumbview_height, size.width, GLOBAL.g_thumbview_height); - [m_Thumbview sizeThatFits:m_Thumbview.frame.size]; - [m_slider sizeThatFits:m_slider.frame.size]; - [m_Thumbview vGoto:pagenow]; - m_slider.value = pagenow +1; - [self setSliderText:(int)m_slider.value]; -} - -- (void)createToolbarItems -{ - toolBar = [[RDToolBar alloc] init]; - toolBar.m_delegate = self; - - // Set images - toolBar.closeImage = _closeImage; - toolBar.searchImage = _searchImage; - toolBar.selectImage = _selectImage; - toolBar.drawImage = _drawImage; - toolBar.undoImage = _undoImage; - toolBar.redoImage = _redoImage; - toolBar.gridImage = _gridImage; - toolBar.deleteImage = _deleteImage; - toolBar.doneImage = _doneImage; - toolBar.removeImage = _removeImage; - toolBar.performImage = _performImage; - toolBar.moreImage = _moreImage; - toolBar.prevImage = _prevImage; - toolBar.nextImage = _nextImage; - - // Hide icons - toolBar.hideSearchImage = _hideSearchImage; - toolBar.hideDrawImage = _hideDrawImage; - toolBar.hideSelImage = _hideSelImage; - toolBar.hideUndoImage = _hideUndoImage; - toolBar.hideRedoImage = _hideRedoImage; - toolBar.hideMoreImage = _hideMoreImage; - toolBar.hideGridImage = YES; - - toolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin; - - [toolBar setupToolBarArray]; -} - -- (void)refreshToolbarPosition { - [self refreshStatusBarHeight]; - - if (@available(iOS 13.0, *)) { - [toolBar setFrame:CGRectMake(0, 0, [self screenRect].size.width, toolBar.barHeight + statusBarHeight)]; - [toolBar.bar setFrame:CGRectMake(0, toolBar.frame.size.height - toolBar.barHeight, [self screenRect].size.width, toolBar.barHeight)]; - } else { - [toolBar setFrame:CGRectMake(0, statusBarHeight, [self screenRect].size.width, toolBar.barHeight)]; - [toolBar.bar setFrame:CGRectMake(0, 0, toolBar.frame.size.width, toolBar.frame.size.height)]; - } - - [self refreshPageNumLabelPosition]; -} - -- (void)refreshPdfViewPosition { - CGRect rect = [self screenRect]; - if (isImmersive) { - m_view.frame = rect; - } - else { - m_view.frame = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height - GLOBAL.g_thumbview_height); - } -} - --(int)PDFOpen:(NSString *)path : (NSString *)pwd { - return [self PDFOpen:path :pwd atPage:0 readOnly:NO autoSave:NO suppressClose:NO author:@""]; -} - --(int)PDFOpen:(NSString *)path : (NSString *)pwd atPage:(int)page readOnly:(BOOL)readOnlyEnabled autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose author:(NSString *)author -{ - GLOBAL.g_author = author; - GLOBAL.g_pdf_path = [[path stringByDeletingLastPathComponent] mutableCopy]; - GLOBAL.g_pdf_name = [[path lastPathComponent] mutableCopy]; - GLOBAL.g_save_doc = autoSave; - GLOBAL.g_suppressClose = suppressClose; - - CGRect rect = [self screenRect]; - m_doc = [[PDFDoc alloc] init]; - int err_code = [m_doc open:path :pwd]; - switch( err_code ) - { - case err_ok: - break; - case err_password: - return 2; - break; - default: return 0; - } - - m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; - [m_view setReadOnly:readOnlyEnabled]; - readOnly = readOnlyEnabled; - BOOL res = [m_view PDFOpen:m_doc :4 :self]; - [self.view addSubview:m_view]; - pagecount = [m_doc pageCount]; - - [self thumbInit:page]; - [self PDFGoto:page]; - - return res; -} - -- (int)PDFOpenStream:(id)stream :(NSString *)password -{ - CGRect rect = [self screenRect]; - m_doc = [[PDFDoc alloc] init]; - int err_code = [m_doc openStream:stream :password]; - switch( err_code ) - { - case err_ok: - break; - case err_password: - return 2; - break; - default: return 0; - } - - m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; - [self.view addSubview:m_view]; - pagecount = [m_doc pageCount]; - - [self thumbInit:0]; - - return [m_view PDFOpen:m_doc :4 :self]; -} - -- (int)PDFOpenMem:(void *)data :(int)data_size :(NSString *)pwd -{ - CGRect rect = [self screenRect]; - m_doc = [[PDFDoc alloc] init]; - int err_code = [m_doc openMem:data :data_size :pwd]; - switch( err_code ) - { - case err_ok: - break; - case err_password: - return 2; - break; - default: return 0; - } - - m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; - [self.view addSubview:m_view]; - pagecount = [m_doc pageCount]; - - [self thumbInit:0]; - - return [m_view PDFOpen:m_doc :4 :self]; -} -/* - #pragma mark - Grid View - - - (void)toggleGrid - { - [self toggleGridView]; - } - - - (void)toggleGridView - { - if (!m_Gridview) { - [self showGridView]; - - } else { - [self hideGridView]; - } - } - - - (void)showGridView - { - if (!m_Gridview) { - m_Gridview = [[PDFGridView alloc] initWithFrame:CGRectMake(100, 100, 500, 500)]; - [m_Gridview PDFOpen:m_doc :4 :(id)self]; - - if (gridBackgroundColor != 0) { - [m_Gridview setThumbBackgroundColor:gridBackgroundColor]; - } - - [self.view addSubview:m_Gridview]; - } - } - - - (void)hideGridView - { - if(m_Gridview) { - [m_Gridview removeFromSuperview]; - [m_Gridview PDFClose]; - m_Gridview = nil; - } - } - - #pragma mark - Slider - - - (void)sliderInit:(int)pageno - { - CGRect boundsc = [self screenRect]; - - int cwidth = boundsc.size.width; - int cheight = boundsc.size.height; - - m_slider = [[UISlider alloc] initWithFrame:CGRectMake(0, cheight-50, cwidth, 50)]; - - m_slider.minimumValue = 1; - m_slider.maximumValue = pagecount; - m_slider.continuous = NO; - m_slider.value = pageno; - - [m_slider addTarget:self action:@selector(OnSliderValueChange:) forControlEvents:UIControlEventValueChanged]; - - [m_slider setBackgroundColor:[UIColor blackColor]]; - - [self.view addSubview:m_slider]; - - [self pageNumLabelInit:pageno]; - } - */ -#pragma mark - Thumbnail - -- (void)thumbInit:(int)pageno { - CGRect rect = [self screenRect]; - - if (GLOBAL.g_thumbview_height == 0) { - GLOBAL.g_thumbview_height = THUMB_HEIGHT; - } - - if (m_Thumbview) { - [m_Thumbview PDFClose]; - [m_Thumbview removeFromSuperview]; - m_Thumbview = NULL; - } - - if (m_slider) { - [m_slider removeFromSuperview]; - m_slider = nil; - } - - m_Thumbview = [[PDFThumbView alloc] initWithFrame:CGRectMake(0, rect.size.height - GLOBAL.g_thumbview_height, rect.size.width, GLOBAL.g_thumbview_height)]; - [m_Thumbview PDFOpen:m_doc :4 :self]; - [m_Thumbview vGoto:pageno];//page 0 for default selected page. - [self.view addSubview:m_Thumbview]; - m_Thumbview.hidden = !GLOBAL.g_navigation_mode; - - sliderLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, GLOBAL.g_thumbview_height / 3)]; - sliderLabel.textColor = [UIColor whiteColor]; - sliderLabel.textAlignment = NSTextAlignmentCenter; - sliderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; - [self setSliderText:pageno + 1]; - - m_slider = [[UISlider alloc] initWithFrame:CGRectMake(0, rect.size.height - GLOBAL.g_thumbview_height, rect.size.width, GLOBAL.g_thumbview_height)]; - m_slider.minimumValue = 1; - m_slider.maximumValue = m_doc.pageCount; - //m_slider.continuous = NO; - m_slider.value = pageno + 1; - [m_slider addTarget:self action:@selector(OnSliderValueChange:) forControlEvents:UIControlEventValueChanged]; - [m_slider addTarget:self action:@selector(OnSliderTouchUp:) forControlEvents:UIControlEventTouchUpInside]; - m_slider.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4]; - [m_slider addSubview:sliderLabel]; - m_slider.hidden = GLOBAL.g_navigation_mode; - [self.view addSubview:m_slider]; -} - -#pragma mark - Slider - -- (void)setSliderText:(int)value { - sliderLabel.text = [NSString stringWithFormat:@"%i/%i", value, m_doc.pageCount]; -} - --(void)OnSliderValueChange:(UISlider *)slider -{ - [self updateSlider:slider.value goto:NO]; -} - - --(void)OnSliderTouchUp:(UISlider *)slider -{ - [self updateSlider:slider.value goto:YES]; -} - -- (void)updateSlider:(int)value goto:(BOOL)haveToGoTo { - int page = value; - if (page <= 0) { - page = 1; - } - if (page >= m_doc.pageCount) { - page = m_doc.pageCount; - } - - if (haveToGoTo) { - [self OnPageClicked:page - 1]; - } else { - [self setSliderText:page]; - } -} - --(void)OnPageClicked:(int)pageno -{ - [self PDFGoto:pageno]; -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; -} -#pragma mark perform annot method --(void)performAnnot -{ - [m_view vAnnotPerform]; - [toolBar changeToNormalToolBar]; -} --(void)deleteAnnot -{ - [m_view vAnnotRemove]; -} --(void)annotCancel -{ - [self removeAnnotToolBar]; -} --(void)removeAnnotToolBar -{ - [toolBar changeToNormalToolBar]; - [m_view vAnnotEnd]; -} -- (void)annotProperties -{ - [self OnAnnotProp:selectedAnnot]; -} -#pragma mark - press annot method -- (void)OnPageChanged :(int)pageno -{ - static int prevPage = -1; - if (_delegate && [_delegate respondsToSelector:@selector(didChangePage:)]) { - if (pageno != prevPage) { - prevPage = pageno; - [_delegate didChangePage:pageno]; - } - } - - [m_Thumbview vGoto:pageno]; - m_slider.value = pageno +1; - [self setSliderText:(int)m_slider.value]; - [self updatePageNumLabel:(pageno + 1)]; -} - -- (void)OnPageUpdated :(int)pageno -{ - [m_Thumbview PDFUpdatePage:pageno]; -} - -- (void)OnLongPressed:(float)x :(float)y -{ - if (_delegate && [_delegate respondsToSelector:@selector(didLongPressOnPage:atPoint:)]) { - [_delegate didLongPressOnPage:(pagenow) atPoint:CGPointMake(x, y)]; - } -} - -- (void)OnSingleTapped:(float)x :(float)y -{ - if (_delegate && [_delegate respondsToSelector:@selector(didTapOnPage:atPoint:)]) { - RDVPos pos; - [m_view vGetPos:&pos x:x y:y]; - [_delegate didTapOnPage:pos.pageno atPoint:CGPointMake(x, y)]; - } - - if (b_noteAnnot) { - posx = x; - posy = y; - [self TextAnnot]; - return; - } - - if (!pickerView.hidden) { - pickerView.hidden = YES; - confirmPickerBtn.hidden = YES; - } - - [m_searchBar resignFirstResponder]; - if(isImmersive) - { - [self showBars]; - } - else - { - [self hideBars]; - } - - b_outline = false; - m_bSel = false; - [m_view vSelEnd]; -} - -- (void)OnDoubleTapped:(float)x :(float)y -{ - if (_delegate && [_delegate respondsToSelector:@selector(didDoubleTapOnPage:atPoint:)]) { - RDVPos pos; - [m_view vGetPos:&pos x:x y:y]; - [_delegate didDoubleTapOnPage:pos.pageno atPoint:CGPointMake(x, y)]; - } -} - -- (void)OnFound:(bool)found -{ - if (_delegate && [_delegate respondsToSelector:@selector(didSearchTerm:found:)]) { - [_delegate didSearchTerm:findString found:found]; - } - - if( !found ) - { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Warning" - message:@"Find Over" - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } -} -/* - -(void)selectText:(id)sender - { - selectToolBar = [UIToolbar new]; - [selectToolBar sizeToFit]; - selectToolBar.barStyle = UIBarStyleBlackOpaque; - UIBarButtonItem *selectDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarStyleBlackOpaque target:self action:@selector(selectDone)]; - selectDoneBtn.width =30; - UIBarButtonItem *selectCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarStyleBlackOpaque target:self action:@selector(selectCancel)]; - selectCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:selectDoneBtn,spacer,selectCancelBtn,nil]; - [selectToolBar setItems:toolbarItem animated:NO]; - self.navigationItem.titleView = selectToolBar; - [m_view vSelStart]; - [m_view vNoteStart]; - } - - -(void)selectDone - { - m_bSel = false; - [drawLineToolBar removeFromSuperview]; - self.navigationItem.titleView =toolBar; - [m_view vSelEnd]; - [m_view vNoteEnd]; - } - - -(void)selectCancel - { - [drawLineToolBar removeFromSuperview]; - self.navigationItem.titleView =toolBar; - [m_view vSelEnd]; - [m_view vNoteEnd]; - } - */ -- (void)OnSelStart:(float)x :(float)y -{ - if(m_bSel) - { - m_bSel = false; - } - m_bSel = YES; -} - -- (void)OnSelEnd:(float)x1 :(float)y1 :(float)x2 :(float)y2 -{ - if (m_bSel) { - NSString *s = [m_view vSelGetText]; - NSLog(@"OnSelEnd select text = %@",s); - if(s) - { - //popup a menu - [selectMenu setTargetRect:CGRectMake(x2,y2, 0, 0) inView:self.view]; - [selectMenu setMenuVisible:YES animated:YES]; - } - } -} -//enter annotation status. -- (void)OnAnnotClicked:(PDFAnnot *)annot :(CGRect)annotRect :(float)x :(float)y -{ - [m_searchBar setHidden:NO]; - - b_outline = false; - m_bSel = false; - - selectedAnnot = annot; - CGFloat scale_pix = [m_view vGetPixSize]; - - if(selectedAnnot.type != 3 && selectedAnnot.type != 20) - { - m_menu_op = [[MenuAnnotOp alloc] init :annot :annotRect.origin :^(int opt){ - switch(opt) - { - case 0://perform - [self performAnnot]; - break; - case 1://edit - [self performAnnot]; - break; - case 2://remove - [self deleteAnnot]; - break; - case 3://property - [self annotProperties]; - break; - } - if(self->m_menu_op) - { - [self->m_menu_op removeFromSuperview]; - self->m_menu_op = nil; - } - }]; - [self.view addSubview:m_menu_op]; - } - - //[toolBar changeToPerformToolBar]; - //[self showBars]; -} - --(void)OnAnnotProp:(PDFAnnot *)annot -{ - int atype = [annot type]; - if(atype == 4 || atype == 8)//line and polyline - { - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropLine" owner:self options:nil]; - DlgAnnotPropLine *view = [views lastObject]; - [view setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1]]; - - PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 200, 293) :YES :^(BOOL is_ok){ - if (is_ok) - { - [view updateAnnot]; - [self->m_view vAnnotEnd]; - [self->m_view vUpdateAnnotPage]; - [self->m_view setModified:YES force:NO]; - } - else - [self->m_view vAnnotEnd]; - }]; - [view setAnnot:annot :dlg]; - [self presentViewController:dlg animated:NO completion:nil]; - } - else if(atype >= 9 && atype <= 12)//markup - { - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropMarkup" owner:self options:nil]; - DlgAnnotPropMarkup *view = [views lastObject]; - [view setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1]]; - - PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 200, 123) :YES :^(BOOL is_ok) - { - if (is_ok) - { - [view updateAnnot]; - [self->m_view vAnnotEnd]; - [self->m_view vUpdateAnnotPage]; - [self->m_view setModified:YES force:NO]; - } - else - [self->m_view vAnnotEnd]; - }]; - [view setAnnot:annot :dlg]; - [self presentViewController:dlg animated:NO completion:nil]; - } - else if(atype == 1 || atype == 17)//sticky note and file attachment. - { - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropIcon" owner:self options:nil]; - DlgAnnotPropIcon *view = [views lastObject]; - [view setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1]]; - - PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 200, 229) :YES :^(BOOL is_ok){ - if (is_ok) - { - [view updateAnnot]; - [self->m_view vAnnotEnd]; - [m_view vUpdateAnnotPage]; - [self->m_view setModified:YES force:NO]; - } - else - [self->m_view vAnnotEnd]; - }]; - [view setAnnot:annot :dlg]; - [self presentViewController:dlg animated:NO completion:nil]; - } - else - { - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgAnnotPropComm" owner:self options:nil]; - DlgAnnotPropComm *view = [views lastObject]; - [view setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1]]; - [view hasFill:(atype != 15)]; - - PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, 200, 229) :YES :^(BOOL is_ok){ - if (is_ok) - { - [view updateAnnot]; - [self->m_view vAnnotEnd]; - [self->m_view vUpdateAnnotPage]; - [self->m_view setModified:YES force:NO]; - } - else - [self->m_view vAnnotEnd]; - }]; - [view setAnnot:annot :dlg]; - [self presentViewController:dlg animated:NO completion:nil]; - } -} - -//notified when annotation status end. -- (void)OnAnnotEnd -{ - if(m_menu_op) - { - [m_menu_op removeFromSuperview]; - m_menu_op = nil; - } - if (!pickerView.hidden) { - pickerView.hidden = YES; - confirmPickerBtn.hidden = YES; - } - if (!textFd.hidden){ - [textFd resignFirstResponder]; - textFd.hidden = YES; - } - selectedAnnot = nil; - [toolBar changeToNormalToolBar]; -} -//this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotGoto:(int)pageno -{ - [self PDFGoto:pageno]; -} -//this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotPopup:(PDFAnnot *)annot -{ - if(annot){ - cachedAnnot = annot; - b_outline = true; - textAnnotVC = [[TextAnnotViewController alloc]init]; - [textAnnotVC setDelegate:self]; - [textAnnotVC setText:[annot getPopupText]]; - [textAnnotVC setSubject:[annot getPopupSubject]]; - if ([annot isAnnotReadOnly]) - textAnnotVC.readOnly = YES; - textAnnotVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical; - UINavigationController *navController = [[UINavigationController alloc] - initWithRootViewController:textAnnotVC]; - [navController setModalPresentationStyle:UIModalPresentationCurrentContext]; - [self presentViewController:navController animated:YES completion:^{ - - }]; - } -} - -- (void)OnAnnotList:(PDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selectedIndexes:(NSArray *)indexes -{ - MenuCombo *view = [[MenuCombo alloc] init]; - PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; - [pop setDismiss:^{ - [self->m_view vAnnotEnd]; - }]; - CGFloat fsize = [m_view vGetScale] * 12 / [m_view vGetPixSize]; - CGRect rect = [self.view convertRect:annotRect toView: pop.view]; - - view.frame = rect; - [view setPara:rect.size.width :fsize :dataArray :^(int idx){ - int sels[1] = {idx}; - [annot setListSels:sels :1]; - [self->m_view vUpdateAnnotPage]; - [self->m_view vAnnotEnd]; - [self->m_view setModified:YES force:NO]; - [pop dismiss]; - }]; - [self presentViewController:pop animated:NO completion:nil]; -} - -- (void)OnAnnotSignature:(PDFAnnot *)annot { - cachedAnnot = annot; - - NSString *annotImage = [m_view getImageFromAnnot:annot]; - NSString *emptyImage = [m_view emptyImageFromAnnot:annot]; - - NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:annotImage error:nil]; - NSDictionary *emptyAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:emptyImage error:nil]; - - if (attr.fileSize != emptyAttr.fileSize) { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") message:NSLocalizedString(@"Signature already exist. Do you want delete it?", nil) preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { - [self presentSignatureViewController]; - }]; - UIAlertAction* cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self->m_view vAnnotEnd]; - }]; - - [alert addAction:ok]; - [alert addAction:cancel]; - [self presentViewController:alert animated:YES completion:nil]; - } else { - [self presentSignatureViewController]; - } -} - -- (void)OnAnnotTapped:(PDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point -{ - if (_delegate && [_delegate respondsToSelector:@selector(didTapOnAnnotationOfType:atPage:atPoint:)]) { - [_delegate didTapOnAnnotationOfType:annot.type atPage:page atPoint:point]; - } -} - -//this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotOpenURL:(NSString *)url -{ - b_outline = YES; - //open URI - if( url ){ - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") - message:[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"Do you want to open:", @"Localizable"), url] - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) - { - [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]]; - - }]; - UIAlertAction* cancel = [UIAlertAction - actionWithTitle:NSLocalizedString(@"Cancel", nil) - style:UIAlertActionStyleDefault - handler:nil]; - - [alert addAction:ok]; - [alert addAction:cancel]; - [self presentViewController:alert animated:YES completion:nil]; - } -} -//this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotMovie:(NSString *)fileName -{ - [tempfiles addObject:fileName]; - NSURL *urlPath = [NSURL fileURLWithPath:fileName]; - if ([[NSFileManager defaultManager] fileExistsAtPath:fileName]) { - avvc = [[AVPlayerViewController alloc] init]; - avvc.player = [AVPlayer playerWithURL:urlPath]; - avvc.view.frame = self.view.bounds; - avvc.modalPresentationStyle = UIModalPresentationFormSheet; - [self presentViewController:avvc animated:YES completion:nil]; - }else { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Error" - message:@"Couldn't find media file" - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } -} -//this mehod fired only when vAnnotPerform method invoked. -- (void)OnAnnotSound:(NSString *)fileName -{ - [tempfiles addObject:fileName]; -} -- (void)OnAnnotEditBox:(PDFAnnot *)annot :(CGRect)annotRect :(NSString *)editText :(float)textSize -{ - PDFPopupCtrl *pop; - if([annot getEditType] == 3)//multi-line - { - UITextView *text = [[UITextView alloc] init]; - pop = [[PDFPopupCtrl alloc] init:text]; - CGRect rect = [self.view convertRect:annotRect toView: pop.view]; - text.frame = rect; - text.text = editText; - text.backgroundColor = [UIColor whiteColor]; - text.font = [UIFont systemFontOfSize:textSize]; - [pop setDismiss:^{ - [annot setEditText:text.text]; - [self->m_view vUpdateAnnotPage]; - [self->m_view vAnnotEnd]; - [self->m_view setModified:YES force:NO]; - }]; - } - else - { - UITextField *text = [[UITextField alloc] init]; - pop = [[PDFPopupCtrl alloc] init:text]; - CGRect rect = [self.view convertRect:annotRect toView: pop.view]; - text.frame = rect; - text.text = editText; - text.backgroundColor = [UIColor whiteColor]; - text.font = [UIFont systemFontOfSize:textSize]; - [pop setDismiss:^{ - [annot setEditText:text.text]; - [self->m_view vUpdateAnnotPage]; - [self->m_view vAnnotEnd]; - [self->m_view setModified:YES force:NO]; - }]; - } - [self presentViewController:pop animated:NO completion:nil]; -} -- (void)OnAnnotCommboBox:(PDFAnnot *)annot :(CGRect)annotRect :(NSArray *)dataArray selected:(int)index -{ - MenuCombo *view = [[MenuCombo alloc] init]; - PDFPopupCtrl *pop = [[PDFPopupCtrl alloc] init:view]; - [pop setDismiss:^{ - [self->m_view vAnnotEnd]; - }]; - CGFloat fsize = [m_view vGetScale] * 12 / [m_view vGetPixSize]; - CGRect rect = [self.view convertRect:annotRect toView: pop.view]; - int max_cnt = (dataArray.count > 5) ? 5 : (int)dataArray.count;//max 5 items height for scrollView - rect.origin.y += rect.size.height; - rect.size.height = (fsize + 2) * max_cnt; - - view.frame = rect; - [view setPara:rect.size.width :fsize :dataArray :^(int idx){ - [annot setComboSel:idx]; - [self->m_view vUpdateAnnotPage]; - [self->m_view vAnnotEnd]; - [self->m_view setModified:YES force:NO]; - [pop dismiss]; - }]; - [self presentViewController:pop animated:NO completion:nil]; -} - -#pragma mark - PickerView DataSource and Delegate --(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ - return 1; -} --(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ - return [pickViewArr count]; -} --(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ - return [pickViewArr objectAtIndex:(int)row]; -} -- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component -{ - selectItem = (int)row; -} -- (void)setComboselect -{ - [m_view setCommboItem:selectItem]; - pickerView.hidden = YES; - confirmPickerBtn.hidden = YES; -} - -#pragma mark - annotList Delegate -- (void)listCheckedAt:(NSArray *)indexes -{ - [annotListTV dismissViewControllerAnimated:YES completion:nil]; - [m_view selectListBoxItems:indexes]; - [m_view vSelEnd]; -} - -#pragma mark - textField Delegate -- (void)textFieldDidEndEditing:(UITextField *)textField; -{ - NSLog(@"textView.text = %@",textField.text); - [m_view setEditBoxWithText:textField.text]; -} -- (BOOL)textFieldShouldReturn:(UITextField *)textField -{ - [textField resignFirstResponder]; - return YES; -} - -//add begin and end editing delegate to add keyboard notifications -- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField -{ - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; - return YES; -} - -- (BOOL)textFieldShouldEndEditing:(UITextField *)textField -{ - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil]; - - [self.view endEditing:YES]; - return YES; -} - -//add keyboard notification -#pragma mark - Keyboard Notifications - -- (void)keyboardDidShow:(NSNotification *)notification -{ - //move the view to avoid the keyboard overlay - NSDictionary* keyboardInfo = [notification userInfo]; - NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey]; - CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue]; - - float gap = (keyboardFrameBeginRect.size.height - 30) - (textFd.frame.origin.y + textFd.frame.size.height); - - if (gap < 0) { - [self.view setFrame:CGRectMake(0, gap, self.view.frame.size.width, self.view.frame.size.height)]; - } -} - -- (void)keyboardDidHide:(NSNotification *)notification -{ - //restore the correct view position - [self.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; -} - -- (BOOL)isPortrait -{ - return ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || - [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown); -} - -#pragma mark - Toolbar Method - -- (void)closeView -{ - UIViewController *presentedViewController = [self.navigationController presentedViewController]; - [presentedViewController dismissViewControllerAnimated:NO completion:nil]; - [self closeView:false]; -} - -- (void)closeView:(BOOL)isFromCordova -{ - if (!isFromCordova && GLOBAL.g_suppressClose) { - - if (_delegate && [_delegate respondsToSelector:@selector(willCloseReader)] && m_doc != nil) { - [_delegate willCloseReader]; - } - } - else if ([m_view isModified] && !GLOBAL.g_save_doc) { - - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Exiting", nil) - message:NSLocalizedString(@"Document modified.\r\nDo you want to save it?", nil) - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"Yes", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) - { - [self PDFClose]; - [self.navigationController setNavigationBarHidden:NO]; - [self.navigationController popViewControllerAnimated:YES]; - [self dismissViewControllerAnimated:YES completion:nil]; - [alert dismissViewControllerAnimated:YES completion:nil]; - - }]; - UIAlertAction* cancel = [UIAlertAction - actionWithTitle:NSLocalizedString(@"No", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) - { - [self->m_view setModified:NO force:YES]; - [self PDFClose]; - [self.navigationController setNavigationBarHidden:NO]; - [self.navigationController popViewControllerAnimated:YES]; - [self dismissViewControllerAnimated:YES completion:nil]; - [alert dismissViewControllerAnimated:YES completion:nil]; - }]; - - [alert addAction:ok]; - [alert addAction:cancel]; - [self presentViewController:alert animated:YES completion:nil]; - } - else { - [self PDFClose]; - self.navigationController.navigationBarHidden = NO; - [self.navigationController popViewControllerAnimated:YES]; - [self dismissViewControllerAnimated:YES completion:nil]; - } -} - --(void)PDFClose -{ - if (_delegate && [_delegate respondsToSelector:@selector(willCloseReader)] && m_doc != nil) { - [_delegate willCloseReader]; - } - - if( m_view != nil ) - { - [m_view PDFClose]; - [m_view removeFromSuperview]; - m_view = NULL; - } - - if (m_Thumbview != nil) { - [m_Thumbview PDFClose]; - [m_Thumbview removeFromSuperview]; - m_Thumbview = NULL; - } - - m_doc = NULL; - [toolBar removeFromSuperview]; -} - -#pragma mark - More - --(void)showMoreButtons{ - [self endSelect]; - - if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){ - - moreItemsContainer = [UIAlertController - alertControllerWithTitle:NSLocalizedString(@"Select Action", nil) - message:@"" - preferredStyle:UIAlertControllerStyleActionSheet]; - - UIAlertAction *viewMode = [UIAlertAction actionWithTitle:NSLocalizedString(@"View Mode", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self showViewModeTableView]; - }]; - UIAlertAction *addBookMark = [UIAlertAction actionWithTitle:NSLocalizedString(@"Add Bookmark", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self composeFile]; - }]; - - UIAlertAction *bookMarkList = [UIAlertAction actionWithTitle:NSLocalizedString(@"Bookmark List", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self bookmarkList]; - }]; - - UIAlertAction *viewMenu = [UIAlertAction actionWithTitle:NSLocalizedString(@"View Menu", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self viewMenu]; - }]; - - UIAlertAction *meta = [UIAlertAction actionWithTitle:NSLocalizedString(@"Meta", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self OnMeta]; - }]; - - UIAlertAction *savePDF = [UIAlertAction actionWithTitle:NSLocalizedString(@"Save and Exit", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self savePdf]; - [self closeView]; - }]; - - UIAlertAction *printPDF = [UIAlertAction actionWithTitle:NSLocalizedString(@"Print", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self printPdf]; - }]; - UIAlertAction *sharePDF = [UIAlertAction actionWithTitle:NSLocalizedString(@"Share", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) - { - [self sharePDF]; - }]; - - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) - { - [self->moreItemsContainer dismissViewControllerAnimated:YES completion:nil]; - }]; - - [viewMode setValue:[(_viewModeImage) ? _viewModeImage : [UIImage imageNamed:@"btn_view"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [addBookMark setValue:[(_addBookmarkImage) ? _addBookmarkImage : [UIImage imageNamed:@"btn_add"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [bookMarkList setValue:[(_bookmarkImage) ? _bookmarkImage : [UIImage imageNamed:@"btn_show"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [viewMenu setValue:[(_outlineImage) ? _outlineImage : [UIImage imageNamed:@"btn_outline"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [meta setValue:[(_metaImage) ? _metaImage : [UIImage imageNamed:@"btn_meta"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [savePDF setValue:[(_saveImage) ? _saveImage : [UIImage imageNamed:@"btn_save"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [printPDF setValue:[(_printImage) ? _printImage : [UIImage imageNamed:@"btn_print"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - [sharePDF setValue:[(_shareImage) ? _shareImage : [UIImage imageNamed:@"btn_share"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - [moreItemsContainer addAction:viewMode]; - [moreItemsContainer addAction:addBookMark]; - [moreItemsContainer addAction:bookMarkList]; - [moreItemsContainer addAction:viewMenu]; - [moreItemsContainer addAction:meta]; - [moreItemsContainer addAction:savePDF]; - [moreItemsContainer addAction:printPDF]; - [moreItemsContainer addAction:sharePDF]; - [moreItemsContainer addAction:cancel]; - moreItemsContainer.view.tintColor = [self getTintColor]; - - [self presentViewController:moreItemsContainer animated:YES completion:nil]; - } - else - { - moreTVContainer = [[RDMoreTableViewController alloc] init]; - moreTVContainer.modalPresentationStyle = UIModalPresentationPopover; - [moreTVContainer setPreferredContentSize:CGSizeMake(300, 320)]; - moreTVContainer.delegate = self; - moreTVContainer.viewModeImage = _viewModeImage; - moreTVContainer.addBookmarkImage = _addBookmarkImage; - moreTVContainer.bookmarkImage = _bookmarkImage; - moreTVContainer.outlineImage = _outlineImage; - moreTVContainer.metaImage = _metaImage; - moreTVContainer.saveImage = _saveImage; - moreTVContainer.printImage = _printImage; - moreTVContainer.shareImage = _shareImage; - moreTVContainer.tintColor = [self getTintColor]; - UIPopoverPresentationController *popPresenter = [moreTVContainer - popoverPresentationController]; - popPresenter.barButtonItem = toolBar.moreButton; - popPresenter.permittedArrowDirections = UIPopoverArrowDirectionAny; - [self presentViewController:moreTVContainer animated:YES completion:nil]; - } - -} - --(void)selectAction:(int)type{ - [moreTVContainer dismissViewControllerAnimated:YES completion:nil]; - - switch (type) { - case 0: - [self showViewModeTableView]; - break; - case 1: - [self composeFile]; - break; - case 2: - [self bookmarkList]; - break; - case 3: - [self viewMenu]; - break; - case 4: - [self OnMeta]; - break; - case 5: - [self savePdf]; - [self closeView]; - break; - case 6: - [self printPdf]; - break; - case 7: - [self sharePDF]; - - default: - break; - } -} - -- (void)showViewModeTableView -{ - ViewModeTableViewController *vm = [[ViewModeTableViewController alloc] init]; - vm.delegate = self; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - - vm.modalPresentationStyle = UIModalPresentationPopover; - vm.delegate = self; - vm.preferredContentSize = CGSizeMake(320, (44 * 4) + 10); - - UIPopoverPresentationController *pop = vm.popoverPresentationController; - pop.permittedArrowDirections = UIPopoverArrowDirectionUp; - pop.barButtonItem = toolBar.moreButton; - - [self presentViewController:vm animated:YES completion:nil]; - } - else - { - UIAlertController *action = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Select View Mode", nil) message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; - - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) - { - [self dismissViewControllerAnimated:YES completion:nil]; - } - }]; - - UIAlertAction *vert = [UIAlertAction actionWithTitle:NSLocalizedString(@"Vertical", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self setReaderViewMode:0]; - }]; - [vert setValue:[[UIImage imageNamed:@"btn_view_vert"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; - - UIAlertAction *horz = [UIAlertAction actionWithTitle:NSLocalizedString(@"Horizontal", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self setReaderViewMode:1]; - }]; - [horz setValue:[[UIImage imageNamed:@"btn_view_horz"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; - - UIAlertAction *singleP = [UIAlertAction actionWithTitle:NSLocalizedString(@"Single Page", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self setReaderViewMode:3]; - }]; - [singleP setValue:[[UIImage imageNamed:@"btn_view_single"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; - - UIAlertAction *doubleP = [UIAlertAction actionWithTitle:NSLocalizedString(@"Double Page", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self setReaderViewMode:6]; - }]; - [doubleP setValue:[[UIImage imageNamed:@"btn_view_dual"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forKey:@"image"]; - - - [action addAction:vert]; - [action addAction:horz]; - [action addAction:singleP]; - [action addAction:doubleP]; - - [action addAction:cancel]; - - [self presentViewController:action animated:YES completion:nil]; - } -} - -- (void)setReaderViewMode:(int)mode -{ - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) - { - [self dismissViewControllerAnimated:YES completion:nil]; - } - - int currentPage = [m_view vGetCurrentPage]; - if( m_view != nil ) - { - [m_view PDFClose]; - [m_view removeFromSuperview]; - m_view = NULL; - } - - GLOBAL.g_render_mode = mode; - - [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_render_mode forKey:@"ViewMode"]; - [[NSUserDefaults standardUserDefaults] synchronize]; - CGRect rect = [self screenRect]; - - m_view = [[PDFLayoutView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; - [m_view PDFOpen:m_doc :4 :self]; - pagecount = [m_doc pageCount]; - - [self.view addSubview:m_view]; - - m_bSel = false; - - [self thumbInit:currentPage]; - [self PDFGoto:currentPage]; - - [self.view bringSubviewToFront:toolBar]; - [self.view bringSubviewToFront:m_Thumbview]; - [self.view bringSubviewToFront:pageNumLabel]; -} - -- (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath -{ - return [self addBookMarks:pdfPath :@"" :[NSFileManager defaultManager] pdfName:[GLOBAL.g_pdf_name stringByDeletingPathExtension] withPath:withPath]; -} - -- (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager* )fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath -{ - NSMutableArray *bookmarks = [NSMutableArray array]; - - NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; - NSString *fName; - while(fName = [fenum nextObject]) - { - NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); - NSString *dst = [dpath stringByAppendingPathComponent:fName]; - NSString *tempString; - - if(fName.length >10) - { - tempString = [fName pathExtension]; - } - - if( [tempString isEqualToString:@"bookmark"] ) - { - if (pdfName.length > 0 && ![fName containsString:pdfName]) { - continue; - } - - //add to list. - NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; - NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; - NSArray *myarray =[content componentsSeparatedByString:@","]; - [myarray objectAtIndex:0]; - NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; - - if (withPath) { - [bookmarks addObject:arr]; - } else { - [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; - } - - } - } - - return bookmarks; -} - -- (void)bookmarkList -{ - BookmarkTableViewController *b = [[BookmarkTableViewController alloc] init]; - b.items = [self loadBookmarkForPdf:GLOBAL.g_pdf_path withPath:YES]; - b.delegate = self; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - - //bookmarkPopover = [[UIPopoverController alloc] initWithContentViewController:b]; - //bookmarkPopover.popoverContentSize = CGSizeMake(300, 44 * b.items.count); - - //[bookmarkPopover presentPopoverFromBarButtonItem:toolBar.moreButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; - b.modalPresentationStyle = UIModalPresentationPopover; - b.delegate = self; - b.preferredContentSize = CGSizeMake(320, (44 * 4) + 10); - - UIPopoverPresentationController *pop = b.popoverPresentationController; - pop.permittedArrowDirections = UIPopoverArrowDirectionUp; - pop.barButtonItem = toolBar.moreButton; - - [self presentViewController:b animated:YES completion:nil]; - } - else - { - b_outline = true; - UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:b]; - [self presentViewController:nav animated:YES completion:nil]; - } -} - --(void)didSelectItem:(int)pageno { - [self PDFGoto:pageno]; -} - -#pragma mark - View Mode - -- (void)viewMenu -{ - b_outline =true; - PDFOutline *root = [m_doc rootOutline]; - if( root ) - { - OutLineViewController *outlineView = [[OutLineViewController alloc] init]; - //First parameter is root node - [outlineView setList:m_doc :NULL :root]; - UINavigationController *nav = self.navigationController; - outlineView.hidesBottomBarWhenPushed = YES; - [outlineView setJump:self]; - [nav pushViewController:outlineView animated:YES]; - } -} - -#pragma mark - Meta --(void)OnMeta -{ - CGRect rect = m_view.frame; - NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"DlgMeta" owner:self options:nil]; - DlgMeta *view = [views lastObject]; - //rect = view.frame; - //"Title", - //"Author", - //"Subject", - //"Keywords", - //"Creator", - //"Producer", - //"CreationDate", - //"ModDate" - [view setTitle:[m_doc meta:@"Title"]]; - [view setAuthor:[m_doc meta:@"Author"]]; - [view setSubject:[m_doc meta:@"Subject"]]; - [view setKeywords:[m_doc meta:@"Keywords"]]; - - [view setBackgroundColor:[UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1]]; - PDFDialog *dlg = [[PDFDialog alloc] init:view :CGRectMake(0, 0, rect.size.width * 0.8, 244) :YES :^(BOOL is_ok){ - if (!is_ok) return;//ok button pressed? - [self->m_doc setMeta:@"Title" :view.title]; - [self->m_doc setMeta:@"Author" :view.author]; - [self->m_doc setMeta:@"Subject" :view.subject]; - [self->m_doc setMeta:@"Keywords" :view.keywords]; - [self->m_view setModified:YES force:NO]; - }]; - [self presentViewController:dlg animated:NO completion:nil]; -} - -#pragma mark - Save - -- (void)savePdf -{ - if([m_view forceSave]) - { - // [self.navigationController popViewControllerAnimated:YES]; - // UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Notice", nil) - // message:NSLocalizedString(@"Document saved", nil) - // preferredStyle:UIAlertControllerStyleAlert]; - - // UIAlertAction* ok = [UIAlertAction - // actionWithTitle:NSLocalizedString(@"OK", nil) - // style:UIAlertActionStyleDefault - // handler:nil]; - // [alert addAction:ok]; - // [self presentViewController:alert animated:YES completion:nil]; - } -} - -- (BOOL)canBecomeFirstResponder -{ - return YES; -} - -#pragma mark - Undo - -- (void)undoAnnot -{ - [self endSelect]; - [m_view vUndo]; -} - -#pragma mark - Redo - -- (void)redoAnnot -{ - [self endSelect]; - [m_view vRedo]; -} - -#pragma mark - Draw - -- (void)showDrawModeTableView -{ - [self endSelect]; - - DrawModeTableViewController *vm = [[DrawModeTableViewController alloc] init]; - vm.delegate = self; - vm.lineImage = _lineImage; - vm.rowImage = _rowImage; - vm.rectImage = _rectImage; - vm.ellipseImage = _ellipseImage; - vm.bitmapImage = _bitmapImage; - vm.noteImage = _noteImage; -#ifdef SIGNATURE_ENABLED - vm.signatureImage = _signatureImage; -#endif - vm.tintColor = [self getTintColor]; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - - vm.modalPresentationStyle = UIModalPresentationPopover; - vm.delegate = self; -#ifdef SIGNATURE_ENABLED - vm.preferredContentSize = CGSizeMake(200, (44 * 7) + 10); -#else - vm.preferredContentSize = CGSizeMake(200, (44 * 6) + 10); -#endif - - UIPopoverPresentationController *pop = vm.popoverPresentationController; - pop.permittedArrowDirections = UIPopoverArrowDirectionUp; - if (_hideSearchImage) { - pop.barButtonItem = [toolBar.bar.items objectAtIndex:1]; - } else { - pop.barButtonItem = [toolBar.bar.items objectAtIndex:2]; - } - - [self presentViewController:vm animated:YES completion:nil]; - } - else - { - UIAlertController *action = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Select Draw Mode", nil) message:@"" preferredStyle:UIAlertControllerStyleActionSheet]; - - UIAlertAction *ink = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ink", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:0]; - }]; - [ink setValue:[(_lineImage) ? _lineImage : [UIImage imageNamed:@"btn_annot_ink"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - UIAlertAction *line = [UIAlertAction actionWithTitle:NSLocalizedString(@"Line", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:1]; - }]; - [line setValue:[(_rowImage) ? _rowImage : [UIImage imageNamed:@"btn_annot_line"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - UIAlertAction *rect = [UIAlertAction actionWithTitle:NSLocalizedString(@"Rect", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:2]; - }]; - [rect setValue:[(_rectImage) ? _rectImage : [UIImage imageNamed:@"btn_annot_rect"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - UIAlertAction *ellipse = [UIAlertAction actionWithTitle:NSLocalizedString(@"Ellipse", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:3]; - }]; - [ellipse setValue:[(_ellipseImage) ? _ellipseImage : [UIImage imageNamed:@"btn_annot_ellipse"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - UIAlertAction *stamp = [UIAlertAction actionWithTitle:NSLocalizedString(@"Stamp", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:4]; - }]; - [stamp setValue:[(_bitmapImage) ? _bitmapImage : [UIImage imageNamed:@"pdf_custom_stamp"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; - - UIAlertAction *note = [UIAlertAction actionWithTitle:NSLocalizedString(@"Note", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:5]; - }]; - [note setValue:[(_noteImage) ? _noteImage : [UIImage imageNamed:@"btn_annot_note"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; -#ifdef SIGNATURE_ENABLED - UIAlertAction *sign = [UIAlertAction actionWithTitle:NSLocalizedString(@"Signature", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - [self didSelectDrawMode:6]; - }]; - - [sign setValue:[(_signatureImage) ? _signatureImage : [UIImage imageNamed:@"btn_annot_ink"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forKey:@"image"]; -#endif - UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) - { - [self dismissViewControllerAnimated:YES completion:nil]; - } - }]; - - [action addAction:ink]; - [action addAction:line]; - [action addAction:rect]; - [action addAction:ellipse]; - [action addAction:stamp]; - [action addAction:note]; -#ifdef SIGNATURE_ENABLED - [action addAction:sign]; -#endif - [action addAction:cancel]; - action.view.tintColor = [self getTintColor]; - - [self presentViewController:action animated:YES completion:nil]; - } -} - -- (void)didSelectDrawMode:(int)mode -{ - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) - { - [self dismissViewControllerAnimated:YES completion:nil]; - } - - switch (mode) { - case 0: - [self drawLine]; - break; - case 1: - [self drawRow]; - break; - case 2: - [self drawRectangle]; - break; - case 3: - [self drawEllipse]; - break; - case 4: - [self drawImageStart]; - break; - case 5: - b_noteAnnot = YES; - break; -#ifdef SIGNATURE_ENABLED - case 6: - [self drawSignature]; - break; -#endif - default: - break; - } -} - -#ifdef SIGNATURE_ENABLED -- (void)drawSignature -{ - b_outline = YES; - AdvSignatureViewController *sign = [[AdvSignatureViewController alloc] init]; - sign.delegate = self; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - sign.modalPresentationStyle = UIModalPresentationFormSheet; - } - - [self presentViewController:sign animated:YES completion:nil]; -} -#endif - -#pragma mark - Signature - -- (void)presentSignatureViewController -{ - b_outline = YES; - SignatureViewController *sv = [[SignatureViewController alloc] init]; - sv.delegate = self; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - sv.modalPresentationStyle = UIModalPresentationFormSheet; - } else { - sv.modalPresentationStyle = UIModalPresentationFullScreen; - } - - [self presentViewController:sv animated:YES completion:nil]; -} - -- (void)didSign -{ - [self dismissViewControllerAnimated:YES completion:^{ - [self->m_view setSignatureImageAtIndex:self->cachedAnnot.getIndex atPage:[self->m_view vGetCurrentPage]]; - [self->m_view vAnnotEnd]; - }]; -} - -- (NSString *)composeFile -{ - NSString *pdfpath = [GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name]; - RDVPos pos; - [m_view vGetPos:&pos]; - int pageno = pos.pageno; - NSString *tempName = [[pdfpath lastPathComponent] stringByDeletingPathExtension]; - NSString *tempFile = [tempName stringByAppendingFormat:@"_%d%@",pageno,@".bookmark"]; - - NSString *fileContent = [NSString stringWithFormat:@"%i",pageno]; - NSString *BookMarkDir = [pdfpath stringByDeletingLastPathComponent]; - - NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; - - if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { - return @"Cannot add bookmark"; - } - - NSLog(@"%@", bookMarkFile); - - if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) - { - [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; - NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; - [fileHandle seekToEndOfFile]; - [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; - [fileHandle closeFile]; - - return @"Add BookMark Success!"; - } - else { - return @"BookMark Already Exist"; - } -} - --(void)searchView -{ - [self endSelect]; - - [toolBar changeToSearchToolBar]; - - CGRect frame = toolBar.bar.frame; - frame.origin.y = [self barHeightDistance]; - - if (m_searchBar) { - if (SEARCH_LIST == 1) { - [self showSearchList]; - } - - return; - } - - m_searchBar = [[UISearchBar alloc] initWithFrame:frame]; - m_searchBar.delegate = self; - m_searchBar.autocorrectionType = UITextAutocorrectionTypeNo; - m_searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone; - m_searchBar.placeholder = @"Search"; - m_searchBar.keyboardType = UIKeyboardTypeDefault; - m_searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth; - - [self toolBarStyle]; - - toolBar.searchButton.enabled = (m_searchBar.text.length > 0); - - [self.view addSubview:m_searchBar]; -} - -- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText -{ - toolBar.searchButton.enabled = (searchText.length > 0); -} - -- (void)showDocReadonlyAlert -{ - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") - message:NSLocalizedString(@"This Document is readonly", @"Localizable") - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"OK", @"Localizable") - style:UIAlertActionStyleDefault - handler:nil]; - - [alert addAction:ok]; - [self presentViewController:alert animated:YES completion:nil]; -} - -- (void)initDrawToolbar { - drawToolbar = [UIToolbar new]; - CGRect frame = toolBar.bar.frame; - drawToolbar.frame = frame; - drawToolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin; - [self toolBarStyle]; -} - --(void)drawLine -{ - if(![m_view vInkStart]) - { - [self showDocReadonlyAlert]; - return; - } - - [self initDrawToolbar]; - UIBarButtonItem *drawLineDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarButtonItemStylePlain target:self action:@selector(drawLineDone:)]; - drawLineDoneBtn.width =30; - UIBarButtonItem *drawLineCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarButtonItemStylePlain target:self action:@selector(drawLineCancel:)]; - drawLineCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:drawLineDoneBtn,spacer,drawLineCancelBtn,nil]; - [drawToolbar setItems:toolbarItem animated:NO]; - [toolBar addSubview:drawToolbar]; -} --(void)drawLineDone:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vInkEnd]; -} --(void)drawLineCancel:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vInkCancel]; -} -- (void)drawRow -{ - if(![m_view vLineStart]) - { - [self showDocReadonlyAlert]; - return; - } - - [self initDrawToolbar]; - UIBarButtonItem *drawLineDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarButtonItemStylePlain target:self action:@selector(drawRowDone)]; - drawLineDoneBtn.width =30; - UIBarButtonItem *drawLineCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarButtonItemStylePlain target:self action:@selector(drawRowCancel)]; - drawLineCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:drawLineDoneBtn,spacer,drawLineCancelBtn,nil]; - [drawToolbar setItems:toolbarItem animated:NO]; - [toolBar addSubview:drawToolbar]; -} - -- (void)drawRowDone -{ - [m_view vLineEnd]; - [drawToolbar removeFromSuperview]; -} - -- (void)drawRowCancel -{ - [drawToolbar removeFromSuperview]; - [m_view vLineCancel]; -} - --(void)drawRectangle -{ - if(![m_view vRectStart]) - { - [self showDocReadonlyAlert]; - return; - } - - [self initDrawToolbar]; - UIBarButtonItem *drawLineDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarButtonItemStylePlain target:self action:@selector(drawRectDone:)]; - drawLineDoneBtn.width =30; - UIBarButtonItem *drawLineCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarButtonItemStylePlain target:self action:@selector(drawRectCancel:)]; - drawLineCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:drawLineDoneBtn,spacer,drawLineCancelBtn,nil]; - [drawToolbar setItems:toolbarItem animated:NO]; - [toolBar addSubview:drawToolbar]; -} --(void)drawRectDone:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vRectEnd]; -} --(void)drawRectCancel:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vRectCancel]; -} --(void)drawEllipse -{ - if(![m_view vEllipseStart]) - { - [self showDocReadonlyAlert]; - return; - } - - [self initDrawToolbar]; - UIBarButtonItem *drawLineDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarButtonItemStylePlain target:self action:@selector(drawEllipseDone:)]; - drawLineDoneBtn.width =30; - UIBarButtonItem *drawLineCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarButtonItemStylePlain target:self action:@selector(drawEllipseCancel:)]; - drawLineCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:drawLineDoneBtn,spacer,drawLineCancelBtn,nil]; - [drawToolbar setItems:toolbarItem animated:NO]; - [toolBar addSubview:drawToolbar]; -} --(void)drawEllipseDone:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vEllipseEnd]; -} --(void)drawEllipseCancel:(id)sender -{ - [drawToolbar removeFromSuperview]; - [m_view vEllipseCancel]; -} - -- (void)drawImageStart -{ - if(![m_view vImageStart]){ - [self showDocReadonlyAlert]; - return; - } - - [self initDrawToolbar]; - UIBarButtonItem *drawLineDoneBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_done"] style:UIBarButtonItemStylePlain target:self action:@selector(drawImageDone)]; - drawLineDoneBtn.width =30; - UIBarButtonItem *drawLineCancelBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"btn_annot_remove"] style:UIBarButtonItemStylePlain target:self action:@selector(drawImageCancel)]; - drawLineCancelBtn.width =30; - UIBarButtonItem *spacer = [[UIBarButtonItem alloc] - initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace - target:nil - action:nil]; - - NSArray *toolbarItem = [[NSArray alloc]initWithObjects:drawLineDoneBtn,spacer,drawLineCancelBtn,nil]; - [drawToolbar setItems:toolbarItem animated:NO]; - [toolBar addSubview:drawToolbar]; -} - -- (void)drawImageDone -{ - [drawToolbar removeFromSuperview]; - [m_view vImageEnd]; -} - -- (void)drawImageCancel -{ - [drawToolbar removeFromSuperview]; - [m_view vImageCancel]; -} - --(void)addBookMark -{ - int pageno = 0; - RDVPos pos; - [m_view vGetPos :&pos]; - pageno = pos.pageno; - float x = pos.pdfx; - float y = pos.pdfy; - NSString *tempFile; - NSString *tempName; - tempName = [GLOBAL.g_pdf_name substringToIndex:GLOBAL.g_pdf_name.length-4]; - tempFile = [tempName stringByAppendingFormat:@"%d%@",pageno,@".bookmark"]; - NSString *tempPath; - tempPath = [GLOBAL.g_pdf_path stringByAppendingFormat:@"%@",GLOBAL.g_pdf_name]; - NSString *fileContent = [NSString stringWithFormat:@"%@,%@,%d,%f,%f",tempPath,tempName,pageno,x,y]; - NSString *BookMarkDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)objectAtIndex:0]; - - NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; - if(![[NSFileManager defaultManager]fileExistsAtPath:bookMarkFile]) - { - [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; - NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; - [fileHandle seekToEndOfFile]; - [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; - [fileHandle closeFile]; - NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2=NSLocalizedString(@"Add BookMark Success!", @"Localizable"); - NSString *str3=NSLocalizedString(@"OK", @"Localizable"); - UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 - message:str2 - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } - else { - NSString *str1=NSLocalizedString(@"Alert", @"Localizable"); - NSString *str2=NSLocalizedString(@"BookMark Already Exist", @"Localizable"); - NSString *str3=NSLocalizedString(@"OK", @"Localizable"); - UIAlertController* alert = [UIAlertController alertControllerWithTitle:str1 - message:str2 - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:str3 style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } -} - --(void)printPdf -{ - NSString *dir = [GLOBAL.g_pdf_path stringByAppendingString:@"/"]; - NSString *path = [dir stringByAppendingString:GLOBAL.g_pdf_name]; - NSString *flattenedDocPath = [path stringByAppendingString:@".flat_print.pdf"]; - - if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Warning" - message:@"PDF file not available" - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - return; - } - - [self saveDocumentToPath:(flattenedDocPath)]; - [self flatAnnotsAtFile:(flattenedDocPath)]; - - - NSData *myData = [NSData dataWithContentsOfFile:flattenedDocPath]; - - UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController]; - - if ( pic && [UIPrintInteractionController canPrintData: myData] ) { - pic.delegate = self; - - UIPrintInfo *printInfo = [UIPrintInfo printInfo]; - printInfo.outputType = UIPrintInfoOutputGeneral; - printInfo.jobName = [flattenedDocPath lastPathComponent]; - printInfo.duplex = UIPrintInfoDuplexLongEdge; - pic.printInfo = printInfo; - pic.showsPageRange = YES; - pic.printingItem = myData; - - void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) { - if (!completed && error) { - NSLog(@"FAILED! due to error in domain %@ with error code %ld", error.domain, (long)error.code); - } - NSError *_error = nil; - [[NSFileManager defaultManager] removeItemAtPath:flattenedDocPath error:&_error]; - }; - - [pic presentAnimated:YES completionHandler:completionHandler]; - } - else - { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Warning" - message:@"Cannot print the file" - preferredStyle:UIAlertControllerStyleAlert]; - UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"Localizable") style:UIAlertActionStyleDefault handler:nil]; - [alert addAction:okAction]; - [self presentViewController:alert animated:YES completion:nil]; - } - isPrint = YES; -} - -- (void)sharePDF -{ - NSString *dir = [GLOBAL.g_pdf_path stringByAppendingString:@"/"]; - NSString *path = [dir stringByAppendingString:GLOBAL.g_pdf_name]; - NSString *flattenedDocPath = [path stringByAppendingString:@".flat_print.pdf"]; - [self saveDocumentToPath:(flattenedDocPath)]; - [self flatAnnotsAtFile:(flattenedDocPath)]; - - NSURL *url = [NSURL fileURLWithPath:flattenedDocPath]; - - if(url) - { - UIActivityViewController *a = [[UIActivityViewController alloc] initWithActivityItems:@[url] applicationActivities:nil]; - NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook, - UIActivityTypePostToWeibo, UIActivityTypeMessage, - UIActivityTypePrint, UIActivityTypeCopyToPasteboard, - UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, - UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, - UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo]; - a.excludedActivityTypes = excludedActivities; - a.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { - NSError *error = nil; - [[NSFileManager defaultManager] removeItemAtPath:flattenedDocPath error:&error]; - }; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - a.modalPresentationStyle = UIModalPresentationPopover; - UIPopoverPresentationController *popover = a.popoverPresentationController; - popover.barButtonItem = toolBar.moreButton; // search bar button item - } else { - b_outline = true; - } - - [self presentViewController:a animated:YES completion:nil]; - - } - else - { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Warning", nil) - message:NSLocalizedString(@"Error", nil) - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:nil]; - - [alert addAction:ok]; - [self presentViewController:alert animated:YES completion:nil]; - } -} - -#pragma mark - Search Bar Method --(void)prevword -{ - NSString *text = m_searchBar.text; - [m_searchBar resignFirstResponder]; - if (m_searchBar.text.length > 40) - return; - - if (SEARCH_LIST == 1) { - int i = [[RDExtendedSearch sharedInstance] getPrevPageFromCurrentPage:pagenow]; - - if (i >= 0) { - [self PDFGoto:i]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [self startSearch:text dir:-1 reset:YES]; - }); - } else { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") - message:NSLocalizedString(@"Reached first occurrence", @"Localizable") - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:nil]; - [alert addAction:ok]; - [self presentViewController:alert animated:YES completion:nil]; - } - } else { - [self startSearch:text dir:-1 reset:NO]; - } -} - --(void)nextword -{ - NSString *text = m_searchBar.text; - [m_searchBar resignFirstResponder]; - if (m_searchBar.text.length > 40){ - return ; - } - - if (SEARCH_LIST == 1) { - int i = [[RDExtendedSearch sharedInstance] getNextPageFromCurrentPage:pagenow]; - - if (i >= 0) { - [self PDFGoto:i]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [self startSearch:text dir:1 reset:YES]; - }); - } else { - UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Alert", @"Localizable") - message:NSLocalizedString(@"Reached last occurrence", @"Localizable") - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction* ok = [UIAlertAction - actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:nil]; - [alert addAction:ok]; - [self presentViewController:alert animated:YES completion:nil]; - } - } else { - NSString *text = m_searchBar.text; - [m_searchBar resignFirstResponder]; - if (m_searchBar.text.length > 40) - return; - - [self startSearch:text dir:1 reset:NO]; - } -} - -- (void)startSearch:(NSString *)text dir:(int)dir reset:(BOOL)reset -{ - if (reset) { - findString = nil; - [m_view vFindEnd]; - b_findStart = NO; - } - - if (!b_findStart) { - findString = text; - [m_view vFindStart:text :GLOBAL.g_case_sensitive :GLOBAL.g_match_whole_word]; - b_findStart = YES; - [m_view vFind:dir]; - } else if (text != nil && text.length > 0) { - bool stringCmp = false; - if (findString != NULL) { - if(GLOBAL.g_case_sensitive) - stringCmp = [text compare:findString] == NSOrderedSame; - else - stringCmp = [text caseInsensitiveCompare:findString] == NSOrderedSame; - } - if (!stringCmp) { - [m_view vFindStart:text :GLOBAL.g_case_sensitive :GLOBAL.g_match_whole_word]; - findString = text; - } - - [m_view vFind:dir]; - } -} - --(void)searchCancel -{ - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad && [self presentedViewController]) { - [self dismissViewControllerAnimated:YES completion:nil]; - } - - if (SEARCH_LIST == 1) { - [[RDExtendedSearch sharedInstance] clearSearch]; - } - - [m_searchBar resignFirstResponder]; - [m_searchBar removeFromSuperview]; - [toolBar changeToNormalToolBar]; - - findString = nil; - [m_view vFindEnd]; - b_findStart = NO; - m_searchBar = NULL; - - [self refreshCurrentPage]; -} -- (void)searchBarSearchButtonClicked:(UISearchBar *)m_SearchBar -{ - NSString *text = m_SearchBar.text; - [m_SearchBar resignFirstResponder]; - if (m_SearchBar.text.length > 40) - return; - - if (SEARCH_LIST == 1) { - [self showSearchList]; - } else { - [self startSearch:text dir:1 reset:NO]; - } -} - -#pragma mark - Search List -- (void)showSearchList -{ - if (SEARCH_LIST == 1) { - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { - toolBar.hidden = YES; - } - - SearchResultTableViewController *viewController = [[SearchResultTableViewController alloc] init]; - viewController.delegate = self; - viewController.searchedString = m_searchBar.text; - viewController.doc = m_doc; - - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { - - viewController.modalPresentationStyle = UIModalPresentationPopover; - [viewController setPreferredContentSize:CGSizeMake(400, 600)]; - UIPopoverPresentationController *popover = viewController.popoverPresentationController; - popover.barButtonItem = (UIBarButtonItem *)[toolBar.bar.items objectAtIndex:0]; // search bar button item - - [self presentViewController:viewController animated:YES completion:nil]; - } - else - { - b_outline = YES; - self.navigationController.navigationBarHidden = NO; - [self.navigationController pushViewController:viewController animated:YES]; - } - } -} - -- (void)didSelectSelectSearchResult:(int)index -{ - if (b_outline) { - b_outline = NO; - [self.navigationController popViewControllerAnimated:YES]; - self.navigationController.navigationBarHidden = YES; - [self goToSearchResult:index]; - } else { - if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) - [self dismissViewControllerAnimated:YES completion:^{ - [self goToSearchResult:index]; - }]; - } -} - -- (void)goToSearchResult:(int)index -{ - [self PDFGoto:index]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [self startSearch:[[RDExtendedSearch sharedInstance] searchTxt] dir:1 reset:YES]; - }); -} - -#pragma mark - Popup Menu Method --(void)selectIsStarting -{ - UIBarButtonItem *item = toolBar.selectTextButton; // Selection button - - if (alreadySelected) - { - [item setTintColor:toolBar.bar.tintColor]; - - [m_view vSelEnd]; - alreadySelected = false; - } - else - { - [item setTintColor:[UIColor lightGrayColor]]; - - [m_view vSelEnd]; - [m_view vSelStart]; - alreadySelected = true; - } -} - --(void)initialPopupView -{ - UIMenuItem *underline = [[UIMenuItem alloc] initWithTitle:@"UDL" action:@selector(UnderLine:)]; - UIMenuItem *highline = [[UIMenuItem alloc] initWithTitle:@"HGL" action:@selector(HighLight:)]; - UIMenuItem *strike = [[UIMenuItem alloc] initWithTitle:@"STR" action:@selector(StrikeOut:)]; - UIMenuItem *textCopy = [[UIMenuItem alloc] initWithTitle:@"COPY" action:@selector(Copy:)]; - NSArray *itemsMC = [[NSArray alloc] initWithObjects:underline, highline, strike, textCopy, nil]; - selectMenu = [UIMenuController sharedMenuController]; - [selectMenu setMenuItems:itemsMC]; -} --(void)Copy :(id)sender -{ - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - NSString* s = [self->m_view vSelGetText]; - UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; - pasteboard.string = s; - [self endSelect]; - }); -} - --(void)HighLight :(id)sender -{ - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (self->readOnly) { - [self showDocReadonlyAlert]; - [self endSelect]; - return; - } - //0HighLight - [self->m_view vSelMarkup :GLOBAL.g_annot_highlight_clr :0]; - [self endSelect]; - }); - -} --(void)UnderLine :(id)sender -{ - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (self->readOnly) { - [self showDocReadonlyAlert]; - [self endSelect]; - return; - } - //1UnderLine - [self->m_view vSelMarkup:GLOBAL.g_annot_underline_clr :1]; - [self endSelect]; - }); -} --(void)StrikeOut :(id)sender -{ - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - if (self->readOnly) { - [self showDocReadonlyAlert]; - [self endSelect]; - return; - } - //2strikethrough - [self->m_view vSelMarkup :GLOBAL.g_annot_strikeout_clr :2]; - [self endSelect]; - }); -} - -- (void)endSelect -{ - if(m_bSel){ - m_bSel = false; - [m_view vSelEnd]; - } - - // Toggle selection mode - alreadySelected = YES; - [self selectIsStarting]; -} - --(void)TextAnnot -{ - b_noteAnnot = NO; - m_bSel = false; - b_outline = true; - [m_view vSelEnd]; - - cachedAnnot = [m_view vGetTextAnnot:posx :posy]; - textAnnotVC = [[TextAnnotViewController alloc]init]; - [textAnnotVC setDelegate:self]; - - textAnnotVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical; - UINavigationController *navController = [[UINavigationController alloc] - initWithRootViewController:textAnnotVC]; - [m_view vNoteStart]; - [self presentViewController:navController animated:YES completion:^{ - - }]; -} - --(void)OnSaveTextAnnot:(NSString *)textAnnot subject:(NSString *)subject -{ - if([textAnnot isEqualToString:@""]) - { - [m_view vNoteEnd]; - } - else{ - [m_view vNoteEnd]; - if(cachedAnnot){ - [cachedAnnot setPopupSubject:subject]; - [cachedAnnot setPopupText:textAnnot]; - }else{ - [m_view vAddTextAnnot:posx :posy:textAnnot :subject]; - } - } -} - -- (void)refreshStatusBarHeight { - if (@available(iOS 11.0, *)) { - UIWindow *window = UIApplication.sharedApplication.keyWindow; - statusBarHeight = window.safeAreaInsets.top; - } else { - statusBarHeight = 20; - } -} - --(void)refreshStatusBar{ - [self setNeedsStatusBarAppearanceUpdate]; -} - --(BOOL)prefersStatusBarHidden -{ - return statusBarHidden; -} - -#pragma mark - lib methods - -- (id)getDoc -{ - return m_doc; -} - -- (int)getCurrentPage -{ - return [m_view vGetCurrentPage]; -} - -- (CGImageRef)imageForPage:(int)pg -{ - CGRect bounds = [self screenRect]; - if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { - if (bounds.size.height > bounds.size.width) { - bounds.size.width = bounds.size.height; - bounds.size.height = [[[[UIApplication sharedApplication] delegate] window] bounds].size.width; - } - } - - PDFPage *page = [m_doc page:pg];; - float w = [m_doc pageWidth:pg]; - float h = [m_doc pageHeight:pg]; - int iw = w; - int ih = h; - PDF_DIB m_dib = NULL; - PDF_DIB bmp = Global_dibGet(m_dib, iw, ih); - float ratiox = 1; - float ratioy = 1; - - if (ratiox>ratioy) { - ratiox = ratioy; - } - - ratiox = ratiox * 1.0; - PDF_MATRIX mat = Matrix_createScale(ratiox, -ratiox, 0, h * ratioy); - Page_renderPrepare(page.handle, bmp); - Page_render(page.handle, bmp, mat, false, 1); - Matrix_destroy(mat); - page = nil; - - void *data = Global_dibGetData(bmp); - CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, iw * ih * 4, NULL); - CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); - CGImageRef imgRef = CGImageCreate(iw, ih, 8, 32, iw<<2, cs, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst, provider, NULL, FALSE, kCGRenderingIntentDefault); - - - CGContextRef context = CGBitmapContextCreate(NULL, (bounds.size.width - ((bounds.size.width - iw) / 2)) * 1, ih * 1, 8, 0, cs, kCGImageAlphaPremultipliedLast); - - - // Draw ... - // - CGContextSetAlpha(context, 1); - CGContextSetRGBFillColor(context, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)0.0, (CGFloat)1.0 ); - CGContextDrawImage(context, CGRectMake(((bounds.size.width- iw) / 2), 1, iw, ih), imgRef); - - - // Get your image - // - CGImageRef cgImage = CGBitmapContextCreateImage(context); - - - CGColorSpaceRelease(cs); - CGDataProviderRelease(provider); - - return cgImage; -} - -- (void)setThumbnailBGColor:(int)color -{ - [m_Thumbview setThumbBackgroundColor:color]; -} - -- (void)setThumbGridBGColor:(int)color -{ - gridBackgroundColor = color; -} - -- (void)setThumbGridElementHeight:(float)height -{ - gridElementHeight = height; -} - -- (void)setThumbGridGap:(float)gap -{ - gridGap = gap; -} - -- (void)setThumbGridViewMode:(int)mode -{ - gridMode = mode; -} - -- (void)setReaderBGColor:(int)color -{ - [m_view setReaderBackgroundColor:color]; -} - -- (void)setToolbarColor:(int)color { - toolbarColor = UIColorFromRGB(color); -} - -- (void)setToolbarTintColor:(int)color { - toolbarTintColor = UIColorFromRGB(color); -} - - -- (void)setThumbHeight:(float)height -{ - GLOBAL.g_thumbview_height = height; - CGRect rect = [self screenRect]; - m_Thumbview.frame = CGRectMake(0, rect.size.height - GLOBAL.g_thumbview_height, rect.size.width, GLOBAL.g_thumbview_height); - [m_Thumbview sizeThatFits:m_Thumbview.frame.size]; -} - -- (void)setFirstPageCover:(BOOL)cover -{ - firstPageCover = cover; -} - -- (void)setDoubleTapZoomMode:(int)mode -{ - doubleTapZoomMode = mode; -} - -- (void)setImmersive:(BOOL)immersive -{ - isImmersive = immersive; - - if (isImmersive) { - [self hideBars]; - } else { - [self showBars]; - } -} - -#pragma mark - Attachments - -- (BOOL)saveImageFromAnnotAtIndex:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size -{ - return [m_view saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:size]; -} - -#pragma mark - Annot render - -- (BOOL)addAttachmentFromPath:(NSString *)path -{ - return [m_view addAttachmentFromPath:path]; -} - -#pragma mark - Flat annot - -- (bool)flatAnnotAtPage:(int)page doc:(PDFDoc *)doc -{ - if (doc == nil) { - doc = [[PDFDoc alloc] init]; - [doc open:[GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name] :@""]; - } - - if(page >= 0 && page < doc.pageCount) - { - PDFPage *ppage = [doc page:page]; - [ppage objsStart]; - if ([ppage flatAnnots]) { - return [doc save]; - } - } - - return NO; -} - -- (bool)flatAnnots -{ - PDFDoc *doc = [[PDFDoc alloc] init]; - if (m_doc == nil) { - [doc open:[GLOBAL.g_pdf_path stringByAppendingPathComponent:GLOBAL.g_pdf_name] :@""]; - } else { - doc = m_doc; - } - for (int page = 0; page != [doc pageCount]; page++) { - [self flatAnnotAtPage:page doc:doc]; - if (page == [m_view vGetCurrentPage]) [m_view refreshCurrentPage]; - } - return nil; -} - -- (bool)flatAnnotsAtFile:(NSString *)path -{ - PDFDoc *doc = [[PDFDoc alloc] init]; - [doc open:path :@""]; - for (int page = 0; page != [doc pageCount]; page++) { - [self flatAnnotAtPage:page doc:doc]; - if (page == [m_view vGetCurrentPage]) [m_view refreshCurrentPage]; - } - [doc save]; - return nil; -} - -#pragma mark - Save document - -- (bool)saveDocumentToPath:(NSString *)path -{ - NSString *prefix = @"file://"; - if([path rangeOfString:prefix].location != NSNotFound) - { - path = [path substringFromIndex:prefix.length]; - } - return [m_doc saveAs:path: NO]; -} - -#pragma mark - Form Manager - -- (NSString *)getJSONFormFields -{ - RDFormManager *fe = [[RDFormManager alloc] initWithDoc:m_doc]; - return [fe jsonInfoForAllPages]; -} - -- (NSString *)getJSONFormFieldsAtPage:(int)page -{ - RDFormManager *fe = [[RDFormManager alloc] initWithDoc:m_doc]; - return [fe jsonInfoForPage:page]; -} - -- (NSString *)setFormFieldWithJSON:(NSString *)json -{ - RDFormManager *fe = [[RDFormManager alloc] initWithDoc:m_doc]; - - NSError *error; - if (json && json.length > 0) { - [fe setInfoWithJson:json error:&error]; - - if (error) { - return error.description; - } else - { - [self refreshCurrentPage]; - } - } else - { - return @"JSON not valid"; - } - - return @""; -} - -#pragma mark - Utils Method - -- (void)clearTempFiles -{ - //delete temp files - for(int i=0; i<[tempfiles count];i++) - { - NSFileManager *fileManager = [NSFileManager defaultManager]; - [fileManager removeItemAtPath:[tempfiles objectAtIndex:i] error:nil]; - [tempfiles removeObjectAtIndex:i]; - } -} - -- (float)barHeightDistance -{ - return toolBar.bar.frame.size.height + statusBarHeight; -} - -- (CGRect)screenRect -{ - CGRect rect = [[UIScreen mainScreen] bounds]; - if ([self isPortrait]){ - if (rect.size.height < rect.size.width) { - - float height = rect.size.height; - rect.size.height = rect.size.width; - rect.size.width = height; - } - } else{ - if (rect.size.height > rect.size.width) { - - float height = rect.size.height; - rect.size.height = rect.size.width; - rect.size.width = height; - } - } - - return rect; -} - -- (UIColor *)getBarColor { - UIColor *barColor = (self.navigationController.navigationBar.barTintColor) ? self.navigationController.navigationBar.barTintColor : [UIColor blackColor]; - - if (toolbarColor) { - barColor = toolbarColor; - } - - return barColor; -} - -- (UIColor *)getTintColor { - UIColor *tintColor = (self.navigationController.navigationBar.tintColor) ? self.navigationController.navigationBar.tintColor : [UIColor orangeColor]; - - if (toolbarTintColor) { - tintColor = toolbarTintColor; - } - - return tintColor; -} - -- (void)toolBarStyle -{ - toolBar.bar.translucent = NO; - - //set tint - toolBar.bar.tintColor = m_searchBar.tintColor = drawToolbar.tintColor = m_slider.tintColor = [self getTintColor]; - toolBar.backgroundColor = toolBar.bar.barTintColor = m_searchBar.barTintColor = drawToolbar.barTintColor = [self getBarColor]; - - if (@available(iOS 13.0, *)) { - - } else { - UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"]; - - if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) { - statusBar.backgroundColor = [self getBarColor]; - } - } -} - -- (void)showBars -{ - m_Thumbview.hidden = !GLOBAL.g_navigation_mode; - m_slider.hidden = GLOBAL.g_navigation_mode; - [pageNumLabel setHidden:false]; - toolBar.hidden = NO; - [self prefersStatusBarHidden]; - [m_searchBar setHidden:NO]; - statusBarHidden = NO; - isImmersive = NO; - [self.view bringSubviewToFront:toolBar]; - [self.view bringSubviewToFront:m_Thumbview]; - [self refreshStatusBar]; - [self refreshToolbarPosition]; - [self refreshPdfViewPosition]; -} - -- (void)hideBars -{ - m_Thumbview.hidden = YES; - m_slider.hidden = YES; - [pageNumLabel setHidden:true]; - toolBar.hidden = YES; - [m_searchBar resignFirstResponder]; - [m_searchBar setHidden:YES]; - statusBarHidden = YES; - isImmersive = YES; - [self refreshStatusBar]; - [self refreshPdfViewPosition]; -} - -- (void)refreshCurrentPage -{ - [m_view refreshCurrentPage]; -} - -- (CGPoint)pdfPointsFromScreenPoints:(int)x :(int)y -{ - RDVPos pos; - [m_view vGetPos:&pos x:x y:y]; - CGPoint pdfPoints; - pdfPoints.x = pos.pdfx; - pdfPoints.y = pos.pdfy; - return pdfPoints; -} - -- (CGPoint)screenPointsFromPdfPoints:(float)x :(float)y :(int)pageNum -{ - return [m_view screenPointsFromPdfPoints:x :y :pageNum]; -} - -- (PDF_RECT)pdfRectFromScreenRect:(CGRect)screenRect -{ - return [m_view pdfRectFromScreenRect:screenRect]; -} - -- (CGRect)screenRectFromPdfRect:(float)top :(float)left :(float)right :(float)bottom :(int)pageNum -{ - return [m_view screenRectFromPdfRect:top :left :right :bottom :pageNum]; -} - - - -@end diff --git a/src/ios/PDFViewer/RDMenu.h b/src/ios/PDFViewer/RDMenu.h new file mode 100755 index 00000000..c3194fec --- /dev/null +++ b/src/ios/PDFViewer/RDMenu.h @@ -0,0 +1,29 @@ +// +// RDMenu.h +// PDFViewer +// +// Created by Emanuele Bortolami on 11/06/2020. +// + +#import +#import "UILShadowView.h" + +NS_ASSUME_NONNULL_BEGIN + +#define rd_menu_width 250 +#define rd_menu_height 40 + +typedef void(^RDBlock)(int); +@interface RDMenu : UILShadowView +{ + RDBlock m_callback; +} + +//definisci property per tipo di menu +@property (nonatomic) BOOL isSearchMenu; +- (instancetype)init:(CGPoint)point :(RDBlock)callback :(NSArray *)items; +- (instancetype)initWithSwitch:(CGPoint)point :(RDBlock)callback :(NSMutableArray *)items; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/RDMenu.m b/src/ios/PDFViewer/RDMenu.m new file mode 100755 index 00000000..c986e367 --- /dev/null +++ b/src/ios/PDFViewer/RDMenu.m @@ -0,0 +1,104 @@ +// +// RDMenu.m +// PDFViewer +// +// Created by Emanuele Bortolami on 11/06/2020. +// + +#import "RDMenu.h" +#import "RDUtils.h" + +@implementation RDMenu + +//createItemWithIcon e createItemWithSwitch ++ (UIView *)createItemWithIcon:(UIImage *)img :(int)tag :(CGFloat)y :(CGFloat)w :(NSString *)val +{ + int margin = 10; + int size = rd_menu_height; + UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y, w, size)]; + UIImageView *vimg = [[UIImageView alloc] initWithFrame:CGRectMake(margin, 0, size, size)]; + vimg.image = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + [view addSubview:vimg]; + UILabel *vlab = [[UILabel alloc] initWithFrame:CGRectMake(size + margin, 0, w - size - margin, size)]; + vlab.text = val; + [vlab setFont:[UIFont systemFontOfSize:14]]; + [view addSubview:vlab]; + view.tag = tag; + return view; +} + ++ (UIView *)createItemWithSwitch:(UISwitch *)swtch :(int)tag :(CGFloat)y :(CGFloat)w :(NSString *)val +{ + int margin = 8; + int h = rd_menu_height; + int sw = swtch.frame.size.width; + int sh = swtch.frame.size.height; + if (y == 0) { + y = 2; + } + UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, y, w, sw)]; + UILabel *vlab = [[UILabel alloc] initWithFrame:CGRectMake(margin, 0, w - sw - (margin * 2), h)]; + vlab.text = val; + [vlab setFont:[UIFont systemFontOfSize:14]]; + [view addSubview:vlab]; + CGRect frame = swtch.frame; + frame.origin = CGPointMake(w - sw - margin, (h - sh) / 2); + [swtch setFrame:frame]; + [view addSubview:swtch]; + view.tag = tag; + return view; +} + +- (instancetype)init:(CGPoint)point :(RDBlock)callback :(NSMutableArray *)items +{ + CGRect frame = CGRectMake(point.x, point.y, 0, 0); + self = [super initWithFrame:frame]; + if(self) + { + m_callback = callback; + int w = rd_menu_width; + int h = rd_menu_height; + UIView *view; + UITapGestureRecognizer *tap; + CGFloat radius = 10.0f; + for (int i = 0; i < items.count; i++) { + if (self.isSearchMenu) { + h = 50; + view = [RDMenu createItemWithSwitch:[[[items objectAtIndex:i] allValues] objectAtIndex:0] :i :(5 + (i * h)) :w :[[[items objectAtIndex:i] allKeys] objectAtIndex:0]]; + radius = 18.0f; + } else { + view = [RDMenu createItemWithIcon:[[[items objectAtIndex:i] allValues] objectAtIndex:0] :i :(i * h) :w :[[[items objectAtIndex:i] allKeys] objectAtIndex:0]]; + } + tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)]; + [view addGestureRecognizer:tap]; + [self addSubview:view]; + } + + [self setBackgroundColor:[RDUtils radaeeWhiteColor]];//[UIColor colorWithRed:0.9f green:0.9f blue:0.9f alpha:1.0f]]; + + frame.size.width = w; + frame.size.height = h * items.count; + frame.origin.y = frame.origin.y - frame.size.height - 10; + self.frame = frame; + + self.layer.cornerRadius = radius; + self.layer.shadowRadius = radius; + + //[self insertSubview:shadow atIndex:0]; + } + return self; +} + +- (instancetype)initWithSwitch:(CGPoint)point :(RDBlock)callback :(NSMutableArray *)items +{ + _isSearchMenu = YES; + self = [self init:point :callback :items]; + return self; +} + +-(void)tapAction:(UITapGestureRecognizer *)tap +{ + if(m_callback) m_callback((int)tap.view.tag); +} + +@end diff --git a/src/ios/PDFViewer/RDMoreTableViewController.h b/src/ios/PDFViewer/RDMoreTableViewController.h deleted file mode 100644 index 912c0611..00000000 --- a/src/ios/PDFViewer/RDMoreTableViewController.h +++ /dev/null @@ -1,25 +0,0 @@ -// -// RDMoreTableViewController.h -// PDFViewer -// -// Created by Federico Vellani on 10/01/18. -// - -#import - -@protocol RDMoreTableViewControllerDelegate --(void) selectAction: (int) type; -@end - -@interface RDMoreTableViewController : UITableViewController -@property (nonatomic, weak) id delegate; -@property (strong, nonatomic) UIImage *viewModeImage; -@property (strong, nonatomic) UIImage *bookmarkImage; -@property (strong, nonatomic) UIImage *addBookmarkImage; -@property (strong, nonatomic) UIImage *outlineImage; -@property (strong, nonatomic) UIImage *metaImage; -@property (strong, nonatomic) UIImage *saveImage; -@property (strong, nonatomic) UIImage *printImage; -@property (strong, nonatomic) UIImage *shareImage; -@property (strong, nonatomic) UIColor *tintColor; -@end diff --git a/src/ios/PDFViewer/RDMoreTableViewController.m b/src/ios/PDFViewer/RDMoreTableViewController.m deleted file mode 100644 index 01e80c3a..00000000 --- a/src/ios/PDFViewer/RDMoreTableViewController.m +++ /dev/null @@ -1,131 +0,0 @@ -// -// RDMoreTableViewController.m -// PDFViewer -// -// Created by Federico Vellani on 10/01/18. -// - -#import "RDMoreTableViewController.h" - -@interface RDMoreTableViewController () -{ - NSArray *actionTitle; - NSArray *actionImage; -} - -@end - -@implementation RDMoreTableViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - UIImage *viewMode = (_viewModeImage) ? _viewModeImage : [UIImage imageNamed:@"btn_view"]; - UIImage *addBookMark = (_addBookmarkImage) ? _addBookmarkImage : [UIImage imageNamed:@"btn_add"]; - UIImage *bookMarkList = (_bookmarkImage) ? _bookmarkImage : [UIImage imageNamed:@"btn_show"]; - UIImage *viewMenu = (_outlineImage) ? _outlineImage : [UIImage imageNamed:@"btn_outline"]; - UIImage *meta = (_metaImage) ? _metaImage : [UIImage imageNamed:@"btn_meta"]; - UIImage *savePDF = (_saveImage) ? _saveImage : [UIImage imageNamed:@"btn_save"]; - UIImage *printPDF = (_printImage) ? _printImage : [UIImage imageNamed:@"btn_print"]; - UIImage *share = (_shareImage) ? _shareImage : [UIImage imageNamed:@"btn_share"]; - - actionTitle = [NSArray arrayWithObjects:NSLocalizedString(@"View Mode", nil),NSLocalizedString(@"Add Bookmark", nil), NSLocalizedString(@"Bookmark List", nil), NSLocalizedString(@"View Menu", nil),NSLocalizedString(@"Meta", nil), NSLocalizedString(@"Save and Exit", nil), NSLocalizedString(@"Print", nil), NSLocalizedString(@"Share", nil), nil]; - actionImage = [NSArray arrayWithObjects:viewMode, addBookMark, bookMarkList, viewMenu, meta, savePDF, printPDF, share, nil]; -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - -#pragma mark - Table view data source - -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { - return 1; -} - -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return actionTitle.count; -} - - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *cellID = @"cell"; - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; - if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:cellID]; - // Configure the cell... - cell.textLabel.text = [NSString stringWithFormat:@"%@", [actionTitle objectAtIndex:indexPath.row]]; - cell.imageView.image = [actionImage objectAtIndex:indexPath.row]; - cell.imageView.image = [cell.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; - cell.imageView.tintColor = self.tintColor; - - return cell; -} - --(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ - - if (indexPath.row < 8) { - [_delegate selectAction:(int)indexPath.row]; - } -} - -/* -// Override to support conditional editing of the table view. -- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { - // Return NO if you do not want the specified item to be editable. - return YES; -} -*/ - -/* -// Override to support editing the table view. -- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { - if (editingStyle == UITableViewCellEditingStyleDelete) { - // Delete the row from the data source - [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; - } else if (editingStyle == UITableViewCellEditingStyleInsert) { - // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view - } -} -*/ - -/* -// Override to support rearranging the table view. -- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { -} -*/ - -/* -// Override to support conditional rearranging of the table view. -- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { - // Return NO if you do not want the item to be re-orderable. - return YES; -} -*/ - -/* -#pragma mark - Table view delegate - -// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath: -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - // Navigation logic may go here, for example: - // Create the next view controller. - <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil]; - - // Pass the selected object to the new view controller. - - // Push the view controller. - [self.navigationController pushViewController:detailViewController animated:YES]; -} -*/ - -/* -#pragma mark - Navigation - -// In a storyboard-based application, you will often want to do a little preparation before navigation -- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { - // Get the new view controller using [segue destinationViewController]. - // Pass the selected object to the new view controller. -} -*/ - -@end diff --git a/src/ios/PDFViewer/RDMoreTableViewController.xib b/src/ios/PDFViewer/RDMoreTableViewController.xib deleted file mode 100644 index a02b054e..00000000 --- a/src/ios/PDFViewer/RDMoreTableViewController.xib +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ios/PDFViewer/RDPageView/RDSinglePageViewController.m b/src/ios/PDFViewer/RDPageView/RDSinglePageViewController.m deleted file mode 100644 index 02b6e546..00000000 --- a/src/ios/PDFViewer/RDPageView/RDSinglePageViewController.m +++ /dev/null @@ -1,119 +0,0 @@ -// -// ViewController.m -// RDPageViewController -// -// Created by Federico Vellani on 06/02/2020. -// Copyright © 2020 Federico Vellani. All rights reserved. -// - -#import "RDSinglePageViewController.h" - -@interface RDSinglePageViewController () - -@end - -@implementation RDSinglePageViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view. -} - -- (void)viewWillAppear:(BOOL)animated -{ - [super viewWillAppear:animated]; - _pdfView = [[PDFLayoutView alloc] initWithFrame:self.view.frame]; - _pdfView.scrollEnabled = NO; - _pdfView.pageViewNo = _pageViewNo; - _pdfView.userInteractionEnabled = NO; - BOOL success = [_pdfView PDFOpen:_doc :4 :self]; - [self.view addSubview:_pdfView]; -} - -- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator -{ - [_pdfView setFrame:CGRectMake(0, 0, size.width, size.height)]; - [_pdfView sizeThatFits:size]; -} - -- (void)OnAnnotClicked:(PDFAnnot *)annot :(float)x :(float)y { - -} - -- (void)OnAnnotCommboBox:(NSArray *)dataArray selected:(int)index { - -} - -- (void)OnAnnotEditBox:(CGRect)annotRect :(NSString *)editText :(float)textSize { - -} - -- (void)OnAnnotEnd { - -} - -- (void)OnAnnotGoto:(int)pageno { - -} - -- (void)OnAnnotList:(PDFAnnot *)annot items:(NSArray *)dataArray selectedIndexes:(NSArray *)indexes { - -} - -- (void)OnAnnotMovie:(NSString *)fileName { - -} - -- (void)OnAnnotOpenURL:(NSString *)url { - -} - -- (void)OnAnnotPopup:(PDFAnnot *)annot { - -} - -- (void)OnAnnotSignature:(PDFAnnot *)annot { - -} - -- (void)OnAnnotSound:(NSString *)fileName { - -} - -- (void)OnDoubleTapped:(float)x :(float)y { - -} - -- (void)OnFound:(bool)found { - -} - -- (void)OnLongPressed:(float)x :(float)y { - -} - -- (void)OnPageChanged:(int)pageno { - -} - -- (void)OnPageUpdated:(int)pageno { - -} - -- (void)OnSelEnd:(float)x1 :(float)y1 :(float)x2 :(float)y2 { - -} - -- (void)OnSelStart:(float)x :(float)y { - -} - -- (void)OnSingleTapped:(float)x :(float)y { - -} - -- (void)didTapAnnot:(PDFAnnot *)annot atPage:(int)page atPoint:(CGPoint)point { - -} - -@end diff --git a/src/ios/PDFViewer/Modules/FormManager/RDFormManager.h b/src/ios/PDFViewer/RDPlugin/RDFormManager.h old mode 100644 new mode 100755 similarity index 100% rename from src/ios/PDFViewer/Modules/FormManager/RDFormManager.h rename to src/ios/PDFViewer/RDPlugin/RDFormManager.h diff --git a/src/ios/PDFViewer/Modules/FormManager/RDFormManager.m b/src/ios/PDFViewer/RDPlugin/RDFormManager.m old mode 100644 new mode 100755 similarity index 89% rename from src/ios/PDFViewer/Modules/FormManager/RDFormManager.m rename to src/ios/PDFViewer/RDPlugin/RDFormManager.m index cc80f0af..49a5f725 --- a/src/ios/PDFViewer/Modules/FormManager/RDFormManager.m +++ b/src/ios/PDFViewer/RDPlugin/RDFormManager.m @@ -10,7 +10,7 @@ #import "PDFObjc.h" @interface RDFormManager() { - PDFDoc *currentDoc; + RDPDFDoc *currentDoc; } @end @@ -18,13 +18,13 @@ @interface RDFormManager() { @implementation RDFormManager #pragma mark - Init -//Init with PDFDoc instance +//Init with RDPDFDoc instance - (instancetype)initWithDoc:(id)doc { self = [super init]; if (self) { - if ([doc isKindOfClass:[PDFDoc class]]) { + if ([doc isKindOfClass:[RDPDFDoc class]]) { currentDoc = doc; } } @@ -38,7 +38,7 @@ - (instancetype)initWithDoc:(id)doc - (void)setInfoWithJson:(NSString *)json error:(NSError **)error { if (![currentDoc canSave]) { - *error = [NSError errorWithDomain:[[[NSBundle mainBundle] bundleIdentifier] stringByAppendingString:@".ErrorDomain"] code:101 userInfo:@{@"readonly-document": @"The PDFDoc instance is readonly"}]; + *error = [NSError errorWithDomain:[[[NSBundle mainBundle] bundleIdentifier] stringByAppendingString:@".ErrorDomain"] code:101 userInfo:@{@"readonly-document": @"The RDPDFDoc instance is readonly"}]; return; } @@ -65,11 +65,11 @@ - (void)parsePage:(NSDictionary *)page error:(NSError **)error NSArray *annots = [page objectForKey:@"Annots"]; if (index >= 0 && index < currentDoc.pageCount) { - PDFPage *pdfPage = [currentDoc page:index]; - [pdfPage objsStart]; + RDPDFPage *page = [currentDoc page:index]; + [page objsStart]; for (NSDictionary *annot in annots) { - [self parseAnnot:annot atPage:pdfPage error:error]; + [self parseAnnot:annot atPage:page error:error]; } } else { *error = [NSError errorWithDomain:[[[NSBundle mainBundle] bundleIdentifier] stringByAppendingString:@".ErrorDomain"] code:104 userInfo:@{@"page-attribute": [NSString stringWithFormat:@"\"Page\" index %i is not correct", index]}]; @@ -82,14 +82,14 @@ - (void)parsePage:(NSDictionary *)page error:(NSError **)error } } -- (void)parseAnnot:(NSDictionary *)annotDict atPage:(PDFPage *)page error:(NSError **)error +- (void)parseAnnot:(NSDictionary *)annotDict atPage:(RDPDFPage *)page error:(NSError **)error { if ([annotDict objectForKey:@"Index"]) { //Get annot index int index = [[annotDict objectForKey:@"Index"] intValue]; //Check if index is valid - PDFAnnot *annot = [page annotAtIndex:index]; + RDPDFAnnot *annot = [page annotAtIndex:index]; if (annot) { switch ([annot type]) { @@ -126,7 +126,7 @@ - (void)saveCurrentDoc } // type: 3 -- (void)setText:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setText:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { if ([self isValidEditText:dict]) { [annot setEditText:[self getEditTextValue:dict]]; @@ -137,7 +137,7 @@ - (void)setText:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError * } // type: 20 -- (void)setWidget:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setWidget:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { switch ([annot fieldType]) { case 1: @@ -156,13 +156,13 @@ - (void)setWidget:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError } // type: 20, fieldType: 2 -- (void)setTextField:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setTextField:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { [self setText:annot withDict:dict error:error]; } // type: 20, fieldType: 1 -- (void)setButtonField:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setButtonField:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { switch ([annot getCheckStatus]) { case 0: @@ -180,7 +180,7 @@ - (void)setButtonField:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NS } // type: 20, fieldType: 2 -- (void)setChoiceField:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setChoiceField:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { //is ComboBox if ([annot getComboItemCount] > 0) { @@ -194,7 +194,7 @@ - (void)setChoiceField:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NS } // type: 20, fieldType: 1, radio -- (void)setRadioButton:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setRadioButton:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { if ([self isValidRadioButton:dict]) { if ([self getRadioValue:dict]) { @@ -207,7 +207,7 @@ - (void)setRadioButton:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NS } // type: 20, fieldType: 1, checkbox -- (void)setCheckBox:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setCheckBox:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { if ([self isValidCheckBox:dict]) { [annot setCheckValue:[self getCheckBoxValue:dict]]; @@ -218,7 +218,7 @@ - (void)setCheckBox:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSErr } // type: 20, fieldType: 2, combobox -- (void)setComboBox:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setComboBox:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { if ([self isValidComboBox:dict annot:annot]) { [annot setComboSel:[self getComboBoxValue:dict]]; @@ -229,7 +229,7 @@ - (void)setComboBox:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSErr } // type: 20, fieldType: 2, list //TODO -- (void)setListSel:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error +- (void)setListSel:(RDPDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSError **)error { if ([self isValidListSel:dict annot:annot]) { //[annot setComboSel:<#(const int *)#> :<#(int)#> @@ -241,7 +241,7 @@ - (void)setListSel:(PDFAnnot *)annot withDict:(NSDictionary *)dict error:(NSErro // readonly -- (void)setAnnot:(PDFAnnot *)annot readOnly:(NSDictionary *)dict { +- (void)setAnnot:(RDPDFAnnot *)annot readOnly:(NSDictionary *)dict { if ([self isValidReadOnly:dict]) { [annot setReadonly:[self getReadOnlyValue:dict]]; } @@ -249,7 +249,7 @@ - (void)setAnnot:(PDFAnnot *)annot readOnly:(NSDictionary *)dict { // locked -- (void)setAnnot:(PDFAnnot *)annot locked:(NSDictionary *)dict { +- (void)setAnnot:(RDPDFAnnot *)annot locked:(NSDictionary *)dict { if ([self isValidLock:dict]) { [annot setLocked:[self getLockValue:dict]]; } @@ -260,7 +260,7 @@ - (void)setAnnot:(PDFAnnot *)annot locked:(NSDictionary *)dict { //Get JSON string for a single page - (NSString *)jsonInfoForPage:(int)page { - //Check if PDFDoc instance exist + //Check if RDPDFDoc instance exist if (!currentDoc) { return @"Document not set"; } @@ -269,7 +269,7 @@ - (NSString *)jsonInfoForPage:(int)page //Check if the page index exist if (page >= 0 && page <= pageCount) { - PDFPage *docPage = [currentDoc page:page]; + RDPDFPage *docPage = [currentDoc page:page]; NSDictionary *dict = [self infoForPage:docPage number:page]; NSString *jsonString = [self jsonStringFromDict:dict]; @@ -283,7 +283,7 @@ - (NSString *)jsonInfoForPage:(int)page //Get JSON string for all pages - (NSString *)jsonInfoForAllPages { - //Check if PDFDoc instance exist + //Check if RDPDFDoc instance exist if (!currentDoc) { return @"Document not set"; } @@ -300,7 +300,7 @@ - (NSDictionary *)infoForAllPages int pageCount = [currentDoc pageCount]; for (int i = 0; i < pageCount; i++) { - PDFPage *page = [currentDoc page:i]; + RDPDFPage *page = [currentDoc page:i]; [page objsStart]; [arr addObject:[self infoForPage:page number:i]]; } @@ -309,7 +309,7 @@ - (NSDictionary *)infoForAllPages } //Get annotations info for a single page -- (NSDictionary *)infoForPage:(PDFPage *)page number:(int)pageNumber +- (NSDictionary *)infoForPage:(RDPDFPage *)page number:(int)pageNumber { NSMutableArray *arr = [NSMutableArray array]; @@ -327,7 +327,7 @@ - (NSDictionary *)infoForPage:(PDFPage *)page number:(int)pageNumber } //Create the single annotation info dictionary -- (NSDictionary *)infoForAnnot:(PDFAnnot *)annot +- (NSDictionary *)infoForAnnot:(RDPDFAnnot *)annot { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; @@ -404,7 +404,7 @@ - (BOOL)isValidCheckBox:(NSDictionary *)dict return NO; } -- (BOOL)isValidComboBox:(NSDictionary *)dict annot:(PDFAnnot *)annot +- (BOOL)isValidComboBox:(NSDictionary *)dict annot:(RDPDFAnnot *)annot { if ([dict objectForKey:@"ComboItemSel"]) { int selItem = [[dict objectForKey:@"ComboItemSel"] intValue]; @@ -414,7 +414,7 @@ - (BOOL)isValidComboBox:(NSDictionary *)dict annot:(PDFAnnot *)annot return NO; } -- (BOOL)isValidListSel:(NSDictionary *)dict annot:(PDFAnnot *)annot +- (BOOL)isValidListSel:(NSDictionary *)dict annot:(RDPDFAnnot *)annot { if ([dict objectForKey:@"ComboItemSel"]) { int selItem = [[dict objectForKey:@"ComboItemSel"] intValue]; @@ -527,7 +527,7 @@ - (NSString *)jsonStringFromDict:(NSDictionary *)dict } //Check if the annot is an editText or a Widget -- (BOOL)canStoreAnnot:(PDFAnnot *)annot +- (BOOL)canStoreAnnot:(RDPDFAnnot *)annot { int annotType = [annot type]; return (annotType == 0 || annotType == 3 || annotType == 20); diff --git a/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.h b/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.h new file mode 100755 index 00000000..90d9ef26 --- /dev/null +++ b/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.h @@ -0,0 +1,170 @@ +#import +#import + +#import "../PDFLayout/RDVGlobal.h" +#import "../PDFReader/RDMetaDataViewController.h" +#import "../PDFReader/DlgAnnotPropMarkup.h" +#import "../PDFReader/DlgAnnotPropIcon.h" +#import "../PDFReader/DlgAnnotPropComm.h" +#import "../PDFReader/DlgAnnotPropLine.h" +#import "../PDFReader/UIColorBtn.h" +#import "../RDToolbar.h" +#import "../PDFReader/PDFReaderCtrl.h" +#import "../PDFPages/PDFPagesCtrl.h" +#import "../PDFPages/PDFPagesView.h" +#import "../PDFPages/UIPageCellView.h" + +@class RDPDFDoc; +@class PDFReaderCtrl; +@class RDPageViewController; + +// define the protocol for the delegate +@protocol RadaeePDFPluginDelegate +// define protocol functions that can be used in any class using this delegate +- (void)willShowReader; +- (void)didShowReader; +- (void)willCloseReader; +- (void)didCloseReader; +- (void)didChangePage:(int)page; +- (void)didSearchTerm:(NSString *)term found:(BOOL)found; +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point; +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point; +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point; +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point; +- (void)onAnnotExported:(NSString *)path; +@end; + +@interface RadaeePDFPlugin : NSObject{ + PDFReaderCtrl *m_pdf; + RDPageViewController *m_pdfP; + + NSURLConnection *pdfConn; + NSString *url; + NSMutableData *receivedData; + void *buffer; + + //colors + int inkColor; + int rectColor; + int underlineColor; + int strikeoutColor; + int highlightColor; + int ovalColor; + int selColor; + int arrowColor; + + int thumbBackgroundColor; + int gridBackgroundColor; + int readerBackgroundColor; + int titleBackgroundColor; + int iconsBackgroundColor; + + float thumbHeight; + int gridElementHeight; + int gridGap; + int gridMode; + + int doubleTapZoomMode; + + BOOL firstPageCover; + BOOL isImmersive; + + int bottomBar; +} + +@property (strong, nonatomic) NSString *lastOpenedPath; +@property (strong, nonatomic) UIImage *viewModeImage; +@property (strong, nonatomic) UIImage *searchImage; +@property (strong, nonatomic) UIImage *bookmarkImage; +@property (strong, nonatomic) UIImage *outlineImage; +@property (strong, nonatomic) UIImage *lineImage; +@property (strong, nonatomic) UIImage *rectImage; +@property (strong, nonatomic) UIImage *ellipseImage; +@property (strong, nonatomic) UIImage *printImage; +@property (strong, nonatomic) UIImage *gridImage; +@property (strong, nonatomic) UIImage *deleteImage; +@property (strong, nonatomic) UIImage *doneImage; +@property (strong, nonatomic) UIImage *removeImage; +@property (strong, nonatomic) UIImage *exportImage; +@property (strong, nonatomic) UIImage *prevImage; +@property (strong, nonatomic) UIImage *nextImage; + ++ (RadaeePDFPlugin *)pluginInit; +- (id)show:(NSString *)file withPassword:(NSString *)password; +- (id)show:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave; +- (id)show:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author; +- (void)activateLicenseWithBundleId:(NSString *)bundleId company:(NSString *)company email:(NSString *)email key:(NSString *)key licenseType:(int)type; +- (id)openFromAssets:(NSString *)file withPassword:(NSString *)password; +- (id)openFromAssets:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave; +- (id)openFromAssets:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author; +- (id)openFromPath:(NSString *)path withPassword:(NSString *)password; +- (id)openFromPath:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author; +- (id)openFromMem:(NSData *)data withPassword:(NSString *)password; +- (NSString *)fileState; +- (int)getPageNumber; +- (int)getPageCount; +- (void)setThumbnailBGColor:(int)color; +- (void)setThumbGridBGColor:(int)color; +- (void)setReaderBGColor:(int)color; +- (void)setThumbGridElementHeight:(float)height; +- (void)setThumbGridGap:(float)gap; +- (void)setThumbGridViewMode:(int)mode; +- (void)setTitleBGColor:(int)color; +- (void)setIconsBGColor:(int)color; +- (void)setThumbHeight:(float)height; +- (void)setFirstPageCover:(BOOL)cover; +- (void)setDoubleTapZoomMode:(int)mode; +- (void)setImmersive:(BOOL)immersive; +- (BOOL)setReaderViewMode:(int)mode; +- (NSString *)extractTextFromPage:(int)pageNum; +- (BOOL)encryptDocAs:(NSString *)path userPwd:(NSString *)userPwd ownerPwd:(NSString *)ownerPwd permission:(int)permission method:(int)method idString:(NSString *)idString; +- (BOOL)addAnnotAttachment:(NSString *)path; +- (BOOL)renderAnnotToFile:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize )size; +- (BOOL)flatAnnots; +- (BOOL)flatAnnotAtPage:(int)pageno; +- (BOOL)saveDocumentToPath:(NSString *)path; + +// Form Manager + +- (NSString *)getJSONFormFields; +- (NSString *)getJSONFormFieldsAtPage:(int)page; +- (NSString *)setFormFieldWithJSON:(NSString *)json; + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfName withPath:(BOOL)withPath; + +// Bookmarks ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label; ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath; ++ (NSString *)getBookmarks:(NSString *)pdfPath; + +//Settings + +- (void)setPagingEnabled:(BOOL)enabled; +- (void)setDoublePageEnabled:(BOOL)enabled; +- (void)toggleThumbSeekBar:(int)mode; +- (void)setColor:(int)color forFeature:(int)feature; + +// Delegate +- (void)setDelegate:(id)myDelegate; + +- (void)refreshCurrentPage; +- (id)getGlobal; + +//get text & markup annot details +- (NSString *)getTextAnnotationDetails:(int)pageNum; +- (NSString *)getMarkupAnnotationDetails:(int)pageNum; + +//add text annot +- (void)addTextAnnotation:(int)pageNum :(float)x :(float)y :(NSString *)text :(NSString *)subject; + +//get char indexes and add markup annot +- (int)getCharIndex:(int)pageNum :(float)x :(float)y; +- (void)addMarkupAnnotation:(int)pageNum :(int)type :(int)index1 :(int)index2; + +//get screen points from pdf points +- (NSString *)getPDFCoordinates:(int)x :(int)y; +- (NSString *)getScreenCoordinates:(int)x :(int)y :(int)pageNum; +- (NSString *)getPDFRect:(float)x :(float)y :(float)width :(float)height; +- (NSString *)getScreenRect:(float)left :(float)top :(float)right :(float)bottom :(int)pageNum; + +@end diff --git a/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.m b/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.m new file mode 100755 index 00000000..fccc2f10 --- /dev/null +++ b/src/ios/PDFViewer/RDPlugin/RadaeePDFPlugin.m @@ -0,0 +1,1069 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// + +#import "RadaeePDFPlugin.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDVGlobal.h" +#import "PDFIOS.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() { + id delegate; +} + +@end + +@implementation RadaeePDFPlugin + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + [r pluginInitialize]; + + return r; +} + +- (void)pluginInitialize +{ + inkColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"InkColor"]; + rectColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"RectColor"]; + underlineColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"UnderlineColor"]; + strikeoutColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"StrikeoutColor"]; + highlightColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"HighlightColor"]; + ovalColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"OvalColor"]; + selColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"SelColor"]; + arrowColor = (int)[[NSUserDefaults standardUserDefaults] integerForKey:@"ArrowColor"]; +} + +#pragma mark - Plugin API + +- (id)show:(NSString *)file withPassword:(NSString *)password +{ + return [self show:file atPage:0 withPassword:password readOnly:NO autoSave:NO]; +} + +- (id)show:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave { + return [self show:file atPage:0 withPassword:password readOnly:NO autoSave:NO author:@""]; +} + +- (id)show:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author +{ + if (!file) + return nil; + + // Get user parameters + url = file; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + int result = [doc openStream:httpStream :password]; + if(!result) [m_pdf setDoc:doc :page :readOnly]; + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + return nil; + } + + return [self showReader]; + + } else { + if ([url containsString:@"file://"]) { + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + return [self openPdf:filePath atPage:page withPassword:password readOnly:readOnly autoSave:autoSave author:author data:nil]; + } else { + return [self openFromPath:url atPage:page withPassword:password readOnly:readOnly autoSave:autoSave author:author]; + } + } + +} + +- (id)openFromAssets:(NSString *)file withPassword:(NSString *)password +{ + return [self openFromAssets:file atPage:0 withPassword:password readOnly:NO autoSave:NO]; +} + +- (id)openFromAssets:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave { + return [self openFromAssets:file atPage:0 withPassword:password readOnly:NO autoSave:NO author:@""]; +} + +- (id)openFromAssets:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author { + if (!file) + return nil; + + // Get user parameters + url = file; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + return [self openPdf:filePath atPage:page withPassword:password readOnly:readOnly autoSave:autoSave author:author data:nil]; +} + +- (id)openFromMem:(NSData *)data withPassword:(NSString *)password +{ + return [self openPdf:nil atPage:0 withPassword:password readOnly:NO autoSave:NO author:@"" data:data]; +} + +- (id)openFromPath:(NSString *)path withPassword:(NSString *)password +{ + // Get user parameters + url = path; + + NSString *filePath = url; + + return [self openPdf:filePath atPage:0 withPassword:password readOnly:NO autoSave:NO author:@"" data:nil]; +} + +- (id)openFromPath:(NSString *)file atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author { + return [self openPdf:file atPage:page withPassword:password readOnly:readOnly autoSave:autoSave author:author data:nil]; +} + +- (id)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave author:(NSString *)author data:(NSData *)data +{ + GLOBAL.g_annot_def_author = (author) ? author : @""; + + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + return nil; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + //Open PDF from Mem demo + if (data != nil) { + const char *path1 = [filePath UTF8String]; + FILE *file1 = fopen(path1, "rb"); + fseek(file1, 0, SEEK_END); + long filesize1 = ftell(file1); + fseek(file1, 0, SEEK_SET); + buffer = malloc((filesize1)*sizeof(char)); + fread(buffer, filesize1, 1, file1); + fclose(file1); + + //Open PDF file + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + int result = [doc openMem:buffer :(int)filesize1 :nil]; + if(!result) [m_pdf setDoc:doc :page :readOnly]; + } else if ([self isPageViewController]) { + //Set PDF file + int result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + + if(result == 1) + { + m_pdfP.hidesBottomBarWhenPushed = YES; + } + } else { + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + int result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_annot_def_author = author; + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + return nil; + } + + if ([self isPageViewController]) return [self showCurlingReader]; + return [self showReader]; +} + + +- (void)activateLicenseWithBundleId:(NSString *)bundleId company:(NSString *)company email:(NSString *)email key:(NSString *)key licenseType:(int)type +{ + [self pluginInitialize]; + + g_id = bundleId; + g_company = company; + g_mail = email; + g_serial = key; + + [RDVGlobal Init]; +} + +- (NSString *)fileState +{ + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + return message; + } + else + return @"File not found"; +} + +- (int)getPageNumber +{ + if (m_pdf == nil || [m_pdf getDoc] == nil) + return -1; + return [m_pdf PDFCurPage]; +} + +- (int)getPageCount +{ + if (m_pdf == nil || [m_pdf getDoc] == nil) { + return -1; + } + + return [(RDPDFDoc *)[m_pdf getDoc] pageCount]; +} + +- (void)setThumbnailBGColor:(int)color +{ + thumbBackgroundColor = color; +} + +- (void)setThumbGridBGColor:(int)color +{ + gridBackgroundColor = color; +} + +- (void)setReaderBGColor:(int)color +{ + readerBackgroundColor = color; +} + +- (void)setThumbGridElementHeight:(float)height +{ + gridElementHeight = height; +} + +- (void)setThumbGridGap:(float)gap +{ + gridGap = gap; +} + +- (void)setThumbGridViewMode:(int)mode +{ + gridMode = mode; +} + +- (void)setTitleBGColor:(int)color +{ + titleBackgroundColor = color; +} + +- (void)setIconsBGColor:(int)color +{ + iconsBackgroundColor = color; +} + +- (void)setThumbHeight:(float)height +{ + thumbHeight = height; +} + +- (void)setFirstPageCover:(BOOL)cover +{ + firstPageCover = cover; +} + +- (void)setDoubleTapZoomMode:(int)mode +{ + doubleTapZoomMode = mode; +} + +- (void)setImmersive:(BOOL)immersive +{ + isImmersive = immersive; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } + + if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:NO]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + } + [self loadSettingsWithDefaults]; +} + +- (id)getGlobal { + return GLOBAL; +} + +- (PDFReaderCtrl *)showReader +{ + [m_pdf setReaderBGColor:readerBackgroundColor]; + //Set thumbGridView + //thumbGridView was not used anymore. + //[m_pdf setThumbGridBGColor:gridBackgroundColor]; + //[m_pdf setThumbGridElementHeight:gridElementHeight]; + //[m_pdf setThumbGridGap:gridGap]; + //[m_pdf setThumbGridViewMode:gridMode]; + + m_pdf.hidesBottomBarWhenPushed = YES; + + return m_pdf; +} + +- (RDPageViewController *)showCurlingReader +{ + m_pdfP.hidesBottomBarWhenPushed = YES; + return m_pdfP; +} + + +- (NSString *)extractTextFromPage:(int)pageNum +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return @""; + } + + RDPDFPage *page = [doc page:pageNum]; + [page objsStart]; + + return [page objsString:0 :page.objsCount]; + + page = nil; +} + +- (BOOL)encryptDocAs:(NSString *)path userPwd:(NSString *)userPwd ownerPwd:(NSString *)ownerPwd permission:(int)permission method:(int)method idString:(NSString *)idString +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return NO; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + return [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; +} + +- (BOOL)addAnnotAttachment:(NSString *)path +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return NO; + } + + return [m_pdf addAttachmentFromPath:path]; +} + +- (BOOL)renderAnnotToFile:(int)index atPage:(int)pageno savePath:(NSString *)path size:(CGSize)size +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return NO; + } + + return [m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:size]; +} + +- (BOOL)flatAnnots +{ + return [m_pdf flatAnnots]; +} + +- (BOOL)flatAnnotAtPage:(int)pageno +{ + return [PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]; +} + +- (BOOL)saveDocumentToPath:(NSString *)path +{ + return [m_pdf saveDocumentToPath:path]; +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (BOOL)setReaderViewMode:(int)mode +{ + GLOBAL.g_view_mode = mode; + return YES; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_view_mode != 2) { + return NO; + } + else return YES; +} + +- (void)setColor:(int)color forFeature:(int)feature +{ + switch (feature) { + case 0: + inkColor = color; + break; + + case 1: + rectColor = color; + break; + + case 2: + underlineColor = color; + break; + + case 3: + strikeoutColor = color; + break; + + case 4: + highlightColor = color; + break; + + case 5: + ovalColor = color; + break; + + case 6: + selColor = color; + break; + + case 7: + arrowColor = color; + break; + + default: + break; + } +} + +#pragma mark - Init defaults + +- (void)loadSettingsWithDefaults +{ + [[NSUserDefaults standardUserDefaults] setBool:GLOBAL.g_case_sensitive forKey:@"CaseSensitive"]; + [[NSUserDefaults standardUserDefaults] setFloat:GLOBAL.g_ink_width forKey:@"InkWidth"]; + [[NSUserDefaults standardUserDefaults] setFloat:GLOBAL.g_rect_annot_width forKey:@"RectWidth"]; + [[NSUserDefaults standardUserDefaults] setFloat:0.15f forKey:@"SwipeSpeed"]; + [[NSUserDefaults standardUserDefaults] setFloat:1.0f forKey:@"SwipeDistance"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_render_quality forKey:@"RenderQuality"]; + [[NSUserDefaults standardUserDefaults] setBool:GLOBAL.g_match_whole_word forKey:@"MatchWholeWord"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_ink_color forKey:@"InkColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_rect_annot_color forKey:@"RectColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_annot_underline_clr forKey:@"UnderlineColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_annot_strikeout_clr forKey:@"StrikeoutColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_annot_highlight_clr forKey:@"HighlightColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_oval_annot_color forKey:@"OvalColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_view_mode forKey:@"DefView"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_sel_color forKey:@"SelColor"]; + [[NSUserDefaults standardUserDefaults] setInteger:GLOBAL.g_line_annot_color forKey:@"ArrowColor"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; +} + +#pragma mark - Bookmarks + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} + +#pragma mark - Form Extractor + +- (NSString *)getJSONFormFields +{ + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + return [fe jsonInfoForAllPages]; +} + +- (NSString *)getJSONFormFieldsAtPage:(int)page +{ + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + return [fe jsonInfoForPage:page]; +} + +- (NSString *)setFormFieldWithJSON:(NSString *)json +{ + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if (json && json.length > 0) { + [fe setInfoWithJson:json error:&error]; + + if (error) { + return error.description; + } else + { + [self refreshCurrentPage]; + } + } else + { + return @"JSON not valid"; + } + + return @""; +} + +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + if (delegate) { + [delegate willShowReader]; + } +} + +- (void)didShowReader +{ + if (delegate) { + [delegate didShowReader]; + } +} + +- (void)willCloseReader +{ + if (delegate) { + [delegate willCloseReader]; + } +} + +- (void)didCloseReader +{ + if (delegate) { + [delegate didCloseReader]; + } +} + +- (void)didChangePage:(int)page +{ + if (delegate) { + [delegate didChangePage:page]; + } +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + if (delegate) { + [delegate didTapOnPage:page atPoint:point]; + } +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + if (delegate) { + [delegate didDoubleTapOnPage:page atPoint:point]; + } +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + if (delegate) { + [delegate didLongPressOnPage:page atPoint:point]; + } +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + if (delegate) { + [delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + if (delegate) { + [delegate didSearchTerm:term found:found]; + } +} + +- (void)onAnnotExported:(NSString *)path +{ + if (delegate) { + [delegate onAnnotExported:path]; + } +} + +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + +#pragma mark - Delegate Setting + +- (void)setDelegate:(id)myDelegate +{ + delegate = myDelegate; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +#pragma mark - get/add text and markup annot + +- (NSString *)getTextAnnotationDetails:(int)pageNum +{ + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + return nil; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return nil; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + return json; +} + +- (NSString *)getMarkupAnnotationDetails:(int)pageNum +{ + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + return nil; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return nil; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + return json; +} + +- (void)addTextAnnotation:(int)pageNum :(float)x :(float)y :(NSString *)text :(NSString *)subject +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + [doc save]; + + [m_pdf updatePage:pageNum]; + + page = nil; + doc = nil; +} + +- (int)getCharIndex:(int)pageNum :(float)x :(float)y +{ + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + return 0; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return 0; + } + + [page objsStart]; + + return [page objsGetCharIndex:x :y]; +} + +- (void)addMarkupAnnotation:(int)pageNum :(int)type :(int)index1 :(int)index2 +{ + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + [page addAnnotMarkup:index1 :index2 :type :color]; + + [doc save]; + + [m_pdf updatePage:pageNum]; + + page = nil; + doc = nil; +} + +- (NSString *)getPDFCoordinates:(int)x :(int)y +{ + if (m_pdf == nil) { + return nil; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + return json; +} + +- (NSString *)getScreenCoordinates:(int)x :(int)y :(int)pageNum +{ + if (m_pdf == nil) { + return nil; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + return json; +} + +- (NSString *)getPDFRect:(float)x :(float)y :(float)width :(float)height +{ + if (m_pdf == nil) { + return nil; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + return json; +} + +- (NSString *)getScreenRect:(float)left :(float)top :(float)right :(float)bottom :(int)pageNum +{ + if (m_pdf == nil) { + return nil; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + return json; +} + +@end diff --git a/src/ios/PDFViewer/Modules/Signature/SignatureViewController.h b/src/ios/PDFViewer/RDSignature/SignatureViewController.h old mode 100644 new mode 100755 similarity index 61% rename from src/ios/PDFViewer/Modules/Signature/SignatureViewController.h rename to src/ios/PDFViewer/RDSignature/SignatureViewController.h index c1abbd2a..c9593391 --- a/src/ios/PDFViewer/Modules/Signature/SignatureViewController.h +++ b/src/ios/PDFViewer/RDSignature/SignatureViewController.h @@ -6,15 +6,19 @@ // #import +#import "RDVPage.h" @protocol SignatureDelegate -- (void)didSign; +- (void)didSign:(RDVPage *)vp :(RDPDFAnnot *)annot; +- (void)onDismissSignView; @end @interface SignatureViewController : UIViewController @property (weak, nonatomic) id delegate; +@property (nonatomic) RDVPage *annotPage; +@property (nonatomic) RDPDFAnnot *annot; @end diff --git a/src/ios/PDFViewer/Modules/Signature/SignatureViewController.m b/src/ios/PDFViewer/RDSignature/SignatureViewController.m old mode 100644 new mode 100755 similarity index 81% rename from src/ios/PDFViewer/Modules/Signature/SignatureViewController.m rename to src/ios/PDFViewer/RDSignature/SignatureViewController.m index a973d543..6b8c9869 --- a/src/ios/PDFViewer/Modules/Signature/SignatureViewController.m +++ b/src/ios/PDFViewer/RDSignature/SignatureViewController.m @@ -25,10 +25,12 @@ - (void)viewDidLoad { UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(getImage)]; UIBarButtonItem *reset = [[UIBarButtonItem alloc] initWithTitle:@"Reset" style:UIBarButtonItemStyleDone target:self action:@selector(resetImage)]; + UIBarButtonItem *close = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStyleDone target:self action:@selector(dismissView)]; UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; + UIBarButtonItem *fix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; toolbar = [[UIToolbar alloc] init]; - [toolbar setItems:@[done, flex, reset]]; + [toolbar setItems:@[done, fix, reset, flex, close]]; toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth; sigView = [[UviSignatureView alloc] init]; @@ -51,7 +53,7 @@ - (void)getImage { // Save image to temp path [sigView signatureImage:CGPointZero text:@"" fitSignature:GLOBAL.g_fit_signature_to_field]; - [_delegate didSign]; + [_delegate didSign:_annotPage :_annot]; } - (void)resetImage @@ -59,6 +61,13 @@ - (void)resetImage [sigView erase]; } +- (void)dismissView +{ + [self dismissViewControllerAnimated:YES completion:^{ + [self->_delegate onDismissSignView]; + }]; +} + - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. diff --git a/src/ios/PDFViewer/Modules/Signature/UviSignatureView.h b/src/ios/PDFViewer/RDSignature/UviSignatureView.h similarity index 100% rename from src/ios/PDFViewer/Modules/Signature/UviSignatureView.h rename to src/ios/PDFViewer/RDSignature/UviSignatureView.h diff --git a/src/ios/PDFViewer/Modules/Signature/UviSignatureView.m b/src/ios/PDFViewer/RDSignature/UviSignatureView.m similarity index 99% rename from src/ios/PDFViewer/Modules/Signature/UviSignatureView.m rename to src/ios/PDFViewer/RDSignature/UviSignatureView.m index ff2a08ef..91f2b481 100755 --- a/src/ios/PDFViewer/Modules/Signature/UviSignatureView.m +++ b/src/ios/PDFViewer/RDSignature/UviSignatureView.m @@ -136,7 +136,7 @@ - (CGPoint)placeholderPoint { CGFloat bottom = 0.90; - CGFloat x1 = 0; + CGFloat x1 = 8; CGFloat y1 = height*bottom; UIFont *font = [UIFont fontWithName:@"Helvetica" size:12]; diff --git a/src/ios/PDFViewer/RDToolBar.h b/src/ios/PDFViewer/RDToolBar.h old mode 100644 new mode 100755 index 46729078..d7129d80 --- a/src/ios/PDFViewer/RDToolBar.h +++ b/src/ios/PDFViewer/RDToolBar.h @@ -1,74 +1,18 @@ // -// RDAnnotToolBar.h +// RDToolbar.h // PDFViewer // -// Created by strong on 2018/3/26. +// Created by Emanuele Bortolami on 23/06/2020. // #import -#define ICON_WIDTH 30 +NS_ASSUME_NONNULL_BEGIN -@protocol RDToolBarDelegate +@interface RDToolbar : UIView -// normalbar delegate -- (void)closeView; -- (void)searchView; -- (void)showDrawModeTableView; -- (void)selectIsStarting; -- (void)stopSelect; -- (void)undoAnnot; -- (void)redoAnnot; -- (void)toggleGrid; -- (void)showMoreButtons; -//performbar delegate -- (void)nextword; -- (void)prevword; -- (void)searchCancel; -//searchbar delegate -- (void)performAnnot; -- (void)deleteAnnot; -- (void)annotCancel; -- (void)annotProperties; +@property (weak, nonatomic) IBOutlet UIToolbar *toolbar; @end -@interface RDToolBar : UIView - -@property (nonatomic, strong) UIToolbar *bar; -@property (nonatomic, strong) UIBarButtonItem *selectTextButton; -@property (nonatomic, strong) UIBarButtonItem *moreButton; -@property (nonatomic, strong) UIBarButtonItem *searchButton; -@property (nonatomic,weak) id m_delegate; - -@property (strong, nonatomic) UIImage *closeImage; -@property (strong, nonatomic) UIImage *searchImage; -@property (strong, nonatomic) UIImage *gridImage; -@property (strong, nonatomic) UIImage *deleteImage; -@property (strong, nonatomic) UIImage *doneImage; -@property (strong, nonatomic) UIImage *removeImage; -@property (strong, nonatomic) UIImage *undoImage; -@property (strong, nonatomic) UIImage *redoImage; -@property (strong, nonatomic) UIImage *performImage; -@property (strong, nonatomic) UIImage *moreImage; -@property (strong, nonatomic) UIImage *drawImage; -@property (strong, nonatomic) UIImage *selectImage; -@property (strong, nonatomic) UIImage *prevImage; -@property (strong, nonatomic) UIImage *nextImage; - -@property (nonatomic) BOOL hideSearchImage; -@property (nonatomic) BOOL hideDrawImage; -@property (nonatomic) BOOL hideSelImage; -@property (nonatomic) BOOL hideUndoImage; -@property (nonatomic) BOOL hideRedoImage; -@property (nonatomic) BOOL hideMoreImage; -@property (nonatomic) BOOL hideGridImage; - -@property (nonatomic) int barHeight; - -- (void)setupToolBarArray; -- (void)changeToPerformToolBar; -- (void)changeToSearchToolBar; -- (void)changeToNormalToolBar; - -@end +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/RDToolBar.m b/src/ios/PDFViewer/RDToolBar.m old mode 100644 new mode 100755 index 7b6b3075..cc753490 --- a/src/ios/PDFViewer/RDToolBar.m +++ b/src/ios/PDFViewer/RDToolBar.m @@ -1,229 +1,27 @@ // -// RDAnnotToolBar.m +// RDToolbar.m // PDFViewer // -// Created by strong on 2018/3/26. +// Created by Emanuele Bortolami on 23/06/2020. // -#import "RDToolBar.h" +#import "RDToolbar.h" -@interface RDToolBar() -{ - NSMutableArray *normalToolBarArray; - NSArray *performToolBarArray; - NSArray *searchToolBarArray; -} -@end - -@implementation RDToolBar - -- (instancetype)init -{ - self = [super init]; - if (self) { - self.bar = [[UIToolbar alloc] init]; - self.bar.barStyle = UIBarStyleBlackOpaque; - [self.bar sizeToFit]; - } - return self; -} - -- (void)setupToolBarArray -{ - self.bar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin; - _barHeight = self.bar.frame.size.height; - - self.bar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin; - - UIImage *closeImg = (_closeImage) ? _closeImage : [UIImage imageNamed:@"btn_back"]; - UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:closeImg style:UIBarButtonItemStylePlain target:self action:@selector(closeClick)]; - closeButton.width = ICON_WIDTH; - - UIImage *searchImg = (_searchImage) ? _searchImage : [UIImage imageNamed:@"btn_search"]; - _searchButton = [[UIBarButtonItem alloc]initWithImage:searchImg style:UIBarButtonItemStylePlain target:self action:@selector(searchClick)]; - _searchButton.width = ICON_WIDTH; - - UIImage *drawImg = (_drawImage) ? _drawImage : [UIImage imageNamed:@"btn_ink"]; - UIBarButtonItem *drawButton = [[UIBarButtonItem alloc]initWithImage:drawImg style:UIBarButtonItemStylePlain target:self action:@selector(drawModeClick)]; - drawButton.width = ICON_WIDTH; - - UIImage *selectImg = (_selectImage) ? _selectImage : [UIImage imageNamed:@"btn_select"]; - _selectTextButton= [[UIBarButtonItem alloc] initWithImage:selectImg style:UIBarButtonItemStylePlain target:self action:@selector(selectClick)]; - _selectTextButton.width = ICON_WIDTH; - - UIImage *undoImg = (_undoImage) ? _undoImage : [UIImage imageNamed:@"btn_undo"]; - UIBarButtonItem *undoButton = [[UIBarButtonItem alloc]initWithImage:undoImg style:UIBarButtonItemStylePlain target:self action:@selector(undoClick)]; - undoButton.width = ICON_WIDTH; - - UIImage *redoImg = (_redoImage) ? _redoImage : [UIImage imageNamed:@"btn_redo"]; - UIBarButtonItem *redoButton=[[UIBarButtonItem alloc]initWithImage:redoImg style:UIBarButtonItemStylePlain target:self action:@selector(redoClick)]; - redoButton.width = ICON_WIDTH; - - UIImage *gridImg = (_gridImage) ? _gridImage : [UIImage imageNamed:@"btn_grid"]; - UIBarButtonItem *gridButton=[[UIBarButtonItem alloc]initWithImage:gridImg style:UIBarButtonItemStylePlain target:self action:@selector(gridlick)]; - gridButton.width = ICON_WIDTH; - - UIImage *moreImg = (_moreImage) ? _moreImage : [UIImage imageNamed:@"btn_more"]; - _moreButton = [[UIBarButtonItem alloc] initWithImage:moreImg style:UIBarButtonItemStylePlain target:self action:@selector(moreClick)]; - normalToolBarArray = [[NSMutableArray alloc] initWithObjects:_searchButton,drawButton,_selectTextButton,undoButton,redoButton,gridButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], _moreButton,nil]; - - UIImage *rightImg = (_nextImage) ? _nextImage : [UIImage imageNamed:@"btn_right"]; - UIBarButtonItem *nextbutton=[[UIBarButtonItem alloc]initWithImage:rightImg style:UIBarButtonItemStylePlain target:self action:@selector(nextword)]; - nextbutton.width = ICON_WIDTH; - - UIImage *leftImg = (_prevImage) ? _prevImage : [UIImage imageNamed:@"btn_left"]; - UIBarButtonItem *prevbutton=[[UIBarButtonItem alloc]initWithImage:leftImg style:UIBarButtonItemStylePlain target:self action:@selector(prevword)]; - prevbutton.width = ICON_WIDTH; - - UIImage *removeImg = (_removeImage) ? _removeImage : [UIImage imageNamed:@"btn_annot_remove"]; - UIBarButtonItem *searchCancelbtn=[[UIBarButtonItem alloc]initWithImage:removeImg style:UIBarButtonItemStylePlain target:self action:@selector(searchCancel)]; - searchCancelbtn.width = ICON_WIDTH; - searchToolBarArray = [[NSArray alloc]initWithObjects:_searchButton,prevbutton,nextbutton,searchCancelbtn,nil]; - - UIImage *performImg = (_performImage) ? _performImage : [UIImage imageNamed:@"btn_perform"]; - UIBarButtonItem *playbutton=[[UIBarButtonItem alloc]initWithImage:performImg style:UIBarButtonItemStylePlain target:self action:@selector(performAnnot)]; - playbutton.width = ICON_WIDTH; - - UIImage *deleteImg = (_deleteImage) ? _deleteImage : [UIImage imageNamed:@"btn_remove"]; - UIBarButtonItem *deletebutton=[[UIBarButtonItem alloc]initWithImage:deleteImg style:UIBarButtonItemStylePlain target:self action:@selector(deleteAnnot)]; - deletebutton.width = ICON_WIDTH; - - UIImage *cancelImg = (_removeImage) ? _removeImage : [UIImage imageNamed:@"btn_annot_remove"]; - UIBarButtonItem *cancelbtn=[[UIBarButtonItem alloc]initWithImage:cancelImg style:UIBarButtonItemStylePlain target:self action:@selector(annotCancel)]; - cancelbtn.width = ICON_WIDTH; - - UIImage *propImg = (_removeImage) ? _removeImage : [UIImage imageNamed:@"btn_prop"]; - UIBarButtonItem *propbutton=[[UIBarButtonItem alloc]initWithImage:propImg style:UIBarButtonItemStylePlain target:self action:@selector(annotProperties)]; - propbutton.width = ICON_WIDTH; - - performToolBarArray = [[NSArray alloc]initWithObjects:playbutton,deletebutton,propbutton,cancelbtn,nil]; - - NSMutableArray *hiddenItems = [NSMutableArray arrayWithObjects: [NSNumber numberWithBool:_hideSearchImage], [NSNumber numberWithBool:_hideDrawImage], [NSNumber numberWithBool:_hideSelImage], [NSNumber numberWithBool:_hideUndoImage], [NSNumber numberWithBool:_hideRedoImage], [NSNumber numberWithBool:_hideGridImage], [NSNumber numberWithBool:NO], [NSNumber numberWithBool:_hideMoreImage], nil]; - - NSMutableArray *objectsToRemove = [NSMutableArray array]; - for (int i = 0; i < hiddenItems.count; i++) { - if ([[hiddenItems objectAtIndex:i] boolValue]) { - [objectsToRemove addObject:[normalToolBarArray objectAtIndex:i]]; - } - } - - [normalToolBarArray removeObjectsInArray:objectsToRemove]; - [normalToolBarArray insertObject:closeButton atIndex:0]; - - [self addSubview:self.bar]; - - [self changeToNormalToolBar]; -} +@implementation RDToolbar -- (void)changeToPerformToolBar -{ - [self.bar setItems:performToolBarArray]; -} -- (void)changeToSearchToolBar -{ - [self.bar setItems:searchToolBarArray]; +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect { + // Drawing code + self.layer.shadowColor = [UIColor blackColor].CGColor; + self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.layer.cornerRadius].CGPath; } -- (void)changeToNormalToolBar -{ - _searchButton.enabled = YES; - [self.bar setItems:normalToolBarArray]; -} -#pragma mark - Delegate -// normalbar delegate -- (void)closeClick -{ - if (self.m_delegate) { - [_m_delegate closeView]; - } -} -- (void)searchClick; -{ - if (self.m_delegate) { - [_m_delegate searchView]; - } -} -- (void)drawModeClick; -{ - if (self.m_delegate) { - [_m_delegate showDrawModeTableView]; - } -} -- (void)selectClick; -{ - if (self.m_delegate) { - [_m_delegate selectIsStarting]; - } -} -- (void)undoClick; -{ - if (self.m_delegate) { - [_m_delegate undoAnnot]; - } -} -- (void)redoClick; -{ - if (self.m_delegate) { - [_m_delegate redoAnnot]; - } -} -- (void)gridlick; -{ - if (self.m_delegate) { - [_m_delegate toggleGrid]; - } -} -- (void)moreClick; -{ - if (self.m_delegate) { - [_m_delegate showMoreButtons]; - } -} -//performbar delegate -- (void)nextword; -{ - if (self.m_delegate) { - [_m_delegate nextword]; - } -} -- (void)prevword; -{ - if (self.m_delegate) { - [_m_delegate prevword]; - } -} -- (void)searchCancel; -{ - if (self.m_delegate) { - [_m_delegate searchCancel]; - } -} -//searchbar delegate -- (void)performAnnot; -{ - if (self.m_delegate) { - [_m_delegate performAnnot]; - } -} -- (void)deleteAnnot; -{ - if (self.m_delegate) { - [_m_delegate deleteAnnot]; - } -} -- (void)annotCancel; -{ - if (self.m_delegate) { - [_m_delegate annotCancel]; - } -} -- (void)annotProperties -{ - if (self.m_delegate) { - [_m_delegate annotProperties]; - } +- (void)setHidden:(BOOL)hidden { + [super setHidden:hidden]; + _toolbar.hidden = hidden; } @end diff --git a/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.h b/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.h new file mode 100755 index 00000000..3d34e016 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.h @@ -0,0 +1,24 @@ +// +// OUTLINE_ITEM.h +// PDFViewer +// +// Created by Radaee on 13-1-20. +// Copyright (c) 2013年 Radaee. All rights reserved. +// + + +#import + +@class RDPDFOutline; + +@interface OUTLINE_ITEM : NSObject +@property(nonatomic,strong) NSString *label; +@property(nonatomic,strong) NSString *url; // Param in Satiz JSON +@property(nonatomic,strong) NSString *name; // Param in Satiz JSON +@property(nonatomic,strong) NSString *link; +@property(nonatomic,assign) int gen; // Param in Satiz JSON +@property(nonatomic,strong) NSMutableArray *childIndexes; +@property(nonatomic,assign) int dest; +@property(nonatomic,assign) int level; +@property(nonatomic,strong) RDPDFOutline *child; +@end diff --git a/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.m b/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.m new file mode 100755 index 00000000..b0c56c62 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/OUTLINE_ITEM.m @@ -0,0 +1,46 @@ +// +// OUTLINE_ITEM.m +// PDFViewer +// +// Created by Radaee on 13-1-20. +// Copyright (c) 2013年 __Radaee__. All rights reserved. +// + + +#import "OUTLINE_ITEM.h" + +@implementation OUTLINE_ITEM + +- (NSString *)label +{ + if (_label) + return _label; + else + return @""; +} + +- (NSString *)name +{ + if (_name) + return _name; + else + return @""; +} + +- (int)gen +{ + if (_gen) + return _gen; + else + return 0; +} + +- (NSString *)url { + if (_url) { + return _url; + } else { + return [NSNull null]; + } +} + +@end diff --git a/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.h b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.h new file mode 100755 index 00000000..8bc66dd3 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.h @@ -0,0 +1,25 @@ +// +// RDTreeTableViewCell.h +// PDFViewer +// +// Created by Emanuele Bortolami on 31/05/2019. +// + +#import +#import "OUTLINE_ITEM.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface RDTreeTableViewCell : UITableViewCell + +@property (strong, nonatomic) UIImageView *arrowImage; +@property (strong, nonatomic) UILabel *outlineLabel; +@property (strong, nonatomic) OUTLINE_ITEM *item; + +- (void)setupWithItem:(OUTLINE_ITEM *)outline; +- (void)rotateArrow; +- (void)resetArrow; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.m b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.m new file mode 100755 index 00000000..cd36d9f0 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeTableViewCell.m @@ -0,0 +1,65 @@ +// +// RDTreeTableViewCell.m +// PDFViewer +// +// Created by Emanuele Bortolami on 31/05/2019. +// + +#import "RDTreeTableViewCell.h" +#import "RDUtils.h" + +@implementation RDTreeTableViewCell + +- (void)awakeFromNib { + [super awakeFromNib]; + // Initialization code +} + +- (void)setSelected:(BOOL)selected animated:(BOOL)animated { + [super setSelected:selected animated:animated]; + + // Configure the view for the selected state +} + +- (void)setupWithItem:(OUTLINE_ITEM *)outline { + _item = outline; + int x = 20 * _item.level; + + CGRect rect = _outlineLabel.frame; + rect.size.width = self.frame.size.width - rect.origin.x - x - 20; + _outlineLabel.frame = rect; + + _outlineLabel.transform = CGAffineTransformMakeTranslation(x, 0); + _arrowImage.transform = CGAffineTransformMakeTranslation(x, 0); + _outlineLabel.text = [self cleanString:_item.label]; + _arrowImage.hidden = ([outline child] == nil); + + if (_item.childIndexes != nil) { + [self rotateArrow]; + } +} + +- (void)rotateArrow { + CGAffineTransform transform = _arrowImage.transform; + _arrowImage.transform = CGAffineTransformConcat(CGAffineTransformMakeRotation(M_PI_2), CGAffineTransformMakeTranslation(transform.tx, 0)); +} + +- (void)resetArrow { + CGAffineTransform transform = _arrowImage.transform; + _arrowImage.transform = CGAffineTransformMakeTranslation(transform.tx, 0); +} + +- (NSString *)cleanString:(NSString *)string { + return [[string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "]; +} + +-(void)prepareForReuse{ + [super prepareForReuse]; + // Then Reset here back to default values that you want. + + _item = nil; + _outlineLabel.transform = CGAffineTransformIdentity; + self.textLabel.text = @""; +} + +@end diff --git a/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.h b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.h new file mode 100755 index 00000000..5c4b6168 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.h @@ -0,0 +1,32 @@ +// +// RDTreeViewController.h +// PDFViewer +// +// Created by Emanuele Bortolami on 31/05/2019. +// + +#import +#import "RDTreeTableViewCell.h" + +@class RDPDFDoc; + +NS_ASSUME_NONNULL_BEGIN + +// define the protocol for the delegate +@protocol RDTreeViewControllerDelegate +// define protocol functions that can be used in any class using this delegate +- (void)didSelectDest:(OUTLINE_ITEM *)item; +@end; + +@interface RDTreeViewController : UIViewController + +@property (strong, nonatomic) RDPDFDoc *doc; +@property (nonatomic, weak) id delegate; + +@property (strong, nonatomic) IBOutlet UITableView *tableView; + +- (IBAction)dismissView:(id)sender; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.m b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.m new file mode 100755 index 00000000..df5c499d --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.m @@ -0,0 +1,213 @@ +// +// RDTreeViewController.m +// PDFViewer +// +// Created by Emanuele Bortolami on 31/05/2019. +// + +#import "RDTreeViewController.h" +#import "RDUtils.h" + +@interface RDTreeViewController () { + + NSMutableArray *items; +} + +@end + +@implementation RDTreeViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + + // Uncomment the following line to preserve selection between presentations. + // self.clearsSelectionOnViewWillAppear = NO; + + self.tableView.delegate = self; + self.tableView.dataSource = self; + + self.tableView.backgroundColor = [RDUtils radaeeWhiteColor]; + self.tableView.layer.cornerRadius = 10.0f; + + items = [NSMutableArray array]; + + // Primo livello + RDPDFOutline *root = [_doc rootOutline]; + while(root) + { + OUTLINE_ITEM *item = [self itemWithObject:root]; + item.level = 0; + root = [root next]; + [items addObject:item]; + } + + self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + [self.tableView reloadData]; +} + +- (void)viewWillAppear:(BOOL)animated { + [super viewWillAppear:animated]; +} + +- (OUTLINE_ITEM *)itemWithObject:(RDPDFOutline *)obj { + OUTLINE_ITEM *outline_item = [[OUTLINE_ITEM alloc]init]; + outline_item.label = [obj label]; + outline_item.dest = [obj dest]; + outline_item.child = [obj child]; + return outline_item; +} + +#pragma mark - Table view data source + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { + return 1; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return items.count; +} + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + static NSString *CellIdentifier = @"Cell"; + + RDTreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; + + if (cell == nil) { + cell = [[RDTreeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; + cell.outlineLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, tableView.frame.size.width - 60, 50)]; + cell.arrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 5, 40, 40)]; + [cell.arrowImage setImage:[[UIImage imageNamed:@"btn_right"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]]; + cell.outlineLabel.numberOfLines = 0; + cell.outlineLabel.lineBreakMode = NSLineBreakByWordWrapping; + cell.outlineLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; + [cell addSubview:cell.outlineLabel]; + [cell addSubview:cell.arrowImage]; + cell.backgroundColor = [RDUtils radaeeWhiteColor]; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + } + + [cell setupWithItem:[items objectAtIndex:indexPath.row]]; + + return cell; +} + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return 50; +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + OUTLINE_ITEM *selectedItem = (OUTLINE_ITEM *)[items objectAtIndex:indexPath.row]; + if ([selectedItem child]) { + // controllo se ho già degli indici salvati (vuol dire che sto già mostrando i child + [self.tableView beginUpdates]; + if (selectedItem.childIndexes) { + RDTreeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; + [cell resetArrow]; + [self closeChild:selectedItem atIndex:(int)indexPath.row]; + } else { + RDTreeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; + [cell rotateArrow]; + [self openChild:selectedItem atIndex:(int)indexPath.row]; + } + [self.tableView endUpdates]; + } else { + if (_delegate) { + [_delegate didSelectDest:selectedItem]; + } + } +} + +- (void)openChild:(OUTLINE_ITEM *)item atIndex:(int)index { + RDPDFOutline *outline = [[items objectAtIndex:index] child]; + if (!outline) { + return; + } + NSMutableArray *indexPaths = [NSMutableArray array]; + while(outline) + { + index++; + OUTLINE_ITEM *child = [self itemWithObject:outline]; + child.level = item.level + 1; + outline = [outline next]; + [items insertObject:child atIndex:index]; + [indexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]]; + } + + if (indexPaths.count > 0) { + item.childIndexes = indexPaths; + } + + [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop]; +} + +- (void)closeChild:(OUTLINE_ITEM *)item atIndex:(int)index { + int i = index + 1; + NSMutableArray *indexPaths = [NSMutableArray array]; + while (i < items.count) { + OUTLINE_ITEM *it = [items objectAtIndex:i]; + if (it.level > item.level) { + [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]]; + } else { + break; + } + i++; + } + + for (i = (int)indexPaths.count - 1; i >= 0; i--) { + [items removeObjectAtIndex:[[indexPaths objectAtIndex:i] row]]; + } + + [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationBottom]; + item.childIndexes = nil; +} + +- (IBAction)dismissView:(id)sender +{ + [self dismissViewControllerAnimated:YES completion:nil]; +} + +/* +// Override to support conditional editing of the table view. +- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { + // Return NO if you do not want the specified item to be editable. + return YES; +} +*/ + +/* +// Override to support editing the table view. +- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { + if (editingStyle == UITableViewCellEditingStyleDelete) { + // Delete the row from the data source + [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; + } else if (editingStyle == UITableViewCellEditingStyleInsert) { + // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view + } +} +*/ + +/* +// Override to support rearranging the table view. +- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { +} +*/ + +/* +// Override to support conditional rearranging of the table view. +- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { + // Return NO if you do not want the item to be re-orderable. + return YES; +} +*/ + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.xib b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.xib new file mode 100755 index 00000000..556e0b74 --- /dev/null +++ b/src/ios/PDFViewer/RDTreeTableViewController/RDTreeViewController.xib @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ios/PDFViewer/RDUPassWord.h b/src/ios/PDFViewer/RDUPassWord.h deleted file mode 100755 index 645220dc..00000000 --- a/src/ios/PDFViewer/RDUPassWord.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// RDUPassWord.h -// PDFViewer -// -// Created by radaee on 13-2-1. -// Copyright (c) 2013年 _Radaee. All rights reserved. -// - -#import - -@interface RDUPassWord : UIAlertView -@property(nonatomic, retain) UITextField* uPwd; // 密码输入框 -@end diff --git a/src/ios/PDFViewer/RDUPassWord.m b/src/ios/PDFViewer/RDUPassWord.m deleted file mode 100755 index 66a78282..00000000 --- a/src/ios/PDFViewer/RDUPassWord.m +++ /dev/null @@ -1,86 +0,0 @@ -// -// RDUPassWord.m -// PDFViewer -// -// Created by radaee on 13-2-1. -// Copyright (c) 2013年 Radaee. All rights reserved. -// - -#import "RDUPassWord.h" - -@implementation RDUPassWord -@synthesize uPwd; -NSString *text; -- (id)initWithFrame:(CGRect)frame -{ - self = [super initWithFrame:frame]; - if (self) { - // Initialization code - } - return self; -} - -- (id)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... { - - self = [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil]; - if (self != nil) { - // 初始化自定义控件,注意摆放的位置,可以多试几次位置参数直到满意为止 - // createTextField函数用来初始化UITextField控件,在文件末尾附上 - if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) - { - self.alertViewStyle = UIAlertViewStyleSecureTextInput; - } - NSString *password =[[NSString alloc]initWithFormat:NSLocalizedString(@"PassWord", @"Localizable")]; - self.uPwd = [self createTextField:password - withFrame:CGRectMake(22, 45, 240, 36)]; - if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0){ - - } - [self addSubview:self.uPwd]; - - - } - - return self; -} - -// Override父类的layoutSubviews方法 -- (void)layoutSubviews { - [super layoutSubviews]; // 当override父类的方法时,要注意一下是否需要调用父类的该方法 - - for (UIView* view in self.subviews) { - // 搜索AlertView底部的按钮,然后将其位置下移 - // IOS5以前按钮类是UIButton, IOS5里该按钮类是UIThreePartButton - if ([view isKindOfClass:[UIButton class]] || - [view isKindOfClass:NSClassFromString(@"UIThreePartButton")]) { - CGRect btnBounds = view.frame; - btnBounds.origin.y = self.uPwd.frame.origin.y + self.uPwd.frame.size.height + 7; - view.frame = btnBounds; - } - } - - // 定义AlertView的大小 - CGRect bounds = self.frame; - bounds.size.height = 160; - self.frame = bounds; -} - -- (UITextField*)createTextField:(NSString*)placeholder withFrame:(CGRect)frame { - UITextField* field = [[UITextField alloc] initWithFrame:frame]; - field.placeholder = placeholder; - field.delegate = (id)self; - field.secureTextEntry = YES; - field.backgroundColor = [UIColor whiteColor]; - field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; - [field addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; - return field; -} -- (void) textFieldDidChange:(id) sender -{ - UITextField *_field = (UITextField *)sender; - text = [_field text]; -} - - - -@end diff --git a/src/ios/PDFViewer/TextAnnotViewController.h b/src/ios/PDFViewer/TextAnnotViewController.h deleted file mode 100644 index da08545f..00000000 --- a/src/ios/PDFViewer/TextAnnotViewController.h +++ /dev/null @@ -1,29 +0,0 @@ -// -// TextAnnotViewController.h -// PDFViewer -// -// Created by strong on 13-7-11. -// -// - -#import -@protocol saveTextAnnotDelegate - --(void)OnSaveTextAnnot:(NSString *)textAnnot subject:(NSString *)subject; -@end - - -@interface TextAnnotViewController : UIViewController -{ id m_delegate; - UITextField *textField; - UITextView *textView; - NSString* text; -} - -@property(nonatomic) BOOL readOnly; -@property(strong, nonatomic) NSString *text; -@property(strong, nonatomic) NSString *subject; - - --(void)setDelegate:(id)delegate; -@end diff --git a/src/ios/PDFViewer/TextAnnotViewController.m b/src/ios/PDFViewer/TextAnnotViewController.m deleted file mode 100644 index fd614d6b..00000000 --- a/src/ios/PDFViewer/TextAnnotViewController.m +++ /dev/null @@ -1,104 +0,0 @@ -// -// TextAnnotViewController.m -// PDFViewer -// -// Created by strong on 13-7-11. -// -// - -#import "TextAnnotViewController.h" - -@interface TextAnnotViewController () - -@end - -@implementation TextAnnotViewController - -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil -{ - self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; - if (self) { - // Custom initialization - } - return self; -} - -- (void)viewDidLoad -{ - [super viewDidLoad]; - NSString *title =[[NSString alloc]initWithFormat:NSLocalizedString(@"Text Annot", @"Localizable")]; - self.title = title; - - UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelTextAnnot)]; - - UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(saveTextAnnot)]; - - self.navigationItem.leftBarButtonItem = cancelBtn; - self.navigationItem.rightBarButtonItem = saveBtn; - self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0]; -} - -- (void)viewWillAppear:(BOOL)animated -{ - UILabel *subjectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height + self.navigationController.navigationBar.frame.size.height + 15, 90, 50)]; - subjectLabel.text = @"Subject:"; - subjectLabel.textAlignment = NSTextAlignmentCenter; - - UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, subjectLabel.frame.origin.y + subjectLabel.frame.size.height + 5, 90, 50)]; - contentLabel.text = @"Content:"; - contentLabel.textAlignment = NSTextAlignmentCenter; - - textField = [[UITextField alloc] initWithFrame:CGRectMake(subjectLabel.frame.size.width, subjectLabel.frame.origin.y, self.view.bounds.size.width - (subjectLabel.frame.size.width + 5) - 5, 44)]; - textField.backgroundColor = [UIColor whiteColor]; - - textView = [[UITextView alloc] initWithFrame:CGRectMake(contentLabel.frame.size.width, contentLabel.frame.origin.y, self.view.bounds.size.width - (contentLabel.frame.size.width + 5) - 5, self.view.bounds.size.height - contentLabel.frame.origin.y - 15)]; - - [self.view addSubview:subjectLabel]; - [self.view addSubview:contentLabel]; - [self.view addSubview:textField]; - [self.view addSubview:textView]; - - textField.text = _subject; - textView.text = _text; - - if (self.readOnly) - { - textView.userInteractionEnabled = NO; - textField.userInteractionEnabled = NO; - } -} - -- (void)didReceiveMemoryWarning -{ - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} --(BOOL)cancelTextAnnot -{ - if(m_delegate && !self.readOnly) - { - [m_delegate OnSaveTextAnnot:@"" subject:@""]; - } - [self dismissViewControllerAnimated:YES completion:^{ - - }]; - - return NO; -} - --(void)saveTextAnnot -{ - if(m_delegate && !self.readOnly) - { - [m_delegate OnSaveTextAnnot:textView.text subject:textField.text]; - } - [self dismissViewControllerAnimated:YES completion:^{ - - }]; -} --(void)setDelegate:(id)delegate -{ - m_delegate = delegate; -} - -@end diff --git a/src/ios/PDFViewer/UILElement.h b/src/ios/PDFViewer/UILElement.h new file mode 100755 index 00000000..dfc925cb --- /dev/null +++ b/src/ios/PDFViewer/UILElement.h @@ -0,0 +1,19 @@ +// +// UILElement.h +// PDFViewer +// +// Created by Emanuele Bortolami on 09/07/2020. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UILElement : UIView + +-(id)initWithCoder:(NSCoder *)aDecoder; +-(id)initWithFrame:(CGRect)frame; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/UILElement.m b/src/ios/PDFViewer/UILElement.m new file mode 100755 index 00000000..8abd0c1d --- /dev/null +++ b/src/ios/PDFViewer/UILElement.m @@ -0,0 +1,48 @@ +// +// UILElement.m +// PDFViewer +// +// Created by Emanuele Bortolami on 09/07/2020. +// + +#import "UILElement.h" +#import "RDUtils.h" + +@implementation UILElement + +/* +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect { + // Drawing code +} +*/ + +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + [self initLayout]; + } + return self; +} +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + [self initLayout]; + } + return self; +} + +- (void)initLayout { + self.clipsToBounds = YES; + self.layer.cornerRadius = 10.0f; + self.layer.masksToBounds = YES; + self.layer.borderColor = [RDUtils radaeeBlackColor].CGColor; + self.layer.borderWidth = 2.0; +} + +@end diff --git a/src/ios/PDFViewer/UILShadowView.h b/src/ios/PDFViewer/UILShadowView.h new file mode 100755 index 00000000..c37efa26 --- /dev/null +++ b/src/ios/PDFViewer/UILShadowView.h @@ -0,0 +1,23 @@ +// +// UILShadowView.h +// PDFViewer +// +// Created by Emanuele Bortolami on 09/07/2020. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface UILShadowView : UIView + +-(id)initWithFrame:(CGRect)frame; +-(id)initWithCoder:(NSCoder *)aDecoder; + +@property (strong, nonatomic) IBOutlet UIView *buttonView; +@property (strong, nonatomic) IBOutlet UIButton *okButton; +@property (strong, nonatomic) IBOutlet UIButton *cancelButton; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/ios/PDFViewer/UILShadowView.m b/src/ios/PDFViewer/UILShadowView.m new file mode 100755 index 00000000..4cc1ffba --- /dev/null +++ b/src/ios/PDFViewer/UILShadowView.m @@ -0,0 +1,52 @@ +// +// UILShadowView.m +// PDFViewer +// +// Created by Emanuele Bortolami on 09/07/2020. +// + +#import "UILShadowView.h" +#import "RDUtils.h" + +@implementation UILShadowView + +/* +// Only override drawRect: if you perform custom drawing. +// An empty implementation adversely affects performance during animation. +- (void)drawRect:(CGRect)rect { + // Drawing code +} +*/ + +-(id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if(self) + { + [self initLayout]; + } + return self; +} +-(id)initWithCoder:(NSCoder *)aDecoder +{ + self = [super initWithCoder:aDecoder]; + if(self) + { + [self initLayout]; + } + return self; +} + +- (void)initLayout { + self.layer.cornerRadius = 10.0f; + self.clipsToBounds = YES; + self.layer.shadowColor = [UIColor blackColor].CGColor; + self.layer.shadowOffset = CGSizeMake(0, 0.0f); + self.layer.shadowRadius = 10.0f; + self.layer.shadowOpacity = 0.25f; + self.layer.masksToBounds = NO; + + self.backgroundColor = [RDUtils radaeeWhiteColor]; +} + +@end diff --git a/src/ios/PDFViewer/ViewModeTableViewController.h b/src/ios/PDFViewer/ViewModeTableViewController.h deleted file mode 100644 index 8ffe8e10..00000000 --- a/src/ios/PDFViewer/ViewModeTableViewController.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// ViewModeTableViewController.h -// Radaee-Cordova -// -// Created by Emanuele Bortolami on 24/06/16. -// -// - -#import - -@protocol ViewModeDelegate - --(void)setReaderViewMode:(int)mode; - -@end - -@interface ViewModeTableViewController : UITableViewController - -@property (nonatomic, weak) id delegate; - -@end diff --git a/src/ios/PDFViewer/ViewModeTableViewController.m b/src/ios/PDFViewer/ViewModeTableViewController.m deleted file mode 100644 index 27930fca..00000000 --- a/src/ios/PDFViewer/ViewModeTableViewController.m +++ /dev/null @@ -1,155 +0,0 @@ -// -// ViewModeTableViewController.m -// Radaee-Cordova -// -// Created by Emanuele Bortolami on 24/06/16. -// -// - -#import "ViewModeTableViewController.h" - -@interface ViewModeTableViewController () - -@end - -@implementation ViewModeTableViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - - // Uncomment the following line to preserve selection between presentations. - // self.clearsSelectionOnViewWillAppear = NO; - - // Uncomment the following line to display an Edit button in the navigation bar for this view controller. - // self.navigationItem.rightBarButtonItem = self.editButtonItem; -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - -#pragma mark - Table view data source - -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { - return 1; -} - -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - return 4; -} - - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *CellIdentifier = @"Cell"; - - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; - if (cell == nil) { - cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; - } - - switch (indexPath.row) { - case 0: - { - cell.textLabel.text = NSLocalizedString(@"Vertical", nil); - cell.imageView.image = [UIImage imageNamed:@"btn_view_vert.png"]; - break; - } - case 1: - { - cell.textLabel.text = NSLocalizedString(@"Horizontal", nil); - cell.imageView.image = [UIImage imageNamed:@"btn_view_single.png"]; - break; - } - case 2: - { - cell.textLabel.text = NSLocalizedString(@"Single Page", nil); - cell.imageView.image = [UIImage imageNamed:@"btn_view_single.png"]; - break; - } - case 3: - { - cell.textLabel.text = NSLocalizedString(@"Double Page", nil); - cell.imageView.image = [UIImage imageNamed:@"btn_view_dual.png"]; - break; - } - default: - break; - } - - return cell; -} - -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath -{ - if (indexPath.row == 2) { - [_delegate setReaderViewMode:3]; - return; - } else if (indexPath.row == 3) { - [_delegate setReaderViewMode:6]; - return; - } - [_delegate setReaderViewMode:(int)indexPath.row]; -} - -/* -// Override to support conditional editing of the table view. -- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { - // Return NO if you do not want the specified item to be editable. - return YES; -} -*/ - -/* -// Override to support editing the table view. -- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { - if (editingStyle == UITableViewCellEditingStyleDelete) { - // Delete the row from the data source - [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; - } else if (editingStyle == UITableViewCellEditingStyleInsert) { - // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view - } -} -*/ - -/* -// Override to support rearranging the table view. -- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { -} -*/ - -/* -// Override to support conditional rearranging of the table view. -- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { - // Return NO if you do not want the item to be re-orderable. - return YES; -} -*/ - -/* -#pragma mark - Table view delegate - -// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath: -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - // Navigation logic may go here, for example: - // Create the next view controller. - <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil]; - - // Pass the selected object to the new view controller. - - // Push the view controller. - [self.navigationController pushViewController:detailViewController animated:YES]; -} -*/ - -/* -#pragma mark - Navigation - -// In a storyboard-based application, you will often want to do a little preparation before navigation -- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { - // Get the new view controller using [segue destinationViewController]. - // Pass the selected object to the new view controller. -} -*/ - -@end diff --git a/src/ios/PDFViewer/en.lproj/Localizable.strings b/src/ios/PDFViewer/en.lproj/RAPDFLocalizable.strings old mode 100644 new mode 100755 similarity index 61% rename from src/ios/PDFViewer/en.lproj/Localizable.strings rename to src/ios/PDFViewer/en.lproj/RAPDFLocalizable.strings index 05f0c93f..2bbb3fb8 --- a/src/ios/PDFViewer/en.lproj/Localizable.strings +++ b/src/ios/PDFViewer/en.lproj/RAPDFLocalizable.strings @@ -9,7 +9,7 @@ "PDF File" = "PDF File"; "Marks" = "Marks"; "Setting" = "Setting"; -"More" = "More"; +"More" = "About"; "Swipe Speed" = "Swipe Speed"; "Render Quality" = "Render Quality"; "Swipe Distance" = "Swipe Distance"; @@ -77,6 +77,53 @@ "Reached last occurrence" = "Reached last occurrence"; "Searching... (%i)" = "Searching... (%i)"; "%i occurrences" = "%i occurrences"; +"Meta" = "Meta"; +"Rename" = "Rename"; +"Last modified" = "Last modified"; +"already exists" = "already exists"; +"Are you sure you want to delete this file?" = "Are you sure you want to delete this file?"; +"Undo" = "Undo"; +"Redo" = "Redo"; +"Selection" = "Selection"; +"Bookmarks" = "Bookmarks"; +"Slider" = "Slider"; +"Night mode" = "Night mode"; +"Light mode" = "Light mode"; +"Thumbnail" = "Thumbnail"; +"Polygon" = "Polygon"; +"Polyline" = "Polyline"; +"Manage pages" = "Manage pages"; +"Cannot add bookmark" = "Cannot add bookmark"; +"Bookmark added!" = "Bookmark added!"; +"Bookmark already exist at page" = "Bookmark already exist at page"; +"No bookmark saved" = "No bookmark saved"; +"This PDF file has no outlines!" = "This PDF file has no outlines!"; +"Title" = "Title"; +"Author" = "Author"; +"Subject" = "Subject"; +"Keywords" = "Keywords"; +"Text" = "Text"; +"Line width" = "Line width"; +"Line style" = "Line style"; +"Line color" = "Line color"; +"Fill color" = "Fill color"; +"Lock" = "Lock"; +"Locked" = "Locked"; +"Icon" = "Icon"; +"Line start" = "Line start"; +"Line end" = "Line end"; +"Color" = "Color"; +"Need password to open the PDF file." = "Need password to open the PDF file."; +"Do you confirm to delete the PDF file?" = "Do you confirm to delete the PDF file?"; +"Page Editing" = "Page Editing"; +"Attachments" = "Attachments"; +"Are you sure to delete this embedded file?" = "Are you sure to delete this embedded file?"; +"successfully saved" = "successfully saved"; +"Success" = "Success"; +"Error on adding new embedded" = "Error on adding new embedded"; +"Embedded files" = "Embedded files"; +"Searching" = "Searching"; +"No more found!" = "No more found!"; /* diff --git a/src/ios/PDFViewer/en.lproj/RDFileTableController.strings b/src/ios/PDFViewer/en.lproj/RDFileTableController.strings old mode 100644 new mode 100755 diff --git a/src/ios/PDFViewer/en.lproj/RDLoPDFViewController.strings b/src/ios/PDFViewer/en.lproj/RDLoPDFViewController.strings deleted file mode 100644 index 8b137891..00000000 --- a/src/ios/PDFViewer/en.lproj/RDLoPDFViewController.strings +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/ios/PDFViewer/fdat/Facebook Cookbook.pdf b/src/ios/PDFViewer/fdat/Facebook Cookbook.pdf deleted file mode 100644 index 1e2fa4ce..00000000 Binary files a/src/ios/PDFViewer/fdat/Facebook Cookbook.pdf and /dev/null differ diff --git a/src/ios/PDFViewer/it.lproj/DistanceList.plist b/src/ios/PDFViewer/it.lproj/DistanceList.plist deleted file mode 100755 index f9945e38..00000000 --- a/src/ios/PDFViewer/it.lproj/DistanceList.plist +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - Distanza lunga - Distanza media - Distanza corta - - - diff --git a/src/ios/PDFViewer/it.lproj/HightLightColorList.plist b/src/ios/PDFViewer/it.lproj/HightLightColorList.plist deleted file mode 100755 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/HightLightColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/InkColorList.plist b/src/ios/PDFViewer/it.lproj/InkColorList.plist deleted file mode 100755 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/InkColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/LineMarkWidth.plist b/src/ios/PDFViewer/it.lproj/LineMarkWidth.plist deleted file mode 100755 index b7f3f387..00000000 --- a/src/ios/PDFViewer/it.lproj/LineMarkWidth.plist +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - 1 - 2 - 4 - 8 - - - diff --git a/src/ios/PDFViewer/it.lproj/Localizable.strings b/src/ios/PDFViewer/it.lproj/Localizable.strings old mode 100644 new mode 100755 index 9bdec164..c5d3f22f --- a/src/ios/PDFViewer/it.lproj/Localizable.strings +++ b/src/ios/PDFViewer/it.lproj/Localizable.strings @@ -9,7 +9,7 @@ "PDF File" = "PDF File"; "Marks" = "Marks"; "Setting" = "Impostazioni"; -"More" = "Altro"; +"More" = "Info"; "Swipe Speed" = "Velocità swipe"; "Render Quality" = "Qualità di visualizzazione"; "Swipe Distance" = "Distanza swipe"; @@ -20,9 +20,9 @@ "Click OK to reset all properties to default" = "Clicca OK per resettare le impostazioni"; "OK" = "OK"; "Cancel" = "Annulla"; -"BookMark Already Exist" = "Bookmark già presente"; +"BookMark Already Exist" = "Segnalibro già presente"; "Page " = "Pagina "; -"Add BookMark Success!"="Bookmark aggiunto!"; +"Add BookMark Success!"="Segnalibro aggiunto!"; "Ink Color" = "Colore Ink"; "Rect Color" = "Colore Rect"; "Draw Line on file" = "Disegna linea nel file"; @@ -40,8 +40,8 @@ "Highlight Color" = "Colore evidenziatura"; "Oval Color" = "Colore ovale"; "Select Action" = "Seleziona Azione"; -"Add Bookmark" = "Aggiungi Bookmark"; -"Bookmark List" = "Lista Bookmark"; +"Add Bookmark" = "Aggiungi Segnalibro"; +"Bookmark List" = "Lista Segnalibro"; "View Mode" = "Modalità visualizzazione"; "View Menu" = "Indice"; "Save" = "Salva"; @@ -63,7 +63,7 @@ "Warning" = "Attenzione"; "Find Over" = "Non ci sono altri risultati"; "Signature already exist. Do you want delete it?" = "Firma già esistente. Vuoi cancellarla?"; -"Delete" = "Cancella"; +"Delete" = "Elimina"; "Error" = "Errore"; "Couldn't find media file" = "Nessun media trovato"; "Select View Mode" = "Modalità di visualizzazione"; @@ -77,6 +77,53 @@ "Reached last occurrence" = "Ultima occorrenza"; "Searching... (%i)" = "Ricerca in corso... (%i)"; "%i occurrences" = "%i occorrenze"; +"Meta" = "Meta"; +"Rename" = "Rinomina"; +"Last modified" = "Ultima modifica"; +"already exists" = "esiste già"; +"Are you sure you want to delete this file?" = "Sei sicuro di voler eliminare questo file?"; +"Undo" = "Annulla"; +"Redo" = "Ripeti"; +"Selection" = "Selezione"; +"Bookmarks" = "Segnalibri"; +"Slider" = "Scorrimento"; +"Night mode" = "Modalità notte"; +"Light mode" = "Modalità chiaro"; +"Thumbnail" = "Thumbnail"; +"Polygon" = "Poligono"; +"Polyline" = "Polilinea"; +"Manage pages" = "Gestione pagine"; +"Cannot add bookmark" = "Impossibile aggiungere un segnalibro"; +"Bookmark added!" = "Segnalibro aggiunto!"; +"Bookmark already exist at page" = "Segnalibro già presente a pagina"; +"No bookmark saved" = "Nessun bookmark salvato"; +"This PDF file has no outlines!" = "Questo file PDF non ha outlines!"; +"Title" = "Titolo"; +"Author" = "Autore"; +"Subject" = "Soggetto"; +"Keywords" = "Keywords"; +"Text" = "Testo"; +"Line width" = "Larghezza linea"; +"Line style" = "Stile linea"; +"Line color" = "Colore linea"; +"Fill color" = "Colore riempimento"; +"Lock" = "Blocco"; +"Locked" = "Bloccato"; +"Icon" = "Icona"; +"Line start" = "Inizio linea"; +"Line end" = "FIne linea"; +"Color" = "Colore"; +"Need password to open the PDF file." = "Serve la password per aprire il file PDF."; +"Do you confirm to delete the PDF file?" = "Confermi di voler eliminare il file pdf?"; +"Page Editing" = "Modifica pagine"; +"Attachments" = "Allegati"; +"Are you sure to delete this embedded file?" = "Sei sicuro di voler eliminare questo allegato?"; +"successfully saved" = "salvato con successo"; +"Success" = "Successo"; +"Error on adding new embedded" = "Errore durante l'aggiunta di nuovi allegati"; +"Embedded files" = "File allegati"; +"Searching" = "Ricerca in corso"; +"No more found!" = "Nessun risultato"; /* diff --git a/src/ios/PDFViewer/it.lproj/OvalColorList.plist b/src/ios/PDFViewer/it.lproj/OvalColorList.plist deleted file mode 100644 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/OvalColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/RDFileTableController.strings b/src/ios/PDFViewer/it.lproj/RDFileTableController.strings old mode 100644 new mode 100755 diff --git a/src/ios/PDFViewer/it.lproj/RDLoPDFViewController.strings b/src/ios/PDFViewer/it.lproj/RDLoPDFViewController.strings deleted file mode 100644 index 8b137891..00000000 --- a/src/ios/PDFViewer/it.lproj/RDLoPDFViewController.strings +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/ios/PDFViewer/it.lproj/RectColorList.plist b/src/ios/PDFViewer/it.lproj/RectColorList.plist deleted file mode 100755 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/RectColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/RenderList.plist b/src/ios/PDFViewer/it.lproj/RenderList.plist deleted file mode 100755 index d9b85ca3..00000000 --- a/src/ios/PDFViewer/it.lproj/RenderList.plist +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - Qualità massima - Qualità normale - Qualità bassa - - - diff --git a/src/ios/PDFViewer/it.lproj/SettingList.plist b/src/ios/PDFViewer/it.lproj/SettingList.plist deleted file mode 100755 index 0acd1e83..00000000 --- a/src/ios/PDFViewer/it.lproj/SettingList.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - %1SEARCH SETTING - - Case sensitive - Match intera parola - - %2READ SETTING - - Colore sottolineatura - Qualità render - Colore sbarramento - Modalità visualizzazione - Colore evidenziatore - Testo allineato a destra - Tieni lo schermo attivo - Colore disegno libero - Largezza disegno libero - Colore rettangolo - Colore ovale - Ripristina impostazioni di default - - - diff --git a/src/ios/PDFViewer/it.lproj/SpeedList.plist b/src/ios/PDFViewer/it.lproj/SpeedList.plist deleted file mode 100755 index d2caa46d..00000000 --- a/src/ios/PDFViewer/it.lproj/SpeedList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Più veloce - Veloce - Normale - Lento - Più lento - - - diff --git a/src/ios/PDFViewer/it.lproj/StrikeoutColorList.plist b/src/ios/PDFViewer/it.lproj/StrikeoutColorList.plist deleted file mode 100755 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/StrikeoutColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/UnderlineColorList.plist b/src/ios/PDFViewer/it.lproj/UnderlineColorList.plist deleted file mode 100755 index 73a0a890..00000000 --- a/src/ios/PDFViewer/it.lproj/UnderlineColorList.plist +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Rosso - Nero - Blu - Giallo - Bianco - - - diff --git a/src/ios/PDFViewer/it.lproj/ViewModeList.plist b/src/ios/PDFViewer/it.lproj/ViewModeList.plist deleted file mode 100755 index a72d7d74..00000000 --- a/src/ios/PDFViewer/it.lproj/ViewModeList.plist +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - Vertical - Horizontal (LTOR) - Page Curling - Paging Single Page - Paging Cover Double Page - Reflow Mode - Paging Double Page - - - diff --git a/src/ios/PDFViewer/zh-Hans.lproj/Localizable.strings b/src/ios/PDFViewer/zh-Hans.lproj/Localizable.strings old mode 100644 new mode 100755 diff --git a/src/ios/PDFViewer/zh-Hans.lproj/RDFileTableController.strings b/src/ios/PDFViewer/zh-Hans.lproj/RDFileTableController.strings old mode 100644 new mode 100755 diff --git a/src/ios/PDFViewer/zh-Hans.lproj/RDLoPDFViewController.strings b/src/ios/PDFViewer/zh-Hans.lproj/RDLoPDFViewController.strings deleted file mode 100644 index 8b137891..00000000 --- a/src/ios/PDFViewer/zh-Hans.lproj/RDLoPDFViewController.strings +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/ios/RadaeePDFPlugin.h b/src/ios/RadaeePDFPlugin.h index f473e541..7e74a984 100644 --- a/src/ios/RadaeePDFPlugin.h +++ b/src/ios/RadaeePDFPlugin.h @@ -1,6 +1,6 @@ #import -@class RDLoPDFViewController; +@class PDFReaderCtrl; @class RDPageViewController; // define the protocol for the delegate @@ -19,7 +19,7 @@ @interface RadaeePDFPlugin : CDVPlugin{ CDVInvokedUrlCommand* cdv_command; - RDLoPDFViewController *m_pdf; + PDFReaderCtrl *m_pdf; RDPageViewController *m_pdfP; NSURLConnection *pdfConn; @@ -97,6 +97,7 @@ - (void)setTitleBGColor:(CDVInvokedUrlCommand*)command; - (void)setIconsBGColor:(CDVInvokedUrlCommand*)command; - (void)setThumbHeight:(CDVInvokedUrlCommand*)command; +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command; - (void)setFirstPageCover:(CDVInvokedUrlCommand*)command; - (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand*)command; - (void)setImmersive:(CDVInvokedUrlCommand*)command; @@ -156,4 +157,23 @@ - (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command; - (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command; +- (void)refreshCurrentPage; + +//get text & markup annot details +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command;//(int)pageNum; +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command;//(int)pageNum; + +//add text annot +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command;//(int)pageNum :(float)x :(float)y :(NSString *)text :(NSString *)subject; + +//get char indexes and add markup annot +- (void)getCharIndex:(CDVInvokedUrlCommand *)command;//(int)pageNum :(float)x :(float)y; +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command;//(int)pageNum :(int)type :(int)index1 :(int)index2; + +//get screen points from pdf points +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command;//(int)x :(int)y; +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command;//(int)x :(int)y :(int)pageNum; +- (void)getPDFRect:(CDVInvokedUrlCommand *)command;//(float)x :(float)y :(float)width :(float)height; +- (void)getScreenRect:(CDVInvokedUrlCommand *)command;//(float)left :(float)top :(float)right :(float)bottom :(int)pageNum; + @end diff --git a/src/ios/RadaeePDFPlugin.m b/src/ios/RadaeePDFPlugin.m index fe65d20e..31334d14 100644 --- a/src/ios/RadaeePDFPlugin.m +++ b/src/ios/RadaeePDFPlugin.m @@ -5,8 +5,15 @@ // Created by Paolo Messina on 06/07/15. // // + +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + #import "RadaeePDFPlugin.h" -#import "RDLoPDFViewController.h" +#import "PDFReaderCtrl.h" #import "RDPageViewController.h" #import "PDFHttpStream.h" #import "RDFormManager.h" @@ -14,7 +21,7 @@ #pragma mark - Synthesize -@interface RadaeePDFPlugin() +@interface RadaeePDFPlugin() @end @@ -34,62 +41,76 @@ + (RadaeePDFPlugin *)pluginInit - (void)show:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + // Get user parameters NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; url = [params objectForKey:@"url"]; - GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; - + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ - + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; - + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; [httpStream open:url :cacheFile]; - + [self readerInit]; - - int result = [m_pdf PDFOpenStream:httpStream :[params objectForKey:@"password"]]; - - NSLog(@"%d", result); - if(result != err_ok && result != err_open){ - [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; - return; + + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int result = [doc openStream:httpStream :@""]; + + switch(result) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc:true]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + [self showReader]; + } + break; + default: { + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + } + break; } - - [self showReader]; - + + } else { if ([url containsString:@"file://"]) { - + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; - + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; } - - [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; } else { [self openFromPath:command]; } } - + } - (void)openFromAssets:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + // Get user parameters NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; url = [params objectForKey:@"url"]; - GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; - + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; - - [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; } - (void)openFromPath:(CDVInvokedUrlCommand *)command @@ -97,11 +118,11 @@ - (void)openFromPath:(CDVInvokedUrlCommand *)command // Get user parameters NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; url = [params objectForKey:@"url"]; - GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; - + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + NSString *filePath = url; - - [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; } - (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose @@ -111,27 +132,35 @@ - (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)p [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; return; } - + _lastOpenedPath = filePath; - + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; - + [self readerInit]; - + int result = 0; - + if ([self isPageViewController]) { result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; } else { - result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave suppressClose:suppressClose author:@""]; + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } } - + NSLog(@"%d", result); if(result != err_ok && result != err_open){ [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; return; } - + [self showReader]; } @@ -149,49 +178,73 @@ - (void)closeReader:(CDVInvokedUrlCommand *)command - (void)activateLicense:(CDVInvokedUrlCommand *)command { [self pluginInitialize]; - + [self copyDocumentsFromAssets]; + self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; - + [[NSUserDefaults standardUserDefaults] synchronize]; - + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = [params objectForKey:@"company"]; + g_mail = [params objectForKey:@"email"]; + g_serial = [params objectForKey:@"key"]; + [RDVGlobal Init]; - + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; } +- (void)copyDocumentsFromAssets +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) + { + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + } + } + } +} + - (void)fileState:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { - + NSString *message = @""; - + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { case 0: message = @"File has not been modified."; break; - + case 1: message = @"File has been modified but not saved."; break; - + case 2: message = @"File has been modified and saved."; break; - + default: break; } - + [self cdvOkWithMessage:message]; } else @@ -201,125 +254,125 @@ - (void)fileState:(CDVInvokedUrlCommand *)command - (void)getPageNumber:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + if (m_pdf == nil || [m_pdf getDoc] == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - + int page = 0; if (![self isPageViewController]) { - page = [m_pdf getCurrentPage]; + page = [m_pdf PDFCurPage]; } else { page = [m_pdfP getCurrentPage]; } - + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; } - (void)getPageCount:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + if (m_pdf == nil || [m_pdf getDoc] == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - - int count = [(PDFDoc *)[m_pdf getDoc] pageCount]; + + int count = [(RDPDFDoc *)[m_pdf getDoc] pageCount]; [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; } - (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; } - (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; } - (void)setReaderBGColor:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; } - (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + gridElementHeight = [[params objectForKey:@"height"] floatValue]; } - (void)setThumbGridGap:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + gridGap = [[params objectForKey:@"gap"] floatValue]; } - (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + gridMode = [[params objectForKey:@"mode"] floatValue]; } - (void)setTitleBGColor:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; } - (void)setIconsBGColor:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; } - (void)setThumbHeight:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; } - (void)getGlobal:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *name = [params objectForKey:@"name"]; id value = [RDUtils getGlobalFromString:name]; - + if (value) { [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; } @@ -328,29 +381,29 @@ - (void)getGlobal:(CDVInvokedUrlCommand *)command - (void)setGlobal:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *name = [params objectForKey:@"name"]; id value = [params objectForKey:@"value"]; - - NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; - - NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; - - NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; - - NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_suppressClose", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; - - NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; - + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_view_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_annot_color", @"g_line_annot_color", @"g_ink_color", @"g_sel_color", @"g_oval_annot_color", @"g_rect_annot_fill_color", @"g_oval_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color",@"g_find_secondary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" , @"g_thumbview_label_color", nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_annot_width", @"g_line_annot_width", @"g_oval_annot_width", @"g_swipe_speed" , @"g_swipe_distance" , @"g_tap_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_rtol", @"g_screen_awake", @"g_auto_save_doc", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_exec_js", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_hand_signature", @"g_readonly" , @"g_fake_sign", @"g_layout_rtol", @"g_auto_scale" , nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects:@"text", @"g_pdf_name", @"g_pdf_path", @"g_annot_def_author", @"g_sign_pad_descr", nil]; + if ([integerGlobals containsObject:name]) { if ([value isKindOfClass:[NSString class]]) { [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; } [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; } - + else if ([uintegerGlobals containsObject:name]) { if ([value isKindOfClass:[NSString class]]) { [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; @@ -364,7 +417,7 @@ - (void)setGlobal:(CDVInvokedUrlCommand *)command } [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; } - + else if ([boolGlobals containsObject:name]) { if ([value isKindOfClass:[NSString class]]) { @@ -372,7 +425,7 @@ - (void)setGlobal:(CDVInvokedUrlCommand *)command } [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; } - + else if ([stringGlobals containsObject:name]) { [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; } @@ -382,29 +435,29 @@ - (void)setGlobal:(CDVInvokedUrlCommand *)command - (void)setFirstPageCover:(CDVInvokedUrlCommand*)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + firstPageCover = [[params objectForKey:@"cover"] boolValue]; } - (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; } - (void)setImmersive:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + isImmersive = [[params objectForKey:@"immersive"] boolValue]; - + if (m_pdf != nil && [m_pdf getDoc] != nil) { [m_pdf setImmersive:isImmersive]; } @@ -414,19 +467,18 @@ - (void)readerInit { if( m_pdf == nil && ![self isPageViewController]) { - m_pdf = [[RDLoPDFViewController alloc] init]; + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; } if ([self isPageViewController]) { m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; } else { [m_pdf setDelegate:self]; - + [self setPagingEnabled:NO]; [self setDoublePageEnabled:YES]; - - [m_pdf setFirstPageCover:firstPageCover]; + [m_pdf setDoubleTapZoomMode:2]; - [m_pdf setImmersive:NO]; - + [m_pdf setImmersive:isImmersive]; + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; @@ -439,39 +491,32 @@ - (void)readerInit [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; - + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; - + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; - + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; - - [m_pdf setHideGridImage:YES]; - + + if (!disableToolbar && toolbarItemEdited) return; - + if (disableToolbar) { [m_pdf setHideSearchImage:YES]; [m_pdf setHideDrawImage:YES]; - [m_pdf setHideSelImage:YES]; - [m_pdf setHideUndoImage:YES]; - [m_pdf setHideRedoImage:YES]; [m_pdf setHideMoreImage:YES]; } else { [m_pdf setHideSearchImage:NO]; [m_pdf setHideDrawImage:NO]; - [m_pdf setHideSelImage:NO]; - [m_pdf setHideUndoImage:NO]; - [m_pdf setHideRedoImage:NO]; [m_pdf setHideMoreImage:NO]; } - + /* SetColor, Available features - + 0: inkColor 1: rectColor 2: underlineColor @@ -480,7 +525,7 @@ - (void)readerInit 5: ovalColor 6: selColor 7: arrowColor - + */ } } @@ -494,17 +539,15 @@ - (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command toolbarItemEdited = YES; if (![self isPageViewController] && !m_pdf) [self readerInit]; - + if ([code isEqualToString:@"btn_search"]) { [m_pdf setHideSearchImage:visibility]; } else if ([code isEqualToString:@"btn_draw"]) { [m_pdf setHideDrawImage:visibility]; - } else if ([code isEqualToString:@"btn_sel"]) { - [m_pdf setHideSelImage:visibility]; - } else if ([code isEqualToString:@"btn_undo"]) { - [m_pdf setHideUndoImage:visibility]; - } else if ([code isEqualToString:@"btn_redo"]) { - [m_pdf setHideRedoImage:visibility];; + } else if ([code isEqualToString:@"btn_view"]) { + [m_pdf setHideViewImage:visibility]; + } else if ([code isEqualToString:@"btn_thumb"]) { + [m_pdf setHideThumbImage:visibility]; } else if ([code isEqualToString:@"btn_more"]) { [m_pdf setHideMoreImage:visibility]; } @@ -516,27 +559,17 @@ - (void)showReader if (![self isPageViewController]) { //toggle thumbnail/seekbar if (bottomBar < 1){ - [m_pdf setThumbHeight:(GLOBAL.g_thumbview_height > 0) ? GLOBAL.g_thumbview_height : 50]; - //[m_pdf PDFThumbNailinit:1]; [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; } - //else - //[m_pdf PDFSeekBarInit:1]; - + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; - - //Set thumbGridView - [m_pdf setThumbGridBGColor:gridBackgroundColor]; - [m_pdf setThumbGridElementHeight:gridElementHeight]; - [m_pdf setThumbGridGap:gridGap]; - [m_pdf setThumbGridViewMode:gridMode]; - + m_pdf.hidesBottomBarWhenPushed = YES; } - - + + UINavigationController *navController; - + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; if (titleBackgroundColor != 0) { @@ -544,67 +577,67 @@ - (void)showReader } else { navController.navigationBar.barTintColor = [UIColor blackColor]; } - + if (iconsBackgroundColor != 0) { navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); } else { navController.navigationBar.tintColor = [UIColor orangeColor]; } - + [navController.navigationBar setTranslucent:NO]; - + navController.modalPresentationStyle = UIModalPresentationFullScreen; - + [self.viewController presentViewController:navController animated:YES completion:nil]; } - (void)extractTextFromPage:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + int pageNum = [[params objectForKey:@"page"] intValue]; - - PDFDoc *doc = [m_pdf getDoc]; - + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - - PDFPage *page = [doc page:pageNum]; + + RDPDFPage *page = [doc page:pageNum]; [page objsStart]; - + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; - + page = nil; } - (void)encryptDocAs:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"dst"]; NSString *userPwd = [params objectForKey:@"user_pwd"]; NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; int permission = [[params objectForKey:@"permission"] intValue]; int method = [[params objectForKey:@"method"] intValue]; NSString *idString = [params objectForKey:@"id"]; - - PDFDoc *doc = [m_pdf getDoc]; - + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; - + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; - + if (res) { [self cdvOkWithMessage:@"Success"]; } else { @@ -615,18 +648,18 @@ - (void)encryptDocAs:(CDVInvokedUrlCommand *)command - (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"path"]; - - PDFDoc *doc = [m_pdf getDoc]; - + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - + if([m_pdf addAttachmentFromPath:path]) { [self cdvOkWithMessage:@"Success"]; @@ -638,22 +671,22 @@ - (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command - (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + int pageno = [[params objectForKey:@"page"] intValue]; int index = [[params objectForKey:@"annotIndex"] intValue]; NSString *path = [params objectForKey:@"renderPath"]; int width = [[params objectForKey:@"width"] intValue]; int height = [[params objectForKey:@"height"] intValue]; - - PDFDoc *doc = [m_pdf getDoc]; - + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { [self cdvErrorWithMessage:@"Error in pdf instance"]; return; } - + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) { [self cdvOkWithMessage:@"Success"]; @@ -665,7 +698,7 @@ - (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command - (void)flatAnnots:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + if([m_pdf flatAnnots]) { [self cdvOkWithMessage:@"Success"]; @@ -676,33 +709,38 @@ - (void)flatAnnots:(CDVInvokedUrlCommand *)command - (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; int pageno = [[params objectForKey:@"page"] intValue]; - - if([m_pdf flatAnnotAtPage:pageno doc:nil]) + + if([PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]) { [self cdvOkWithMessage:@"Success"]; } else { [self cdvErrorWithMessage:@"Failure"]; } - + } - (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"path"]; - + + if(![[[path pathExtension] lowercaseString] isEqualToString:@"pdf"]) + { + path = [path stringByAppendingPathComponent:@"newFile.pdf"]; + } + if([m_pdf saveDocumentToPath:path]) { [self cdvOkWithMessage:@"Success"]; } else { [self cdvErrorWithMessage:@"Failure"]; } - + } #pragma mark - Settings @@ -725,28 +763,28 @@ - (void)setDoublePageEnabled:(BOOL)enabled - (void)setReaderViewMode:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + int mode = [[params objectForKey:@"mode"] intValue]; - - GLOBAL.g_render_mode = mode; + + GLOBAL.g_view_mode = mode; } - (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; - + disableToolbar = !enabled; } - (BOOL)isPageViewController { - if (GLOBAL.g_render_mode != 2) { + if (GLOBAL.g_view_mode != 2) { return NO; } else return YES; @@ -757,33 +795,33 @@ - (BOOL)isPageViewController - (void)addToBookmarks:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"pdfPath"]; - + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; } - (void)removeBookmark:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"pdfPath"]; - + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; } - (void)getBookmarks:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + NSString *path = [params objectForKey:@"pdfPath"]; - + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; } @@ -841,18 +879,18 @@ + (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; - + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; - + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; - + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { return @"Cannot add bookmark"; } - + NSLog(@"%@", bookMarkFile); - + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) { [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; @@ -860,7 +898,7 @@ + (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString [fileHandle seekToEndOfFile]; [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; [fileHandle closeFile]; - + return @"Add BookMark Success!"; } else { @@ -874,7 +912,7 @@ + (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; NSString *folder = [pdfPath stringByDeletingLastPathComponent]; NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; - + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; } @@ -889,7 +927,7 @@ + (NSString *)getBookmarks:(NSString *)pdfPath NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; return jsonString; } - + return @""; } @@ -901,7 +939,7 @@ + (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPa + (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath { NSMutableArray *bookmarks = [NSMutableArray array]; - + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; NSString *fName; while(fName = [fenum nextObject]) @@ -909,34 +947,34 @@ + (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileM NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); NSString *dst = [dpath stringByAppendingPathComponent:fName]; NSString *tempString; - + if(fName.length >10) { tempString = [fName pathExtension]; } - + if( [tempString isEqualToString:@"bookmark"] ) { if (pdfName.length > 0 && ![fName containsString:pdfName]) { continue; } - + //add to list. NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; NSArray *myarray =[content componentsSeparatedByString:@","]; [myarray objectAtIndex:0]; NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; - + if (withPath) { [bookmarks addObject:arr]; } else { [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; } - + } } - + return bookmarks; } #pragma mark - Delegate Methods @@ -1012,9 +1050,9 @@ - (void)setFormFieldsResult - (void)JSONFormFields:(CDVInvokedUrlCommand *)command { self.cdv_command = command; - + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; - + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; } @@ -1022,23 +1060,23 @@ - (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; - - [self cdvOkWithMessage:[fe jsonInfoForPage:(int)[params objectForKey:@"page"]]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:[[params objectForKey:@"page"]intValue]]]; } - (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; - + NSError *error; if ([params objectForKey:@"json"]) { [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; - + if (error) { [self cdvErrorWithMessage:[error description]]; } else @@ -1061,7 +1099,7 @@ - (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; [self cdvOkWithMessage:@"Success"]; } @@ -1069,7 +1107,7 @@ - (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) [self cdvOkWithMessage:@"Success"]; else @@ -1079,7 +1117,7 @@ - (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; [self cdvOkWithMessage:@"Success"]; } @@ -1087,19 +1125,19 @@ - (void)FTS_Search:(CDVInvokedUrlCommand*)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { - + // Return the JSON as string if (!didWriteFile) { NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; - + for (FTSOccurrence *occurrence in occurrences) { [jsonArray addObject:[occurrence getDictionaryFormat]]; } - + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; - + [self cdvOkWithMessage:jsonString]; } else { [self cdvOkWithMessage:@"Success"]; @@ -1110,7 +1148,7 @@ - (void)SetSearchType:(CDVInvokedUrlCommand*)command { self.cdv_command = command; NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; - + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; [self cdvOkWithMessage:@"Success"]; } @@ -1129,7 +1167,7 @@ - (void)willShowReader [_delegate willShowReader]; } */ - + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; } @@ -1140,7 +1178,7 @@ - (void)didShowReader [_delegate didShowReader]; } */ - + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; } @@ -1151,7 +1189,7 @@ - (void)willCloseReader [_delegate willCloseReader]; } */ - + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; } @@ -1162,7 +1200,7 @@ - (void)didCloseReader [_delegate didCloseReader]; } */ - + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; } @@ -1173,7 +1211,7 @@ - (void)didChangePage:(int)page [_delegate didChangePage:page]; } */ - + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; } @@ -1184,7 +1222,7 @@ - (void)didSearchTerm:(NSString *)term found:(BOOL)found [_delegate didSearchTerm:term found:found]; } */ - + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; } @@ -1195,7 +1233,7 @@ - (void)didTapOnPage:(int)page atPoint:(CGPoint)point [_delegate didTapOnPage:page atPoint:point]; } */ - + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; } @@ -1224,6 +1262,11 @@ - (void)onAnnotExported:(NSString *)path [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; } +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + #pragma mark - Path Utils - (NSString *)getCustomPath @@ -1231,30 +1274,348 @@ - (NSString *)getCustomPath NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryPath = [paths objectAtIndex:0]; NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; - + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; } - + return customDirectory; } - (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite { NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; - + BOOL res = NO; BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; - + if (exist && overwrite) { [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; } - + if (!exist) { res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; } - + return res; } +#pragma mark - get/add text and markup annot + +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + NSString *text = [params objectForKey:@"text"]; + NSString *subject = [params objectForKey:@"subject"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + if (annot) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +- (void)getCharIndex:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", [page objsGetCharIndex:x :y]]]; +} + +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + int type = [[params objectForKey:@"type"] intValue]; + int index1 = [[params objectForKey:@"index1"] intValue]; + int index2 = [[params objectForKey:@"index2"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + + if ([page addAnnotMarkup:index1 :index2 :type :color]) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +#pragma mark - PDF/Screen rect and coordinates + +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getPDFRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + float width = [[params objectForKey:@"width"] floatValue]; + float height = [[params objectForKey:@"height"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float left = [[params objectForKey:@"left"] floatValue]; + float top = [[params objectForKey:@"top"] floatValue]; + float right = [[params objectForKey:@"right"] floatValue]; + float bottom = [[params objectForKey:@"bottom"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + @end diff --git a/src/ios/RadaeePDFPlugin_BACKUP_14052.m b/src/ios/RadaeePDFPlugin_BACKUP_14052.m new file mode 100644 index 00000000..d4e13ad6 --- /dev/null +++ b/src/ios/RadaeePDFPlugin_BACKUP_14052.m @@ -0,0 +1,1657 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// + +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + +#import "RadaeePDFPlugin.h" +#import "PDFReaderCtrl.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int result = [doc openStream:httpStream :@""]; + + switch(result) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc:true]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + [self showReader]; + } + break; + default: { + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + } + break; + } + + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { +<<<<<<< .merge_file_65nIPi + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave suppressClose:suppressClose author:@""]; +======= + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } +>>>>>>> .merge_file_6VCvC9 + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView:true]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + [self copyDocumentsFromAssets]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = [params objectForKey:@"company"]; + g_mail = [params objectForKey:@"email"]; + g_serial = [params objectForKey:@"key"]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)copyDocumentsFromAssets +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) + { + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + } + } + } +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf PDFCurPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(RDPDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; +<<<<<<< .merge_file_65nIPi + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_suppressClose", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + +======= + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_view_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_annot_color", @"g_line_annot_color", @"g_ink_color", @"g_sel_color", @"g_oval_annot_color", @"g_rect_annot_fill_color", @"g_oval_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color",@"g_find_secondary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" , @"g_thumbview_label_color", nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_annot_width", @"g_line_annot_width", @"g_oval_annot_width", @"g_swipe_speed" , @"g_swipe_distance" , @"g_tap_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_rtol", @"g_screen_awake", @"g_auto_save_doc", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_exec_js", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_hand_signature", @"g_readonly" , @"g_fake_sign", @"g_layout_rtol", @"g_auto_scale" , nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects:@"text", @"g_pdf_name", @"g_pdf_path", @"g_annot_def_author", @"g_sign_pad_descr", nil]; + +>>>>>>> .merge_file_6VCvC9 + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:isImmersive]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_view"]) { + [m_pdf setHideViewImage:visibility]; + } else if ([code isEqualToString:@"btn_thumb"]) { + [m_pdf setHideThumbImage:visibility]; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if(![[[path pathExtension] lowercaseString] isEqualToString:@"pdf"]) + { + path = [path stringByAppendingPathComponent:@"newFile.pdf"]; + } + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_view_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_view_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:[[params objectForKey:@"page"]intValue]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [m_pdf refreshCurrentPage]; + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +<<<<<<< .merge_file_65nIPi +======= +#pragma mark - get/add text and markup annot + +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + NSString *text = [params objectForKey:@"text"]; + NSString *subject = [params objectForKey:@"subject"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + if (annot) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +- (void)getCharIndex:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", [page objsGetCharIndex:x :y]]]; +} + +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + int type = [[params objectForKey:@"type"] intValue]; + int index1 = [[params objectForKey:@"index1"] intValue]; + int index2 = [[params objectForKey:@"index2"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + + if ([page addAnnotMarkup:index1 :index2 :type :color]) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +#pragma mark - PDF/Screen rect and coordinates + +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getPDFRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + float width = [[params objectForKey:@"width"] floatValue]; + float height = [[params objectForKey:@"height"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float left = [[params objectForKey:@"left"] floatValue]; + float top = [[params objectForKey:@"top"] floatValue]; + float right = [[params objectForKey:@"right"] floatValue]; + float bottom = [[params objectForKey:@"bottom"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +>>>>>>> .merge_file_6VCvC9 +@end diff --git a/src/ios/RadaeePDFPlugin_BACKUP_14164.m b/src/ios/RadaeePDFPlugin_BACKUP_14164.m new file mode 100644 index 00000000..d4e13ad6 --- /dev/null +++ b/src/ios/RadaeePDFPlugin_BACKUP_14164.m @@ -0,0 +1,1657 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// + +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + +#import "RadaeePDFPlugin.h" +#import "PDFReaderCtrl.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int result = [doc openStream:httpStream :@""]; + + switch(result) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc:true]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + [self showReader]; + } + break; + default: { + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + } + break; + } + + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; +<<<<<<< .merge_file_65nIPi + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +======= + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +>>>>>>> .merge_file_6VCvC9 +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { +<<<<<<< .merge_file_65nIPi + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave suppressClose:suppressClose author:@""]; +======= + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } +>>>>>>> .merge_file_6VCvC9 + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView:true]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + [self copyDocumentsFromAssets]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = [params objectForKey:@"company"]; + g_mail = [params objectForKey:@"email"]; + g_serial = [params objectForKey:@"key"]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)copyDocumentsFromAssets +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) + { + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + } + } + } +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf PDFCurPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(RDPDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; +<<<<<<< .merge_file_65nIPi + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_suppressClose", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + +======= + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_view_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_annot_color", @"g_line_annot_color", @"g_ink_color", @"g_sel_color", @"g_oval_annot_color", @"g_rect_annot_fill_color", @"g_oval_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color",@"g_find_secondary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" , @"g_thumbview_label_color", nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_annot_width", @"g_line_annot_width", @"g_oval_annot_width", @"g_swipe_speed" , @"g_swipe_distance" , @"g_tap_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_rtol", @"g_screen_awake", @"g_auto_save_doc", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_exec_js", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_hand_signature", @"g_readonly" , @"g_fake_sign", @"g_layout_rtol", @"g_auto_scale" , nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects:@"text", @"g_pdf_name", @"g_pdf_path", @"g_annot_def_author", @"g_sign_pad_descr", nil]; + +>>>>>>> .merge_file_6VCvC9 + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:isImmersive]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_view"]) { + [m_pdf setHideViewImage:visibility]; + } else if ([code isEqualToString:@"btn_thumb"]) { + [m_pdf setHideThumbImage:visibility]; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if(![[[path pathExtension] lowercaseString] isEqualToString:@"pdf"]) + { + path = [path stringByAppendingPathComponent:@"newFile.pdf"]; + } + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_view_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_view_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:[[params objectForKey:@"page"]intValue]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [m_pdf refreshCurrentPage]; + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +<<<<<<< .merge_file_65nIPi +======= +#pragma mark - get/add text and markup annot + +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + NSString *text = [params objectForKey:@"text"]; + NSString *subject = [params objectForKey:@"subject"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + if (annot) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +- (void)getCharIndex:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", [page objsGetCharIndex:x :y]]]; +} + +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + int type = [[params objectForKey:@"type"] intValue]; + int index1 = [[params objectForKey:@"index1"] intValue]; + int index2 = [[params objectForKey:@"index2"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + + if ([page addAnnotMarkup:index1 :index2 :type :color]) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +#pragma mark - PDF/Screen rect and coordinates + +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getPDFRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + float width = [[params objectForKey:@"width"] floatValue]; + float height = [[params objectForKey:@"height"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float left = [[params objectForKey:@"left"] floatValue]; + float top = [[params objectForKey:@"top"] floatValue]; + float right = [[params objectForKey:@"right"] floatValue]; + float bottom = [[params objectForKey:@"bottom"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +>>>>>>> .merge_file_6VCvC9 +@end diff --git a/src/ios/RadaeePDFPlugin_BASE_14052.m b/src/ios/RadaeePDFPlugin_BASE_14052.m new file mode 100644 index 00000000..d153d75f --- /dev/null +++ b/src/ios/RadaeePDFPlugin_BASE_14052.m @@ -0,0 +1,1260 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// +#import "RadaeePDFPlugin.h" +#import "RDLoPDFViewController.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + int result = [m_pdf PDFOpenStream:httpStream :[params objectForKey:@"password"]]; + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave author:@""]; + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf getCurrentPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(PDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[RDLoPDFViewController alloc] init]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setFirstPageCover:firstPageCover]; + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:NO]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + [m_pdf setHideGridImage:YES]; + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideSelImage:YES]; + [m_pdf setHideUndoImage:YES]; + [m_pdf setHideRedoImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideSelImage:NO]; + [m_pdf setHideUndoImage:NO]; + [m_pdf setHideRedoImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_sel"]) { + [m_pdf setHideSelImage:visibility]; + } else if ([code isEqualToString:@"btn_undo"]) { + [m_pdf setHideUndoImage:visibility]; + } else if ([code isEqualToString:@"btn_redo"]) { + [m_pdf setHideRedoImage:visibility];; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbHeight:(GLOBAL.g_thumbview_height > 0) ? GLOBAL.g_thumbview_height : 50]; + //[m_pdf PDFThumbNailinit:1]; + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + //else + //[m_pdf PDFSeekBarInit:1]; + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + //Set thumbGridView + [m_pdf setThumbGridBGColor:gridBackgroundColor]; + [m_pdf setThumbGridElementHeight:gridElementHeight]; + [m_pdf setThumbGridGap:gridGap]; + [m_pdf setThumbGridViewMode:gridMode]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + PDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([m_pdf flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_render_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_render_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:(int)[params objectForKey:@"page"]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +@end + diff --git a/src/ios/RadaeePDFPlugin_BASE_14164.m b/src/ios/RadaeePDFPlugin_BASE_14164.m new file mode 100644 index 00000000..d153d75f --- /dev/null +++ b/src/ios/RadaeePDFPlugin_BASE_14164.m @@ -0,0 +1,1260 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// +#import "RadaeePDFPlugin.h" +#import "RDLoPDFViewController.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + int result = [m_pdf PDFOpenStream:httpStream :[params objectForKey:@"password"]]; + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave author:@""]; + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf getCurrentPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(PDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[RDLoPDFViewController alloc] init]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setFirstPageCover:firstPageCover]; + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:NO]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + [m_pdf setHideGridImage:YES]; + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideSelImage:YES]; + [m_pdf setHideUndoImage:YES]; + [m_pdf setHideRedoImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideSelImage:NO]; + [m_pdf setHideUndoImage:NO]; + [m_pdf setHideRedoImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_sel"]) { + [m_pdf setHideSelImage:visibility]; + } else if ([code isEqualToString:@"btn_undo"]) { + [m_pdf setHideUndoImage:visibility]; + } else if ([code isEqualToString:@"btn_redo"]) { + [m_pdf setHideRedoImage:visibility];; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbHeight:(GLOBAL.g_thumbview_height > 0) ? GLOBAL.g_thumbview_height : 50]; + //[m_pdf PDFThumbNailinit:1]; + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + //else + //[m_pdf PDFSeekBarInit:1]; + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + //Set thumbGridView + [m_pdf setThumbGridBGColor:gridBackgroundColor]; + [m_pdf setThumbGridElementHeight:gridElementHeight]; + [m_pdf setThumbGridGap:gridGap]; + [m_pdf setThumbGridViewMode:gridMode]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + PDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([m_pdf flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_render_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_render_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:(int)[params objectForKey:@"page"]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +@end + diff --git a/src/ios/RadaeePDFPlugin_LOCAL_14052.m b/src/ios/RadaeePDFPlugin_LOCAL_14052.m new file mode 100644 index 00000000..fe65d20e --- /dev/null +++ b/src/ios/RadaeePDFPlugin_LOCAL_14052.m @@ -0,0 +1,1260 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// +#import "RadaeePDFPlugin.h" +#import "RDLoPDFViewController.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + int result = [m_pdf PDFOpenStream:httpStream :[params objectForKey:@"password"]]; + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave suppressClose:suppressClose author:@""]; + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView:true]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf getCurrentPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(PDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_suppressClose", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[RDLoPDFViewController alloc] init]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setFirstPageCover:firstPageCover]; + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:NO]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + [m_pdf setHideGridImage:YES]; + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideSelImage:YES]; + [m_pdf setHideUndoImage:YES]; + [m_pdf setHideRedoImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideSelImage:NO]; + [m_pdf setHideUndoImage:NO]; + [m_pdf setHideRedoImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_sel"]) { + [m_pdf setHideSelImage:visibility]; + } else if ([code isEqualToString:@"btn_undo"]) { + [m_pdf setHideUndoImage:visibility]; + } else if ([code isEqualToString:@"btn_redo"]) { + [m_pdf setHideRedoImage:visibility];; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbHeight:(GLOBAL.g_thumbview_height > 0) ? GLOBAL.g_thumbview_height : 50]; + //[m_pdf PDFThumbNailinit:1]; + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + //else + //[m_pdf PDFSeekBarInit:1]; + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + //Set thumbGridView + [m_pdf setThumbGridBGColor:gridBackgroundColor]; + [m_pdf setThumbGridElementHeight:gridElementHeight]; + [m_pdf setThumbGridGap:gridGap]; + [m_pdf setThumbGridViewMode:gridMode]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + PDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([m_pdf flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_render_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_render_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:(int)[params objectForKey:@"page"]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [m_pdf refreshCurrentPage]; + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +@end diff --git a/src/ios/RadaeePDFPlugin_LOCAL_14164.m b/src/ios/RadaeePDFPlugin_LOCAL_14164.m new file mode 100644 index 00000000..fe65d20e --- /dev/null +++ b/src/ios/RadaeePDFPlugin_LOCAL_14164.m @@ -0,0 +1,1260 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// +#import "RadaeePDFPlugin.h" +#import "RDLoPDFViewController.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + int result = [m_pdf PDFOpenStream:httpStream :[params objectForKey:@"password"]]; + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue] suppressClose:[[params objectForKey:@"suppressClose"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave suppressClose:(BOOL)suppressClose +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + result = [m_pdf PDFOpen:filePath :password atPage:page readOnly:readOnly autoSave:autoSave suppressClose:suppressClose author:@""]; + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView:true]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf getCurrentPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(PDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_render_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_color", @"g_line_color", @"g_ink_color", @"g_sel_color", @"g_oval_color", @"g_rect_annot_fill_color" @"g_ellipse_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" ,nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_width", @"g_line_width", @"g_oval_width", @"g_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_right", @"g_save_doc", @"g_suppressClose", @"g_static_scale", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_execute_annot_JS", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_enable_graphical_signature", nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects: @"g_pdf_name", @"g_pdf_path", @"g_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[RDLoPDFViewController alloc] init]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setFirstPageCover:firstPageCover]; + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:NO]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + [m_pdf setHideGridImage:YES]; + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideSelImage:YES]; + [m_pdf setHideUndoImage:YES]; + [m_pdf setHideRedoImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideSelImage:NO]; + [m_pdf setHideUndoImage:NO]; + [m_pdf setHideRedoImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_sel"]) { + [m_pdf setHideSelImage:visibility]; + } else if ([code isEqualToString:@"btn_undo"]) { + [m_pdf setHideUndoImage:visibility]; + } else if ([code isEqualToString:@"btn_redo"]) { + [m_pdf setHideRedoImage:visibility];; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbHeight:(GLOBAL.g_thumbview_height > 0) ? GLOBAL.g_thumbview_height : 50]; + //[m_pdf PDFThumbNailinit:1]; + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + //else + //[m_pdf PDFSeekBarInit:1]; + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + //Set thumbGridView + [m_pdf setThumbGridBGColor:gridBackgroundColor]; + [m_pdf setThumbGridElementHeight:gridElementHeight]; + [m_pdf setThumbGridGap:gridGap]; + [m_pdf setThumbGridViewMode:gridMode]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + PDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + PDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([m_pdf flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_render_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_render_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:(int)[params objectForKey:@"page"]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [m_pdf refreshCurrentPage]; + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +@end diff --git a/src/ios/RadaeePDFPlugin_REMOTE_14052.m b/src/ios/RadaeePDFPlugin_REMOTE_14052.m new file mode 100644 index 00000000..2df433d5 --- /dev/null +++ b/src/ios/RadaeePDFPlugin_REMOTE_14052.m @@ -0,0 +1,1620 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// + +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + +#import "RadaeePDFPlugin.h" +#import "PDFReaderCtrl.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int result = [doc openStream:httpStream :@""]; + + switch(result) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc:true]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + [self showReader]; + } + break; + default: { + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + } + break; + } + + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + [self copyDocumentsFromAssets]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = [params objectForKey:@"company"]; + g_mail = [params objectForKey:@"email"]; + g_serial = [params objectForKey:@"key"]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)copyDocumentsFromAssets +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) + { + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + } + } + } +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf PDFCurPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(RDPDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_view_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_annot_color", @"g_line_annot_color", @"g_ink_color", @"g_sel_color", @"g_oval_annot_color", @"g_rect_annot_fill_color", @"g_oval_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color",@"g_find_secondary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" , @"g_thumbview_label_color", nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_annot_width", @"g_line_annot_width", @"g_oval_annot_width", @"g_swipe_speed" , @"g_swipe_distance" , @"g_tap_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_rtol", @"g_screen_awake", @"g_auto_save_doc", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_exec_js", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_hand_signature", @"g_readonly" , @"g_fake_sign", @"g_layout_rtol", @"g_auto_scale" , nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects:@"text", @"g_pdf_name", @"g_pdf_path", @"g_annot_def_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:isImmersive]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_view"]) { + [m_pdf setHideViewImage:visibility]; + } else if ([code isEqualToString:@"btn_thumb"]) { + [m_pdf setHideThumbImage:visibility]; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if(![[[path pathExtension] lowercaseString] isEqualToString:@"pdf"]) + { + path = [path stringByAppendingPathComponent:@"newFile.pdf"]; + } + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_view_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_view_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:[[params objectForKey:@"page"]intValue]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +#pragma mark - get/add text and markup annot + +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + NSString *text = [params objectForKey:@"text"]; + NSString *subject = [params objectForKey:@"subject"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + if (annot) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +- (void)getCharIndex:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", [page objsGetCharIndex:x :y]]]; +} + +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + int type = [[params objectForKey:@"type"] intValue]; + int index1 = [[params objectForKey:@"index1"] intValue]; + int index2 = [[params objectForKey:@"index2"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + + if ([page addAnnotMarkup:index1 :index2 :type :color]) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +#pragma mark - PDF/Screen rect and coordinates + +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getPDFRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + float width = [[params objectForKey:@"width"] floatValue]; + float height = [[params objectForKey:@"height"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float left = [[params objectForKey:@"left"] floatValue]; + float top = [[params objectForKey:@"top"] floatValue]; + float right = [[params objectForKey:@"right"] floatValue]; + float bottom = [[params objectForKey:@"bottom"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +@end diff --git a/src/ios/RadaeePDFPlugin_REMOTE_14164.m b/src/ios/RadaeePDFPlugin_REMOTE_14164.m new file mode 100644 index 00000000..2df433d5 --- /dev/null +++ b/src/ios/RadaeePDFPlugin_REMOTE_14164.m @@ -0,0 +1,1620 @@ +// +// AlmaZBarReaderViewController.h +// Paolo Messina +// +// Created by Paolo Messina on 06/07/15. +// +// + +#define UIColorFromRGB(rgbValue) \ +[UIColor colorWithRed:((float)((rgbValue & 0x00FF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0x0000FF00) >> 8))/255.0 \ +blue:((float)((rgbValue & 0x000000FF) >> 0))/255.0 \ +alpha:((float)((rgbValue & 0xFF000000) >> 24))/255.0] + +#import "RadaeePDFPlugin.h" +#import "PDFReaderCtrl.h" +#import "RDPageViewController.h" +#import "PDFHttpStream.h" +#import "RDFormManager.h" +#import "RDUtils.h" + +#pragma mark - Synthesize + +@interface RadaeePDFPlugin() + +@end + +@implementation RadaeePDFPlugin +@synthesize cdv_command; + +#pragma mark - Cordova Plugin + ++ (RadaeePDFPlugin *)pluginInit +{ + RadaeePDFPlugin *r = [[RadaeePDFPlugin alloc] init]; + return r; +} + +#pragma mark - Plugin API + +- (void)show:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + if([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]){ + + NSString *cacheFile = [[NSTemporaryDirectory() stringByAppendingString:@""] stringByAppendingString:@"cacheFile.pdf"]; + + PDFHttpStream *httpStream = [[PDFHttpStream alloc] init]; + [httpStream open:url :cacheFile]; + + [self readerInit]; + + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + [RDPDFDoc setOpenFlag:3]; + int result = [doc openStream:httpStream :@""]; + + switch(result) + { + case err_ok: { + [doc getLinearizedStatus]; + [m_pdf setDoc:doc:true]; + GLOBAL.g_pdf_name = [NSMutableString stringWithFormat:@"%@", [url lastPathComponent]]; + [self showReader]; + } + break; + default: { + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + } + break; + } + + + } else { + if ([url containsString:@"file://"]) { + + NSString *filePath = [url stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + filePath = [documentsDirectory stringByAppendingPathComponent:filePath]; + } + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; + } else { + [self openFromPath:command]; + } + } + +} + +- (void)openFromAssets:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = [[NSBundle mainBundle] pathForResource:url ofType:nil]; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openFromPath:(CDVInvokedUrlCommand *)command +{ + // Get user parameters + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + url = [params objectForKey:@"url"]; + GLOBAL.g_annot_def_author = ([params objectForKey:@"author"]) ? [params objectForKey:@"author"] : @""; + + NSString *filePath = url; + + [self openPdf:filePath atPage:[[params objectForKey:@"gotoPage"] intValue] withPassword:[params objectForKey:@"password"] readOnly:[[params objectForKey:@"readOnlyMode"] boolValue] autoSave:[[params objectForKey:@"automaticSave"] boolValue]]; +} + +- (void)openPdf:(NSString *)filePath atPage:(int)page withPassword:(NSString *)password readOnly:(BOOL)readOnly autoSave:(BOOL)autoSave +{ + NSLog(@"File Path: %@", filePath); + if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { + [self pdfChargeDidFailWithError:@"File not exist" andCode:200]; + return; + } + + _lastOpenedPath = filePath; + + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:0] forKey:@"fileStat"]; + + [self readerInit]; + + int result = 0; + + if ([self isPageViewController]) { + result = [m_pdfP PDFOpenAtPath:filePath withPwd:password]; + } else { + RDPDFDoc *doc = [[RDPDFDoc alloc] init]; + result = [doc open:filePath :password]; + if(!result) + { + GLOBAL.g_pdf_path = [[filePath stringByDeletingLastPathComponent] mutableCopy]; + GLOBAL.g_pdf_name = [[filePath lastPathComponent] mutableCopy]; + GLOBAL.g_auto_save_doc = autoSave; + [m_pdf setDoc:doc :page :readOnly]; + } + } + + NSLog(@"%d", result); + if(result != err_ok && result != err_open){ + [self pdfChargeDidFailWithError:@"Error open pdf" andCode:(NSInteger) result]; + return; + } + + [self showReader]; +} + +- (void)closeReader:(CDVInvokedUrlCommand *)command +{ + if (m_pdf != nil && ![self isPageViewController]) { + [m_pdf closeView]; + } + else if (m_pdfP != nil && [self isPageViewController]) + { + [m_pdfP closeView]; + } +} + +- (void)activateLicense:(CDVInvokedUrlCommand *)command +{ + [self pluginInitialize]; + [self copyDocumentsFromAssets]; + + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[NSUserDefaults standardUserDefaults] setObject:[[NSBundle mainBundle] bundleIdentifier] forKey:@"actBundleId"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"company"] forKey:@"actCompany"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"email"] forKey:@"actEmail"]; + [[NSUserDefaults standardUserDefaults] setObject:[params objectForKey:@"key"] forKey:@"actSerial"]; + [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[[params objectForKey:@"licenseType"] intValue]] forKey:@"actActivationType"]; + + [[NSUserDefaults standardUserDefaults] synchronize]; + + g_id = [[NSBundle mainBundle] bundleIdentifier]; + g_company = [params objectForKey:@"company"]; + g_mail = [params objectForKey:@"email"]; + g_serial = [params objectForKey:@"key"]; + + [RDVGlobal Init]; + + [self activateLicenseResult:[[NSUserDefaults standardUserDefaults] boolForKey:@"actIsActive"]]; +} + +- (void)copyDocumentsFromAssets +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *dpath = [paths objectAtIndex:0]; + NSString *hf = [[NSBundle mainBundle] pathForResource:@"PDFRes" ofType:nil]; + for (NSString *fpath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:hf error:nil]) { + if([fpath.pathExtension isEqualToString:@"pdf"] || [fpath.pathExtension isEqualToString:@"PDF"]) + { + NSString *documentPath = [hf stringByAppendingPathComponent:fpath]; + NSString *destPath = [dpath stringByAppendingPathComponent:fpath]; + + if(![[NSFileManager defaultManager] fileExistsAtPath:destPath]) { + [[NSFileManager defaultManager] copyItemAtPath:documentPath toPath:destPath error:nil]; + } + } + } +} + +- (void)fileState:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if ([[NSFileManager defaultManager] fileExistsAtPath:_lastOpenedPath]) { + + NSString *message = @""; + + switch ([[NSUserDefaults standardUserDefaults] integerForKey:@"fileStat"]) { + case 0: + message = @"File has not been modified."; + break; + + case 1: + message = @"File has been modified but not saved."; + break; + + case 2: + message = @"File has been modified and saved."; + break; + + default: + break; + } + + [self cdvOkWithMessage:message]; + } + else + [self cdvErrorWithMessage:@"File not found"]; +} + +- (void)getPageNumber:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int page = 0; + if (![self isPageViewController]) { + page = [m_pdf PDFCurPage]; + } else { + page = [m_pdfP getCurrentPage]; + } + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", page]]; +} + +- (void)getPageCount:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if (m_pdf == nil || [m_pdf getDoc] == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + int count = [(RDPDFDoc *)[m_pdf getDoc] pageCount]; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", count]]; +} + +- (void)setThumbnailBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setReaderBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_readerview_bg_color = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbGridElementHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridElementHeight = [[params objectForKey:@"height"] floatValue]; +} + +- (void)setThumbGridGap:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridGap = [[params objectForKey:@"gap"] floatValue]; +} + +- (void)setThumbGridViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + gridMode = [[params objectForKey:@"mode"] floatValue]; +} + +- (void)setTitleBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + titleBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setIconsBGColor:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + iconsBackgroundColor = [[params objectForKey:@"color"] intValue]; +} + +- (void)setThumbHeight:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + GLOBAL.g_thumbview_height = [[params objectForKey:@"height"] floatValue]; +} + +- (void)getGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [RDUtils getGlobalFromString:name]; + + if (value) { + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@ = %@", name, value]]; + } +} + +- (void)setGlobal:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *name = [params objectForKey:@"name"]; + id value = [params objectForKey:@"value"]; + + NSArray *integerGlobals = [NSArray arrayWithObjects: @"g_render_quality", @"g_view_mode", @"g_navigation_mode", @"g_line_annot_style1", @"g_line_annot_style2", @"g_thumbview_height", nil]; + + NSArray *uintegerGlobals = [NSArray arrayWithObjects: @"g_rect_annot_color", @"g_line_annot_color", @"g_ink_color", @"g_sel_color", @"g_oval_annot_color", @"g_rect_annot_fill_color", @"g_oval_annot_fill_color", @"g_line_annot_fill_color", @"g_annot_highlight_clr", @"g_annot_underline_clr", @"g_annot_strikeout_clr", @"g_annot_squiggly_clr", @"g_annot_transparency", @"g_find_primary_color",@"g_find_secondary_color", @"g_readerview_bg_color", @"g_thumbview_bg_color" , @"g_thumbview_label_color", nil]; + + NSArray *floatGlobals = [NSArray arrayWithObjects: @"g_ink_width", @"g_rect_annot_width", @"g_line_annot_width", @"g_oval_annot_width", @"g_swipe_speed" , @"g_swipe_distance" , @"g_tap_zoom_level", @"g_layout_zoom_level", @"g_zoom_step", nil]; + + NSArray *boolGlobals = [NSArray arrayWithObjects: @"g_case_sensitive", @"g_match_whole_word", @"g_sel_rtol", @"g_screen_awake", @"g_auto_save_doc", @"g_paging_enabled", @"g_double_page_enabled", @"g_curl_enabled", @"g_cover_page_enabled", @"g_fit_signature_to_field", @"g_exec_js", @"g_dark_mode", @"g_annot_lock", @"g_annot_readonly", @"g_auto_launch_link", @"g_highlight_annotation", @"g_hand_signature", @"g_readonly" , @"g_fake_sign", @"g_layout_rtol", @"g_auto_scale" , nil]; + + NSArray *stringGlobals = [NSArray arrayWithObjects:@"text", @"g_pdf_name", @"g_pdf_path", @"g_annot_def_author", @"g_sign_pad_descr", nil]; + + if ([integerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithInt:[value intValue]]]; + } + + else if ([uintegerGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithUnsignedInt:(uint)value]]; + } + + else if ([floatGlobals containsObject:name]) { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithFloat:[value floatValue]]]; + } + + else if ([boolGlobals containsObject:name]) + { + if ([value isKindOfClass:[NSString class]]) { + [self cdvErrorWithMessage:[NSString stringWithFormat:@"Bad property"]]; + } + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:[NSNumber numberWithBool:(BOOL)value]]; + } + + else if ([stringGlobals containsObject:name]) { + [RDUtils setGlobalFromString:[params objectForKey:@"name"] withValue:value]; + } +} + + +- (void)setFirstPageCover:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + firstPageCover = [[params objectForKey:@"cover"] boolValue]; +} + +- (void)setDoubleTapZoomMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + doubleTapZoomMode = [[params objectForKey:@"mode"] intValue]; +} + +- (void)setImmersive:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + isImmersive = [[params objectForKey:@"immersive"] boolValue]; + + if (m_pdf != nil && [m_pdf getDoc] != nil) { + [m_pdf setImmersive:isImmersive]; + } +} + +- (void)readerInit +{ + if( m_pdf == nil && ![self isPageViewController]) + { + m_pdf = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil] instantiateViewControllerWithIdentifier:@"rdpdfreader"]; + } if ([self isPageViewController]) { + m_pdfP = [[RDPageViewController alloc] initWithNibName:@"RDPageViewController" bundle:nil]; + } else { + [m_pdf setDelegate:self]; + + [self setPagingEnabled:NO]; + [self setDoublePageEnabled:YES]; + + [m_pdf setDoubleTapZoomMode:2]; + [m_pdf setImmersive:isImmersive]; + + [m_pdf setViewModeImage:[UIImage imageNamed:@"btn_view.png"]]; + [m_pdf setSearchImage:[UIImage imageNamed:@"btn_search.png"]]; + [m_pdf setLineImage:[UIImage imageNamed:@"btn_annot_ink.png"]]; + [m_pdf setRectImage:[UIImage imageNamed:@"btn_annot_rect.png"]]; + [m_pdf setEllipseImage:[UIImage imageNamed:@"btn_annot_ellipse.png"]]; + [m_pdf setOutlineImage:[UIImage imageNamed:@"btn_outline.png"]]; + [m_pdf setPrintImage:[UIImage imageNamed:@"btn_print.png"]]; + [m_pdf setGridImage:[UIImage imageNamed:@"btn_grid.png"]]; + [m_pdf setUndoImage:[UIImage imageNamed:@"btn_undo.png"]]; + [m_pdf setRedoImage:[UIImage imageNamed:@"btn_redo.png"]]; + [m_pdf setMoreImage:[UIImage imageNamed:@"btn_more.png"]]; + [m_pdf setRemoveImage:[UIImage imageNamed:@"annot_remove.png"]]; + + [m_pdf setPrevImage:[UIImage imageNamed:@"btn_left.png"]]; + [m_pdf setNextImage:[UIImage imageNamed:@"btn_right.png"]]; + + [m_pdf setPerformImage:[UIImage imageNamed:@"btn_perform.png"]]; + [m_pdf setDeleteImage:[UIImage imageNamed:@"btn_remove.png"]]; + + [m_pdf setDoneImage:[UIImage imageNamed:@"btn_done.png"]]; + + + if (!disableToolbar && toolbarItemEdited) + return; + + if (disableToolbar) { + [m_pdf setHideSearchImage:YES]; + [m_pdf setHideDrawImage:YES]; + [m_pdf setHideMoreImage:YES]; + } else { + [m_pdf setHideSearchImage:NO]; + [m_pdf setHideDrawImage:NO]; + [m_pdf setHideMoreImage:NO]; + } + + /* + SetColor, Available features + + 0: inkColor + 1: rectColor + 2: underlineColor + 3: strikeoutColor + 4: highlightColor + 5: ovalColor + 6: selColor + 7: arrowColor + + */ + } +} + +- (void)setBarButtonVisibility:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + NSString *code = [params objectForKey:@"code"]; + BOOL visibility = ![[params objectForKey:@"visibility"] boolValue]; + toolbarItemEdited = YES; + if (![self isPageViewController] && !m_pdf) + [self readerInit]; + + if ([code isEqualToString:@"btn_search"]) { + [m_pdf setHideSearchImage:visibility]; + } else if ([code isEqualToString:@"btn_draw"]) { + [m_pdf setHideDrawImage:visibility]; + } else if ([code isEqualToString:@"btn_view"]) { + [m_pdf setHideViewImage:visibility]; + } else if ([code isEqualToString:@"btn_thumb"]) { + [m_pdf setHideThumbImage:visibility]; + } else if ([code isEqualToString:@"btn_more"]) { + [m_pdf setHideMoreImage:visibility]; + } +} + +- (void)showReader +{ + [self pdfChargeDidFinishLoading]; + if (![self isPageViewController]) { + //toggle thumbnail/seekbar + if (bottomBar < 1){ + [m_pdf setThumbnailBGColor:GLOBAL.g_thumbview_bg_color]; + } + + [m_pdf setReaderBGColor:GLOBAL.g_readerview_bg_color]; + + m_pdf.hidesBottomBarWhenPushed = YES; + } + + + UINavigationController *navController; + + navController = [[UINavigationController alloc] initWithRootViewController:([self isPageViewController]) ? m_pdfP : m_pdf]; + + if (titleBackgroundColor != 0) { + navController.navigationBar.barTintColor = UIColorFromRGB(titleBackgroundColor); + } else { + navController.navigationBar.barTintColor = [UIColor blackColor]; + } + + if (iconsBackgroundColor != 0) { + navController.navigationBar.tintColor = UIColorFromRGB(iconsBackgroundColor); + } else { + navController.navigationBar.tintColor = [UIColor orangeColor]; + } + + [navController.navigationBar setTranslucent:NO]; + + navController.modalPresentationStyle = UIModalPresentationFullScreen; + + [self.viewController presentViewController:navController animated:YES completion:nil]; +} + +- (void)extractTextFromPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + [page objsStart]; + + [self cdvOkWithMessage:[page objsString:0 :page.objsCount]]; + + page = nil; +} + +- (void)encryptDocAs:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"dst"]; + NSString *userPwd = [params objectForKey:@"user_pwd"]; + NSString *ownerPwd = [params objectForKey:@"owner_pwd"]; + int permission = [[params objectForKey:@"permission"] intValue]; + int method = [[params objectForKey:@"method"] intValue]; + NSString *idString = [params objectForKey:@"id"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + unsigned char *c = (unsigned char *)[idString cStringUsingEncoding:NSUTF8StringEncoding]; + + bool res = [doc encryptAs:path :userPwd :ownerPwd :permission :method :c]; + + if (res) { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)addAnnotAttachment:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf addAttachmentFromPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)renderAnnotToFile:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int pageno = [[params objectForKey:@"page"] intValue]; + int index = [[params objectForKey:@"annotIndex"] intValue]; + NSString *path = [params objectForKey:@"renderPath"]; + int width = [[params objectForKey:@"width"] intValue]; + int height = [[params objectForKey:@"height"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Error in pdf instance"]; + return; + } + + if([m_pdf saveImageFromAnnotAtIndex:index atPage:pageno savePath:path size:CGSizeMake(width, height)]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} + +- (void)flatAnnots:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + if([m_pdf flatAnnots]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } +} +- (void)flatAnnotAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageno = [[params objectForKey:@"page"] intValue]; + + if([PDFReaderCtrl flatAnnotAtPage:pageno doc:nil]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} +- (void)saveDocumentToPath:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"path"]; + + if(![[[path pathExtension] lowercaseString] isEqualToString:@"pdf"]) + { + path = [path stringByAppendingPathComponent:@"newFile.pdf"]; + } + + if([m_pdf saveDocumentToPath:path]) + { + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + +} + +#pragma mark - Settings + +- (void)toggleThumbSeekBar:(int)mode +{ + bottomBar = mode; +} + +- (void)setPagingEnabled:(BOOL)enabled +{ + GLOBAL.g_paging_enabled = enabled; +} + +- (void)setDoublePageEnabled:(BOOL)enabled +{ + GLOBAL.g_double_page_enabled = enabled; +} + +- (void)setReaderViewMode:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + int mode = [[params objectForKey:@"mode"] intValue]; + + GLOBAL.g_view_mode = mode; +} + +- (void)setToolbarEnabled:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + BOOL enabled = [[params objectForKey:@"enabled"] boolValue]; + + disableToolbar = !enabled; +} + +- (BOOL)isPageViewController +{ + if (GLOBAL.g_view_mode != 2) { + return NO; + } + else return YES; +} + +#pragma mark - Bookmarks + +- (void)addToBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin addToBookmarks:path page:[[params objectForKey:@"page"] intValue] label:[params objectForKey:@"label"]]]; +} + +- (void)removeBookmark:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [RadaeePDFPlugin removeBookmark:[[params objectForKey:@"page"] intValue] pdfPath:path]; +} + +- (void)getBookmarks:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + NSString *path = [params objectForKey:@"pdfPath"]; + + [self cdvOkWithMessage:[RadaeePDFPlugin getBookmarks:path]]; +} + +#pragma mark - Callbacks + +- (void)willShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willShowReader = command; +} +- (void)didShowReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didShowReader = command; +} +- (void)willCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_willCloseReader = command; +} +- (void)didCloseReaderCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didCloseReader = command; +} +- (void)didChangePageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didChangePage = command; +} +- (void)didSearchTermCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didSearchTerm = command; +} +- (void)didTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnPage = command; +} +- (void)didDoubleTapOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didDoubleTapOnPage = command; +} + +- (void)didLongPressOnPageCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didLongPressOnPage = command; +} +- (void)didTapOnAnnotationOfTypeCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_didTapOnAnnotationOfType = command; +} + +- (void)onAnnotExportedCallback:(CDVInvokedUrlCommand *)command +{ + self.cdv_onAnnotExported = command; +} + ++ (NSString *)addToBookmarks:(NSString *)pdfPath page:(int)page label:(NSString *)label +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *tempName = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *tempFile = [tempName stringByAppendingFormat:@"%d%@",page,@".bookmark"]; + + NSString *fileContent = [NSString stringWithFormat:@"%i",page]; + NSString *BookMarkDir = [pdfPath stringByDeletingLastPathComponent]; + + NSString *bookMarkFile = [BookMarkDir stringByAppendingPathComponent:tempFile]; + + if (![[NSFileManager defaultManager] isWritableFileAtPath:BookMarkDir]) { + return @"Cannot add bookmark"; + } + + NSLog(@"%@", bookMarkFile); + + if(![[NSFileManager defaultManager] fileExistsAtPath:bookMarkFile]) + { + [[NSFileManager defaultManager]createFileAtPath:bookMarkFile contents:nil attributes:nil]; + NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:bookMarkFile]; + [fileHandle seekToEndOfFile]; + [fileHandle writeData:[fileContent dataUsingEncoding:NSUTF8StringEncoding]]; + [fileHandle closeFile]; + + return @"Add BookMark Success!"; + } + else { + return @"BookMark Already Exist"; + } +} + ++ (void)removeBookmark:(int)page pdfPath:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + NSString *item = [[pdfPath lastPathComponent] stringByDeletingPathExtension]; + NSString *folder = [pdfPath stringByDeletingLastPathComponent]; + NSString *bookmarkFile = [folder stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%i.bookmark", item, page]]; + + if ([[NSFileManager defaultManager] fileExistsAtPath:bookmarkFile]) { + [[NSFileManager defaultManager] removeItemAtPath:bookmarkFile error:nil]; + } +} + ++ (NSString *)getBookmarks:(NSString *)pdfPath +{ + pdfPath = [pdfPath stringByReplacingOccurrencesOfString:@"file://" withString:@""]; + if ([[NSFileManager defaultManager] fileExistsAtPath:pdfPath]) { + NSMutableArray *bookmarks = [RadaeePDFPlugin loadBookmarkForPdf:pdfPath withPath:NO]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:bookmarks options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + return jsonString; + } + + return @""; +} + ++ (NSMutableArray *)loadBookmarkForPdf:(NSString *)pdfPath withPath:(BOOL)withPath +{ + return [RadaeePDFPlugin addBookMarks:[pdfPath stringByDeletingLastPathComponent] :@"" :[NSFileManager defaultManager] pdfName:[[pdfPath lastPathComponent] stringByDeletingPathExtension] withPath:withPath]; +} + ++ (NSMutableArray *)addBookMarks:(NSString *)dpath :(NSString *)subdir :(NSFileManager *)fm pdfName:(NSString *)pdfName withPath:(BOOL)withPath +{ + NSMutableArray *bookmarks = [NSMutableArray array]; + + NSDirectoryEnumerator *fenum = [fm enumeratorAtPath:dpath]; + NSString *fName; + while(fName = [fenum nextObject]) + { + NSLog(@"%@", [dpath stringByAppendingPathComponent:fName]); + NSString *dst = [dpath stringByAppendingPathComponent:fName]; + NSString *tempString; + + if(fName.length >10) + { + tempString = [fName pathExtension]; + } + + if( [tempString isEqualToString:@"bookmark"] ) + { + if (pdfName.length > 0 && ![fName containsString:pdfName]) { + continue; + } + + //add to list. + NSFileHandle *fileHandle =[NSFileHandle fileHandleForReadingAtPath:dst]; + NSString *content = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding]; + NSArray *myarray =[content componentsSeparatedByString:@","]; + [myarray objectAtIndex:0]; + NSArray *arr = [[NSArray alloc] initWithObjects:[myarray objectAtIndex:0],dst,nil]; + + if (withPath) { + [bookmarks addObject:arr]; + } else { + [bookmarks addObject:@{@"Page:": [NSNumber numberWithInteger:[[myarray objectAtIndex:0] intValue]], @"Label": @""}]; + } + + } + } + + return bookmarks; +} +#pragma mark - Delegate Methods + +- (void)activateLicenseResult:(BOOL)success +{ + if (success) { + [self.commandDelegate sendPluginResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"License activated"] callbackId:[self.cdv_command callbackId]]; + } + else + { + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"License NOT activated"] callbackId:[self.cdv_command callbackId]]; + } +} + +- (void)chargePdfSendResult:(CDVPluginResult*)result +{ + //m_pdf = nil; + [self.commandDelegate sendPluginResult:result callbackId: [self.cdv_command callbackId]]; +} + +- (void)pdfChargeDidFinishLoading +{ + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus:CDVCommandStatus_OK + messageAsString:@"Pdf Succesfully charged"]]; +} + +- (void)pdfChargeDidFailWithError:(NSString*)errorMessage andCode:(NSInteger)statusCode{ + //if(m_pdf) + //[m_pdf dismissViewControllerAnimated:YES completion:nil]; + NSDictionary *dict = @{@"errorMessage" : errorMessage, @"statusCode" : [NSNumber numberWithInteger:statusCode]}; + [self chargePdfSendResult:[CDVPluginResult + resultWithStatus: CDVCommandStatus_ERROR + messageAsDictionary:dict]]; +} + +- (void)cdvSendDictCallback:(NSDictionary *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvSendCallback:(NSString *)message orCommand:(CDVInvokedUrlCommand *)command +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallbackAsBool:YES]; + [self.commandDelegate sendPluginResult:res callbackId:[command callbackId]]; +} + +- (void)cdvOkWithMessage:(NSString *)message +{ + CDVPluginResult *res = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message]; + [res setKeepCallback:0]; + [self.commandDelegate sendPluginResult:res callbackId:[self.cdv_command callbackId]]; +} + +- (void)cdvErrorWithMessage:(NSString *)errorMessage +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:errorMessage] callbackId:[self.cdv_command callbackId]]; +} + +- (void)setFormFieldsResult +{ + [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:[self.cdv_command callbackId]]; +} + +#pragma mark - Form Extractor + +- (void)JSONFormFields:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForAllPages]]; +} + +- (void)JSONFormFieldsAtPage:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + [self cdvOkWithMessage:[fe jsonInfoForPage:[[params objectForKey:@"page"]intValue]]]; +} + +- (void)setFormFieldWithJSON:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + RDFormManager *fe = [[RDFormManager alloc] initWithDoc:[m_pdf getDoc]]; + + NSError *error; + if ([params objectForKey:@"json"]) { + [fe setInfoWithJson:[params objectForKey:@"json"] error:&error]; + + if (error) { + [self cdvErrorWithMessage:[error description]]; + } else + { + if (m_pdf) { + [[NSNotificationCenter defaultCenter] postNotificationName:@"Radaee-Refresh-Page" object:nil]; + } + [self setFormFieldsResult]; + } + } else + { + [self cdvErrorWithMessage:@"JSON not found"]; + } +} + +#pragma mark - FTS Methods +#ifdef FTS_ENABLED +- (void)FTS_SetIndexDB:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_SetIndexDB:[params objectForKey:@"dbPath"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_AddIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + if([[FTSManager sharedInstance] FTS_AddIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]) + [self cdvOkWithMessage:@"Success"]; + else + [self cdvErrorWithMessage:@"Failure"]; +} +- (void)FTS_RemoveFromIndex:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_RemoveFromIndex:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)FTS_Search:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] FTS_Search:[params objectForKey:@"term"] filter:[params objectForKey:@"filePath"] password:[params objectForKey:@"password"] writeJSON:[params objectForKey:@"resultPath"] success:^(NSMutableArray *occurrences, BOOL didWriteFile) { + + // Return the JSON as string + if (!didWriteFile) { + NSMutableArray *jsonArray = [NSMutableArray arrayWithCapacity:occurrences.count]; + + for (FTSOccurrence *occurrence in occurrences) { + [jsonArray addObject:[occurrence getDictionaryFormat]]; + } + + NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:jsonString]; + } else { + [self cdvOkWithMessage:@"Success"]; + } + }]; +} +- (void)SetSearchType:(CDVInvokedUrlCommand*)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + + [[FTSManager sharedInstance] SetSearchType:[[params objectForKey:@"type"] intValue]]; + [self cdvOkWithMessage:@"Success"]; +} +- (void)GetSearchType:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i",[[FTSManager sharedInstance] GetSearchType]]]; +} +#endif +#pragma mark - Reader Delegate + +- (void)willShowReader +{ + /* + if (_delegate) { + [_delegate willShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willShowReader]; +} + +- (void)didShowReader +{ + /* + if (_delegate) { + [_delegate didShowReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didShowReader]; +} + +- (void)willCloseReader +{ + /* + if (_delegate) { + [_delegate willCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_willCloseReader]; +} + +- (void)didCloseReader +{ + /* + if (_delegate) { + [_delegate didCloseReader]; + } + */ + + [self cdvSendCallback:@"" orCommand:self.cdv_didCloseReader]; +} + +- (void)didChangePage:(int)page +{ + /* + if (_delegate) { + [_delegate didChangePage:page]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didChangePage]; +} + +- (void)didSearchTerm:(NSString *)term found:(BOOL)found +{ + /* + if (_delegate) { + [_delegate didSearchTerm:term found:found]; + } + */ + + [self cdvSendCallback:term orCommand:self.cdv_didSearchTerm]; +} + +- (void)didTapOnPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnPage:page atPoint:point]; + } + */ + + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didTapOnPage]; +} + +- (void)didDoubleTapOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didDoubleTapOnPage]; +} + +- (void)didLongPressOnPage:(int)page atPoint:(CGPoint)point +{ + [self cdvSendCallback:[NSString stringWithFormat:@"%i", page] orCommand:self.cdv_didLongPressOnPage]; +} + +- (void)didTapOnAnnotationOfType:(int)type atPage:(int)page atPoint:(CGPoint)point +{ + /* + if (_delegate) { + [_delegate didTapOnAnnotationOfType:type atPage:page atPoint:point]; + } + */ + [self cdvSendDictCallback:@{@"index": [NSNumber numberWithInt:page], @"type": [NSNumber numberWithInt:type]} orCommand:self.cdv_didTapOnAnnotationOfType]; +} + +- (void)onAnnotExported:(NSString *)path +{ + [self cdvSendCallback:path orCommand:self.cdv_onAnnotExported]; +} + +- (void)refreshCurrentPage +{ + //[m_pdf updateAllPages]; +} + +#pragma mark - Path Utils + +- (NSString *)getCustomPath +{ + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *libraryPath = [paths objectAtIndex:0]; + NSString *customDirectory = [libraryPath stringByAppendingPathComponent:@"customDirectory"]; + + if (![[NSFileManager defaultManager] fileExistsAtPath:customDirectory]) { + [[NSFileManager defaultManager] createDirectoryAtPath:customDirectory withIntermediateDirectories:NO attributes:nil error:nil]; + } + + return customDirectory; +} + +- (BOOL)moveFileToCustomDir:(NSString *)path overwrite:(BOOL)overwrite +{ + NSString *itemPath = [[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]]; + + BOOL res = NO; + BOOL exist = [[NSFileManager defaultManager] fileExistsAtPath:itemPath]; + + if (exist && overwrite) { + [[NSFileManager defaultManager] removeItemAtPath:itemPath error:nil]; + } + + if (!exist) { + res = [[NSFileManager defaultManager] copyItemAtPath:path toPath:[[self getCustomPath] stringByAppendingPathComponent:[path lastPathComponent]] error:nil]; + } + + return res; +} + +#pragma mark - get/add text and markup annot + +- (void)getTextAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type == 1) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[annot getPopupText] forKey:@"text"]; + [dict setObject:[annot getPopupSubject] forKey:@"subject"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getMarkupAnnotationDetails:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + NSMutableArray *array = [NSMutableArray array]; + NSString *json = @""; + + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + for (int c = 0; c < [page annotCount]; c++) { + RDPDFAnnot *annot = [page annotAtIndex:c]; + //detect if is annot text + if (annot.type >= 9 && annot.type <= 12) { + NSMutableDictionary *dict = [NSMutableDictionary dictionary]; + PDF_RECT rect; + [annot getRect:&rect]; + [dict setObject:[NSNumber numberWithInt:[annot getIndex]] forKey:@"index"]; + [dict setObject:[NSNumber numberWithFloat:rect.top] forKey:@"top"]; + [dict setObject:[NSNumber numberWithFloat:rect.left] forKey:@"left"]; + [dict setObject:[NSNumber numberWithFloat:rect.right] forKey:@"right"]; + [dict setObject:[NSNumber numberWithFloat:rect.bottom] forKey:@"bottom"]; + [dict setObject:[NSNumber numberWithInt:[annot type]] forKey:@"type"]; + [array addObject:dict]; + } + } + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; + json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + page = nil; + doc = nil; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)addTextAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + NSString *text = [params objectForKey:@"text"]; + NSString *subject = [params objectForKey:@"subject"]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + PDF_POINT pt; + pt.x = x; + pt.y = y; + [page addAnnotNote:&pt]; + + RDPDFAnnot *annot = [page annotAtIndex:[page annotCount]-1]; + [annot setPopupText:text]; + [annot setPopupSubject:subject]; + + if (annot) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +- (void)getCharIndex:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + if (m_pdf == nil || doc == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + [page objsStart]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%i", [page objsGetCharIndex:x :y]]]; +} + +- (void)addMarkupAnnotation:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + int pageNum = [[params objectForKey:@"page"] intValue]; + int type = [[params objectForKey:@"type"] intValue]; + int index1 = [[params objectForKey:@"index1"] intValue]; + int index2 = [[params objectForKey:@"index2"] intValue]; + + RDPDFDoc *doc = [m_pdf getDoc]; + + if (m_pdf == nil || doc == nil) { + return; + } + + RDPDFPage *page = [doc page:pageNum]; + + if (page == nil) { + return; + } + + [page objsStart]; + + int color = GLOBAL.g_annot_highlight_clr; + if( type == 1 ) color = GLOBAL.g_annot_underline_clr; + if( type == 2 ) color = GLOBAL.g_annot_strikeout_clr; + if( type == 4 ) color = GLOBAL.g_annot_squiggly_clr; + + if ([page addAnnotMarkup:index1 :index2 :type :color]) { + [doc save]; + [m_pdf updatePage:pageNum]; + [self cdvOkWithMessage:@"Success"]; + } else { + [self cdvErrorWithMessage:@"Failure"]; + } + + page = nil; + doc = nil; +} + +#pragma mark - PDF/Screen rect and coordinates + +- (void)getPDFCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf pdfPointsFromScreenPoints:x :y]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenCoordinates:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGPoint pdfPoints = [m_pdf screenPointsFromPdfPoints:x :y :pageNum]; + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:pdfPoints.x], @"x",[NSNumber numberWithInt:pdfPoints.y], @"y", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getPDFRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float x = [[params objectForKey:@"x"] floatValue]; + float y = [[params objectForKey:@"y"] floatValue]; + float width = [[params objectForKey:@"width"] floatValue]; + float height = [[params objectForKey:@"height"] floatValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + NSArray *arect = [m_pdf pdfRectFromScreenRect:CGRectMake(x, y, width, height)]; + + PDF_RECT rect; + rect.top = [[arect objectAtIndex:0] floatValue]; + rect.left = [[arect objectAtIndex:1] floatValue]; + rect.right = [[arect objectAtIndex:2] floatValue]; + rect.bottom = [[arect objectAtIndex:3] floatValue]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.top], @"top", [NSNumber numberWithFloat:rect.left], @"left",[NSNumber numberWithFloat:rect.right], @"right",[NSNumber numberWithFloat:rect.bottom], @"bottom", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +- (void)getScreenRect:(CDVInvokedUrlCommand *)command +{ + self.cdv_command = command; + NSDictionary *params = (NSDictionary*) [cdv_command argumentAtIndex:0]; + float left = [[params objectForKey:@"left"] floatValue]; + float top = [[params objectForKey:@"top"] floatValue]; + float right = [[params objectForKey:@"right"] floatValue]; + float bottom = [[params objectForKey:@"bottom"] floatValue]; + int pageNum = [[params objectForKey:@"page"] intValue]; + + if (m_pdf == nil) { + [self cdvErrorWithMessage:@"Failure"]; + return; + } + + CGRect rect = [m_pdf screenRectFromPdfRect:left :top :right :bottom :pageNum]; + + NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:rect.origin.x], @"x",[NSNumber numberWithFloat:rect.origin.y], @"y",[NSNumber numberWithFloat:rect.size.width], @"width",[NSNumber numberWithFloat:rect.size.height], @"height", nil]; + + NSError *error; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; + NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + + [self cdvOkWithMessage:[NSString stringWithFormat:@"%@", json]]; +} + +@end diff --git a/src/ios/docs/global_variant_ios.pdf b/src/ios/docs/global_variant_ios.pdf new file mode 100644 index 00000000..96ad49dc Binary files /dev/null and b/src/ios/docs/global_variant_ios.pdf differ diff --git a/src/ios/docs/license.pdf b/src/ios/docs/license.pdf index d43c6996..961b3386 100644 Binary files a/src/ios/docs/license.pdf and b/src/ios/docs/license.pdf differ diff --git a/src/ios/docs/release_history_ios.txt b/src/ios/docs/release_history_ios.txt index 2306bf2f..9955f17c 100755 --- a/src/ios/docs/release_history_ios.txt +++ b/src/ios/docs/release_history_ios.txt @@ -1,22 +1,129 @@ PDFViewer SDK for iOS - Release notes -3.74 +4.6.4 +- FIX paging issue on single and double pages +- FIX thumbnail issues on horizontal pages +- FIX crash issues caused by invalid data + +4.6.3 +- NEW GLOBAL.g_disable_text_copy +- NEW search progress bar +- FIX checkbox when wrong value is set to the field + +4.6.2 +- FIX jpg decoding issue +- FIX Auto generate checked icon of checkbox when icon of checkbox is empty +- FIX Code cleanup + +4.6.1 +- UPDATE changed native class names to make it compatible with PDFKit.framework by Apple +- FIX Italian localization +- FIX Rendering issues + +4.6 +- NEW objsStart support rtol now. +- UPDATE core lib +- FIX Polygon and Polyline color palette +- FIX Stamp crash when size < 0 +- FIX Signature issue. +- FIX Layout issue for vertical and horizontal layout. + +4.5.4 +- NEW GLOBAL.g_layout_rtol option +- UPDATE core lib to fix some special case rendering glitch +- UPDATE GLOBAL.g_render_mode renamed to GLOBAL.g_view_mode +- FIX rendering issue for RTOL in dual mode +- FIX Double page with first page single +- FIX Zoom scale values +- FIX Curl / PageView crash +- FIX Share pdf crash +- FIX Form Fields background color changed from yellow to light blue +- FIX Form Fields Text color changed from white to black + +4.5.3 +- FIX CMYK->RGB conversion may bring to unexpected crash during some special bitmap decoding + +4.5.2 +-fix dark mode status bar + +4.5.1 +- Font mapping improvement. +- found a memory leak for bitmap scaling(very long time ago to adjust scaling algorithm). +- added GLOBAL.g_readonly to make the reader in readonly mode +- fix readonly pdf +- fix Slider/Thumbnail and Night Mode/Light Mode button + +4.5 +- Improved the page browsing experience when single page mode is set +- Added Polygon annotation- Added Polyline annotation +- Bookmark functionality is restored from 3.7x +- Improved the support to M1 architecture +- Minor fix + +4.4 - FIX render issue +- Adapted classes for modules compatibility - FIX set/get popup text/subject issue - -3.73 +- FIX bad linearized header loading issue +- FIX specific editbox crash +- Minor fixes +- FIX missing outlines issue +- FIX indirect stream object references issue (on importing context) +- FIX minor fixes and clean up +- FIX font loading during framework startup +- Code cleanup + +4.3 - NEW method to get name of signer - EDIT SignField method: add a parameter to set name of signer -3.72 +4.2 - NEW PDFSign features - getFieldName methods will return original name without remove blanks - CHANGE libjpeg marco JDCT_DEFAULT from JDCT_ISLOW to JDCT_IFAST - ADD thumbview label's color global - FIX OOM issue for special condition +4.1 +- ADD create edit box feature +- NEW static method to set open flag, relate to linearized PDF +- NEW method to get linearized pdf status +- FIX issue loop all page objects in layout time +- ENHANCED PDFHttpStream class, removed all deprecated ios class +- ENHANCED PDFHttpStream class, fix http issue +- ADD get pdf/screen point feature +- ADD get pdf/screen rect feature +- ADD signature annot management +- FIX crash issue on field just signed + +4.0 +- NEW UI +- NEW reader controller class PDFReaderCtrl +- NEW Storyboard-based reader controller +- NEW menu classes (search, annot, view mode, more) +- REMOVED bookmarks and setting view controllers +- REMOVED Modules folder +- ADD lock/unlock feature in annot's menu operations +- ADD case/whole search features in search mode +- NEW file collection view +- NEW imageset +- NEW toolbars UI +- NEW toolbars' feature (switch and show thumb/slider, night mode, meta) +- NEW color picker +- NEW search mode UI +- NEW full text search feature +- NEW popup text view UI +- NEW outline view UI +- NEW annots' properties UI +- ADD support for dark mode +- FIX minor UI issues +- FIX crash issue when linerazed data damaged +- FIX open from url issue +- FIX specific pdf crash issue +- ADD edit pages feature + 3.71 -- FIX issue for ImportAnnot when page is rotated page +- FIX issue for ImportAnnot when page is rotated - FIX ink annotation import - FIX OverPrint when issue - CalRGB colorspace enhanced @@ -26,17 +133,6 @@ PDFViewer SDK for iOS - Release notes - CHANGE iOS build option "iOS Deployment Target" to "iOS 8.0". - SetInkPath will calculate annotation area automatically - FIX square and circle annotation issue on setRect -- FIX crash issue when linerazed data damaged -- FIX crash issue for special PDF file -- NEW addAnnotEditText feature -- NEW static method to set open flag, relate to linearized PDF -- NEW method to get linearized pdf status -- FIX issue loop all page objects in layout time -- ENHANCED PDFHttpStream class, removed all deprecated ios class -- ENHANCED PDFHttpStream class, fix http issue -- ADD get pdf/screen point feature -- ADD get pdf/screen rect feature -- FIX crash issue on field just signed 3.70 - NEW annots' properties feature diff --git a/www/RadaeePDFPlugin.js b/www/RadaeePDFPlugin.js index 95ca92b6..f733388d 100644 --- a/www/RadaeePDFPlugin.js +++ b/www/RadaeePDFPlugin.js @@ -235,6 +235,77 @@ RadaeePDFPlugin.prototype.setGlobal = function (params, successCallback, errorCa exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'setGlobal', [params]); }; + +RadaeePDFPlugin.prototype.refreshCurrentPage = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'refreshCurrentPage', [params]); +}; + +RadaeePDFPlugin.prototype.getTextAnnotationDetails = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getTextAnnotationDetails', [params]); +}; + +RadaeePDFPlugin.prototype.getMarkupAnnotationDetails = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getMarkupAnnotationDetails', [params]); +}; + +RadaeePDFPlugin.prototype.addTextAnnotation = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'addTextAnnotation', [params]); +}; + +RadaeePDFPlugin.prototype.getCharIndex = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getCharIndex', [params]); +}; + +RadaeePDFPlugin.prototype.addMarkupAnnotation = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'addMarkupAnnotation', [params]); +}; + +RadaeePDFPlugin.prototype.getPDFCoordinates = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getPDFCoordinates', [params]); +}; + +RadaeePDFPlugin.prototype.getScreenCoordinates = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getScreenCoordinates', [params]); +}; + +RadaeePDFPlugin.prototype.getPDFRect = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getPDFRect', [params]); +}; + +RadaeePDFPlugin.prototype.getScreenRect = function (params, successCallback, errorCallback) { + //iOS only + params = params || {}; + + exec(successCallback, errorCallback, 'RadaeePDFPlugin', 'getScreenRect', [params]); +}; + // Callbacks RadaeePDFPlugin.prototype.willShowReaderCallback = function (successCallback) {