mu-office-lib.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. // Copyright (C) 2004-2025 Artifex Software, Inc.
  2. //
  3. // This file is part of MuPDF.
  4. //
  5. // MuPDF is free software: you can redistribute it and/or modify it under the
  6. // terms of the GNU Affero General Public License as published by the Free
  7. // Software Foundation, either version 3 of the License, or (at your option)
  8. // any later version.
  9. //
  10. // MuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
  11. // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  13. // details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
  17. //
  18. // Alternative licensing terms are available from the licensor.
  19. // For commercial licensing, see <https://www.artifex.com/> or contact
  20. // Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
  21. // CA 94129, USA, for further information.
  22. /**
  23. * Mu Office Library
  24. *
  25. * Provided access to the core document, loading, displaying and
  26. * editing routines
  27. *
  28. * Intended for use with native UI
  29. */
  30. #include "mupdf/fitz.h"
  31. #include "mupdf/pdf.h"
  32. #include "mupdf/helpers/mu-office-lib.h"
  33. #include "mupdf/helpers/mu-threads.h"
  34. #include "mupdf/memento.h"
  35. #include <assert.h>
  36. enum
  37. {
  38. MuError_OK = 0,
  39. MuError_OOM = -1,
  40. MuError_BadNull = -2,
  41. MuError_Generic = -3,
  42. MuError_NotImplemented = -4,
  43. MuError_PasswordPending = -5,
  44. };
  45. enum {
  46. LAYOUT_W = 450,
  47. LAYOUT_H = 600,
  48. LAYOUT_EM = 12
  49. };
  50. #ifdef DISABLE_MUTHREADS
  51. #error "mu-office-lib requires threading to be enabled"
  52. #endif
  53. /*
  54. If we are building as part of a smartoffice build, then we
  55. should appeal to Pal_Mem_etc to get memory. If not, then
  56. we should use malloc instead.
  57. FIXME: Allow for something other than malloc/calloc/realloc/
  58. free here.
  59. */
  60. #ifndef SMARTOFFICE_BUILD
  61. void *Pal_Mem_calloc(unsigned int num, size_t size)
  62. {
  63. return calloc(num, size);
  64. }
  65. void *Pal_Mem_malloc(size_t size)
  66. {
  67. return malloc(size);
  68. }
  69. void *Pal_Mem_realloc(void *ptr, size_t size)
  70. {
  71. return realloc(ptr, size);
  72. }
  73. void Pal_Mem_free(void *address)
  74. {
  75. free(address);
  76. }
  77. #endif
  78. /*
  79. All MuPDF's allocations are redirected through the
  80. following functions.
  81. */
  82. static void *muoffice_malloc(void *arg, size_t size)
  83. {
  84. return Pal_Mem_malloc(size);
  85. }
  86. static void *muoffice_realloc(void *arg, void *old, size_t size)
  87. {
  88. return Pal_Mem_realloc(old, size);
  89. }
  90. static void muoffice_free(void *arg, void *ptr)
  91. {
  92. Pal_Mem_free(ptr);
  93. }
  94. static fz_alloc_context muoffice_alloc =
  95. {
  96. /* user */
  97. NULL,
  98. /* void *(*malloc)(void *, size_t); */
  99. muoffice_malloc,
  100. /* void *(*realloc)(void *, void *, size_t); */
  101. muoffice_realloc,
  102. /* void (*free)(void *, void *); */
  103. muoffice_free
  104. };
  105. /*
  106. All MuPDF's locking is done using the following functions
  107. */
  108. static void muoffice_lock(void *user, int lock);
  109. static void muoffice_unlock(void *user, int lock);
  110. struct MuOfficeLib
  111. {
  112. fz_context *ctx;
  113. mu_mutex mutexes[FZ_LOCK_MAX+1];
  114. fz_locks_context locks;
  115. };
  116. /*
  117. We add 1 extra lock which we use in this helper to protect
  118. against accessing the fz_document from multiple threads
  119. inadvertently when the caller is calling 'run' or
  120. 'runBackground'.
  121. */
  122. enum
  123. {
  124. DOCLOCK = FZ_LOCK_MAX
  125. };
  126. static void muoffice_lock(void *user, int lock)
  127. {
  128. MuOfficeLib *mu = (MuOfficeLib *)user;
  129. mu_lock_mutex(&mu->mutexes[lock]);
  130. }
  131. static void muoffice_unlock(void *user, int lock)
  132. {
  133. MuOfficeLib *mu = (MuOfficeLib *)user;
  134. mu_unlock_mutex(&mu->mutexes[lock]);
  135. }
  136. static void muoffice_doc_lock(MuOfficeLib *mu)
  137. {
  138. mu_lock_mutex(&mu->mutexes[DOCLOCK]);
  139. }
  140. static void muoffice_doc_unlock(MuOfficeLib *mu)
  141. {
  142. mu_unlock_mutex(&mu->mutexes[DOCLOCK]);
  143. }
  144. static void fin_muoffice_locks(MuOfficeLib *mu)
  145. {
  146. int i;
  147. for (i = 0; i < FZ_LOCK_MAX+1; i++)
  148. mu_destroy_mutex(&mu->mutexes[i]);
  149. }
  150. static fz_locks_context *init_muoffice_locks(MuOfficeLib *mu)
  151. {
  152. int i;
  153. int failed = 0;
  154. for (i = 0; i < FZ_LOCK_MAX+1; i++)
  155. failed |= mu_create_mutex(&mu->mutexes[i]);
  156. if (failed)
  157. {
  158. fin_muoffice_locks(mu);
  159. return NULL;
  160. }
  161. mu->locks.user = mu;
  162. mu->locks.lock = muoffice_lock;
  163. mu->locks.unlock = muoffice_unlock;
  164. return &mu->locks;
  165. }
  166. MuError MuOfficeLib_create(MuOfficeLib **pMu)
  167. {
  168. MuOfficeLib *mu;
  169. fz_locks_context *locks;
  170. if (pMu == NULL)
  171. return MuOfficeDocErrorType_IllegalArgument;
  172. mu = Pal_Mem_calloc(1, sizeof(MuOfficeLib));
  173. if (mu == NULL)
  174. return MuOfficeDocErrorType_OutOfMemory;
  175. locks = init_muoffice_locks(mu);
  176. if (locks == NULL)
  177. goto Fail;
  178. mu->ctx = fz_new_context(&muoffice_alloc, locks, FZ_STORE_DEFAULT);
  179. if (mu->ctx == NULL)
  180. goto Fail;
  181. fz_try(mu->ctx)
  182. fz_register_document_handlers(mu->ctx);
  183. fz_catch(mu->ctx)
  184. goto Fail;
  185. *pMu = mu;
  186. return MuOfficeDocErrorType_NoError;
  187. Fail:
  188. if (mu)
  189. {
  190. fin_muoffice_locks(mu);
  191. Pal_Mem_free(mu);
  192. }
  193. return MuOfficeDocErrorType_OutOfMemory;
  194. }
  195. /**
  196. * Destroy a MuOfficeLib instance
  197. *
  198. * @param mu the instance to destroy
  199. */
  200. void MuOfficeLib_destroy(MuOfficeLib *mu)
  201. {
  202. if (mu == NULL)
  203. return;
  204. fz_drop_context(mu->ctx);
  205. fin_muoffice_locks(mu);
  206. Pal_Mem_free(mu);
  207. }
  208. /**
  209. * Perform MuPDF native operations on a given MuOfficeLib
  210. * instance.
  211. *
  212. * The function is called with a fz_context value that can
  213. * be safely used (i.e. the context is cloned/dropped
  214. * appropriately around the call). The function should signal
  215. * errors by fz_throw-ing.
  216. *
  217. * @param mu the MuOfficeLib instance.
  218. * @param fn the function to call to run the operations.
  219. * @param arg Opaque data pointer.
  220. *
  221. * @return error indication - 0 for success
  222. */
  223. MuError MuOfficeLib_run(MuOfficeLib *mu, void (*fn)(fz_context *ctx, void *arg), void *arg)
  224. {
  225. fz_context *ctx;
  226. MuError err = MuError_OK;
  227. if (mu == NULL)
  228. return MuError_BadNull;
  229. if (fn == NULL)
  230. return err;
  231. ctx = fz_clone_context(mu->ctx);
  232. if (ctx == NULL)
  233. return MuError_OOM;
  234. fz_try(ctx)
  235. fn(ctx, arg);
  236. fz_catch(ctx)
  237. err = MuError_Generic;
  238. fz_drop_context(ctx);
  239. return err;
  240. }
  241. /**
  242. * Find the type of a file given its filename extension.
  243. *
  244. * @param path path to the file (in utf8)
  245. *
  246. * @return a valid MuOfficeDocType value, or MuOfficeDocType_Other
  247. */
  248. MuOfficeDocType MuOfficeLib_getDocTypeFromFileExtension(const char *path)
  249. {
  250. return /* FIXME */MuOfficeDocType_PDF;
  251. }
  252. /**
  253. * Return a list of file extensions supported by Mu Office library.
  254. *
  255. * @return comma-delimited list of extensions, without the leading ".".
  256. * The caller should free the returned pointer..
  257. */
  258. char * MuOfficeLib_getSupportedFileExtensions(void)
  259. {
  260. /* FIXME */
  261. return NULL;
  262. }
  263. struct MuOfficeDoc
  264. {
  265. MuOfficeLib *mu;
  266. fz_context *ctx;
  267. MuOfficeLoadingProgressFn *progress;
  268. MuOfficeLoadingErrorFn *error;
  269. void *cookie;
  270. char *path;
  271. char *password;
  272. mu_semaphore password_sem;
  273. mu_thread thread;
  274. int needs_password;
  275. int aborted;
  276. fz_document *doc;
  277. MuOfficePage *pages;
  278. };
  279. struct MuOfficePage
  280. {
  281. MuOfficePage *next;
  282. MuOfficeDoc *doc;
  283. int pageNum;
  284. void *cookie;
  285. MuOfficePageUpdateFn *updateFn;
  286. fz_page *page;
  287. fz_display_list *list;
  288. };
  289. struct MuOfficeRender
  290. {
  291. MuOfficePage *page;
  292. float zoom;
  293. const MuOfficeBitmap *bitmap;
  294. int area_valid;
  295. MuOfficeRenderArea area;
  296. MuOfficeRenderProgressFn *progress;
  297. MuError error;
  298. mu_thread thread;
  299. void *cookie;
  300. fz_cookie mu_cookie;
  301. };
  302. static void load_worker(void *arg)
  303. {
  304. MuOfficeDoc *doc = (MuOfficeDoc *)arg;
  305. int numPages = 0;
  306. fz_context *ctx = fz_clone_context(doc->ctx);
  307. int err = 0;
  308. if (ctx == NULL)
  309. {
  310. return;
  311. }
  312. muoffice_doc_lock(doc->mu);
  313. fz_try(ctx)
  314. {
  315. doc->doc = fz_open_document(ctx, doc->path);
  316. doc->needs_password = fz_needs_password(ctx, doc->doc);
  317. }
  318. fz_catch(ctx)
  319. {
  320. err = MuOfficeDocErrorType_UnsupportedDocumentType;
  321. goto fail;
  322. }
  323. fz_try(ctx)
  324. {
  325. if (doc->needs_password && doc->error)
  326. {
  327. do
  328. {
  329. doc->error(doc->cookie, MuOfficeDocErrorType_PasswordRequest);
  330. mu_wait_semaphore(&doc->password_sem);
  331. if (doc->aborted)
  332. break;
  333. doc->needs_password = (fz_authenticate_password(ctx, doc->doc, doc->password) != 0);
  334. Pal_Mem_free(doc->password);
  335. doc->password = NULL;
  336. }
  337. while (doc->needs_password);
  338. }
  339. fz_layout_document(ctx, doc->doc, LAYOUT_W, LAYOUT_H, LAYOUT_EM);
  340. numPages = fz_count_pages(ctx, doc->doc);
  341. }
  342. fz_catch(ctx)
  343. err = MuOfficeDocErrorType_UnableToLoadDocument;
  344. fail:
  345. muoffice_doc_unlock(doc->mu);
  346. if (err)
  347. doc->error(doc->cookie, err);
  348. if (doc->progress)
  349. doc->progress(doc->cookie, numPages, 1);
  350. fz_drop_context(ctx);
  351. }
  352. /**
  353. * Load a document
  354. *
  355. * Call will return immediately, leaving the document loading
  356. * in the background
  357. *
  358. * @param so a MuOfficeLib instance
  359. * @param path path to the file to load (in utf8)
  360. * @param progressFn callback for monitoring progress
  361. * @param errorFn callback for monitoring errors
  362. * @param cookie a pointer to pass back to the callbacks
  363. * @param pDoc address for return of a MuOfficeDoc object
  364. *
  365. * @return error indication - 0 for success
  366. *
  367. * The progress callback may be called several times, with increasing
  368. * values of pagesLoaded. Unless MuOfficeDoc_destroy is called,
  369. * before loading completes, a call with "completed" set to true
  370. * is guaranteed.
  371. *
  372. * Once MuOfficeDoc_destroy is called there will be no
  373. * further callbacks.
  374. *
  375. * Alternatively, in a synchronous context, MuOfficeDoc_getNumPages
  376. * can be called to wait for loading to complete and return the total
  377. * number of pages. In this mode of use, progressFn can be NULL.
  378. */
  379. MuError MuOfficeLib_loadDocument( MuOfficeLib *mu,
  380. const char *path,
  381. MuOfficeLoadingProgressFn *progressFn,
  382. MuOfficeLoadingErrorFn *errorFn,
  383. void *cookie,
  384. MuOfficeDoc **pDoc)
  385. {
  386. MuOfficeDoc *doc;
  387. fz_context *ctx;
  388. if (mu == NULL || pDoc == NULL)
  389. return MuOfficeDocErrorType_IllegalArgument;
  390. *pDoc = NULL;
  391. doc = Pal_Mem_calloc(1, sizeof(*doc));
  392. if (doc == NULL)
  393. return MuOfficeDocErrorType_NoError;
  394. ctx = mu->ctx;
  395. doc->mu = mu;
  396. doc->ctx = fz_clone_context(ctx);
  397. doc->progress = progressFn;
  398. doc->error = errorFn;
  399. doc->cookie = cookie;
  400. doc->path = fz_strdup(ctx, path);
  401. if (mu_create_semaphore(&doc->password_sem))
  402. goto fail;
  403. if (mu_create_thread(&doc->thread, load_worker, doc))
  404. goto fail;
  405. *pDoc = doc;
  406. return MuError_OK;
  407. fail:
  408. mu_destroy_semaphore(&doc->password_sem);
  409. Pal_Mem_free(doc);
  410. return MuError_OOM;
  411. }
  412. /**
  413. * Provide the password for a document
  414. *
  415. * This function should be called to provide a password with a document
  416. * error of MuOfficeError_PasswordRequired is received.
  417. *
  418. * If a password is requested again, this means the password was incorrect.
  419. *
  420. * @param doc the document object
  421. * @param password the password (UTF8 encoded)
  422. * @return error indication - 0 for success
  423. */
  424. int MuOfficeDoc_providePassword(MuOfficeDoc *doc, const char *password)
  425. {
  426. size_t len;
  427. if (doc->password)
  428. return MuError_PasswordPending;
  429. if (!password)
  430. password = "";
  431. len = strlen(password);
  432. doc->password = Pal_Mem_malloc(len+1);
  433. strcpy(doc->password, password);
  434. mu_trigger_semaphore(&doc->password_sem);
  435. return MuError_OK;
  436. }
  437. /**
  438. * Return the type of an open document
  439. *
  440. * @param doc the document object
  441. *
  442. * @return the document type
  443. */
  444. MuOfficeDocType MuOfficeDoc_docType(MuOfficeDoc *doc)
  445. {
  446. return /* FIXME */MuOfficeDocType_PDF;
  447. }
  448. static void
  449. ensure_doc_loaded(MuOfficeDoc *doc)
  450. {
  451. if (doc == NULL)
  452. return;
  453. mu_destroy_thread(&doc->thread);
  454. }
  455. /**
  456. * Return the number of pages of a document
  457. *
  458. * This function waits for document loading to complete before returning
  459. * the result. It may block the calling thread for a significant period of
  460. * time. To avoid blocking, this call should be avoided in favour of using
  461. * the MuOfficeLib_loadDocument callbacks to monitor loading.
  462. *
  463. * If background loading fails, the associated error will be returned
  464. * from this call.
  465. *
  466. * @param doc the document
  467. * @param pNumPages address for return of the number of pages
  468. *
  469. * @return error indication - 0 for success
  470. */
  471. MuError MuOfficeDoc_getNumPages(MuOfficeDoc *doc, int *pNumPages)
  472. {
  473. fz_context *ctx;
  474. MuError err = MuError_OK;
  475. if (doc == NULL)
  476. {
  477. *pNumPages = 0;
  478. return MuError_BadNull;
  479. }
  480. ensure_doc_loaded(doc);
  481. ctx = doc->ctx;
  482. fz_try(ctx)
  483. {
  484. *pNumPages = fz_count_pages(ctx, doc->doc);
  485. }
  486. fz_catch(ctx)
  487. {
  488. err = MuError_Generic;
  489. }
  490. return err;
  491. }
  492. /**
  493. * Determine if the document has been modified
  494. *
  495. * @param doc the document
  496. *
  497. * @return modified flag
  498. */
  499. int MuOfficeDoc_hasBeenModified(MuOfficeDoc *doc)
  500. {
  501. fz_context *ctx;
  502. pdf_document *pdoc;
  503. int modified = 0;
  504. if (doc == NULL)
  505. return 0;
  506. ensure_doc_loaded(doc);
  507. ctx = doc->ctx;
  508. pdoc = pdf_specifics(ctx, doc->doc);
  509. if (pdoc == NULL)
  510. return 0;
  511. fz_try(ctx)
  512. modified = pdf_has_unsaved_changes(ctx, pdoc);
  513. fz_catch(ctx)
  514. modified = 0;
  515. return modified;
  516. }
  517. /**
  518. * Start a save operation
  519. *
  520. * @param doc the document
  521. * @param path path of the file to which to save
  522. * @param resultFn callback used to report completion
  523. * @param cookie a pointer to pass to the callback
  524. *
  525. * @return error indication - 0 for success
  526. */
  527. MuError MuOfficeDoc_save( MuOfficeDoc *doc,
  528. const char *path,
  529. MuOfficeSaveResultFn *resultFn,
  530. void *cookie)
  531. {
  532. return MuError_NotImplemented; /* FIXME */
  533. }
  534. /**
  535. * Stop a document loading. The document is not destroyed, but
  536. * no further content will be read from the file.
  537. *
  538. * @param doc the MuOfficeDoc object
  539. */
  540. void MuOfficeDoc_abortLoad(MuOfficeDoc *doc)
  541. {
  542. fz_context *ctx;
  543. if (doc == NULL)
  544. return;
  545. ctx = doc->ctx;
  546. doc->aborted = 1;
  547. mu_trigger_semaphore(&doc->password_sem);
  548. }
  549. /**
  550. * Destroy a MuOfficeDoc object. Loading of the document is shutdown
  551. * and no further callbacks will be issued for the specified object.
  552. *
  553. * @param doc the MuOfficeDoc object
  554. */
  555. void MuOfficeDoc_destroy(MuOfficeDoc *doc)
  556. {
  557. MuOfficeDoc_abortLoad(doc);
  558. mu_destroy_thread(&doc->thread);
  559. mu_destroy_semaphore(&doc->password_sem);
  560. fz_drop_document(doc->ctx, doc->doc);
  561. fz_drop_context(doc->ctx);
  562. Pal_Mem_free(doc->path);
  563. Pal_Mem_free(doc);
  564. }
  565. /**
  566. * Get a page of a document
  567. *
  568. * @param doc the document object
  569. * @param pageNumber the number of the page to load (lying in the
  570. * range 0 to one less than the number of pages)
  571. * @param updateFn Function to be called back when the page updates
  572. * @param cookie Opaque value to pass for any updates
  573. * @param pPage Address for return of the page object
  574. *
  575. * @return error indication - 0 for success
  576. */
  577. MuError MuOfficeDoc_getPage( MuOfficeDoc *doc,
  578. int pageNumber,
  579. MuOfficePageUpdateFn *updateFn,
  580. void *cookie,
  581. MuOfficePage **pPage)
  582. {
  583. MuOfficePage *page;
  584. MuError err = MuError_OK;
  585. fz_context *ctx;
  586. if (!doc)
  587. return MuError_BadNull;
  588. if (!pPage)
  589. return MuError_OK;
  590. *pPage = NULL;
  591. ensure_doc_loaded(doc);
  592. ctx = doc->ctx;
  593. page = Pal_Mem_calloc(1, sizeof(*page));
  594. if (page == NULL)
  595. return MuError_OOM;
  596. muoffice_doc_lock(doc->mu);
  597. fz_try(ctx)
  598. {
  599. page->doc = doc;
  600. page->pageNum = pageNumber;
  601. page->cookie = cookie;
  602. page->updateFn = updateFn;
  603. page->page = fz_load_page(doc->ctx, doc->doc, pageNumber);
  604. page->next = doc->pages;
  605. doc->pages = page;
  606. *pPage = page;
  607. }
  608. fz_catch(ctx)
  609. {
  610. Pal_Mem_free(page);
  611. err = MuError_Generic;
  612. }
  613. muoffice_doc_unlock(doc->mu);
  614. return err;
  615. }
  616. /**
  617. * Perform MuPDF native operations on a given document.
  618. *
  619. * The function is called with fz_context and fz_document
  620. * values that can be safely used (i.e. the context is
  621. * cloned/dropped appropriately around the function, and
  622. * locking is used to ensure that no other threads are
  623. * simultaneously using the document). Functions can
  624. * signal errors by fz_throw-ing.
  625. *
  626. * Due to the locking, it is best to ensure that as little
  627. * time is taken here as possible (i.e. if you fetch some
  628. * data and then spend a long time processing it, it is
  629. * probably best to fetch the data using MuOfficeDoc_run
  630. * and then process it outside). This avoids potentially
  631. * blocking the UI.
  632. *
  633. * @param doc the document object.
  634. * @param fn the function to call with fz_context/fz_document
  635. * values.
  636. * @param arg Opaque data pointer.
  637. *
  638. * @return error indication - 0 for success
  639. */
  640. MuError MuOfficeDoc_run(MuOfficeDoc *doc, void (*fn)(fz_context *ctx, fz_document *doc, void *arg), void *arg)
  641. {
  642. fz_context *ctx;
  643. MuError err = MuError_OK;
  644. if (doc == NULL)
  645. return MuError_BadNull;
  646. if (fn == NULL)
  647. return err;
  648. ensure_doc_loaded(doc);
  649. ctx = fz_clone_context(doc->mu->ctx);
  650. if (ctx == NULL)
  651. return MuError_OOM;
  652. muoffice_doc_lock(doc->mu);
  653. fz_try(ctx)
  654. fn(ctx, doc->doc, arg);
  655. fz_catch(ctx)
  656. err = MuError_Generic;
  657. muoffice_doc_unlock(doc->mu);
  658. fz_drop_context(ctx);
  659. return err;
  660. }
  661. /**
  662. * Destroy a page object
  663. *
  664. * Note this does not delete or remove the page from the document.
  665. * It simply destroys the page object which is merely a reference
  666. * to the page.
  667. *
  668. * @param page the page object
  669. */
  670. void MuOfficePage_destroy(MuOfficePage *page)
  671. {
  672. MuOfficeDoc *doc;
  673. MuOfficePage **ptr;
  674. if (!page)
  675. return;
  676. /* Unlink page from doc */
  677. doc = page->doc;
  678. ptr = &doc->pages;
  679. while (*ptr && *ptr != page)
  680. ptr = &(*ptr)->next;
  681. assert(*ptr);
  682. *ptr = page->next;
  683. fz_drop_page(doc->ctx, page->page);
  684. fz_drop_display_list(doc->ctx, page->list);
  685. fz_free(doc->ctx, page);
  686. }
  687. /**
  688. * Get the size of a page in pixels
  689. *
  690. * This returns the size of the page in pixels. Pages can be rendered
  691. * with a zoom factor. The returned value is the size of bitmap
  692. * appropriate for rendering with a zoom of 1.0 and corresponds to
  693. * 90 dpi. The returned values are not necessarily whole numbers.
  694. *
  695. * @param page the page object
  696. * @param pWidth address for return of the width
  697. * @param pHeight address for return of the height
  698. *
  699. * @return error indication - 0 for success
  700. */
  701. MuError MuOfficePage_getSize( MuOfficePage *page,
  702. float *pWidth,
  703. float *pHeight)
  704. {
  705. MuOfficeDoc *doc;
  706. fz_rect rect;
  707. if (!page)
  708. return MuError_BadNull;
  709. doc = page->doc;
  710. if (!doc)
  711. return MuError_BadNull;
  712. rect = fz_bound_page(doc->ctx, page->page);
  713. /* MuPDF measures in points (72ths of an inch). This API wants
  714. * 90ths of an inch, so adjust. */
  715. if (pWidth)
  716. *pWidth = 90 * (rect.x1 - rect.x0) / 72;
  717. if (pHeight)
  718. *pHeight = 90 * (rect.y1 - rect.y0) / 72;
  719. return MuError_OK;
  720. }
  721. /**
  722. * Return the zoom factors necessary to render at to a given
  723. * size in pixels. (deprecated)
  724. *
  725. * @param page the page object
  726. * @param width the desired width
  727. * @param height the desired height
  728. * @param pXZoom Address for return of zoom necessary to fit width
  729. * @param pYZoom Address for return of zoom necessary to fit height
  730. *
  731. * @return error indication - 0 for success
  732. */
  733. MuError MuOfficePage_calculateZoom( MuOfficePage *page,
  734. int width,
  735. int height,
  736. float *pXZoom,
  737. float *pYZoom)
  738. {
  739. MuOfficeDoc *doc;
  740. fz_rect rect;
  741. float w, h;
  742. if (!page)
  743. return MuError_BadNull;
  744. doc = page->doc;
  745. if (!doc)
  746. return MuError_BadNull;
  747. rect = fz_bound_page(doc->ctx, page->page);
  748. /* MuPDF measures in points (72ths of an inch). This API wants
  749. * 90ths of an inch, so adjust. */
  750. w = 90 * (rect.x1 - rect.x0) / 72;
  751. h = 90 * (rect.y1 - rect.y0) / 72;
  752. if (pXZoom)
  753. *pXZoom = width/w;
  754. if (pYZoom)
  755. *pYZoom = height/h;
  756. return MuError_OK;
  757. }
  758. /**
  759. * Get the size of a page in pixels for a specified zoom factor
  760. * (deprecated)
  761. *
  762. * This returns the size of bitmap that should be used to display
  763. * the entire page at the given zoom factor. A zoom of 1.0
  764. * corresponds to 90 dpi.
  765. *
  766. * @param page the page object
  767. * @param zoom the zoom factor
  768. * @param pWidth address for return of the width
  769. * @param pHeight address for return of the height
  770. *
  771. * @return error indication - 0 for success
  772. */
  773. MuError MuOfficePage_getSizeForZoom( MuOfficePage *page,
  774. float zoom,
  775. int *pWidth,
  776. int *pHeight)
  777. {
  778. MuOfficeDoc *doc;
  779. fz_rect rect;
  780. float w, h;
  781. if (!page)
  782. return MuError_BadNull;
  783. doc = page->doc;
  784. if (!doc)
  785. return MuError_BadNull;
  786. rect = fz_bound_page(doc->ctx, page->page);
  787. /* MuPDF measures in points (72ths of an inch). This API wants
  788. * 90ths of an inch, so adjust. */
  789. w = 90 * (rect.x1 - rect.x0) / 72;
  790. h = 90 * (rect.y1 - rect.y0) / 72;
  791. if (pWidth)
  792. *pWidth = (int)(w * zoom + 0.5f);
  793. if (pHeight)
  794. *pHeight = (int)(h * zoom + 0.5f);
  795. return MuError_OK;
  796. }
  797. /**
  798. * Perform MuPDF native operations on a given page.
  799. *
  800. * The function is called with fz_context and fz_page
  801. * values that can be safely used (i.e. the context is
  802. * cloned/dropped appropriately around the function, and
  803. * locking is used to ensure that no other threads are
  804. * simultaneously using the document). Functions can
  805. * signal errors by fz_throw-ing.
  806. *
  807. * Due to the locking, it is best to ensure that as little
  808. * time is taken here as possible (i.e. if you fetch some
  809. * data and then spend a long time processing it, it is
  810. * probably best to fetch the data using MuOfficePage_run
  811. * and then process it outside). This avoids potentially
  812. * blocking the UI.
  813. *
  814. * @param page the page object.
  815. * @param fn the function to call with fz_context/fz_document
  816. * values.
  817. * @param arg Opaque data pointer.
  818. *
  819. * @return error indication - 0 for success
  820. */
  821. MuError MuOfficePage_run(MuOfficePage *page, void (*fn)(fz_context *ctx, fz_page *page, void *arg), void *arg)
  822. {
  823. fz_context *ctx;
  824. MuError err = MuError_OK;
  825. if (page == NULL)
  826. return MuError_BadNull;
  827. if (fn == NULL)
  828. return err;
  829. ctx = fz_clone_context(page->doc->mu->ctx);
  830. if (ctx == NULL)
  831. return MuError_OOM;
  832. muoffice_doc_lock(page->doc->mu);
  833. fz_try(ctx)
  834. fn(ctx, page->page, arg);
  835. fz_catch(ctx)
  836. err = MuError_Generic;
  837. muoffice_doc_unlock(page->doc->mu);
  838. fz_drop_context(ctx);
  839. return err;
  840. }
  841. static void render_worker(void *arg)
  842. {
  843. MuOfficeRender *render = (MuOfficeRender *)arg;
  844. MuOfficePage *page = render->page;
  845. fz_context *ctx = fz_clone_context(page->doc->ctx);
  846. int err = 0;
  847. fz_pixmap *pixmap = NULL;
  848. fz_device *dev = NULL;
  849. float scalex;
  850. float scaley;
  851. fz_rect page_bounds;
  852. int locked = 0;
  853. if (ctx == NULL)
  854. return;
  855. fz_var(pixmap);
  856. fz_var(dev);
  857. fz_var(locked);
  858. fz_try(ctx)
  859. {
  860. if (page->list == NULL)
  861. {
  862. muoffice_doc_lock(page->doc->mu);
  863. locked = 1;
  864. page->list = fz_new_display_list_from_page(ctx, page->page);
  865. locked = 0;
  866. muoffice_doc_unlock(page->doc->mu);
  867. }
  868. /* Make a pixmap from the bitmap */
  869. if (!render->area_valid)
  870. {
  871. render->area.renderArea.x = 0;
  872. render->area.renderArea.y = 0;
  873. render->area.renderArea.width = render->bitmap->width;
  874. render->area.renderArea.height = render->bitmap->height;
  875. }
  876. pixmap = fz_new_pixmap_with_data(ctx,
  877. fz_device_rgb(ctx),
  878. render->area.renderArea.width,
  879. render->area.renderArea.height,
  880. NULL,
  881. 1,
  882. render->bitmap->lineSkip,
  883. ((unsigned char *)render->bitmap->memptr) +
  884. render->bitmap->lineSkip * ((int)render->area.renderArea.x + (int)render->area.origin.x) +
  885. 4 * ((int)render->area.renderArea.y + (int)render->area.origin.y));
  886. /* Be a bit clever with the scaling to make sure we get
  887. * integer width/heights. First calculate the target
  888. * width/height. */
  889. page_bounds = fz_bound_page(ctx, render->page->page);
  890. scalex = (int)(90 * render->zoom * (page_bounds.x1 - page_bounds.x0) / 72 + 0.5f);
  891. scaley = (int)(90 * render->zoom * (page_bounds.y1 - page_bounds.y0) / 72 + 0.5f);
  892. /* Now calculate the actual scale factors required */
  893. scalex /= (page_bounds.x1 - page_bounds.x0);
  894. scaley /= (page_bounds.y1 - page_bounds.y0);
  895. /* Render the list */
  896. fz_clear_pixmap_with_value(ctx, pixmap, 0xFF);
  897. dev = fz_new_draw_device(ctx, fz_post_scale(fz_translate(-page_bounds.x0, -page_bounds.y0), scalex, scaley), pixmap);
  898. fz_run_display_list(ctx, page->list, dev, fz_identity, fz_infinite_rect, NULL);
  899. fz_close_device(ctx, dev);
  900. }
  901. fz_always(ctx)
  902. {
  903. fz_drop_pixmap(ctx, pixmap);
  904. fz_drop_device(ctx, dev);
  905. }
  906. fz_catch(ctx)
  907. {
  908. if (locked)
  909. muoffice_doc_unlock(page->doc->mu);
  910. err = MuError_Generic;
  911. goto fail;
  912. }
  913. fail:
  914. if (render->progress)
  915. render->progress(render->cookie, err);
  916. render->error = err;
  917. fz_drop_context(ctx);
  918. }
  919. /**
  920. * Schedule the rendering of an area of document page to
  921. * an area of a bitmap.
  922. *
  923. * The alignment between page and bitmap is defined by specifying
  924. * document's origin within the bitmap, possibly either positive or
  925. * negative. A render object is returned via which the process can
  926. * be monitored or terminated.
  927. *
  928. * The progress function is called exactly once per render in either
  929. * the success or failure case.
  930. *
  931. * Note that, since a render object represents a running thread that
  932. * needs access to the page, document, and library objects, it is important
  933. * to call MuOfficeRender_destroy, not only before using or deallocating
  934. * the bitmap, but also before calling MuOfficePage_destroy, etc..
  935. *
  936. * @param page the page to render
  937. * @param zoom the zoom factor
  938. * @param bitmap the bitmap
  939. * @param area area to render
  940. * @param progressFn the progress callback function
  941. * @param cookie a pointer to pass to the callback function
  942. * @param pRender Address for return of the render object
  943. *
  944. * @return error indication - 0 for success
  945. */
  946. MuError MuOfficePage_render( MuOfficePage *page,
  947. float zoom,
  948. const MuOfficeBitmap *bitmap,
  949. const MuOfficeRenderArea *area,
  950. MuOfficeRenderProgressFn *progressFn,
  951. void *cookie,
  952. MuOfficeRender **pRender)
  953. {
  954. MuOfficeRender *render;
  955. MuOfficeDoc *doc;
  956. fz_context *ctx;
  957. if (!pRender)
  958. return MuError_BadNull;
  959. *pRender = NULL;
  960. if (!page)
  961. return MuError_BadNull;
  962. doc = page->doc;
  963. ctx = doc->ctx;
  964. render = Pal_Mem_calloc(1, sizeof(*render));
  965. if (render == NULL)
  966. return MuError_OOM;
  967. render->page = page;
  968. render->zoom = zoom;
  969. render->bitmap = bitmap;
  970. if (area)
  971. {
  972. render->area = *area;
  973. render->area_valid = 1;
  974. }
  975. else
  976. {
  977. render->area_valid = 0;
  978. }
  979. render->progress = progressFn;
  980. render->cookie = cookie;
  981. if (mu_create_thread(&render->thread, render_worker, render))
  982. {
  983. Pal_Mem_free(render);
  984. return MuError_OOM;
  985. }
  986. *pRender = render;
  987. return MuError_OK;
  988. }
  989. /**
  990. * Destroy a render
  991. *
  992. * This call destroys a MuOfficeRender object, aborting any current
  993. * render.
  994. *
  995. * This call is intended to support an app dealing with a user quickly
  996. * flicking through document pages. A render may be scheduled but, before
  997. * completion, be found not to be needed. In that case the bitmap will
  998. * need to be reused, which requires any existing render to be aborted.
  999. * The call to MuOfficeRender_destroy will cut short the render and
  1000. * allow the bitmap to be reused immediately.
  1001. *
  1002. * @note If an active render thread is destroyed, it will be aborted.
  1003. * While fast, this is not an instant operation. For maximum
  1004. * responsiveness, it is best to 'abort' as soon as you realise you
  1005. * don't need the render, and to destroy when you get the callback.
  1006. *
  1007. * @param render The render object
  1008. */
  1009. void MuOfficeRender_destroy(MuOfficeRender *render)
  1010. {
  1011. if (!render)
  1012. return;
  1013. MuOfficeRender_abort(render);
  1014. mu_destroy_thread(&render->thread);
  1015. Pal_Mem_free(render);
  1016. }
  1017. /**
  1018. * Abort a render
  1019. *
  1020. * This call aborts any rendering currently underway. The 'render
  1021. * complete' callback (if any) given when the render was created will
  1022. * still be called. If a render has completed, this call will have no
  1023. * effect.
  1024. *
  1025. * This call will not block to wait for the render thread to stop, but
  1026. * will cause it to stop as soon as it can in the background.
  1027. *
  1028. * @note It is important not to start any new render to the same bitmap
  1029. * until the callback comes in (or until waitUntilComplete returns), as
  1030. * otherwise you can have multiple renders drawing to the same bitmap
  1031. * with unpredictable consequences.
  1032. *
  1033. * @param render The render object to abort
  1034. */
  1035. void MuOfficeRender_abort(MuOfficeRender *render)
  1036. {
  1037. if (render)
  1038. render->mu_cookie.abort = 1;
  1039. }
  1040. /**
  1041. * Wait for a render to complete.
  1042. *
  1043. * This call will not return until rendering is complete, so on return
  1044. * the bitmap will contain the page image (assuming the render didn't
  1045. * run into an error condition) and will not be used further by any
  1046. * background processing. Any error during rendering will be returned
  1047. * from this function.
  1048. *
  1049. * This call may block the calling thread for a significant period of
  1050. * time. To avoid blocking, supply a progress-monitoring callback
  1051. * function to MuOfficePage_render.
  1052. *
  1053. * @param render The render object to destroy
  1054. * @return render error condition - 0 for no error.
  1055. */
  1056. MuError MuOfficeRender_waitUntilComplete(MuOfficeRender *render)
  1057. {
  1058. if (!render)
  1059. return MuError_OK;
  1060. mu_destroy_thread(&render->thread);
  1061. return render->error;
  1062. }