PageRenderTime 65ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/pptx/src/com/example/poipptxnew/OpenActivity.java

https://github.com/minstrelsy/POI-Android
Java | 628 lines | 513 code | 93 blank | 22 comment | 70 complexity | 60182dc8ef352d0f524a48473f01d46e MD5 | raw file
  1. package com.example.poipptxnew;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.StringReader;
  7. import java.util.HashMap;
  8. import java.util.concurrent.ExecutorService;
  9. import java.util.concurrent.Executors;
  10. import java.util.concurrent.Future;
  11. import java.util.concurrent.atomic.AtomicBoolean;
  12. import javax.xml.stream.XMLEventReader;
  13. import javax.xml.stream.XMLInputFactory;
  14. import javax.xml.stream.XMLStreamException;
  15. import javax.xml.stream.events.XMLEvent;
  16. import net.pbdavey.awt.Graphics2D;
  17. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  18. import org.apache.poi.openxml4j.opc.OPCPackage;
  19. import org.apache.poi.openxml4j.opc.PackageAccess;
  20. import org.apache.poi.xslf.usermodel.XMLSlideShow;
  21. import org.apache.poi.xslf.usermodel.XSLFSlide;
  22. import and.awt.Dimension;
  23. import android.app.Activity;
  24. import android.app.ProgressDialog;
  25. import android.content.Intent;
  26. import android.graphics.Bitmap;
  27. import android.graphics.Bitmap.Config;
  28. import android.graphics.Canvas;
  29. import android.graphics.Color;
  30. import android.graphics.Matrix;
  31. import android.graphics.Paint;
  32. import android.graphics.RectF;
  33. import android.graphics.drawable.BitmapDrawable;
  34. import android.graphics.drawable.ColorDrawable;
  35. import android.net.Uri;
  36. import android.os.AsyncTask;
  37. import android.os.Build;
  38. import android.os.Bundle;
  39. import android.os.Handler;
  40. import android.os.Message;
  41. import android.os.Parcelable;
  42. import android.util.Log;
  43. import android.view.MotionEvent;
  44. import android.view.View;
  45. import android.view.View.OnTouchListener;
  46. import android.view.ViewGroup;
  47. import android.view.ViewGroup.LayoutParams;
  48. import android.view.Window;
  49. import android.widget.ImageView;
  50. import android.widget.Toast;
  51. import com.qhm123.slide.GestureDetector;
  52. import com.qhm123.slide.ImageViewTouch;
  53. import com.qhm123.slide.PagerAdapter;
  54. import com.qhm123.slide.ScaleGestureDetector;
  55. import com.qhm123.slide.ViewPager;
  56. public class OpenActivity extends Activity {
  57. private static final String TAG = OpenActivity.class.getSimpleName();
  58. private ViewPager mViewPager;
  59. private PagerAdapter mPagerAdapter;
  60. private GestureDetector mGestureDetector;
  61. private ScaleGestureDetector mScaleGestureDetector;
  62. private boolean mPaused;
  63. private boolean mOnScale = false;
  64. private boolean mOnPagerScoll = false;
  65. private int slideCount = 0;
  66. private XSLFSlide[] slide;
  67. private XMLSlideShow ppt;
  68. private Dimension pgsize;
  69. private ProgressDialog mProgressDialog;
  70. @Override
  71. public void onCreate(Bundle savedInstanceState) {
  72. System.setProperty("javax.xml.stream.XMLInputFactory",
  73. "com.sun.xml.stream.ZephyrParserFactory");
  74. System.setProperty("javax.xml.stream.XMLOutputFactory",
  75. "com.sun.xml.stream.ZephyrWriterFactory");
  76. System.setProperty("javax.xml.stream.XMLEventFactory",
  77. "com.sun.xml.stream.events.ZephyrEventFactory");
  78. Thread.currentThread().setContextClassLoader(
  79. getClass().getClassLoader());
  80. // some test
  81. try {
  82. XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  83. XMLEventReader reader = inputFactory
  84. .createXMLEventReader(new StringReader(
  85. "<doc att=\"value\">some text</doc>"));
  86. while (reader.hasNext()) {
  87. XMLEvent e = reader.nextEvent();
  88. Log.e("HelloStax", "Event:[" + e + "]");
  89. }
  90. } catch (XMLStreamException e) {
  91. Log.e("HelloStax", "Error parsing XML", e);
  92. }
  93. requestWindowFeature(Window.FEATURE_PROGRESS);
  94. super.onCreate(savedInstanceState);
  95. setContentView(R.layout.activity_open);
  96. setProgressBarVisibility(true);
  97. setProgressBarIndeterminate(true);
  98. mViewPager = (ViewPager) findViewById(R.id.pager);
  99. mViewPager.setPageMargin(10);
  100. mViewPager.setPageMarginDrawable(new ColorDrawable(Color.BLACK));
  101. mViewPager.setOffscreenPageLimit(1);
  102. mViewPager.setOnPageChangeListener(mPageChangeListener);
  103. setupOnTouchListeners(mViewPager);
  104. mProgressDialog = new ProgressDialog(this);
  105. mProgressDialog.setMessage("Loading");
  106. mProgressDialog.setIndeterminate(true);
  107. String path = null;
  108. Intent i = getIntent();
  109. if (i != null) {
  110. Uri uri = i.getData();
  111. if (uri != null) {
  112. Log.d(TAG, "uri.getPath: " + uri.getPath());
  113. path = uri.getPath();
  114. } else {
  115. path = "/sdcard/talkaboutjvm.pptx";
  116. File demoFile = new File(path);
  117. if (!demoFile.exists()) {
  118. InputStream inputStream = getResources().openRawResource(
  119. R.raw.talkaboutjvm);
  120. try {
  121. FileOutputStream fos = new FileOutputStream(path);
  122. byte[] buffer = new byte[512 * 1024];
  123. int count;
  124. while ((count = inputStream.read(buffer)) > 0) {
  125. fos.write(buffer, 0, count);
  126. }
  127. fos.flush();
  128. fos.close();
  129. inputStream.close();
  130. } catch (IOException e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. }
  135. }
  136. try {
  137. setTitle(path);
  138. pptx2png(path);
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. } catch (InvalidFormatException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. private void pptx2png(final String path) throws IOException,
  146. InvalidFormatException {
  147. mProgressDialog.show();
  148. new AsyncTask<Void, Void, Void>() {
  149. protected void onPostExecute(Void result) {
  150. mProgressDialog.dismiss();
  151. mViewPager.setAdapter(mPagerAdapter);
  152. };
  153. @Override
  154. protected Void doInBackground(Void... params) {
  155. System.out.println("Processing " + path);
  156. long time = System.currentTimeMillis();
  157. try {
  158. ppt = new XMLSlideShow(OPCPackage.open(path,
  159. PackageAccess.READ));
  160. pgsize = ppt.getPageSize();
  161. System.out.println("pgsize.width: " + pgsize.getWidth()
  162. + ", pgsize.height: " + pgsize.getHeight());
  163. slide = ppt.getSlides();
  164. slideCount = slide.length;
  165. } catch (InvalidFormatException e) {
  166. e.printStackTrace();
  167. }
  168. Log.d(TAG, "time: " + (System.currentTimeMillis() - time));
  169. return null;
  170. }
  171. }.execute();
  172. final ExecutorService es = Executors.newSingleThreadExecutor();
  173. final Handler handler = new Handler() {
  174. @Override
  175. public void handleMessage(Message msg) {
  176. super.handleMessage(msg);
  177. if (mViewPager == null) {
  178. return;
  179. }
  180. switch (msg.what) {
  181. case 0: {
  182. Log.d(TAG, "draw finish");
  183. View v = (View) msg.obj;
  184. v.invalidate();
  185. int position = msg.arg1;
  186. if (position == mViewPager.getCurrentItem()) {
  187. setProgress(10000);
  188. }
  189. }
  190. break;
  191. case 1: {
  192. int progress = msg.arg1;
  193. int max = msg.arg2;
  194. int p = (int) ((float) progress / max * 10000);
  195. int position = (Integer) msg.obj;
  196. Log.d(TAG, "update progress: " + progress + ", max: " + max
  197. + ", p: " + p + ", position: " + position);
  198. if (position == 1) {
  199. setProgressBarIndeterminate(false);
  200. }
  201. if (position == mViewPager.getCurrentItem()) {
  202. if (position != 0 && progress == 0) {
  203. setProgressBarIndeterminate(false);
  204. }
  205. setProgress(p);
  206. }
  207. }
  208. break;
  209. default:
  210. break;
  211. }
  212. }
  213. };
  214. mPagerAdapter = new PagerAdapter() {
  215. @Override
  216. public void destroyItem(View container, int position, Object object) {
  217. ImageViewTouch view = (ImageViewTouch) object;
  218. view.getCanceled().set(true);
  219. Future<?> task = (Future<?>) view.getTag();
  220. task.cancel(false);
  221. ((ViewGroup) container).removeView(view);
  222. BitmapDrawable bitmapDrawable = (BitmapDrawable) view
  223. .getDrawable();
  224. if (!bitmapDrawable.getBitmap().isRecycled()) {
  225. bitmapDrawable.getBitmap().recycle();
  226. }
  227. mCache.remove(position);
  228. }
  229. @Override
  230. public Object instantiateItem(View container, final int position) {
  231. if (position == mViewPager.getCurrentItem()) {
  232. setProgressBarIndeterminate(true);
  233. }
  234. final ImageViewTouch imageView = new ImageViewTouch(
  235. OpenActivity.this);
  236. imageView.setLayoutParams(new LayoutParams(
  237. LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
  238. imageView.setBackgroundColor(Color.BLACK);
  239. imageView.setFocusableInTouchMode(true);
  240. String title = slide[position].getTitle();
  241. System.out.println("Rendering slide " + (position + 1)
  242. + (title == null ? "" : ": " + title));
  243. Bitmap bmp = Bitmap.createBitmap((int) pgsize.getWidth(),
  244. (int) pgsize.getHeight(), Config.RGB_565);
  245. Canvas canvas = new Canvas(bmp);
  246. Paint paint = new Paint();
  247. paint.setColor(android.graphics.Color.WHITE);
  248. paint.setFlags(Paint.ANTI_ALIAS_FLAG);
  249. canvas.drawPaint(paint);
  250. final Graphics2D graphics2d = new Graphics2D(canvas);
  251. final AtomicBoolean isCanceled = new AtomicBoolean(false);
  252. Runnable runnable = new Runnable() {
  253. @Override
  254. public void run() {
  255. // render
  256. try {
  257. slide[position].draw(graphics2d, isCanceled,
  258. handler, position);
  259. // slide[position].draw(graphics2d);
  260. handler.sendMessage(Message.obtain(handler, 0,
  261. position, 0, imageView));
  262. } catch (Exception e) {
  263. e.printStackTrace();
  264. }
  265. }
  266. };
  267. Log.d(TAG, "ViewGroup addView");
  268. Future<?> task = es.submit(runnable);
  269. imageView.setTag(task);
  270. imageView.setIsCanceled(isCanceled);
  271. imageView.setImageBitmapResetBase(bmp, true);
  272. ((ViewGroup) container).addView(imageView);
  273. Log.d(TAG, "ViewGroup addView");
  274. mCache.put(position, imageView);
  275. return imageView;
  276. }
  277. @Override
  278. public boolean isViewFromObject(View view, Object object) {
  279. return view == ((ImageView) object);
  280. }
  281. @Override
  282. public int getCount() {
  283. return slide.length;
  284. }
  285. @Override
  286. public void startUpdate(View container) {
  287. }
  288. @Override
  289. public void finishUpdate(View container) {
  290. }
  291. @Override
  292. public Parcelable saveState() {
  293. return null;
  294. }
  295. @Override
  296. public void restoreState(Parcelable state, ClassLoader loader) {
  297. }
  298. };
  299. }
  300. HashMap<Integer, View> mCache = new HashMap<Integer, View>();
  301. public View getView(int position) {
  302. return mCache.get(position);
  303. }
  304. Toast mPreToast;
  305. ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
  306. @Override
  307. public void onPageSelected(int position, int prePosition) {
  308. ImageViewTouch preImageView = (ImageViewTouch) getView(prePosition);
  309. if (preImageView != null) {
  310. preImageView.setImageBitmapResetBase(
  311. preImageView.mBitmapDisplayed.getBitmap(), true);
  312. }
  313. Log.d(TAG, "onPageSelected: " + position);
  314. if (mPreToast == null) {
  315. mPreToast = Toast.makeText(OpenActivity.this,
  316. String.format("%d/%d", position + 1, slideCount),
  317. Toast.LENGTH_SHORT);
  318. } else {
  319. mPreToast.cancel();
  320. mPreToast.setText(String.format("%d/%d", position + 1,
  321. slideCount));
  322. mPreToast.setDuration(Toast.LENGTH_SHORT);
  323. }
  324. mPreToast.show();
  325. }
  326. @Override
  327. public void onPageScrolled(int position, float positionOffset,
  328. int positionOffsetPixels) {
  329. mOnPagerScoll = true;
  330. }
  331. @Override
  332. public void onPageScrollStateChanged(int state) {
  333. if (state == ViewPager.SCROLL_STATE_DRAGGING) {
  334. mOnPagerScoll = true;
  335. } else if (state == ViewPager.SCROLL_STATE_SETTLING) {
  336. mOnPagerScoll = false;
  337. } else {
  338. mOnPagerScoll = false;
  339. }
  340. }
  341. };
  342. public ImageViewTouch getCurrentImageView() {
  343. return (ImageViewTouch) getView(mViewPager.getCurrentItem());
  344. }
  345. private class MyGestureListener extends
  346. GestureDetector.SimpleOnGestureListener {
  347. @Override
  348. public boolean onScroll(MotionEvent e1, MotionEvent e2,
  349. float distanceX, float distanceY) {
  350. // Logger.d(TAG, "gesture onScroll");
  351. if (mOnScale) {
  352. return true;
  353. }
  354. if (mPaused) {
  355. return false;
  356. }
  357. ImageViewTouch imageView = getCurrentImageView();
  358. if (imageView != null) {
  359. imageView.panBy(-distanceX, -distanceY);
  360. // 超出边界效果去掉这个
  361. imageView.center(true, true);
  362. }
  363. return true;
  364. }
  365. @Override
  366. public boolean onSingleTapConfirmed(MotionEvent e) {
  367. return true;
  368. }
  369. @Override
  370. public boolean onDoubleTap(MotionEvent e) {
  371. if (mPaused) {
  372. return false;
  373. }
  374. ImageViewTouch imageView = getCurrentImageView();
  375. // Switch between the original scale and 3x scale.
  376. if (imageView.mBaseZoom < 1) {
  377. if (imageView.getScale() > 2F) {
  378. imageView.zoomTo(1f);
  379. } else {
  380. imageView.zoomToPoint(3f, e.getX(), e.getY());
  381. }
  382. } else {
  383. if (imageView.getScale() > (imageView.mMinZoom + imageView.mMaxZoom) / 2f) {
  384. imageView.zoomTo(imageView.mMinZoom);
  385. } else {
  386. imageView.zoomToPoint(imageView.mMaxZoom, e.getX(),
  387. e.getY());
  388. }
  389. }
  390. return true;
  391. }
  392. }
  393. private class MyOnScaleGestureListener extends
  394. ScaleGestureDetector.SimpleOnScaleGestureListener {
  395. float currentScale;
  396. float currentMiddleX;
  397. float currentMiddleY;
  398. @Override
  399. public void onScaleEnd(ScaleGestureDetector detector) {
  400. final ImageViewTouch imageView = getCurrentImageView();
  401. Log.d(TAG, "currentScale: " + currentScale + ", maxZoom: "
  402. + imageView.mMaxZoom);
  403. if (currentScale > imageView.mMaxZoom) {
  404. imageView
  405. .zoomToNoCenterWithAni(currentScale
  406. / imageView.mMaxZoom, 1, currentMiddleX,
  407. currentMiddleY);
  408. currentScale = imageView.mMaxZoom;
  409. imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
  410. currentMiddleY);
  411. } else if (currentScale < imageView.mMinZoom) {
  412. // imageView.zoomToNoCenterWithAni(currentScale,
  413. // imageView.mMinZoom, currentMiddleX, currentMiddleY);
  414. currentScale = imageView.mMinZoom;
  415. imageView.zoomToNoCenterValue(currentScale, currentMiddleX,
  416. currentMiddleY);
  417. } else {
  418. imageView.zoomToNoCenter(currentScale, currentMiddleX,
  419. currentMiddleY);
  420. }
  421. imageView.center(true, true);
  422. // NOTE: 延迟修正缩放后可能移动问题
  423. imageView.postDelayed(new Runnable() {
  424. @Override
  425. public void run() {
  426. mOnScale = false;
  427. }
  428. }, 300);
  429. // Logger.d(TAG, "gesture onScaleEnd");
  430. }
  431. @Override
  432. public boolean onScaleBegin(ScaleGestureDetector detector) {
  433. // Logger.d(TAG, "gesture onScaleStart");
  434. mOnScale = true;
  435. return true;
  436. }
  437. @Override
  438. public boolean onScale(ScaleGestureDetector detector, float mx, float my) {
  439. // Logger.d(TAG, "gesture onScale");
  440. ImageViewTouch imageView = getCurrentImageView();
  441. float ns = imageView.getScale() * detector.getScaleFactor();
  442. currentScale = ns;
  443. currentMiddleX = mx;
  444. currentMiddleY = my;
  445. if (detector.isInProgress()) {
  446. imageView.zoomToNoCenter(ns, mx, my);
  447. }
  448. return true;
  449. }
  450. }
  451. @Override
  452. public boolean dispatchTouchEvent(MotionEvent m) {
  453. if (mPaused)
  454. return true;
  455. return super.dispatchTouchEvent(m);
  456. }
  457. private void setupOnTouchListeners(View rootView) {
  458. mGestureDetector = new GestureDetector(this, new MyGestureListener(),
  459. null, true);
  460. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
  461. mScaleGestureDetector = new ScaleGestureDetector(this,
  462. new MyOnScaleGestureListener());
  463. }
  464. OnTouchListener rootListener = new OnTouchListener() {
  465. public boolean onTouch(View v, MotionEvent event) {
  466. // NOTE: gestureDetector may handle onScroll..
  467. if (!mOnScale) {
  468. if (!mOnPagerScoll) {
  469. try {
  470. mGestureDetector.onTouchEvent(event);
  471. } catch (Exception e) {
  472. e.printStackTrace();
  473. }
  474. }
  475. }
  476. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
  477. if (!mOnPagerScoll) {
  478. mScaleGestureDetector.onTouchEvent(event);
  479. }
  480. }
  481. ImageViewTouch imageView = getCurrentImageView();
  482. if (!mOnScale && imageView != null
  483. && imageView.mBitmapDisplayed != null
  484. && imageView.mBitmapDisplayed.getBitmap() != null) {
  485. Matrix m = imageView.getImageViewMatrix();
  486. RectF rect = new RectF(0, 0, imageView.mBitmapDisplayed
  487. .getBitmap().getWidth(), imageView.mBitmapDisplayed
  488. .getBitmap().getHeight());
  489. m.mapRect(rect);
  490. // Logger.d(TAG, "rect.right: " + rect.right +
  491. // ", rect.left: "
  492. // + rect.left + ", imageView.getWidth(): "
  493. // + imageView.getWidth());
  494. // 图片超出屏幕范围后移动
  495. if (!(rect.right > imageView.getWidth() + 0.1 && rect.left < -0.1)) {
  496. try {
  497. mViewPager.onTouchEvent(event);
  498. } catch (Exception e) {
  499. // why?
  500. e.printStackTrace();
  501. }
  502. }
  503. }
  504. // We do not use the return value of
  505. // mGestureDetector.onTouchEvent because we will not receive
  506. // the "up" event if we return false for the "down" event.
  507. return true;
  508. }
  509. };
  510. rootView.setOnTouchListener(rootListener);
  511. }
  512. @Override
  513. public void onStart() {
  514. super.onStart();
  515. mPaused = false;
  516. }
  517. @Override
  518. public void onStop() {
  519. super.onStop();
  520. mPaused = true;
  521. }
  522. @Override
  523. protected void onDestroy() {
  524. super.onDestroy();
  525. ImageViewTouch imageView = getCurrentImageView();
  526. if (imageView != null) {
  527. imageView.mBitmapDisplayed.recycle();
  528. imageView.clear();
  529. }
  530. ppt = null;
  531. slide = null;
  532. mPagerAdapter = null;
  533. mViewPager = null;
  534. }
  535. }