Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3718 lines
98 KiB

4 years ago
  1. /* Copyright (C) 2013, 2014 Andreas Politz
  2. *
  3. * Author: Andreas Politz <politza@fh-trier.de>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>. */
  17. #include <config.h>
  18. #include <assert.h>
  19. #ifdef HAVE_ERR_H
  20. # include <err.h>
  21. #endif
  22. #ifdef HAVE_ERROR_H
  23. # include <error.h>
  24. #endif
  25. #include <glib.h>
  26. #include <poppler.h>
  27. #include <cairo.h>
  28. #include <stdarg.h>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <strings.h>
  33. #include <sys/types.h>
  34. #include <sys/stat.h>
  35. #include <fcntl.h>
  36. #include <errno.h>
  37. #include <png.h>
  38. #include <math.h>
  39. #include <regex.h>
  40. #include "synctex_parser.h"
  41. #include "epdfinfo.h"
  42. /* ================================================================== *
  43. * Helper Functions
  44. * ================================================================== */
  45. #ifndef HAVE_ERR_H
  46. /**
  47. * Print error message and quit.
  48. *
  49. * @param eval Return code
  50. * @param fmt Formatting string
  51. */
  52. static void
  53. err(int eval, const char *fmt, ...)
  54. {
  55. va_list args;
  56. fprintf (stderr, "epdfinfo: ");
  57. if (fmt != NULL)
  58. {
  59. va_start (args, fmt);
  60. vfprintf (stderr, fmt, args);
  61. va_end (args);
  62. fprintf (stderr, ": %s\n", strerror(errno));
  63. }
  64. else
  65. {
  66. fprintf (stderr, "\n");
  67. }
  68. fflush (stderr);
  69. exit (eval);
  70. }
  71. #endif
  72. #ifndef HAVE_GETLINE
  73. /**
  74. * Read one line from a file.
  75. *
  76. * @param lineptr Pointer to malloc() allocated buffer
  77. * @param n Pointer to size of buffer
  78. * @param stream File pointer to read from
  79. */
  80. static ssize_t
  81. getline(char **lineptr, size_t *n, FILE *stream)
  82. {
  83. size_t len = 0;
  84. int ch;
  85. if ((lineptr == NULL) || (n == NULL))
  86. {
  87. errno = EINVAL;
  88. return -1;
  89. }
  90. if (*lineptr == NULL)
  91. {
  92. *lineptr = malloc (128);
  93. *n = 128;
  94. }
  95. while ((ch = fgetc (stream)) != EOF)
  96. {
  97. (*lineptr)[len] = ch;
  98. if (++len >= *n)
  99. {
  100. *n += 128;
  101. *lineptr = realloc (*lineptr, *n);
  102. }
  103. if (ch == '\n')
  104. break;
  105. }
  106. (*lineptr)[len] = '\0';
  107. if (!len)
  108. {
  109. len = -1;
  110. }
  111. return len;
  112. }
  113. #endif
  114. /**
  115. * Free a list of command arguments.
  116. *
  117. * @param args An array of command arguments.
  118. * @param n The length of the array.
  119. */
  120. static void
  121. free_command_args (command_arg_t *args, size_t n)
  122. {
  123. if (! args)
  124. return;
  125. g_free (args);
  126. }
  127. /**
  128. * Free resources held by document.
  129. *
  130. * @param doc The document to be freed.
  131. */
  132. static void
  133. free_document (document_t *doc)
  134. {
  135. if (! doc)
  136. return;
  137. g_free (doc->filename);
  138. g_free (doc->passwd);
  139. if (doc->annotations.pages)
  140. {
  141. int npages = poppler_document_get_n_pages (doc->pdf);
  142. int i;
  143. for (i = 0; i < npages; ++i)
  144. {
  145. GList *item;
  146. GList *annots = doc->annotations.pages[i];
  147. for (item = annots; item; item = item->next)
  148. {
  149. annotation_t *a = (annotation_t*) item->data;
  150. poppler_annot_mapping_free(a->amap);
  151. g_free (a->key);
  152. g_free (a);
  153. }
  154. g_list_free (annots);
  155. }
  156. g_hash_table_destroy (doc->annotations.keys);
  157. g_free (doc->annotations.pages);
  158. }
  159. g_object_unref (doc->pdf);
  160. g_free (doc);
  161. }
  162. /**
  163. * Parse a list of whitespace separated double values.
  164. *
  165. * @param str The input string.
  166. * @param values[out] Values are put here.
  167. * @param nvalues How many values to parse.
  168. *
  169. * @return TRUE, if str contained exactly nvalues, else FALSE.
  170. */
  171. static gboolean
  172. parse_double_list (const char *str, gdouble *values, size_t nvalues)
  173. {
  174. char *end;
  175. int i;
  176. if (! str)
  177. return FALSE;
  178. errno = 0;
  179. for (i = 0; i < nvalues; ++i)
  180. {
  181. gdouble n = g_ascii_strtod (str, &end);
  182. if (str == end || errno)
  183. return FALSE;
  184. values[i] = n;
  185. str = end;
  186. }
  187. if (*end)
  188. return FALSE;
  189. return TRUE;
  190. }
  191. static gboolean
  192. parse_rectangle (const char *str, PopplerRectangle *r)
  193. {
  194. gdouble values[4];
  195. if (! r)
  196. return FALSE;
  197. if (! parse_double_list (str, values, 4))
  198. return FALSE;
  199. r->x1 = values[0];
  200. r->y1 = values[1];
  201. r->x2 = values[2];
  202. r->y2 = values[3];
  203. return TRUE;
  204. }
  205. static gboolean
  206. parse_edges_or_position (const char *str, PopplerRectangle *r)
  207. {
  208. return (parse_rectangle (str, r)
  209. && r->x1 >= 0 && r->x1 <= 1
  210. && r->x2 <= 1
  211. && r->y1 >= 0 && r->y1 <= 1
  212. && r->y2 <= 1);
  213. }
  214. static gboolean
  215. parse_edges (const char *str, PopplerRectangle *r)
  216. {
  217. return (parse_rectangle (str, r)
  218. && r->x1 >= 0 && r->x1 <= 1
  219. && r->x2 >= 0 && r->x2 <= 1
  220. && r->y1 >= 0 && r->y1 <= 1
  221. && r->y2 >= 0 && r->y2 <= 1);
  222. }
  223. /**
  224. * Print a string properly escaped for a response.
  225. *
  226. * @param str The string to be printed.
  227. * @param suffix_char Append a newline if NEWLINE, a colon if COLON.
  228. */
  229. static void
  230. print_response_string (const char *str, enum suffix_char suffix)
  231. {
  232. if (str)
  233. {
  234. while (*str)
  235. {
  236. switch (*str)
  237. {
  238. case '\n':
  239. printf ("\\n");
  240. break;
  241. case '\\':
  242. printf ("\\\\");
  243. break;
  244. case ':':
  245. printf ("\\:");
  246. break;
  247. default:
  248. putchar (*str);
  249. }
  250. ++str;
  251. }
  252. }
  253. switch (suffix)
  254. {
  255. case NEWLINE:
  256. putchar ('\n');
  257. break;
  258. case COLON:
  259. putchar (':');
  260. break;
  261. default: ;
  262. }
  263. }
  264. /**
  265. * Print a formatted error response.
  266. *
  267. * @param fmt The printf-like format string.
  268. */
  269. static void
  270. printf_error_response (const char *fmt, ...)
  271. {
  272. va_list va;
  273. puts ("ERR");
  274. va_start (va, fmt);
  275. vprintf (fmt, va);
  276. va_end (va);
  277. puts ("\n.");
  278. fflush (stdout);
  279. }
  280. /**
  281. * Remove one trailing newline character. Does nothing, if str does
  282. * not end with a newline.
  283. *
  284. * @param str The string.
  285. *
  286. * @return str with trailing newline removed.
  287. */
  288. static char*
  289. strchomp (char *str)
  290. {
  291. size_t length;
  292. if (! str)
  293. return str;
  294. length = strlen (str);
  295. if (str[length - 1] == '\n')
  296. str[length - 1] = '\0';
  297. return str;
  298. }
  299. /**
  300. * Create a new, temporary file and returns it's name.
  301. *
  302. * @return The filename.
  303. */
  304. static char*
  305. mktempfile()
  306. {
  307. char *filename = NULL;
  308. int tries = 3;
  309. while (! filename && tries-- > 0)
  310. {
  311. filename = tempnam(NULL, "epdfinfo");
  312. if (filename)
  313. {
  314. int fd = open(filename, O_CREAT | O_EXCL | O_RDONLY, S_IRWXU);
  315. if (fd > 0)
  316. close (fd);
  317. else
  318. {
  319. free (filename);
  320. filename = NULL;
  321. }
  322. }
  323. }
  324. if (! filename)
  325. fprintf (stderr, "Unable to create tempfile");
  326. return filename;
  327. }
  328. static void
  329. image_recolor (cairo_surface_t * surface, const PopplerColor * fg,
  330. const PopplerColor * bg)
  331. {
  332. /* uses a representation of a rgb color as follows:
  333. - a lightness scalar (between 0,1), which is a weighted average of r, g, b,
  334. - a hue vector, which indicates a radian direction from the grey axis,
  335. inside the equal lightness plane.
  336. - a saturation scalar between 0,1. It is 0 when grey, 1 when the color is
  337. in the boundary of the rgb cube.
  338. */
  339. const unsigned int page_width = cairo_image_surface_get_width (surface);
  340. const unsigned int page_height = cairo_image_surface_get_height (surface);
  341. const int rowstride = cairo_image_surface_get_stride (surface);
  342. unsigned char *image = cairo_image_surface_get_data (surface);
  343. /* RGB weights for computing lightness. Must sum to one */
  344. static const double a[] = { 0.30, 0.59, 0.11 };
  345. const double f = 65535.;
  346. const double rgb_fg[] = {
  347. fg->red / f, fg->green / f, fg->blue / f
  348. };
  349. const double rgb_bg[] = {
  350. bg->red / f, bg->green / f, bg->blue / f
  351. };
  352. const double rgb_diff[] = {
  353. rgb_bg[0] - rgb_fg[0],
  354. rgb_bg[1] - rgb_fg[1],
  355. rgb_bg[2] - rgb_fg[2]
  356. };
  357. unsigned int y;
  358. for (y = 0; y < page_height * rowstride; y += rowstride)
  359. {
  360. unsigned char *data = image + y;
  361. unsigned int x;
  362. for (x = 0; x < page_width; x++, data += 4)
  363. {
  364. /* Careful. data color components blue, green, red. */
  365. const double rgb[3] = {
  366. (double) data[2] / 256.,
  367. (double) data[1] / 256.,
  368. (double) data[0] / 256.
  369. };
  370. /* compute h, s, l data */
  371. double l = a[0] * rgb[0] + a[1] * rgb[1] + a[2] * rgb[2];
  372. /* linear interpolation between dark and light with color ligtness as
  373. * a parameter */
  374. data[2] =
  375. (unsigned char) round (255. * (l * rgb_diff[0] + rgb_fg[0]));
  376. data[1] =
  377. (unsigned char) round (255. * (l * rgb_diff[1] + rgb_fg[1]));
  378. data[0] =
  379. (unsigned char) round (255. * (l * rgb_diff[2] + rgb_fg[2]));
  380. }
  381. }
  382. }
  383. /**
  384. * Render a PDF page.
  385. *
  386. * @param pdf The PDF document.
  387. * @param page The page to be rendered.
  388. * @param width The desired width of the image.
  389. *
  390. * @return A cairo_t context encapsulating the rendered image, or
  391. * NULL, if rendering failed for some reason.
  392. */
  393. static cairo_surface_t*
  394. image_render_page(PopplerDocument *pdf, PopplerPage *page,
  395. int width, gboolean do_render_annotaions,
  396. const render_options_t *options)
  397. {
  398. cairo_t *cr = NULL;
  399. cairo_surface_t *surface = NULL;
  400. double pt_width, pt_height;
  401. int height;
  402. double scale = 1;
  403. if (! page || ! pdf)
  404. return NULL;
  405. if (width < 1)
  406. width = 1;
  407. poppler_page_get_size (page, &pt_width, &pt_height);
  408. scale = width / pt_width;
  409. height = (int) ((scale * pt_height) + 0.5);
  410. surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
  411. width, height);
  412. if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS)
  413. {
  414. fprintf (stderr, "Failed to create cairo surface\n");
  415. goto error;
  416. }
  417. cr = cairo_create (surface);
  418. if (cairo_status(cr) != CAIRO_STATUS_SUCCESS)
  419. {
  420. fprintf (stderr, "Failed to create cairo handle\n");
  421. goto error;
  422. }
  423. cairo_translate (cr, 0, 0);
  424. cairo_scale (cr, scale, scale);
  425. /* Render w/o annotations. */
  426. if (! do_render_annotaions || (options && options->printed))
  427. poppler_page_render_for_printing_with_options
  428. (page, cr, POPPLER_PRINT_DOCUMENT);
  429. else
  430. poppler_page_render (page, cr) ;
  431. if (cairo_status(cr) != CAIRO_STATUS_SUCCESS)
  432. {
  433. fprintf (stderr, "Failed to render page\n");
  434. goto error;
  435. }
  436. /* This makes the colors look right. */
  437. cairo_set_operator (cr, CAIRO_OPERATOR_DEST_OVER);
  438. cairo_set_source_rgb (cr, 1., 1., 1.);
  439. cairo_paint (cr);
  440. if (options && options->usecolors)
  441. image_recolor (surface, &options->fg, &options->bg);
  442. cairo_destroy (cr);
  443. return surface;
  444. error:
  445. if (surface != NULL)
  446. cairo_surface_destroy (surface);
  447. if (cr != NULL)
  448. cairo_destroy (cr);
  449. return NULL;
  450. }
  451. /**
  452. * Write an image to a filename.
  453. *
  454. * @param cr The cairo context encapsulating the image.
  455. * @param filename The filename to be written to.
  456. * @param type The desired image type.
  457. *
  458. * @return 1 if the image was written successfully, else 0.
  459. */
  460. static gboolean
  461. image_write (cairo_surface_t *surface, const char *filename, enum image_type type)
  462. {
  463. int i, j;
  464. unsigned char *data;
  465. int width, height;
  466. FILE *file = NULL;
  467. gboolean success = 0;
  468. if (! surface ||
  469. cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS)
  470. {
  471. fprintf (stderr, "Invalid cairo surface\n");
  472. return 0;
  473. }
  474. if (! (file = fopen (filename, "wb")))
  475. {
  476. fprintf (stderr, "Can not open file: %s\n", filename);
  477. return 0;
  478. }
  479. cairo_surface_flush (surface);
  480. width = cairo_image_surface_get_width (surface);
  481. height = cairo_image_surface_get_height (surface);
  482. data = cairo_image_surface_get_data (surface);
  483. switch (type)
  484. {
  485. case PPM:
  486. {
  487. unsigned char *buffer = g_malloc (width * height * 3);
  488. unsigned char *buffer_p = buffer;
  489. fprintf (file, "P6\n%d %d\n255\n", width, height);
  490. for (i = 0; i < width * height; ++i, data += 4, buffer_p += 3)
  491. ARGB_TO_RGB (buffer_p, data);
  492. fwrite (buffer, 1, width * height * 3, file);
  493. g_free (buffer);
  494. success = 1;
  495. }
  496. break;
  497. case PNG:
  498. {
  499. png_infop info_ptr = NULL;
  500. png_structp png_ptr = NULL;
  501. unsigned char *row = NULL;
  502. png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
  503. if (!png_ptr)
  504. goto finalize;
  505. info_ptr = png_create_info_struct(png_ptr);
  506. if (!info_ptr)
  507. goto finalize;
  508. if (setjmp(png_jmpbuf(png_ptr)))
  509. goto finalize;
  510. png_init_io (png_ptr, file);
  511. png_set_compression_level (png_ptr, 1);
  512. png_set_IHDR (png_ptr, info_ptr, width, height,
  513. 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
  514. PNG_COMPRESSION_TYPE_BASE,
  515. PNG_FILTER_TYPE_DEFAULT);
  516. png_set_filter (png_ptr, PNG_FILTER_TYPE_BASE,
  517. PNG_FILTER_NONE);
  518. png_write_info (png_ptr, info_ptr);
  519. row = g_malloc (3 * width);
  520. for (i = 0; i < height; ++i)
  521. {
  522. unsigned char *row_p = row;
  523. for (j = 0; j < width; ++j, data += 4, row_p += 3)
  524. {
  525. ARGB_TO_RGB (row_p, data);
  526. }
  527. png_write_row (png_ptr, row);
  528. }
  529. png_write_end (png_ptr, NULL);
  530. success = 1;
  531. finalize:
  532. if (png_ptr)
  533. png_destroy_write_struct (&png_ptr, &info_ptr);
  534. if (row)
  535. g_free (row);
  536. if (! success)
  537. fprintf (stderr, "Error writing png data\n");
  538. }
  539. break;
  540. default:
  541. internal_error ("switch fell through");
  542. }
  543. fclose (file);
  544. return success;
  545. }
  546. static void
  547. image_write_print_response(cairo_surface_t *surface, enum image_type type)
  548. {
  549. char *filename = mktempfile ();
  550. perror_if_not (filename, "Unable to create temporary file");
  551. if (image_write (surface, filename, type))
  552. {
  553. OK_BEGIN ();
  554. print_response_string (filename, NEWLINE);
  555. OK_END ();
  556. }
  557. else
  558. {
  559. printf_error_response ("Unable to write image");
  560. }
  561. free (filename);
  562. error:
  563. return;
  564. }
  565. static void
  566. region_print (cairo_region_t *region, double width, double height)
  567. {
  568. int i;
  569. for (i = 0; i < cairo_region_num_rectangles (region); ++i)
  570. {
  571. cairo_rectangle_int_t r;
  572. cairo_region_get_rectangle (region, i, &r);
  573. printf ("%f %f %f %f",
  574. r.x / width,
  575. r.y / height,
  576. (r.x + r.width) / width,
  577. (r.y + r.height) / height);
  578. if (i < cairo_region_num_rectangles (region) - 1)
  579. putchar (':');
  580. }
  581. if (0 == cairo_region_num_rectangles (region))
  582. printf ("0.0 0.0 0.0 0.0");
  583. }
  584. /**
  585. * Return a string representation of a PopplerActionType.
  586. *
  587. * @param type The PopplerActionType.
  588. *
  589. * @return It's string representation.
  590. */
  591. static const char *
  592. xpoppler_action_type_string(PopplerActionType type)
  593. {
  594. switch (type)
  595. {
  596. case POPPLER_ACTION_UNKNOWN: return "unknown";
  597. case POPPLER_ACTION_NONE: return "none";
  598. case POPPLER_ACTION_GOTO_DEST: return "goto-dest";
  599. case POPPLER_ACTION_GOTO_REMOTE: return "goto-remote";
  600. case POPPLER_ACTION_LAUNCH: return "launch";
  601. case POPPLER_ACTION_URI: return "uri";
  602. case POPPLER_ACTION_NAMED: return "goto-dest"; /* actually "named" */
  603. case POPPLER_ACTION_MOVIE: return "movie";
  604. case POPPLER_ACTION_RENDITION: return "rendition";
  605. case POPPLER_ACTION_OCG_STATE: return "ocg-state";
  606. case POPPLER_ACTION_JAVASCRIPT: return "javascript";
  607. default: return "invalid";
  608. }
  609. }
  610. /**
  611. * Return a string representation of a PopplerAnnotType.
  612. *
  613. * @param type The PopplerAnnotType.
  614. *
  615. * @return It's string representation.
  616. */
  617. static const char *
  618. xpoppler_annot_type_string (PopplerAnnotType type)
  619. {
  620. switch (type)
  621. {
  622. case POPPLER_ANNOT_UNKNOWN: return "unknown";
  623. case POPPLER_ANNOT_TEXT: return "text";
  624. case POPPLER_ANNOT_LINK: return "link";
  625. case POPPLER_ANNOT_FREE_TEXT: return "free-text";
  626. case POPPLER_ANNOT_LINE: return "line";
  627. case POPPLER_ANNOT_SQUARE: return "square";
  628. case POPPLER_ANNOT_CIRCLE: return "circle";
  629. case POPPLER_ANNOT_POLYGON: return "polygon";
  630. case POPPLER_ANNOT_POLY_LINE: return "poly-line";
  631. case POPPLER_ANNOT_HIGHLIGHT: return "highlight";
  632. case POPPLER_ANNOT_UNDERLINE: return "underline";
  633. case POPPLER_ANNOT_SQUIGGLY: return "squiggly";
  634. case POPPLER_ANNOT_STRIKE_OUT: return "strike-out";
  635. case POPPLER_ANNOT_STAMP: return "stamp";
  636. case POPPLER_ANNOT_CARET: return "caret";
  637. case POPPLER_ANNOT_INK: return "ink";
  638. case POPPLER_ANNOT_POPUP: return "popup";
  639. case POPPLER_ANNOT_FILE_ATTACHMENT: return "file";
  640. case POPPLER_ANNOT_SOUND: return "sound";
  641. case POPPLER_ANNOT_MOVIE: return "movie";
  642. case POPPLER_ANNOT_WIDGET: return "widget";
  643. case POPPLER_ANNOT_SCREEN: return "screen";
  644. case POPPLER_ANNOT_PRINTER_MARK: return "printer-mark";
  645. case POPPLER_ANNOT_TRAP_NET: return "trap-net";
  646. case POPPLER_ANNOT_WATERMARK: return "watermark";
  647. case POPPLER_ANNOT_3D: return "3d";
  648. default: return "invalid";
  649. }
  650. }
  651. /**
  652. * Return a string representation of a PopplerAnnotTextState.
  653. *
  654. * @param type The PopplerAnnotTextState.
  655. *
  656. * @return It's string representation.
  657. */
  658. static const char *
  659. xpoppler_annot_text_state_string (PopplerAnnotTextState state)
  660. {
  661. switch (state)
  662. {
  663. case POPPLER_ANNOT_TEXT_STATE_MARKED: return "marked";
  664. case POPPLER_ANNOT_TEXT_STATE_UNMARKED: return "unmarked";
  665. case POPPLER_ANNOT_TEXT_STATE_ACCEPTED: return "accepted";
  666. case POPPLER_ANNOT_TEXT_STATE_REJECTED: return "rejected";
  667. case POPPLER_ANNOT_TEXT_STATE_CANCELLED: return "cancelled";
  668. case POPPLER_ANNOT_TEXT_STATE_COMPLETED: return "completed";
  669. case POPPLER_ANNOT_TEXT_STATE_NONE: return "none";
  670. case POPPLER_ANNOT_TEXT_STATE_UNKNOWN:
  671. default: return "unknown";
  672. }
  673. };
  674. static document_t*
  675. document_open (const epdfinfo_t *ctx, const char *filename,
  676. const char *passwd, GError **gerror)
  677. {
  678. char *uri;
  679. document_t *doc = g_hash_table_lookup (ctx->documents, filename);
  680. if (NULL != doc)
  681. return doc;
  682. doc = g_malloc0(sizeof (document_t));
  683. uri = g_filename_to_uri (filename, NULL, gerror);
  684. if (uri != NULL)
  685. doc->pdf = poppler_document_new_from_file(uri, passwd, gerror);
  686. if (NULL == doc->pdf)
  687. {
  688. g_free (doc);
  689. doc = NULL;
  690. }
  691. else
  692. {
  693. doc->filename = g_strdup (filename);
  694. doc->passwd = g_strdup (passwd);
  695. g_hash_table_insert (ctx->documents, doc->filename, doc);
  696. }
  697. g_free (uri);
  698. return doc;
  699. }
  700. /**
  701. * Split command args into a list of strings.
  702. *
  703. * @param args The colon separated list of arguments.
  704. * @param nargs[out] The number of returned arguments.
  705. *
  706. * @return The list of arguments, which should be freed by the caller.
  707. */
  708. static char **
  709. command_arg_split (const char *args, int *nargs)
  710. {
  711. char **list = g_malloc (sizeof (char*) * 16);
  712. int i = 0;
  713. size_t allocated = 16;
  714. char *buffer = NULL;
  715. gboolean last = FALSE;
  716. if (! args)
  717. goto theend;
  718. buffer = g_malloc (strlen (args) + 1);
  719. while (*args || last)
  720. {
  721. gboolean esc = FALSE;
  722. char *buffer_p = buffer;
  723. while (*args && (*args != ':' || esc))
  724. {
  725. if (esc)
  726. {
  727. if (*args == 'n')
  728. {
  729. ++args;
  730. *buffer_p++ = '\n';
  731. }
  732. else
  733. {
  734. *buffer_p++ = *args++;
  735. }
  736. esc = FALSE;
  737. }
  738. else if (*args == '\\')
  739. {
  740. ++args;
  741. esc = TRUE;
  742. }
  743. else
  744. {
  745. *buffer_p++ = *args++;
  746. }
  747. }
  748. *buffer_p = '\0';
  749. if (i >= allocated)
  750. {
  751. allocated = 2 * allocated + 1;
  752. list = g_realloc (list, sizeof (char*) * allocated);
  753. }
  754. list[i++] = g_strdup (buffer);
  755. last = FALSE;
  756. if (*args)
  757. {
  758. ++args;
  759. if (! *args)
  760. last = TRUE;
  761. }
  762. }
  763. theend:
  764. g_free (buffer);
  765. *nargs = i;
  766. return list;
  767. }
  768. static gboolean
  769. command_arg_parse_arg (const epdfinfo_t *ctx, const char *arg,
  770. command_arg_t *cmd_arg, command_arg_type_t type,
  771. gchar **error_msg)
  772. {
  773. GError *gerror = NULL;
  774. if (! arg || !cmd_arg)
  775. return FALSE;
  776. switch (type)
  777. {
  778. case ARG_DOC:
  779. {
  780. document_t *doc = document_open (ctx, arg, NULL, &gerror);
  781. cerror_if_not (doc, error_msg,
  782. "Error opening %s:%s", arg,
  783. gerror ? gerror->message : "Unknown reason");
  784. cmd_arg->value.doc = doc;
  785. break;
  786. }
  787. case ARG_BOOL:
  788. cerror_if_not (! strcmp (arg, "0") || ! strcmp (arg, "1"),
  789. error_msg, "Expected 0 or 1:%s", arg);
  790. cmd_arg->value.flag = *arg == '1';
  791. break;
  792. case ARG_NONEMPTY_STRING:
  793. cerror_if_not (*arg, error_msg, "Non-empty string expected");
  794. /* fall through */
  795. case ARG_STRING:
  796. cmd_arg->value.string = arg;
  797. break;
  798. case ARG_NATNUM:
  799. {
  800. char *endptr;
  801. long n = strtol (arg, &endptr, 0);
  802. cerror_if_not (! (*endptr || (n < 0)), error_msg,
  803. "Expected natural number:%s", arg);
  804. cmd_arg->value.natnum = n;
  805. }
  806. break;
  807. case ARG_EDGES_OR_POSITION:
  808. {
  809. PopplerRectangle *r = &cmd_arg->value.rectangle;
  810. cerror_if_not (parse_edges_or_position (arg, r),
  811. error_msg,
  812. "Expected a relative position or rectangle: %s", arg);
  813. }
  814. break;
  815. case ARG_EDGES:
  816. {
  817. PopplerRectangle *r = &cmd_arg->value.rectangle;
  818. cerror_if_not (parse_edges (arg, r),
  819. error_msg,
  820. "Expected a relative rectangle: %s", arg);
  821. }
  822. break;
  823. case ARG_EDGE_OR_NEGATIVE:
  824. case ARG_EDGE:
  825. {
  826. char *endptr;
  827. double n = strtod (arg, &endptr);
  828. cerror_if_not (! (*endptr || (type != ARG_EDGE_OR_NEGATIVE && n < 0.0) || n > 1.0),
  829. error_msg, "Expected a relative edge: %s", arg);
  830. cmd_arg->value.edge = n;
  831. }
  832. break;
  833. case ARG_COLOR:
  834. {
  835. guint r,g,b;
  836. cerror_if_not ((strlen (arg) == 7
  837. && 3 == sscanf (arg, "#%2x%2x%2x", &r, &g, &b)),
  838. error_msg, "Invalid color: %s", arg);
  839. cmd_arg->value.color.red = r << 8;
  840. cmd_arg->value.color.green = g << 8;
  841. cmd_arg->value.color.blue = b << 8;
  842. }
  843. break;
  844. case ARG_INVALID:
  845. default:
  846. internal_error ("switch fell through");
  847. }
  848. cmd_arg->type = type;
  849. return TRUE;
  850. error:
  851. if (gerror)
  852. {
  853. g_error_free (gerror);
  854. gerror = NULL;
  855. }
  856. return FALSE;
  857. }
  858. /**
  859. * Parse arguments for a command.
  860. *
  861. * @param ctx The epdfinfo context.
  862. * @param args A string holding the arguments. This is either empty
  863. * or the suffix of the command starting at the first
  864. * colon after the command name.
  865. * @param len The length of args.
  866. * @param cmd The command for which the arguments should be parsed.
  867. *
  868. * @return
  869. */
  870. static command_arg_t*
  871. command_arg_parse(epdfinfo_t *ctx, char **args, int nargs,
  872. const command_t *cmd, gchar **error_msg)
  873. {
  874. command_arg_t *cmd_args = g_malloc0 (cmd->nargs * sizeof (command_arg_t));
  875. int i;
  876. if (nargs < cmd->nargs - 1
  877. || (nargs == cmd->nargs - 1
  878. && cmd->args_spec[cmd->nargs - 1] != ARG_REST)
  879. || (nargs > cmd->nargs
  880. && (cmd->nargs == 0
  881. || cmd->args_spec[cmd->nargs - 1] != ARG_REST)))
  882. {
  883. if (error_msg)
  884. {
  885. *error_msg =
  886. g_strdup_printf ("Command `%s' expects %d argument(s), %d given",
  887. cmd->name, cmd->nargs, nargs);
  888. }
  889. goto failure;
  890. }
  891. for (i = 0; i < cmd->nargs; ++i)
  892. {
  893. if (i == cmd->nargs - 1 && cmd->args_spec[i] == ARG_REST)
  894. {
  895. cmd_args[i].value.rest.args = args + i;
  896. cmd_args[i].value.rest.nargs = nargs - i;
  897. cmd_args[i].type = ARG_REST;
  898. }
  899. else if (i >= nargs
  900. || ! command_arg_parse_arg (ctx, args[i], cmd_args + i,
  901. cmd->args_spec[i], error_msg))
  902. {
  903. goto failure;
  904. }
  905. }
  906. return cmd_args;
  907. failure:
  908. free_command_args (cmd_args, cmd->nargs);
  909. return NULL;
  910. }
  911. static void
  912. command_arg_print(const command_arg_t *arg)
  913. {
  914. switch (arg->type)
  915. {
  916. case ARG_INVALID:
  917. printf ("[invalid]");
  918. break;
  919. case ARG_DOC:
  920. print_response_string (arg->value.doc->filename, NONE);
  921. break;
  922. case ARG_BOOL:
  923. printf ("%d", arg->value.flag ? 1 : 0);
  924. break;
  925. case ARG_NONEMPTY_STRING: /* fall */
  926. case ARG_STRING:
  927. print_response_string (arg->value.string, NONE);
  928. break;
  929. case ARG_NATNUM:
  930. printf ("%ld", arg->value.natnum);
  931. break;
  932. case ARG_EDGE_OR_NEGATIVE: /* fall */
  933. case ARG_EDGE:
  934. printf ("%f", arg->value.edge);
  935. break;
  936. case ARG_EDGES_OR_POSITION: /* fall */
  937. case ARG_EDGES:
  938. {
  939. const PopplerRectangle *r = &arg->value.rectangle;
  940. if (r->x2 < 0 && r->y2 < 0)
  941. printf ("%f %f", r->x1, r->y1);
  942. else
  943. printf ("%f %f %f %f", r->x1, r->y1, r->x2, r->y2);
  944. break;
  945. }
  946. case ARG_COLOR:
  947. {
  948. const PopplerColor *c = &arg->value.color;
  949. printf ("#%.2x%.2x%.2x", c->red >> 8,
  950. c->green >> 8, c->blue >> 8);
  951. break;
  952. }
  953. case ARG_REST:
  954. {
  955. int i;
  956. for (i = 0; i < arg->value.rest.nargs; ++i)
  957. print_response_string (arg->value.rest.args[i], COLON);
  958. if (arg->value.rest.nargs > 0)
  959. print_response_string (arg->value.rest.args[i], NONE);
  960. break;
  961. }
  962. default:
  963. internal_error ("switch fell through");
  964. }
  965. }
  966. static size_t
  967. command_arg_type_size(command_arg_type_t type)
  968. {
  969. command_arg_t arg;
  970. switch (type)
  971. {
  972. case ARG_INVALID: return 0;
  973. case ARG_DOC: return sizeof (arg.value.doc);
  974. case ARG_BOOL: return sizeof (arg.value.flag);
  975. case ARG_NONEMPTY_STRING: /* fall */
  976. case ARG_STRING: return sizeof (arg.value.string);
  977. case ARG_NATNUM: return sizeof (arg.value.natnum);
  978. case ARG_EDGE_OR_NEGATIVE: /* fall */
  979. case ARG_EDGE: return sizeof (arg.value.edge);
  980. case ARG_EDGES_OR_POSITION: /* fall */
  981. case ARG_EDGES: return sizeof (arg.value.rectangle);
  982. case ARG_COLOR: return sizeof (arg.value.color);
  983. case ARG_REST: return sizeof (arg.value.rest);
  984. default:
  985. internal_error ("switch fell through");
  986. return 0;
  987. }
  988. }
  989. /* ------------------------------------------------------------------ *
  990. * PDF Actions
  991. * ------------------------------------------------------------------ */
  992. static gboolean
  993. action_is_handled (PopplerAction *action)
  994. {
  995. if (! action)
  996. return FALSE;
  997. switch (action->any.type)
  998. {
  999. case POPPLER_ACTION_GOTO_REMOTE:
  1000. case POPPLER_ACTION_GOTO_DEST:
  1001. case POPPLER_ACTION_NAMED:
  1002. /* case POPPLER_ACTION_LAUNCH: */
  1003. case POPPLER_ACTION_URI:
  1004. return TRUE;
  1005. default: ;
  1006. }
  1007. return FALSE;
  1008. }
  1009. static void
  1010. action_print_destination (PopplerDocument *doc, PopplerAction *action)
  1011. {
  1012. PopplerDest *dest = NULL;
  1013. gboolean free_dest = FALSE;
  1014. double width, height, top;
  1015. PopplerPage *page;
  1016. int saved_stdin;
  1017. if (action->any.type == POPPLER_ACTION_GOTO_DEST
  1018. && action->goto_dest.dest->type == POPPLER_DEST_NAMED)
  1019. {
  1020. DISCARD_STDOUT (saved_stdin);
  1021. /* poppler_document_find_dest reports errors to stdout, so
  1022. discard them. */
  1023. dest = poppler_document_find_dest
  1024. (doc, action->goto_dest.dest->named_dest);
  1025. UNDISCARD_STDOUT (saved_stdin);
  1026. free_dest = TRUE;
  1027. }
  1028. else if (action->any.type == POPPLER_ACTION_NAMED)
  1029. {
  1030. DISCARD_STDOUT (saved_stdin);
  1031. dest = poppler_document_find_dest (doc, action->named.named_dest);
  1032. UNDISCARD_STDOUT (saved_stdin);
  1033. free_dest = TRUE;
  1034. }
  1035. else if (action->any.type == POPPLER_ACTION_GOTO_REMOTE)
  1036. {
  1037. print_response_string (action->goto_remote.file_name, COLON);
  1038. dest = action->goto_remote.dest;
  1039. }
  1040. else if (action->any.type == POPPLER_ACTION_GOTO_DEST)
  1041. dest = action->goto_dest.dest;
  1042. if (!dest
  1043. || dest->type == POPPLER_DEST_UNKNOWN
  1044. || dest->page_num < 1
  1045. || dest->page_num > poppler_document_get_n_pages (doc))
  1046. {
  1047. printf (":");
  1048. goto theend;
  1049. }
  1050. printf ("%d:", dest->page_num);
  1051. if (action->type == POPPLER_ACTION_GOTO_REMOTE
  1052. || NULL == (page = poppler_document_get_page (doc, dest->page_num - 1)))
  1053. {
  1054. goto theend;
  1055. }
  1056. poppler_page_get_size (page, &width, &height);
  1057. g_object_unref (page);
  1058. top = (height - dest->top) / height;
  1059. /* adapted from xpdf */
  1060. switch (dest->type)
  1061. {
  1062. case POPPLER_DEST_XYZ:
  1063. if (dest->change_top)
  1064. printf ("%f", top);
  1065. break;
  1066. case POPPLER_DEST_FIT:
  1067. case POPPLER_DEST_FITB:
  1068. case POPPLER_DEST_FITH:
  1069. case POPPLER_DEST_FITBH:
  1070. putchar ('0');
  1071. break;
  1072. case POPPLER_DEST_FITV:
  1073. case POPPLER_DEST_FITBV:
  1074. case POPPLER_DEST_FITR:
  1075. printf ("%f", top);
  1076. break;
  1077. default: ;
  1078. }
  1079. theend:
  1080. if (free_dest)
  1081. poppler_dest_free (dest);
  1082. }
  1083. static void
  1084. action_print (PopplerDocument *doc, PopplerAction *action)
  1085. {
  1086. if (! action_is_handled (action))
  1087. return;
  1088. print_response_string (xpoppler_action_type_string (action->any.type), COLON);
  1089. print_response_string (action->any.title, COLON);
  1090. switch (action->any.type)
  1091. {
  1092. case POPPLER_ACTION_GOTO_REMOTE:
  1093. case POPPLER_ACTION_GOTO_DEST:
  1094. case POPPLER_ACTION_NAMED:
  1095. action_print_destination (doc, action);
  1096. putchar ('\n');
  1097. break;
  1098. case POPPLER_ACTION_LAUNCH:
  1099. print_response_string (action->launch.file_name, COLON);
  1100. print_response_string (action->launch.params, NEWLINE);
  1101. break;
  1102. case POPPLER_ACTION_URI:
  1103. print_response_string (action->uri.uri, NEWLINE);
  1104. break;
  1105. default:
  1106. ;
  1107. }
  1108. }
  1109. /* ------------------------------------------------------------------ *
  1110. * PDF Annotations and Attachments
  1111. * ------------------------------------------------------------------ */
  1112. /* static gint
  1113. * annotation_cmp_edges (const annotation_t *a1, const annotation_t *a2)
  1114. * {
  1115. * PopplerRectangle *e1 = &a1->amap->area;
  1116. * PopplerRectangle *e2 = &a2->amap->area;
  1117. *
  1118. * return (e1->y1 > e2->y1 ? -1
  1119. * : e1->y1 < e2->y1 ? 1
  1120. * : e1->x1 < e2->x1 ? -1
  1121. * : e1->x1 != e2->x1);
  1122. * } */
  1123. static GList*
  1124. annoation_get_for_page (document_t *doc, gint pn)
  1125. {
  1126. GList *annot_list, *item;
  1127. PopplerPage *page;
  1128. gint i = 0;
  1129. gint npages = poppler_document_get_n_pages (doc->pdf);
  1130. if (pn < 1 || pn > npages)
  1131. return NULL;
  1132. if (! doc->annotations.pages)
  1133. doc->annotations.pages = g_malloc0 (npages * sizeof(GList*));
  1134. if (doc->annotations.pages[pn - 1])
  1135. return doc->annotations.pages[pn - 1];
  1136. if (! doc->annotations.keys)
  1137. doc->annotations.keys = g_hash_table_new (g_str_hash, g_str_equal);
  1138. page = poppler_document_get_page (doc->pdf, pn - 1);
  1139. if (NULL == page)
  1140. return NULL;
  1141. annot_list = poppler_page_get_annot_mapping (page);
  1142. for (item = annot_list; item; item = item->next)
  1143. {
  1144. PopplerAnnotMapping *map = (PopplerAnnotMapping *)item->data;
  1145. gchar *key = g_strdup_printf ("annot-%d-%d", pn, i);
  1146. annotation_t *a = g_malloc (sizeof (annotation_t));
  1147. a->amap = map;
  1148. a->key = key;
  1149. doc->annotations.pages[pn - 1] =
  1150. g_list_prepend (doc->annotations.pages[pn - 1], a);
  1151. assert (NULL == g_hash_table_lookup (doc->annotations.keys, key));
  1152. g_hash_table_insert (doc->annotations.keys, key, a);
  1153. ++i;
  1154. }
  1155. g_list_free (annot_list);
  1156. g_object_unref (page);
  1157. return doc->annotations.pages[pn - 1];
  1158. }
  1159. static annotation_t*
  1160. annotation_get_by_key (document_t *doc, const gchar *key)
  1161. {
  1162. if (! doc->annotations.keys)
  1163. return NULL;
  1164. return g_hash_table_lookup (doc->annotations.keys, key);
  1165. }
  1166. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1167. void
  1168. annotation_translate_quadrilateral (PopplerPage *page, PopplerQuadrilateral *q, gboolean inverse)
  1169. {
  1170. PopplerRectangle cbox;
  1171. gdouble xs, ys;
  1172. poppler_page_get_crop_box (page, &cbox);
  1173. xs = MIN (cbox.x1, cbox.x2);
  1174. ys = MIN (cbox.y1, cbox.y2);
  1175. if (inverse)
  1176. {
  1177. xs = -xs; ys = -ys;
  1178. }
  1179. q->p1.x -= xs, q->p2.x -= xs; q->p3.x -= xs; q->p4.x -= xs;
  1180. q->p1.y -= ys, q->p2.y -= ys; q->p3.y -= ys; q->p4.y -= ys;
  1181. }
  1182. static cairo_region_t*
  1183. annotation_markup_get_text_regions (PopplerPage *page, PopplerAnnotTextMarkup *a)
  1184. {
  1185. GArray *quads = poppler_annot_text_markup_get_quadrilaterals (a);
  1186. int i;
  1187. cairo_region_t *region = cairo_region_create ();
  1188. gdouble height;
  1189. poppler_page_get_size (page, NULL, &height);
  1190. for (i = 0; i < quads->len; ++i)
  1191. {
  1192. PopplerQuadrilateral *q = &g_array_index (quads, PopplerQuadrilateral, i);
  1193. cairo_rectangle_int_t r;
  1194. annotation_translate_quadrilateral (page, q, FALSE);
  1195. q->p1.y = height - q->p1.y;
  1196. q->p2.y = height - q->p2.y;
  1197. q->p3.y = height - q->p3.y;
  1198. q->p4.y = height - q->p4.y;
  1199. r.x = (int) (MIN (q->p1.x, MIN (q->p2.x, MIN (q->p3.x, q->p4.x))) + 0.5);
  1200. r.y = (int) (MIN (q->p1.y, MIN (q->p2.y, MIN (q->p3.y, q->p4.y))) + 0.5);
  1201. r.width = (int) (MAX (q->p1.x, MAX (q->p2.x, MAX (q->p3.x, q->p4.x))) + 0.5)
  1202. - r.x;
  1203. r.height = (int) (MAX (q->p1.y, MAX (q->p2.y, MAX (q->p3.y, q->p4.y))) + 0.5)
  1204. - r.y;
  1205. cairo_region_union_rectangle (region, &r);
  1206. }
  1207. g_array_unref (quads);
  1208. return region;
  1209. }
  1210. /**
  1211. * Append quadrilaterals equivalent to region to an array.
  1212. *
  1213. * @param page The page of the annotation. This is used to get the
  1214. * text regions and pagesize.
  1215. * @param region The region to add.
  1216. * @param garray[in,out] An array of PopplerQuadrilateral, where the
  1217. * new quadrilaterals will be appended.
  1218. */
  1219. static void
  1220. annotation_markup_append_text_region (PopplerPage *page, PopplerRectangle *region,
  1221. GArray *garray)
  1222. {
  1223. gdouble height;
  1224. /* poppler_page_get_selection_region is deprecated w/o a
  1225. replacement. (poppler_page_get_selected_region returns a union
  1226. of rectangles.) */
  1227. GList *regions =
  1228. poppler_page_get_selection_region (page, 1.0, POPPLER_SELECTION_GLYPH, region);
  1229. GList *item;
  1230. poppler_page_get_size (page, NULL, &height);
  1231. for (item = regions; item; item = item->next)
  1232. {
  1233. PopplerRectangle *r = item->data;
  1234. PopplerQuadrilateral q;
  1235. q.p1.x = r->x1;
  1236. q.p1.y = height - r->y1;
  1237. q.p2.x = r->x2;
  1238. q.p2.y = height - r->y1;
  1239. q.p4.x = r->x2;
  1240. q.p4.y = height - r->y2;
  1241. q.p3.x = r->x1;
  1242. q.p3.y = height - r->y2;
  1243. annotation_translate_quadrilateral (page, &q, TRUE);
  1244. g_array_append_val (garray, q);
  1245. }
  1246. g_list_free (regions);
  1247. }
  1248. #endif
  1249. /**
  1250. * Create a new annotation.
  1251. *
  1252. * @param doc The document for which to create it.
  1253. * @param type The type of the annotation.
  1254. * @param r The rectangle where annotation will end up on the page.
  1255. *
  1256. * @return The new annotation, or NULL, if the annotation type is
  1257. * not available.
  1258. */
  1259. static PopplerAnnot*
  1260. annotation_new (const epdfinfo_t *ctx, document_t *doc, PopplerPage *page,
  1261. const char *type, PopplerRectangle *r,
  1262. const command_arg_t *rest, char **error_msg)
  1263. {
  1264. PopplerAnnot *a = NULL;
  1265. int nargs = rest->value.rest.nargs;
  1266. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1267. char * const *args = rest->value.rest.args;
  1268. int i;
  1269. GArray *garray = NULL;
  1270. command_arg_t carg;
  1271. double width, height;
  1272. cairo_region_t *region = NULL;
  1273. #endif
  1274. if (! strcmp (type, "text"))
  1275. {
  1276. cerror_if_not (nargs == 0, error_msg, "%s", "Too many arguments");
  1277. return poppler_annot_text_new (doc->pdf, r);
  1278. }
  1279. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1280. garray = g_array_new (FALSE, FALSE, sizeof (PopplerQuadrilateral));
  1281. poppler_page_get_size (page, &width, &height);
  1282. for (i = 0; i < nargs; ++i)
  1283. {
  1284. PopplerRectangle *rr = &carg.value.rectangle;
  1285. error_if_not (command_arg_parse_arg (ctx, args[i], &carg,
  1286. ARG_EDGES, error_msg));
  1287. rr->x1 *= width; rr->x2 *= width;
  1288. rr->y1 *= height; rr->y2 *= height;
  1289. annotation_markup_append_text_region (page, rr, garray);
  1290. }
  1291. cerror_if_not (garray->len > 0, error_msg, "%s",
  1292. "Unable to create empty markup annotation");
  1293. if (! strcmp (type, "highlight"))
  1294. a = poppler_annot_text_markup_new_highlight (doc->pdf, r, garray);
  1295. else if (! strcmp (type, "squiggly"))
  1296. a = poppler_annot_text_markup_new_squiggly (doc->pdf, r, garray);
  1297. else if (! strcmp (type, "strike-out"))
  1298. a = poppler_annot_text_markup_new_strikeout (doc->pdf, r, garray);
  1299. else if (! strcmp (type, "underline"))
  1300. a = poppler_annot_text_markup_new_underline (doc->pdf, r, garray);
  1301. else
  1302. cerror_if_not (0, error_msg, "Unknown annotation type: %s", type);
  1303. #endif
  1304. error:
  1305. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1306. if (garray) g_array_unref (garray);
  1307. if (region) cairo_region_destroy (region);
  1308. #endif
  1309. return a;
  1310. }
  1311. static gboolean
  1312. annotation_edit_validate (const epdfinfo_t *ctx, const command_arg_t *rest,
  1313. PopplerAnnot *annotation, char **error_msg)
  1314. {
  1315. int nargs = rest->value.rest.nargs;
  1316. char * const *args = rest->value.rest.args;
  1317. int i = 0;
  1318. command_arg_t carg;
  1319. const char* error_fmt =
  1320. "Can modify `%s' property only for %s annotations";
  1321. while (i < nargs)
  1322. {
  1323. command_arg_type_t atype = ARG_INVALID;
  1324. const char *key = args[i++];
  1325. cerror_if_not (i < nargs, error_msg, "Missing a value argument");
  1326. if (! strcmp (key, "flags"))
  1327. atype = ARG_NATNUM;
  1328. else if (! strcmp (key, "color"))
  1329. atype = ARG_COLOR;
  1330. else if (! strcmp (key, "contents"))
  1331. atype = ARG_STRING;
  1332. else if (! strcmp (key, "edges"))
  1333. atype = ARG_EDGES_OR_POSITION;
  1334. else if (! strcmp (key, "label"))
  1335. {
  1336. cerror_if_not (POPPLER_IS_ANNOT_MARKUP (annotation), error_msg,
  1337. error_fmt, key, "markup");
  1338. atype = ARG_STRING;
  1339. }
  1340. else if (! strcmp (key, "opacity"))
  1341. {
  1342. cerror_if_not (POPPLER_IS_ANNOT_MARKUP (annotation), error_msg,
  1343. error_fmt, key, "markup");
  1344. atype = ARG_EDGE;
  1345. }
  1346. else if (! strcmp (key, "popup"))
  1347. {
  1348. cerror_if_not (POPPLER_IS_ANNOT_MARKUP (annotation), error_msg,
  1349. error_fmt, key, "markup");
  1350. atype = ARG_EDGES;
  1351. }
  1352. else if (! strcmp (key, "popup-is-open"))
  1353. {
  1354. cerror_if_not (POPPLER_IS_ANNOT_MARKUP (annotation), error_msg,
  1355. error_fmt, key, "markup");
  1356. atype = ARG_BOOL;
  1357. }
  1358. else if (! strcmp (key, "icon"))
  1359. {
  1360. cerror_if_not (POPPLER_IS_ANNOT_TEXT (annotation), error_msg,
  1361. error_fmt, key, "text");
  1362. atype = ARG_STRING;
  1363. }
  1364. else if (! strcmp (key, "is-open"))
  1365. {
  1366. cerror_if_not (POPPLER_IS_ANNOT_TEXT (annotation), error_msg,
  1367. error_fmt, key, "text");
  1368. atype = ARG_BOOL;
  1369. }
  1370. else
  1371. {
  1372. cerror_if_not (0, error_msg,
  1373. "Unable to modify property `%s'", key);
  1374. }
  1375. if (! command_arg_parse_arg (ctx, args[i++], &carg, atype, error_msg))
  1376. return FALSE;
  1377. }
  1378. return TRUE;
  1379. error:
  1380. return FALSE;
  1381. }
  1382. static void
  1383. annotation_print (const annotation_t *annot, /* const */ PopplerPage *page)
  1384. {
  1385. double width, height;
  1386. PopplerAnnotMapping *m;
  1387. const gchar *key;
  1388. PopplerAnnot *a;
  1389. PopplerAnnotMarkup *ma;
  1390. PopplerAnnotText *ta;
  1391. PopplerRectangle r;
  1392. PopplerColor *color;
  1393. gchar *text;
  1394. gdouble opacity;
  1395. cairo_region_t *region = NULL;
  1396. if (! annot || ! page)
  1397. return;
  1398. m = annot->amap;
  1399. key = annot->key;
  1400. a = m->annot;
  1401. poppler_page_get_size (page, &width, &height);
  1402. r.x1 = m->area.x1;
  1403. r.x2 = m->area.x2;
  1404. r.y1 = height - m->area.y2;
  1405. r.y2 = height - m->area.y1;
  1406. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1407. if (POPPLER_IS_ANNOT_TEXT_MARKUP (a))
  1408. {
  1409. region = annotation_markup_get_text_regions (page, POPPLER_ANNOT_TEXT_MARKUP (a));
  1410. perror_if_not (region, "%s", "Unable to extract annotation's text regions");
  1411. }
  1412. #endif
  1413. /* >>> Any Annotation >>> */
  1414. /* Page */
  1415. printf ("%d:", poppler_page_get_index (page) + 1);
  1416. /* Area */
  1417. printf ("%f %f %f %f:", r.x1 / width, r.y1 / height
  1418. , r.x2 / width, r.y2 / height);
  1419. /* Type */
  1420. printf ("%s:", xpoppler_annot_type_string (poppler_annot_get_annot_type (a)));
  1421. /* Internal Key */
  1422. print_response_string (key, COLON);
  1423. /* Flags */
  1424. printf ("%d:", poppler_annot_get_flags (a));
  1425. /* Color */
  1426. color = poppler_annot_get_color (a);
  1427. if (color)
  1428. {
  1429. /* Reduce 2 Byte to 1 Byte color space */
  1430. printf ("#%.2x%.2x%.2x", (color->red >> 8)
  1431. , (color->green >> 8)
  1432. , (color->blue >> 8));
  1433. g_free (color);
  1434. }
  1435. putchar (':');
  1436. /* Text Contents */
  1437. text = poppler_annot_get_contents (a);
  1438. print_response_string (text, COLON);
  1439. g_free (text);
  1440. /* Modified Date */
  1441. text = poppler_annot_get_modified (a);
  1442. print_response_string (text, NONE);
  1443. g_free (text);
  1444. /* <<< Any Annotation <<< */
  1445. /* >>> Markup Annotation >>> */
  1446. if (! POPPLER_IS_ANNOT_MARKUP (a))
  1447. {
  1448. putchar ('\n');
  1449. goto theend;
  1450. }
  1451. putchar (':');
  1452. ma = POPPLER_ANNOT_MARKUP (a);
  1453. /* Label */
  1454. text = poppler_annot_markup_get_label (ma);
  1455. print_response_string (text, COLON);
  1456. g_free (text);
  1457. /* Subject */
  1458. text = poppler_annot_markup_get_subject (ma);
  1459. print_response_string (text, COLON);
  1460. g_free (text);
  1461. /* Opacity */
  1462. opacity = poppler_annot_markup_get_opacity (ma);
  1463. printf ("%f:", opacity);
  1464. /* Popup (Area + isOpen) */
  1465. if (poppler_annot_markup_has_popup (ma)
  1466. && poppler_annot_markup_get_popup_rectangle (ma, &r))
  1467. {
  1468. gdouble tmp = r.y1;
  1469. r.y1 = height - r.y2;
  1470. r.y2 = height - tmp;
  1471. printf ("%f %f %f %f:%d:", r.x1 / width, r.y1 / height
  1472. , r.x2 / width, r.y2 / height
  1473. , poppler_annot_markup_get_popup_is_open (ma) ? 1 : 0);
  1474. }
  1475. else
  1476. printf ("::");
  1477. /* Creation Date */
  1478. text = xpoppler_annot_markup_get_created (ma);
  1479. if (text)
  1480. {
  1481. print_response_string (text, NONE);
  1482. g_free (text);
  1483. }
  1484. /* <<< Markup Annotation <<< */
  1485. /* >>> Text Annotation >>> */
  1486. if (POPPLER_IS_ANNOT_TEXT (a))
  1487. {
  1488. putchar (':');
  1489. ta = POPPLER_ANNOT_TEXT (a);
  1490. /* Text Icon */
  1491. text = poppler_annot_text_get_icon (ta);
  1492. print_response_string (text, COLON);
  1493. g_free (text);
  1494. /* Text State */
  1495. printf ("%s:%d",
  1496. xpoppler_annot_text_state_string (poppler_annot_text_get_state (ta)),
  1497. poppler_annot_text_get_is_open (ta));
  1498. }
  1499. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1500. /* <<< Text Annotation <<< */
  1501. else if (POPPLER_IS_ANNOT_TEXT_MARKUP (a))
  1502. {
  1503. /* >>> Markup Text Annotation >>> */
  1504. putchar (':');
  1505. region_print (region, width, height);
  1506. /* <<< Markup Text Annotation <<< */
  1507. }
  1508. #endif
  1509. putchar ('\n');
  1510. theend:
  1511. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1512. error:
  1513. #endif
  1514. if (region) cairo_region_destroy (region);
  1515. }
  1516. static void
  1517. attachment_print (PopplerAttachment *att, const char *id, gboolean do_save)
  1518. {
  1519. time_t time;
  1520. print_response_string (id, COLON);
  1521. print_response_string (att->name, COLON);
  1522. print_response_string (att->description, COLON);
  1523. if (att->size + 1 != 0)
  1524. printf ("%" G_GSIZE_FORMAT ":", att->size);
  1525. else
  1526. printf ("-1:");
  1527. time = (time_t) att->mtime;
  1528. print_response_string (time > 0 ? strchomp (ctime (&time)) : "", COLON);
  1529. time = (time_t) att->ctime;
  1530. print_response_string (time > 0 ? strchomp (ctime (&time)) : "", COLON);
  1531. print_response_string (att->checksum ? att->checksum->str : "" , COLON);
  1532. if (do_save)
  1533. {
  1534. char *filename = mktempfile ();
  1535. GError *error = NULL;
  1536. if (filename)
  1537. {
  1538. if (! poppler_attachment_save (att, filename, &error))
  1539. {
  1540. fprintf (stderr, "Writing attachment failed: %s"
  1541. , error ? error->message : "reason unknown");
  1542. if (error)
  1543. g_free (error);
  1544. }
  1545. else
  1546. {
  1547. print_response_string (filename, NONE);
  1548. }
  1549. free (filename);
  1550. }
  1551. }
  1552. putchar ('\n');
  1553. }
  1554. /* ================================================================== *
  1555. * Server command implementations
  1556. * ================================================================== */
  1557. /* Name: features
  1558. Args: None
  1559. Returns: A list of compile-time features.
  1560. Errors: None
  1561. */
  1562. const command_arg_type_t cmd_features_spec[] = {};
  1563. static void
  1564. cmd_features (const epdfinfo_t *ctx, const command_arg_t *args)
  1565. {
  1566. const char *features[] = {
  1567. #ifdef HAVE_POPPLER_FIND_OPTS
  1568. "case-sensitive-search",
  1569. #else
  1570. "no-case-sensitive-search",
  1571. #endif
  1572. #ifdef HAVE_POPPLER_ANNOT_WRITE
  1573. "writable-annotations",
  1574. #else
  1575. "no-writable-annotations",
  1576. #endif
  1577. #ifdef HAVE_POPPLER_ANNOT_MARKUP
  1578. "markup-annotations"
  1579. #else
  1580. "no-markup-annotations"
  1581. #endif
  1582. };
  1583. int i;
  1584. OK_BEGIN ();
  1585. for (i = 0; i < G_N_ELEMENTS (features); ++i)
  1586. {
  1587. printf ("%s", features[i]);
  1588. if (i < G_N_ELEMENTS (features) - 1)
  1589. putchar (':');
  1590. }
  1591. putchar ('\n');
  1592. OK_END ();
  1593. }
  1594. /* Name: open
  1595. Args: filename password
  1596. Returns: Nothing
  1597. Errors: If file can't be opened or is not a PDF document.
  1598. */
  1599. const command_arg_type_t cmd_open_spec[] =
  1600. {
  1601. ARG_NONEMPTY_STRING, /* filename */
  1602. ARG_STRING, /* password */
  1603. };
  1604. static void
  1605. cmd_open (const epdfinfo_t *ctx, const command_arg_t *args)
  1606. {
  1607. const char *filename = args[0].value.string;
  1608. const char *passwd = args[1].value.string;
  1609. GError *gerror = NULL;
  1610. document_t *doc;
  1611. if (! *passwd)
  1612. passwd = NULL;
  1613. doc = document_open(ctx, filename, passwd, &gerror);
  1614. perror_if_not (doc, "Error opening %s:%s", filename,
  1615. gerror ? gerror->message : "unknown error");
  1616. OK ();
  1617. error:
  1618. if (gerror)
  1619. {
  1620. g_error_free (gerror);
  1621. gerror = NULL;
  1622. }
  1623. }
  1624. /* Name: close
  1625. Args: filename
  1626. Returns: 1 if file was open, otherwise 0.
  1627. Errors: None
  1628. */
  1629. const command_arg_type_t cmd_close_spec[] =
  1630. {
  1631. ARG_NONEMPTY_STRING /* filename */
  1632. };
  1633. static void
  1634. cmd_close (const epdfinfo_t *ctx, const command_arg_t *args)
  1635. {
  1636. document_t *doc = g_hash_table_lookup(ctx->documents, args->value.string);
  1637. g_hash_table_remove (ctx->documents, args->value.string);
  1638. free_document (doc);
  1639. OK_BEGIN ();
  1640. puts (doc ? "1" : "0");
  1641. OK_END ();
  1642. }
  1643. /* Name: closeall
  1644. Args: None
  1645. Returns: Nothing
  1646. Errors: None
  1647. */
  1648. static void
  1649. cmd_closeall (const epdfinfo_t *ctx, const command_arg_t *args)
  1650. {
  1651. GHashTableIter iter;
  1652. gpointer key, value;
  1653. g_hash_table_iter_init (&iter, ctx->documents);
  1654. while (g_hash_table_iter_next (&iter, &key, &value))
  1655. {
  1656. document_t *doc = (document_t*) value;
  1657. free_document (doc);
  1658. g_hash_table_iter_remove (&iter);
  1659. }
  1660. OK ();
  1661. }
  1662. const command_arg_type_t cmd_search_regexp_spec[] =
  1663. {
  1664. ARG_DOC,
  1665. ARG_NATNUM, /* first page */
  1666. ARG_NATNUM, /* last page */
  1667. ARG_NONEMPTY_STRING, /* regexp */
  1668. ARG_NATNUM, /* compile flags */
  1669. ARG_NATNUM /* match flags */
  1670. };
  1671. static void
  1672. cmd_search_regexp(const epdfinfo_t *ctx, const command_arg_t *args)
  1673. {
  1674. PopplerDocument *doc = args[0].value.doc->pdf;
  1675. int first = args[1].value.natnum;
  1676. int last = args[2].value.natnum;
  1677. const gchar *regexp = args[3].value.string;
  1678. GRegexCompileFlags cflags = args[4].value.natnum;
  1679. GRegexMatchFlags mflags = args[5].value.natnum;
  1680. double width, height;
  1681. int pn;
  1682. GError *gerror = NULL;
  1683. GRegex *re = NULL;
  1684. NORMALIZE_PAGE_ARG (doc, &first, &last);
  1685. re = g_regex_new (regexp, cflags, mflags, &gerror);
  1686. perror_if_not (NULL == gerror, "Invalid regexp: %s", gerror->message);
  1687. OK_BEGIN ();
  1688. for (pn = first; pn <= last; ++pn)
  1689. {
  1690. PopplerPage *page = poppler_document_get_page(doc, pn - 1);
  1691. char *text;
  1692. PopplerRectangle *rectangles = NULL;
  1693. guint nrectangles;
  1694. GMatchInfo *match = NULL;
  1695. if (! page)
  1696. continue;
  1697. text = poppler_page_get_text (page);
  1698. poppler_page_get_text_layout (page, &rectangles, &nrectangles);
  1699. poppler_page_get_size (page, &width, &height);
  1700. g_regex_match (re, text, 0, &match);
  1701. while (g_match_info_matches (match))
  1702. {
  1703. const double scale = 100.0;
  1704. gint start, end, ustart, ulen;
  1705. gchar *string = NULL;
  1706. gchar *line = NULL;
  1707. int i;
  1708. /* Does this ever happen ? */
  1709. if (! g_match_info_fetch_pos (match, 0, &start, &end))
  1710. continue;
  1711. string = g_match_info_fetch (match, 0);
  1712. ustart = g_utf8_strlen (text, start);
  1713. ulen = g_utf8_strlen (string, -1);
  1714. cairo_region_t *region = cairo_region_create ();
  1715. /* Merge matched glyph rectangles. Scale them so we're able
  1716. to use cairo . */
  1717. if (ulen > 0)
  1718. {
  1719. assert (ustart < nrectangles
  1720. && ustart + ulen <= nrectangles);
  1721. line = poppler_page_get_selected_text
  1722. (page, POPPLER_SELECTION_LINE, rectangles + ustart);
  1723. for (i = ustart; i < ustart + ulen; ++i)
  1724. {
  1725. PopplerRectangle *r = rectangles + i;
  1726. cairo_rectangle_int_t c;
  1727. c.x = (int) (scale * r->x1 + 0.5);
  1728. c.y = (int) (scale * r->y1 + 0.5);
  1729. c.width = (int) (scale * (r->x2 - r->x1) + 0.5);
  1730. c.height = (int) (scale * (r->y2 - r->y1) + 0.5);
  1731. cairo_region_union_rectangle (region, &c);
  1732. }
  1733. }
  1734. printf ("%d:", pn);
  1735. print_response_string (string, COLON);
  1736. print_response_string (strchomp (line), COLON);
  1737. region_print (region, width * scale, height * scale);
  1738. putchar ('\n');
  1739. cairo_region_destroy (region);
  1740. g_free (string);
  1741. g_free (line);
  1742. g_match_info_next (match, NULL);
  1743. }
  1744. g_free (rectangles);
  1745. g_object_unref (page);
  1746. g_free (text);
  1747. g_match_info_free (match);
  1748. }
  1749. OK_END ();
  1750. error:
  1751. if (re) g_regex_unref (re);
  1752. if (gerror) g_error_free (gerror);
  1753. }
  1754. const command_arg_type_t cmd_regexp_flags_spec[] =
  1755. {
  1756. };
  1757. static void
  1758. cmd_regexp_flags (const epdfinfo_t *ctx, const command_arg_t *args)
  1759. {
  1760. OK_BEGIN ();
  1761. printf ("caseless:%d\n", G_REGEX_CASELESS);
  1762. printf ("multiline:%d\n", G_REGEX_MULTILINE);
  1763. printf ("dotall:%d\n", G_REGEX_DOTALL);
  1764. printf ("extended:%d\n", G_REGEX_EXTENDED);
  1765. printf ("anchored:%d\n", G_REGEX_ANCHORED);
  1766. printf ("dollar-endonly:%d\n", G_REGEX_DOLLAR_ENDONLY);
  1767. printf ("ungreedy:%d\n", G_REGEX_UNGREEDY);
  1768. printf ("raw:%d\n", G_REGEX_RAW);
  1769. printf ("no-auto-capture:%d\n", G_REGEX_NO_AUTO_CAPTURE);
  1770. printf ("optimize:%d\n", G_REGEX_OPTIMIZE);
  1771. printf ("dupnames:%d\n", G_REGEX_DUPNAMES);
  1772. printf ("newline-cr:%d\n", G_REGEX_NEWLINE_CR);
  1773. printf ("newline-lf:%d\n", G_REGEX_NEWLINE_LF);
  1774. printf ("newline-crlf:%d\n", G_REGEX_NEWLINE_CRLF);
  1775. printf ("match-anchored:%d\n", G_REGEX_MATCH_ANCHORED);
  1776. printf ("match-notbol:%d\n", G_REGEX_MATCH_NOTBOL);
  1777. printf ("match-noteol:%d\n", G_REGEX_MATCH_NOTEOL);
  1778. printf ("match-notempty:%d\n", G_REGEX_MATCH_NOTEMPTY);
  1779. printf ("match-partial:%d\n", G_REGEX_MATCH_PARTIAL);
  1780. printf ("match-newline-cr:%d\n", G_REGEX_MATCH_NEWLINE_CR);
  1781. printf ("match-newline-lf:%d\n", G_REGEX_MATCH_NEWLINE_LF);
  1782. printf ("match-newline-crlf:%d\n", G_REGEX_MATCH_NEWLINE_CRLF);
  1783. printf ("match-newline-any:%d\n", G_REGEX_MATCH_NEWLINE_ANY);
  1784. OK_END ();
  1785. }
  1786. const command_arg_type_t cmd_search_string_spec[] =
  1787. {
  1788. ARG_DOC,
  1789. ARG_NATNUM, /* first page */
  1790. ARG_NATNUM, /* last page */
  1791. ARG_NONEMPTY_STRING, /* search string */
  1792. ARG_BOOL, /* ignore-case */
  1793. };
  1794. static void
  1795. cmd_search_string(const epdfinfo_t *ctx, const command_arg_t *args)
  1796. {
  1797. PopplerDocument *doc = args[0].value.doc->pdf;
  1798. int first = args[1].value.natnum;
  1799. int last = args[2].value.natnum;
  1800. const char *string = args[3].value.string;
  1801. gboolean ignore_case = args[4].value.flag;
  1802. GList *list, *item;
  1803. double width, height;
  1804. int pn;
  1805. #ifdef HAVE_POPPLER_FIND_OPTS
  1806. PopplerFindFlags flags = ignore_case ? 0 : POPPLER_FIND_CASE_SENSITIVE;
  1807. #endif
  1808. NORMALIZE_PAGE_ARG (doc, &first, &last);
  1809. OK_BEGIN ();
  1810. for (pn = first; pn <= last; ++pn)
  1811. {
  1812. PopplerPage *page = poppler_document_get_page(doc, pn - 1);
  1813. if (! page)
  1814. continue;
  1815. #ifdef HAVE_POPPLER_FIND_OPTS
  1816. list = poppler_page_find_text_with_options(page, string, flags);
  1817. #else
  1818. list = poppler_page_find_text(page, string);
  1819. #endif
  1820. poppler_page_get_size (page, &width, &height);
  1821. for (item = list; item; item = item->next)
  1822. {
  1823. gchar *line, *match;
  1824. PopplerRectangle *r = item->data;
  1825. gdouble y1 = r->y1;
  1826. r->y1 = height - r->y2;
  1827. r->y2 = height - y1;
  1828. printf ("%d:", pn);
  1829. line = strchomp (poppler_page_get_selected_text
  1830. (page, POPPLER_SELECTION_LINE, r));
  1831. match = strchomp (poppler_page_get_selected_text
  1832. (page, POPPLER_SELECTION_GLYPH, r));
  1833. print_response_string (match, COLON);
  1834. print_response_string (line, COLON);
  1835. printf ("%f %f %f %f\n",
  1836. r->x1 / width, r->y1 / height,
  1837. r->x2 / width, r->y2 / height);
  1838. g_free (line);
  1839. g_free (match);
  1840. poppler_rectangle_free (r);
  1841. }
  1842. g_list_free (list);
  1843. g_object_unref (page);
  1844. }
  1845. OK_END ();
  1846. }
  1847. /* Name: metadata
  1848. Args: filename
  1849. Returns: PDF's metadata
  1850. Errors: None
  1851. title author subject keywords creator producer pdf-version create-date mod-date
  1852. Dates are in seconds since the epoche.
  1853. */
  1854. const command_arg_type_t cmd_metadata_spec[] =
  1855. {
  1856. ARG_DOC,
  1857. };
  1858. static void
  1859. cmd_metadata (const epdfinfo_t *ctx, const command_arg_t *args)
  1860. {
  1861. PopplerDocument *doc = args[0].value.doc->pdf;
  1862. time_t date;
  1863. gchar *md[6];
  1864. gchar *title;
  1865. int i;
  1866. char *time_str;
  1867. OK_BEGIN ();
  1868. title = poppler_document_get_title (doc);
  1869. print_response_string (title, COLON);
  1870. g_free (title);
  1871. md[0] = poppler_document_get_author (doc);
  1872. md[1] = poppler_document_get_subject (doc);
  1873. md[2] = poppler_document_get_keywords (doc);
  1874. md[3] = poppler_document_get_creator (doc);
  1875. md[4] = poppler_document_get_producer (doc);
  1876. md[5] = poppler_document_get_pdf_version_string (doc);
  1877. for (i = 0; i < 6; ++i)
  1878. {
  1879. print_response_string (md[i], COLON);
  1880. g_free (md[i]);
  1881. }
  1882. date = poppler_document_get_creation_date (doc);
  1883. time_str = strchomp (ctime (&date));
  1884. print_response_string (time_str ? time_str : "", COLON);
  1885. date = poppler_document_get_modification_date (doc);
  1886. time_str = strchomp (ctime (&date));
  1887. print_response_string (time_str ? time_str : "", NEWLINE);
  1888. OK_END ();
  1889. }
  1890. /* Name: outline
  1891. Args: filename
  1892. Returns: The documents outline (or index) as a, possibly empty,
  1893. list of records:
  1894. tree-level ACTION
  1895. See cmd_pagelinks for how ACTION is constructed.
  1896. Errors: None
  1897. */
  1898. static void
  1899. cmd_outline_walk (PopplerDocument *doc, PopplerIndexIter *iter, int depth)
  1900. {
  1901. do
  1902. {
  1903. PopplerIndexIter *child;
  1904. PopplerAction *action = poppler_index_iter_get_action (iter);
  1905. if (! action)
  1906. continue;
  1907. if (action_is_handled (action))
  1908. {
  1909. printf ("%d:", depth);
  1910. action_print (doc, action);
  1911. }
  1912. child = poppler_index_iter_get_child (iter);
  1913. if (child)
  1914. {
  1915. cmd_outline_walk (doc, child, depth + 1);
  1916. }
  1917. poppler_action_free (action);
  1918. poppler_index_iter_free (child);
  1919. } while (poppler_index_iter_next (iter));
  1920. }
  1921. const command_arg_type_t cmd_outline_spec[] =
  1922. {
  1923. ARG_DOC,
  1924. };
  1925. static void
  1926. cmd_outline (const epdfinfo_t *ctx, const command_arg_t *args)
  1927. {
  1928. PopplerIndexIter *iter = poppler_index_iter_new (args->value.doc->pdf);
  1929. OK_BEGIN ();
  1930. if (iter)
  1931. {
  1932. cmd_outline_walk (args->value.doc->pdf, iter, 1);
  1933. poppler_index_iter_free (iter);
  1934. }
  1935. OK_END ();
  1936. }
  1937. /* Name: quit
  1938. Args: None
  1939. Returns: Nothing
  1940. Errors: None
  1941. Close all documents and exit.
  1942. */
  1943. const command_arg_type_t cmd_quit_spec[] = {};
  1944. static void
  1945. cmd_quit (const epdfinfo_t *ctx, const command_arg_t *args)
  1946. {
  1947. cmd_closeall (ctx, args);
  1948. exit (EXIT_SUCCESS);
  1949. }
  1950. /* Name: number-of-pages
  1951. Args: filename
  1952. Returns: The number of pages.
  1953. Errors: None
  1954. */
  1955. const command_arg_type_t cmd_number_of_pages_spec[] =
  1956. {
  1957. ARG_DOC
  1958. };
  1959. static void
  1960. cmd_number_of_pages (const epdfinfo_t *ctx, const command_arg_t *args)
  1961. {
  1962. int npages = poppler_document_get_n_pages (args->value.doc->pdf);
  1963. OK_BEGIN ();
  1964. printf ("%d\n", npages);
  1965. OK_END ();
  1966. }
  1967. /* Name: pagelinks
  1968. Args: filename page
  1969. Returns: A list of linkmaps:
  1970. edges ACTION ,
  1971. where ACTION is one of
  1972. 'goto-dest' title page top
  1973. 'goto-remote' title filename page top
  1974. 'uri' title URI
  1975. 'launch' title program arguments
  1976. top is desired vertical position, filename is the target PDF of the
  1977. `goto-remote' link.
  1978. Errors: None
  1979. */
  1980. const command_arg_type_t cmd_pagelinks_spec[] =
  1981. {
  1982. ARG_DOC,
  1983. ARG_NATNUM /* page number */
  1984. };
  1985. static void
  1986. cmd_pagelinks(const epdfinfo_t *ctx, const command_arg_t *args)
  1987. {
  1988. PopplerDocument *doc = args[0].value.doc->pdf;
  1989. PopplerPage *page = NULL;
  1990. int pn = args[1].value.natnum;
  1991. double width, height;
  1992. GList *link_map = NULL, *item;
  1993. page = poppler_document_get_page (doc, pn - 1);
  1994. perror_if_not (page, "No such page %d", pn);
  1995. poppler_page_get_size (page, &width, &height);
  1996. link_map = poppler_page_get_link_mapping (page);
  1997. OK_BEGIN ();
  1998. for (item = g_list_last (link_map); item; item = item->prev)
  1999. {
  2000. PopplerLinkMapping *link = item->data;
  2001. PopplerRectangle *r = &link->area;
  2002. gdouble y1 = r->y1;
  2003. /* LinkMappings have a different gravity. */
  2004. r->y1 = height - r->y2;
  2005. r->y2 = height - y1;
  2006. if (! action_is_handled (link->action))
  2007. continue;
  2008. printf ("%f %f %f %f:",
  2009. r->x1 / width, r->y1 / height,
  2010. r->x2 / width, r->y2 / height);
  2011. action_print (doc, link->action);
  2012. }
  2013. OK_END ();
  2014. error:
  2015. if (page) g_object_unref (page);
  2016. if (link_map) poppler_page_free_link_mapping (link_map);
  2017. }
  2018. /* Name: gettext
  2019. Args: filename page edges selection-style
  2020. Returns: The selection's text.
  2021. Errors: If page is out of range.
  2022. For the selection-style argument see getselection command.
  2023. */
  2024. const command_arg_type_t cmd_gettext_spec[] =
  2025. {
  2026. ARG_DOC,
  2027. ARG_NATNUM, /* page number */
  2028. ARG_EDGES, /* selection */
  2029. ARG_NATNUM /* selection-style */
  2030. };
  2031. static void
  2032. cmd_gettext(const epdfinfo_t *ctx, const command_arg_t *args)
  2033. {
  2034. PopplerDocument *doc = args[0].value.doc->pdf;
  2035. int pn = args[1].value.natnum;
  2036. PopplerRectangle r = args[2].value.rectangle;
  2037. int selection_style = args[3].value.natnum;
  2038. PopplerPage *page = NULL;
  2039. double width, height;
  2040. gchar *text = NULL;
  2041. switch (selection_style)
  2042. {
  2043. case POPPLER_SELECTION_GLYPH: break;
  2044. case POPPLER_SELECTION_LINE: break;
  2045. case POPPLER_SELECTION_WORD: break;
  2046. default: selection_style = POPPLER_SELECTION_GLYPH;
  2047. }
  2048. page = poppler_document_get_page (doc, pn - 1);
  2049. perror_if_not (page, "No such page %d", pn);
  2050. poppler_page_get_size (page, &width, &height);
  2051. r.x1 = r.x1 * width;
  2052. r.x2 = r.x2 * width;
  2053. r.y1 = r.y1 * height;
  2054. r.y2 = r.y2 * height;
  2055. /* printf ("%f %f %f %f , %f %f\n", r.x1, r.y1, r.x2, r.y2, width, height); */
  2056. text = poppler_page_get_selected_text (page, selection_style, &r);
  2057. OK_BEGIN ();
  2058. print_response_string (text, NEWLINE);
  2059. OK_END ();
  2060. error:
  2061. g_free (text);
  2062. if (page) g_object_unref (page);
  2063. }
  2064. /* Name: getselection
  2065. Args: filename page edges selection-selection_style
  2066. Returns: The selection's text.
  2067. Errors: If page is out of range.
  2068. selection-selection_style should be as follows.
  2069. 0 (POPPLER_SELECTION_GLYPH)
  2070. glyph is the minimum unit for selection
  2071. 1 (POPPLER_SELECTION_WORD)
  2072. word is the minimum unit for selection
  2073. 2 (POPPLER_SELECTION_LINE)
  2074. line is the minimum unit for selection
  2075. */
  2076. const command_arg_type_t cmd_getselection_spec[] =
  2077. {
  2078. ARG_DOC,
  2079. ARG_NATNUM, /* page number */
  2080. ARG_EDGES, /* selection */
  2081. ARG_NATNUM /* selection-style */
  2082. };
  2083. static void
  2084. cmd_getselection (const epdfinfo_t *ctx, const command_arg_t *args)
  2085. {
  2086. PopplerDocument *doc = args[0].value.doc->pdf;
  2087. int pn = args[1].value.natnum;
  2088. PopplerRectangle r = args[2].value.rectangle;
  2089. int selection_style = args[3].value.natnum;
  2090. gdouble width, height;
  2091. cairo_region_t *region = NULL;
  2092. PopplerPage *page = NULL;
  2093. int i;
  2094. switch (selection_style)
  2095. {
  2096. case POPPLER_SELECTION_GLYPH: break;
  2097. case POPPLER_SELECTION_LINE: break;
  2098. case POPPLER_SELECTION_WORD: break;
  2099. default: selection_style = POPPLER_SELECTION_GLYPH;
  2100. }
  2101. page = poppler_document_get_page (doc, pn - 1);
  2102. perror_if_not (page, "No such page %d", pn);
  2103. poppler_page_get_size (page, &width, &height);
  2104. r.x1 = r.x1 * width;
  2105. r.x2 = r.x2 * width;
  2106. r.y1 = r.y1 * height;
  2107. r.y2 = r.y2 * height;
  2108. region = poppler_page_get_selected_region (page, 1.0, selection_style, &r);
  2109. OK_BEGIN ();
  2110. for (i = 0; i < cairo_region_num_rectangles (region); ++i)
  2111. {
  2112. cairo_rectangle_int_t r;
  2113. cairo_region_get_rectangle (region, i, &r);
  2114. printf ("%f %f %f %f\n",
  2115. r.x / width,
  2116. r.y / height,
  2117. (r.x + r.width) / width,
  2118. (r.y + r.height) / height);
  2119. }
  2120. OK_END ();
  2121. error:
  2122. if (region) cairo_region_destroy (region);
  2123. if (page) g_object_unref (page);
  2124. }
  2125. /* Name: pagesize
  2126. Args: filename page
  2127. Returns: width height
  2128. Errors: If page is out of range.
  2129. */
  2130. const command_arg_type_t cmd_pagesize_spec[] =
  2131. {
  2132. ARG_DOC,
  2133. ARG_NATNUM /* page number */
  2134. };
  2135. static void
  2136. cmd_pagesize(const epdfinfo_t *ctx, const command_arg_t *args)
  2137. {
  2138. PopplerDocument *doc = args[0].value.doc->pdf;
  2139. int pn = args[1].value.natnum;
  2140. PopplerPage *page = NULL;
  2141. double width, height;
  2142. page = poppler_document_get_page (doc, pn - 1);
  2143. perror_if_not (page, "No such page %d", pn);
  2144. poppler_page_get_size (page, &width, &height);
  2145. OK_BEGIN ();
  2146. printf ("%f:%f\n", width, height);
  2147. OK_END ();
  2148. error:
  2149. if (page) g_object_unref (page);
  2150. }
  2151. /* Annotations */
  2152. /* Name: getannots
  2153. Args: filename firstpage lastpage
  2154. Returns: The list of annotations of this page.
  2155. For all annotations
  2156. page edges type key flags color contents mod-date
  2157. ,where
  2158. name is a document-unique name,
  2159. flags is PopplerAnnotFlag bitmask,
  2160. color is 3-byte RGB hex number and
  2161. Then
  2162. label subject opacity popup-edges popup-is-open create-date
  2163. if this is a markup annotation and additionally
  2164. text-icon text-state
  2165. for markup text annotations.
  2166. Errors: If page is out of range.
  2167. */
  2168. const command_arg_type_t cmd_getannots_spec[] =
  2169. {
  2170. ARG_DOC,
  2171. ARG_NATNUM, /* first page */
  2172. ARG_NATNUM /* last page */
  2173. };
  2174. static void
  2175. cmd_getannots(const epdfinfo_t *ctx, const command_arg_t *args)
  2176. {
  2177. PopplerDocument *doc = args[0].value.doc->pdf;
  2178. gint first = args[1].value.natnum;
  2179. gint last = args[2].value.natnum;
  2180. GList *list;
  2181. gint pn;
  2182. first = MAX(1, first);
  2183. if (last <= 0)
  2184. last = poppler_document_get_n_pages (doc);
  2185. else
  2186. last = MIN(last, poppler_document_get_n_pages (doc));
  2187. OK_BEGIN ();
  2188. for (pn = first; pn <= last; ++pn)
  2189. {
  2190. GList *annots = annoation_get_for_page (args->value.doc, pn);
  2191. PopplerPage *page = poppler_document_get_page (doc, pn - 1);
  2192. if (! page)
  2193. continue;
  2194. for (list = annots; list; list = list->next)
  2195. {
  2196. annotation_t *annot = (annotation_t *)list->data;
  2197. annotation_print (annot, page);
  2198. }
  2199. g_object_unref (page);
  2200. }
  2201. OK_END ();
  2202. }
  2203. /* Name: getannot
  2204. Args: filename name
  2205. Returns: The annotation for name, see cmd_getannots.
  2206. Errors: If no annotation named ,name' exists.
  2207. */
  2208. const command_arg_type_t cmd_getannot_spec[] =
  2209. {
  2210. ARG_DOC,
  2211. ARG_NONEMPTY_STRING, /* annotation's key */
  2212. };
  2213. static void
  2214. cmd_getannot (const epdfinfo_t *ctx, const command_arg_t *args)
  2215. {
  2216. document_t *doc = args->value.doc;
  2217. const gchar *key = args[1].value.string;
  2218. PopplerPage *page = NULL;
  2219. annotation_t *a = annotation_get_by_key (doc, key);
  2220. gint index;
  2221. perror_if_not (a, "No such annotation: %s", key);
  2222. index = poppler_annot_get_page_index (a->amap->annot);
  2223. if (index >= 0)
  2224. page = poppler_document_get_page (doc->pdf, index);
  2225. perror_if_not (page, "Unable to get page %d", index + 1);
  2226. OK_BEGIN ();
  2227. annotation_print (a, page);
  2228. OK_END ();
  2229. error:
  2230. if (page) g_object_unref (page);
  2231. }
  2232. /* Name: getannot_attachment
  2233. Args: filename name [output-filename]
  2234. Returns: name description size mtime ctime output-filename
  2235. Errors: If no annotation named ,name' exists or output-filename is
  2236. not writable.
  2237. */
  2238. const command_arg_type_t cmd_getattachment_from_annot_spec[] =
  2239. {
  2240. ARG_DOC,
  2241. ARG_NONEMPTY_STRING, /* annotation's name */
  2242. ARG_BOOL /* save attachment */
  2243. };
  2244. static void
  2245. cmd_getattachment_from_annot (const epdfinfo_t *ctx, const command_arg_t *args)
  2246. {
  2247. document_t *doc = args->value.doc;
  2248. const gchar *key = args[1].value.string;
  2249. gboolean do_save = args[2].value.flag;
  2250. PopplerAttachment *att = NULL;
  2251. annotation_t *a = annotation_get_by_key (doc, key);
  2252. gchar *id = NULL;
  2253. perror_if_not (a, "No such annotation: %s", key);
  2254. perror_if_not (POPPLER_IS_ANNOT_FILE_ATTACHMENT (a->amap->annot),
  2255. "Not a file annotation: %s", key);
  2256. att = poppler_annot_file_attachment_get_attachment
  2257. (POPPLER_ANNOT_FILE_ATTACHMENT (a->amap->annot));
  2258. perror_if_not (att, "Unable to get attachment: %s", key);
  2259. id = g_strdup_printf ("attachment-%s", key);
  2260. OK_BEGIN ();
  2261. attachment_print (att, id, do_save);
  2262. OK_END ();
  2263. error:
  2264. if (att) g_object_unref (att);
  2265. if (id) g_free (id);
  2266. }
  2267. /* document-level attachments */
  2268. const command_arg_type_t cmd_getattachments_spec[] =
  2269. {
  2270. ARG_DOC,
  2271. ARG_BOOL, /* save attachments */
  2272. };
  2273. static void
  2274. cmd_getattachments (const epdfinfo_t *ctx, const command_arg_t *args)
  2275. {
  2276. document_t *doc = args->value.doc;
  2277. gboolean do_save = args[1].value.flag;
  2278. GList *item;
  2279. GList *attmnts = poppler_document_get_attachments (doc->pdf);
  2280. int i;
  2281. OK_BEGIN ();
  2282. for (item = attmnts, i = 0; item; item = item->next, ++i)
  2283. {
  2284. PopplerAttachment *att = (PopplerAttachment*) item->data;
  2285. gchar *id = g_strdup_printf ("attachment-document-%d", i);
  2286. attachment_print (att, id, do_save);
  2287. g_object_unref (att);
  2288. g_free (id);
  2289. }
  2290. g_list_free (attmnts);
  2291. OK_END ();
  2292. }
  2293. #ifdef HAVE_POPPLER_ANNOT_WRITE
  2294. const command_arg_type_t cmd_addannot_spec[] =
  2295. {
  2296. ARG_DOC,
  2297. ARG_NATNUM, /* page number */
  2298. ARG_STRING, /* type */
  2299. ARG_EDGES_OR_POSITION, /* edges or position (uses default size) */
  2300. ARG_REST, /* markup regions */
  2301. };
  2302. static void
  2303. cmd_addannot (const epdfinfo_t *ctx, const command_arg_t *args)
  2304. {
  2305. document_t *doc = args->value.doc;
  2306. gint pn = args[1].value.natnum;
  2307. const char *type_string = args[2].value.string;
  2308. PopplerRectangle r = args[3].value.rectangle;
  2309. int i;
  2310. PopplerPage *page = NULL;
  2311. double width, height;
  2312. PopplerAnnot *pa;
  2313. PopplerAnnotMapping *amap;
  2314. annotation_t *a;
  2315. gchar *key;
  2316. GList *annotations;
  2317. gdouble y2;
  2318. char *error_msg = NULL;
  2319. page = poppler_document_get_page (doc->pdf, pn - 1);
  2320. perror_if_not (page, "Unable to get page %d", pn);
  2321. poppler_page_get_size (page, &width, &height);
  2322. r.x1 *= width; r.x2 *= width;
  2323. r.y1 *= height; r.y2 *= height;
  2324. if (r.y2 < 0)
  2325. r.y2 = r.y1 + 24;
  2326. if (r.x2 < 0)
  2327. r.x2 = r.x1 + 24;
  2328. y2 = r.y2;
  2329. r.y2 = height - r.y1;
  2330. r.y1 = height - y2;
  2331. pa = annotation_new (ctx, doc, page, type_string, &r, &args[4], &error_msg);
  2332. perror_if_not (pa, "Creating annotation failed: %s",
  2333. error_msg ? error_msg : "Reason unknown");
  2334. amap = poppler_annot_mapping_new ();
  2335. amap->area = r;
  2336. amap->annot = pa;
  2337. annotations = annoation_get_for_page (doc, pn);
  2338. i = g_list_length (annotations);
  2339. key = g_strdup_printf ("annot-%d-%d", pn, i);
  2340. while (g_hash_table_lookup (doc->annotations.keys, key))
  2341. {
  2342. g_free (key);
  2343. key = g_strdup_printf ("annot-%d-%d", pn, ++i);
  2344. }
  2345. a = g_malloc (sizeof (annotation_t));
  2346. a->amap = amap;
  2347. a->key = key;
  2348. doc->annotations.pages[pn - 1] =
  2349. g_list_prepend (annotations, a);
  2350. g_hash_table_insert (doc->annotations.keys, key, a);
  2351. poppler_page_add_annot (page, pa);
  2352. OK_BEGIN ();
  2353. annotation_print (a, page);
  2354. OK_END ();
  2355. error:
  2356. if (page) g_object_unref (page);
  2357. if (error_msg) g_free (error_msg);
  2358. }
  2359. const command_arg_type_t cmd_delannot_spec[] =
  2360. {
  2361. ARG_DOC,
  2362. ARG_NONEMPTY_STRING /* Annotation's key */
  2363. };
  2364. static void
  2365. cmd_delannot (const epdfinfo_t *ctx, const command_arg_t *args)
  2366. {
  2367. document_t *doc = args->value.doc;
  2368. const gchar *key = args[1].value.string;
  2369. PopplerPage *page = NULL;
  2370. annotation_t *a = annotation_get_by_key (doc, key);
  2371. gint pn;
  2372. perror_if_not (a, "No such annotation: %s", key);
  2373. pn = poppler_annot_get_page_index (a->amap->annot) + 1;
  2374. if (pn >= 1)
  2375. page = poppler_document_get_page (doc->pdf, pn - 1);
  2376. perror_if_not (page, "Unable to get page %d", pn);
  2377. poppler_page_remove_annot (page, a->amap->annot);
  2378. doc->annotations.pages[pn - 1] =
  2379. g_list_remove (doc->annotations.pages[pn - 1], a);
  2380. g_hash_table_remove (doc->annotations.keys, a->key);
  2381. poppler_annot_mapping_free(a->amap);
  2382. OK ();
  2383. error:
  2384. if (a)
  2385. {
  2386. g_free (a->key);
  2387. g_free (a);
  2388. }
  2389. if (page) g_object_unref (page);
  2390. }
  2391. const command_arg_type_t cmd_editannot_spec[] =
  2392. {
  2393. ARG_DOC,
  2394. ARG_NONEMPTY_STRING, /* annotation key */
  2395. ARG_REST /* (KEY VALUE ...) */
  2396. };
  2397. static void
  2398. cmd_editannot (const epdfinfo_t *ctx, const command_arg_t *args)
  2399. {
  2400. document_t *doc = args->value.doc;
  2401. const char *key = args[1].value.string;
  2402. int nrest_args = args[2].value.rest.nargs;
  2403. char * const *rest_args = args[2].value.rest.args;
  2404. annotation_t *a = annotation_get_by_key (doc, key);
  2405. PopplerAnnot *pa;
  2406. PopplerPage *page = NULL;
  2407. int i = 0;
  2408. gint index;
  2409. char *error_msg = NULL;
  2410. command_arg_t carg;
  2411. const char *unexpected_parse_error = "Internal error while parsing arg `%s'";
  2412. perror_if_not (a, "No such annotation: %s", key);
  2413. pa = a->amap->annot;
  2414. perror_if_not (annotation_edit_validate (ctx, &args[2], pa, &error_msg),
  2415. "%s", error_msg);
  2416. index = poppler_annot_get_page_index (pa);
  2417. page = poppler_document_get_page (doc->pdf, index);
  2418. perror_if_not (page, "Unable to get page %d for annotation", index);
  2419. for (i = 0; i < nrest_args; ++i)
  2420. {
  2421. const char *key = rest_args[i++];
  2422. if (! strcmp (key, "flags"))
  2423. {
  2424. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2425. ARG_NATNUM, NULL),
  2426. unexpected_parse_error, rest_args[i]);
  2427. poppler_annot_set_flags (pa, carg.value.natnum);
  2428. }
  2429. else if (! strcmp (key, "color"))
  2430. {
  2431. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2432. ARG_COLOR, NULL),
  2433. unexpected_parse_error, rest_args[i]);
  2434. poppler_annot_set_color (pa, &carg.value.color);
  2435. }
  2436. else if (! strcmp (key, "contents"))
  2437. {
  2438. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2439. ARG_STRING, NULL),
  2440. unexpected_parse_error, rest_args[i]);
  2441. poppler_annot_set_contents (pa, carg.value.string);
  2442. }
  2443. else if (! strcmp (key, "edges"))
  2444. {
  2445. PopplerRectangle *area = &a->amap->area;
  2446. gdouble width, height;
  2447. PopplerRectangle r;
  2448. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2449. ARG_EDGES_OR_POSITION, NULL),
  2450. unexpected_parse_error, rest_args[i]);
  2451. r = carg.value.rectangle;
  2452. poppler_page_get_size (page, &width, &height);
  2453. /* Translate Gravity and maybe keep the width and height. */
  2454. if (r.x2 < 0)
  2455. area->x2 += (r.x1 * width) - area->x1;
  2456. else
  2457. area->x2 = r.x2 * width;
  2458. if (r.y2 < 0)
  2459. area->y1 -= (r.y1 * height) - (height - area->y2);
  2460. else
  2461. area->y1 = height - (r.y2 * height);
  2462. area->x1 = r.x1 * width;
  2463. area->y2 = height - (r.y1 * height);
  2464. xpoppler_annot_set_rectangle (pa, area);
  2465. }
  2466. else if (! strcmp (key, "label"))
  2467. {
  2468. PopplerAnnotMarkup *ma = POPPLER_ANNOT_MARKUP (pa);
  2469. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2470. ARG_STRING, NULL),
  2471. unexpected_parse_error, rest_args[i]);
  2472. poppler_annot_markup_set_label (ma, carg.value.string);
  2473. }
  2474. else if (! strcmp (key, "opacity"))
  2475. {
  2476. PopplerAnnotMarkup *ma = POPPLER_ANNOT_MARKUP (pa);
  2477. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2478. ARG_EDGE, NULL),
  2479. unexpected_parse_error, rest_args[i]);
  2480. poppler_annot_markup_set_opacity (ma, carg.value.edge);
  2481. }
  2482. else if (! strcmp (key, "popup"))
  2483. {
  2484. PopplerAnnotMarkup *ma = POPPLER_ANNOT_MARKUP (pa);
  2485. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2486. ARG_EDGES, NULL),
  2487. unexpected_parse_error, rest_args[i]);
  2488. poppler_annot_markup_set_popup (ma, &carg.value.rectangle);
  2489. }
  2490. else if (! strcmp (key, "popup-is-open"))
  2491. {
  2492. PopplerAnnotMarkup *ma = POPPLER_ANNOT_MARKUP (pa);
  2493. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2494. ARG_BOOL, NULL),
  2495. unexpected_parse_error, rest_args[i]);
  2496. poppler_annot_markup_set_popup_is_open (ma, carg.value.flag);
  2497. }
  2498. else if (! strcmp (key, "icon"))
  2499. {
  2500. PopplerAnnotText *ta = POPPLER_ANNOT_TEXT (pa);
  2501. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2502. ARG_STRING, NULL),
  2503. unexpected_parse_error, rest_args[i]);
  2504. poppler_annot_text_set_icon (ta, carg.value.string);
  2505. }
  2506. else if (! strcmp (key, "is-open"))
  2507. {
  2508. PopplerAnnotText *ta = POPPLER_ANNOT_TEXT (pa);
  2509. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &carg,
  2510. ARG_BOOL, NULL),
  2511. unexpected_parse_error, rest_args[i]);
  2512. poppler_annot_text_set_is_open (ta, carg.value.flag);
  2513. }
  2514. else
  2515. {
  2516. perror_if_not (0, "internal error: annotation property validation failed");
  2517. }
  2518. }
  2519. OK_BEGIN ();
  2520. annotation_print (a, page);
  2521. OK_END ();
  2522. error:
  2523. if (error_msg) g_free (error_msg);
  2524. if (page) g_object_unref (page);
  2525. }
  2526. const command_arg_type_t cmd_save_spec[] =
  2527. {
  2528. ARG_DOC,
  2529. };
  2530. static void
  2531. cmd_save (const epdfinfo_t *ctx, const command_arg_t *args)
  2532. {
  2533. document_t *doc = args->value.doc;
  2534. char *filename = mktempfile ();
  2535. GError *gerror = NULL;
  2536. gchar *uri;
  2537. gboolean success = FALSE;
  2538. if (!filename)
  2539. {
  2540. printf_error_response ("Unable to create temporary file");
  2541. return;
  2542. }
  2543. uri = g_filename_to_uri (filename, NULL, &gerror);
  2544. if (uri)
  2545. {
  2546. success = poppler_document_save (doc->pdf, uri, &gerror);
  2547. g_free (uri);
  2548. }
  2549. if (! success)
  2550. {
  2551. printf_error_response ("Error while saving %s:%s"
  2552. , filename, gerror ? gerror->message : "?");
  2553. if (gerror)
  2554. g_error_free (gerror);
  2555. return;
  2556. }
  2557. OK_BEGIN ();
  2558. print_response_string (filename, NEWLINE);
  2559. OK_END ();
  2560. }
  2561. #endif /* HAVE_POPPLER_ANNOT_WRITE */
  2562. const command_arg_type_t cmd_synctex_forward_search_spec[] =
  2563. {
  2564. ARG_DOC,
  2565. ARG_NONEMPTY_STRING, /* source file */
  2566. ARG_NATNUM, /* line number */
  2567. ARG_NATNUM /* column number */
  2568. };
  2569. static void
  2570. cmd_synctex_forward_search (const epdfinfo_t *ctx, const command_arg_t *args)
  2571. {
  2572. document_t *doc = args[0].value.doc;
  2573. const char *source = args[1].value.string;
  2574. int line = args[2].value.natnum;
  2575. int column = args[3].value.natnum;
  2576. synctex_scanner_t scanner = NULL;
  2577. synctex_node_t node;
  2578. float x1, y1, x2, y2;
  2579. PopplerPage *page = NULL;
  2580. double width, height;
  2581. int pn;
  2582. scanner = synctex_scanner_new_with_output_file (doc->filename, NULL, 1);
  2583. perror_if_not (scanner, "Unable to create synctex scanner,\
  2584. did you run latex with `--synctex=1' ?");
  2585. perror_if_not (synctex_display_query (scanner, source, line, column)
  2586. && (node = synctex_next_result (scanner)),
  2587. "Destination not found");
  2588. pn = synctex_node_page (node);
  2589. page = poppler_document_get_page(doc->pdf, pn - 1);
  2590. perror_if_not (page, "Page not found");
  2591. x1 = synctex_node_box_visible_h (node);
  2592. y1 = synctex_node_box_visible_v (node)
  2593. - synctex_node_box_visible_height (node);
  2594. x2 = synctex_node_box_visible_width (node) + x1;
  2595. y2 = synctex_node_box_visible_depth (node)
  2596. + synctex_node_box_visible_height (node) + y1;
  2597. poppler_page_get_size (page, &width, &height);
  2598. x1 /= width;
  2599. y1 /= height;
  2600. x2 /= width;
  2601. y2 /= height;
  2602. OK_BEGIN ();
  2603. printf("%d:%f:%f:%f:%f\n", pn, x1, y1, x2, y2);
  2604. OK_END ();
  2605. error:
  2606. if (page) g_object_unref (page);
  2607. if (scanner) synctex_scanner_free (scanner);
  2608. }
  2609. const command_arg_type_t cmd_synctex_backward_search_spec[] =
  2610. {
  2611. ARG_DOC,
  2612. ARG_NATNUM, /* page number */
  2613. ARG_EDGE, /* x */
  2614. ARG_EDGE /* y */
  2615. };
  2616. static void
  2617. cmd_synctex_backward_search (const epdfinfo_t *ctx, const command_arg_t *args)
  2618. {
  2619. document_t *doc = args[0].value.doc;
  2620. int pn = args[1].value.natnum;
  2621. double x = args[2].value.edge;
  2622. double y = args[3].value.edge;
  2623. synctex_scanner_t scanner = NULL;
  2624. const char *filename;
  2625. PopplerPage *page = NULL;
  2626. synctex_node_t node;
  2627. double width, height;
  2628. int line, column;
  2629. scanner = synctex_scanner_new_with_output_file (doc->filename, NULL, 1);
  2630. perror_if_not (scanner, "Unable to create synctex scanner,\
  2631. did you run latex with `--synctex=1' ?");
  2632. page = poppler_document_get_page(doc->pdf, pn - 1);
  2633. perror_if_not (page, "Page not found");
  2634. poppler_page_get_size (page, &width, &height);
  2635. x = x * width;
  2636. y = y * height;
  2637. if (! synctex_edit_query (scanner, pn, x, y)
  2638. || ! (node = synctex_next_result (scanner))
  2639. || ! (filename =
  2640. synctex_scanner_get_name (scanner, synctex_node_tag (node))))
  2641. {
  2642. printf_error_response ("Destination not found");
  2643. goto error;
  2644. }
  2645. line = synctex_node_line (node);
  2646. column = synctex_node_column (node);
  2647. OK_BEGIN ();
  2648. print_response_string (filename, COLON);
  2649. printf("%d:%d\n", line, column);
  2650. OK_END ();
  2651. error:
  2652. if (page) g_object_unref (page);
  2653. if (scanner) synctex_scanner_free (scanner);
  2654. }
  2655. const command_arg_type_t cmd_renderpage_spec[] =
  2656. {
  2657. ARG_DOC,
  2658. ARG_NATNUM, /* page number */
  2659. ARG_NATNUM, /* width */
  2660. ARG_REST, /* commands */
  2661. };
  2662. static void
  2663. cmd_renderpage (const epdfinfo_t *ctx, const command_arg_t *args)
  2664. {
  2665. document_t *doc = args[0].value.doc;
  2666. int pn = args[1].value.natnum;
  2667. int width = args[2].value.natnum;
  2668. int nrest_args = args[3].value.rest.nargs;
  2669. char * const *rest_args = args[3].value.rest.args;
  2670. PopplerPage *page = poppler_document_get_page(doc->pdf, pn - 1);
  2671. cairo_surface_t *surface = NULL;
  2672. cairo_t *cr = NULL;
  2673. command_arg_t rest_arg;
  2674. gchar *error_msg = NULL;
  2675. double pt_width, pt_height;
  2676. PopplerColor fg = { 0, 0, 0 };
  2677. PopplerColor bg = { 65535, 0, 0 };
  2678. double alpha = 1.0;
  2679. double line_width = 1.5;
  2680. PopplerRectangle cb = {0.0, 0.0, 1.0, 1.0};
  2681. int i = 0;
  2682. perror_if_not (page, "No such page %d", pn);
  2683. poppler_page_get_size (page, &pt_width, &pt_height);
  2684. surface = image_render_page (doc->pdf, page, width, 1,
  2685. &doc->options.render);
  2686. perror_if_not (surface, "Failed to render page %d", pn);
  2687. if (! nrest_args)
  2688. goto theend;
  2689. cr = cairo_create (surface);
  2690. cairo_scale (cr, width / pt_width, width / pt_width);
  2691. while (i < nrest_args)
  2692. {
  2693. const char* keyword;
  2694. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &rest_arg,
  2695. ARG_STRING, &error_msg),
  2696. "%s", error_msg);
  2697. keyword = rest_arg.value.string;
  2698. ++i;
  2699. perror_if_not (i < nrest_args, "Keyword is `%s' missing an argument",
  2700. keyword);
  2701. if (! strcmp (keyword, ":foreground")
  2702. || ! strcmp (keyword, ":background"))
  2703. {
  2704. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &rest_arg,
  2705. ARG_COLOR, &error_msg),
  2706. "%s", error_msg);
  2707. ++i;
  2708. if (! strcmp (keyword, ":foreground"))
  2709. fg = rest_arg.value.color;
  2710. else
  2711. bg = rest_arg.value.color;
  2712. }
  2713. else if (! strcmp (keyword, ":alpha"))
  2714. {
  2715. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &rest_arg,
  2716. ARG_EDGE, &error_msg),
  2717. "%s", error_msg);
  2718. ++i;
  2719. alpha = rest_arg.value.edge;
  2720. }
  2721. else if (! strcmp (keyword, ":crop-to")
  2722. || ! strcmp (keyword, ":highlight-region")
  2723. || ! strcmp (keyword, ":highlight-text")
  2724. || ! strcmp (keyword, ":highlight-line"))
  2725. {
  2726. PopplerRectangle *r;
  2727. perror_if_not (command_arg_parse_arg (ctx, rest_args[i], &rest_arg,
  2728. ARG_EDGES, &error_msg),
  2729. "%s", error_msg);
  2730. ++i;
  2731. r = &rest_arg.value.rectangle;
  2732. if (! strcmp (keyword, ":crop-to"))
  2733. {
  2734. gdouble w = (cb.x2 - cb.x1);
  2735. gdouble h = (cb.y2 - cb.y1);
  2736. gdouble x1 = cb.x1;
  2737. gdouble y1 = cb.y1;
  2738. cb.x1 = r->x1 * w + x1;
  2739. cb.x2 = r->x2 * w + x1;
  2740. cb.y1 = r->y1 * h + y1;
  2741. cb.y2 = r->y2 * h + y1;
  2742. }
  2743. else
  2744. {
  2745. r->x1 = pt_width * r->x1 * (cb.x2 - cb.x1) + pt_width * cb.x1;
  2746. r->x2 = pt_width * r->x2 * (cb.x2 - cb.x1) + pt_width * cb.x1;
  2747. r->y1 = pt_height * r->y1 * (cb.y2 - cb.y1) + pt_height * cb.y1;
  2748. r->y2 = pt_height * r->y2 * (cb.y2 - cb.y1) + pt_height * cb.y1;
  2749. if (! strcmp (keyword, ":highlight-region"))
  2750. {
  2751. const double deg = M_PI / 180.0;
  2752. double rad;
  2753. r->x1 += line_width / 2;
  2754. r->x2 -= line_width / 2;
  2755. r->y1 += line_width / 2;
  2756. r->y2 -= line_width / 2;
  2757. rad = MIN (5, MIN (r->x2 - r->x1, r->y2 - r->y1) / 2.0);
  2758. cairo_move_to (cr, r->x1 , r->y1 + rad);
  2759. cairo_arc (cr, r->x1 + rad, r->y1 + rad, rad, 180 * deg, 270 * deg);
  2760. cairo_arc (cr, r->x2 - rad, r->y1 + rad, rad, 270 * deg, 360 * deg);
  2761. cairo_arc (cr, r->x2 - rad, r->y2 - rad, rad, 0 * deg, 90 * deg);
  2762. cairo_arc (cr, r->x1 + rad, r->y2 - rad, rad, 90 * deg, 180 * deg);
  2763. cairo_close_path (cr);
  2764. cairo_set_source_rgba (cr,
  2765. bg.red / 65535.0,
  2766. bg.green / 65535.0,
  2767. bg.blue / 65535.0, alpha);
  2768. cairo_fill_preserve (cr);
  2769. cairo_set_source_rgba (cr,
  2770. fg.red / 65535.0,
  2771. fg.green / 65535.0,
  2772. fg.blue / 65535.0, 1.0);
  2773. cairo_set_line_width (cr, line_width);
  2774. cairo_stroke (cr);
  2775. }
  2776. else
  2777. {
  2778. gboolean is_single_line = ! strcmp (keyword, ":highlight-line");
  2779. if (is_single_line)
  2780. {
  2781. gdouble m = r->y1 + (r->y2 - r->y1) / 2;
  2782. /* Make the rectangle flat, otherwise poppler frequently
  2783. renders neighboring lines.*/
  2784. r->y1 = m;
  2785. r->y2 = m;
  2786. }
  2787. poppler_page_render_selection (page, cr, r, NULL,
  2788. POPPLER_SELECTION_GLYPH, &fg, &bg);
  2789. }
  2790. }
  2791. }
  2792. else
  2793. perror_if_not (0, "Unknown render command: %s", keyword);
  2794. }
  2795. if (cb.x1 != 0 || cb.y1 != 0 || cb.x2 != 1 || cb.y2 != 1)
  2796. {
  2797. int height = cairo_image_surface_get_height (surface);
  2798. cairo_rectangle_int_t r = {(int) (width * cb.x1 + 0.5),
  2799. (int) (height * cb.y1 + 0.5),
  2800. (int) (width * (cb.x2 - cb.x1) + 0.5),
  2801. (int) (height * (cb.y2 - cb.y1) + 0.5)};
  2802. cairo_surface_t *nsurface =
  2803. cairo_image_surface_create (CAIRO_FORMAT_ARGB32, r.width, r.height);
  2804. perror_if_not (cairo_surface_status (surface) == CAIRO_STATUS_SUCCESS,
  2805. "%s", "Failed to create cairo surface");
  2806. cairo_destroy (cr);
  2807. cr = cairo_create (nsurface);
  2808. perror_if_not (cairo_status (cr) == CAIRO_STATUS_SUCCESS,
  2809. "%s", "Failed to create cairo context");
  2810. cairo_set_source_surface (cr, surface, -r.x, -r.y);
  2811. cairo_paint (cr);
  2812. cairo_surface_destroy (surface);
  2813. surface = nsurface;
  2814. }
  2815. theend:
  2816. image_write_print_response (surface, PNG);
  2817. error:
  2818. if (error_msg) g_free (error_msg);
  2819. if (cr) cairo_destroy (cr);
  2820. if (surface) cairo_surface_destroy (surface);
  2821. if (page) g_object_unref (page);
  2822. }
  2823. const command_arg_type_t cmd_boundingbox_spec[] =
  2824. {
  2825. ARG_DOC,
  2826. ARG_NATNUM, /* page number */
  2827. /* region */
  2828. };
  2829. static void
  2830. cmd_boundingbox (const epdfinfo_t *ctx, const command_arg_t *args)
  2831. {
  2832. document_t *doc = args[0].value.doc;
  2833. int pn = args[1].value.natnum;
  2834. PopplerPage *page = poppler_document_get_page(doc->pdf, pn - 1);
  2835. cairo_surface_t *surface = NULL;
  2836. int width, height;
  2837. double pt_width, pt_height;
  2838. unsigned char *data, *data_p;
  2839. PopplerRectangle bbox;
  2840. int i, j;
  2841. perror_if_not (page, "No such page %d", pn);
  2842. poppler_page_get_size (page, &pt_width, &pt_height);
  2843. surface = image_render_page (doc->pdf, page, (int) pt_width, 1,
  2844. &doc->options.render);
  2845. perror_if_not (cairo_surface_status(surface) == CAIRO_STATUS_SUCCESS,
  2846. "Failed to render page");
  2847. width = cairo_image_surface_get_width (surface);
  2848. height = cairo_image_surface_get_height (surface);
  2849. data = cairo_image_surface_get_data (surface);
  2850. /* Determine the bbox by comparing each pixel in the 4 corner
  2851. stripes with the origin. */
  2852. for (i = 0; i < width; ++i)
  2853. {
  2854. data_p = data + 4 * i;
  2855. for (j = 0; j < height; ++j, data_p += 4 * width)
  2856. {
  2857. if (! ARGB_EQUAL (data, data_p))
  2858. break;
  2859. }
  2860. if (j < height)
  2861. break;
  2862. }
  2863. bbox.x1 = i;
  2864. for (i = width - 1; i > -1; --i)
  2865. {
  2866. data_p = data + 4 * i;
  2867. for (j = 0; j < height; ++j, data_p += 4 * width)
  2868. {
  2869. if (! ARGB_EQUAL (data, data_p))
  2870. break;
  2871. }
  2872. if (j < height)
  2873. break;
  2874. }
  2875. bbox.x2 = i + 1;
  2876. for (i = 0; i < height; ++i)
  2877. {
  2878. data_p = data + 4 * i * width;
  2879. for (j = 0; j < width; ++j, data_p += 4)
  2880. {
  2881. if (! ARGB_EQUAL (data, data_p))
  2882. break;
  2883. }
  2884. if (j < width)
  2885. break;
  2886. }
  2887. bbox.y1 = i;
  2888. for (i = height - 1; i > -1; --i)
  2889. {
  2890. data_p = data + 4 * i * width;
  2891. for (j = 0; j < width; ++j, data_p += 4)
  2892. {
  2893. if (! ARGB_EQUAL (data, data_p))
  2894. break;
  2895. }
  2896. if (j < width)
  2897. break;
  2898. }
  2899. bbox.y2 = i + 1;
  2900. OK_BEGIN ();
  2901. if (bbox.x1 >= bbox.x2 || bbox.y1 >= bbox.y2)
  2902. {
  2903. /* empty page */
  2904. puts ("0:0:1:1");
  2905. }
  2906. else
  2907. {
  2908. printf ("%f:%f:%f:%f\n",
  2909. bbox.x1 / width,
  2910. bbox.y1 / height,
  2911. bbox.x2 / width,
  2912. bbox.y2 / height);
  2913. }
  2914. OK_END ();
  2915. error:
  2916. if (surface) cairo_surface_destroy (surface);
  2917. if (page) g_object_unref (page);
  2918. }
  2919. const command_arg_type_t cmd_charlayout_spec[] =
  2920. {
  2921. ARG_DOC,
  2922. ARG_NATNUM, /* page number */
  2923. ARG_EDGES_OR_POSITION, /* region or position */
  2924. };
  2925. static void
  2926. cmd_charlayout(const epdfinfo_t *ctx, const command_arg_t *args)
  2927. {
  2928. PopplerDocument *doc = args[0].value.doc->pdf;
  2929. int pn = args[1].value.natnum;
  2930. PopplerRectangle region = args[2].value.rectangle;
  2931. double width, height;
  2932. PopplerPage *page = poppler_document_get_page(doc, pn - 1);
  2933. char *text = NULL;
  2934. char *text_p;
  2935. PopplerRectangle *rectangles = NULL;
  2936. guint nrectangles;
  2937. int i;
  2938. gboolean have_position = region.y2 < 0;
  2939. perror_if_not (page, "No such page %d", pn);
  2940. text = poppler_page_get_text (page);
  2941. text_p = text;
  2942. poppler_page_get_text_layout (page, &rectangles, &nrectangles);
  2943. poppler_page_get_size (page, &width, &height);
  2944. region.x1 *= width;
  2945. region.x2 *= width;
  2946. region.y1 *= height;
  2947. region.y2 *= height;
  2948. OK_BEGIN ();
  2949. for (i = 0; i < nrectangles && *text_p; ++i)
  2950. {
  2951. PopplerRectangle *r = &rectangles[i];
  2952. char *nextc = g_utf8_offset_to_pointer (text_p, 1);
  2953. if ((have_position
  2954. && region.x1 >= r->x1
  2955. && region.x1 <= r->x2
  2956. && region.y1 >= r->y1
  2957. && region.y1 <= r->y2)
  2958. || (! have_position
  2959. && r->x1 >= region.x1
  2960. && r->y1 >= region.y1
  2961. && r->x2 <= region.x2
  2962. && r->y2 <= region.y2))
  2963. {
  2964. char endc = *nextc;
  2965. printf ("%f %f %f %f:",
  2966. r->x1 / width, r->y1 / height,
  2967. r->x2 / width, r->y2 / height);
  2968. *nextc = '\0';
  2969. print_response_string (text_p, NEWLINE);
  2970. *nextc = endc;
  2971. }
  2972. text_p = nextc;
  2973. }
  2974. OK_END ();
  2975. g_free (rectangles);
  2976. g_object_unref (page);
  2977. g_free (text);
  2978. error:
  2979. return;
  2980. }
  2981. const document_option_t document_options [] =
  2982. {
  2983. DEC_DOPT (":render/usecolors", ARG_BOOL, render.usecolors),
  2984. DEC_DOPT (":render/printed", ARG_BOOL, render.printed),
  2985. DEC_DOPT (":render/foreground", ARG_COLOR, render.fg),
  2986. DEC_DOPT (":render/background", ARG_COLOR, render.bg),
  2987. };
  2988. const command_arg_type_t cmd_getoptions_spec[] =
  2989. {
  2990. ARG_DOC,
  2991. };
  2992. static void
  2993. cmd_getoptions(const epdfinfo_t *ctx, const command_arg_t *args)
  2994. {
  2995. document_t *doc = args[0].value.doc;
  2996. int i;
  2997. OK_BEGIN ();
  2998. for (i = 0; i < G_N_ELEMENTS (document_options); ++i)
  2999. {
  3000. command_arg_t arg;
  3001. arg.type = document_options[i].type;
  3002. memcpy (&arg.value,
  3003. ((char*) &doc->options) + document_options[i].offset,
  3004. command_arg_type_size (arg.type));
  3005. print_response_string (document_options[i].name, COLON);
  3006. command_arg_print (&arg);
  3007. puts("");
  3008. }
  3009. OK_END ();
  3010. }
  3011. const command_arg_type_t cmd_setoptions_spec[] =
  3012. {
  3013. ARG_DOC,
  3014. ARG_REST /* key value pairs */
  3015. };
  3016. static void
  3017. cmd_setoptions(const epdfinfo_t *ctx, const command_arg_t *args)
  3018. {
  3019. int i = 0;
  3020. document_t *doc = args[0].value.doc;
  3021. int nrest = args[1].value.rest.nargs;
  3022. char * const *rest = args[1].value.rest.args;
  3023. gchar *error_msg = NULL;
  3024. document_options_t opts = doc->options;
  3025. const size_t nopts = G_N_ELEMENTS (document_options);
  3026. perror_if_not (nrest % 2 == 0, "Even number of key/value pairs expected");
  3027. while (i < nrest)
  3028. {
  3029. int j;
  3030. command_arg_t key, value;
  3031. perror_if_not (command_arg_parse_arg
  3032. (ctx, rest[i], &key, ARG_NONEMPTY_STRING, &error_msg),
  3033. "%s", error_msg);
  3034. ++i;
  3035. for (j = 0; j < nopts; ++j)
  3036. {
  3037. const document_option_t *dopt = &document_options[j];
  3038. if (! strcmp (key.value.string, dopt->name))
  3039. {
  3040. perror_if_not (command_arg_parse_arg
  3041. (ctx, rest[i], &value, dopt->type, &error_msg),
  3042. "%s", error_msg);
  3043. memcpy (((char*) &opts) + dopt->offset,
  3044. &value.value, command_arg_type_size (value.type));
  3045. break;
  3046. }
  3047. }
  3048. perror_if_not (j < nopts, "Unknown option: %s", key.value.string);
  3049. ++i;
  3050. }
  3051. doc->options = opts;
  3052. cmd_getoptions (ctx, args);
  3053. error:
  3054. if (error_msg) g_free (error_msg);
  3055. }
  3056. const command_arg_type_t cmd_pagelabels_spec[] =
  3057. {
  3058. ARG_DOC,
  3059. };
  3060. static void
  3061. cmd_pagelabels(const epdfinfo_t *ctx, const command_arg_t *args)
  3062. {
  3063. PopplerDocument *doc = args[0].value.doc->pdf;
  3064. int i;
  3065. OK_BEGIN ();
  3066. for (i = 0; i < poppler_document_get_n_pages (doc); ++i)
  3067. {
  3068. PopplerPage *page = poppler_document_get_page(doc, i);
  3069. gchar *label = poppler_page_get_label (page);
  3070. print_response_string (label ? label : "", NEWLINE);
  3071. g_object_unref (page);
  3072. g_free (label);
  3073. }
  3074. OK_END ();
  3075. }
  3076. const command_arg_type_t cmd_ping_spec[] =
  3077. {
  3078. ARG_STRING /* any message */
  3079. };
  3080. static void
  3081. cmd_ping (const epdfinfo_t *ctx, const command_arg_t *args)
  3082. {
  3083. const gchar *msg = args[0].value.string;
  3084. OK_BEGIN ();
  3085. print_response_string (msg, NEWLINE);
  3086. OK_END ();
  3087. }
  3088. /* ================================================================== *
  3089. * Main
  3090. * ================================================================== */
  3091. static const command_t commands [] =
  3092. {
  3093. /* Basic */
  3094. DEC_CMD (ping),
  3095. DEC_CMD (features),
  3096. DEC_CMD (open),
  3097. DEC_CMD (close),
  3098. DEC_CMD (quit),
  3099. DEC_CMD (getoptions),
  3100. DEC_CMD (setoptions),
  3101. /* Searching */
  3102. DEC_CMD2 (search_string, "search-string"),
  3103. DEC_CMD2 (search_regexp, "search-regexp"),
  3104. DEC_CMD2 (regexp_flags, "regexp-flags"),
  3105. /* General Information */
  3106. DEC_CMD (metadata),
  3107. DEC_CMD (outline),
  3108. DEC_CMD2 (number_of_pages, "number-of-pages"),
  3109. DEC_CMD (pagelinks),
  3110. DEC_CMD (gettext),
  3111. DEC_CMD (getselection),
  3112. DEC_CMD (pagesize),
  3113. DEC_CMD (boundingbox),
  3114. DEC_CMD (charlayout),
  3115. /* General Information */
  3116. DEC_CMD (metadata),
  3117. DEC_CMD (outline),
  3118. DEC_CMD2 (number_of_pages, "number-of-pages"),
  3119. DEC_CMD (pagelinks),
  3120. DEC_CMD (gettext),
  3121. DEC_CMD (getselection),
  3122. DEC_CMD (pagesize),
  3123. DEC_CMD (boundingbox),
  3124. DEC_CMD (charlayout),
  3125. DEC_CMD (pagelabels),
  3126. /* Annotations */
  3127. DEC_CMD (getannots),
  3128. DEC_CMD (getannot),
  3129. #ifdef HAVE_POPPLER_ANNOT_WRITE
  3130. DEC_CMD (addannot),
  3131. DEC_CMD (delannot),
  3132. DEC_CMD (editannot),
  3133. DEC_CMD (save),
  3134. #endif
  3135. /* Attachments */
  3136. DEC_CMD2 (getattachment_from_annot, "getattachment-from-annot"),
  3137. DEC_CMD (getattachments),
  3138. /* Synctex */
  3139. DEC_CMD2 (synctex_forward_search, "synctex-forward-search"),
  3140. DEC_CMD2 (synctex_backward_search, "synctex-backward-search"),
  3141. /* Rendering */
  3142. DEC_CMD (renderpage),
  3143. };
  3144. int main(int argc, char **argv)
  3145. {
  3146. epdfinfo_t ctx = {0};
  3147. char *line = NULL;
  3148. ssize_t read;
  3149. size_t line_size;
  3150. const char *error_log = "/dev/null";
  3151. #ifdef __MINGW32__
  3152. error_log = "NUL";
  3153. _setmode(_fileno(stdin), _O_BINARY);
  3154. _setmode(_fileno(stdout), _O_BINARY);
  3155. #endif
  3156. if (argc > 2)
  3157. {
  3158. fprintf(stderr, "usage: epdfinfo [ERROR-LOGFILE]\n");
  3159. exit (EXIT_FAILURE);
  3160. }
  3161. if (argc == 2)
  3162. error_log = argv[1];
  3163. if (! freopen (error_log, "a", stderr))
  3164. err (2, "Unable to redirect stderr");
  3165. #if ! GLIB_CHECK_VERSION(2,36,0)
  3166. g_type_init ();
  3167. #endif
  3168. ctx.documents = g_hash_table_new (g_str_hash, g_str_equal);
  3169. setvbuf (stdout, NULL, _IOFBF, BUFSIZ);
  3170. while ((read = getline (&line, &line_size, stdin)) != -1)
  3171. {
  3172. int nargs = 0;
  3173. command_arg_t *cmd_args = NULL;
  3174. char **args = NULL;
  3175. gchar *error_msg = NULL;
  3176. int i;
  3177. if (read <= 1 || line[read - 1] != '\n')
  3178. {
  3179. fprintf (stderr, "Skipped parts of a line: `%s'\n", line);
  3180. goto next_line;
  3181. }
  3182. line[read - 1] = '\0';
  3183. args = command_arg_split (line, &nargs);
  3184. if (nargs == 0)
  3185. continue;
  3186. for (i = 0; i < G_N_ELEMENTS (commands); i++)
  3187. {
  3188. if (! strcmp (commands[i].name, args[0]))
  3189. {
  3190. if (commands[i].nargs == 0
  3191. || (cmd_args = command_arg_parse (&ctx, args + 1, nargs - 1,
  3192. commands + i, &error_msg)))
  3193. {
  3194. commands[i].execute (&ctx, cmd_args);
  3195. if (commands[i].nargs > 0)
  3196. free_command_args (cmd_args, commands[i].nargs);
  3197. }
  3198. else
  3199. {
  3200. printf_error_response ("%s", error_msg ? error_msg :
  3201. "Unknown error (this is a bug)");
  3202. }
  3203. if (error_msg)
  3204. g_free (error_msg);
  3205. break;
  3206. }
  3207. }
  3208. if (G_N_ELEMENTS (commands) == i)
  3209. {
  3210. printf_error_response ("Unknown command: %s", args[0]);
  3211. }
  3212. for (i = 0; i < nargs; ++i)
  3213. g_free (args[i]);
  3214. g_free (args);
  3215. next_line:
  3216. free (line);
  3217. line = NULL;
  3218. }
  3219. if (ferror (stdin))
  3220. err (2, NULL);
  3221. exit (EXIT_SUCCESS);
  3222. }