-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpagination.R
More file actions
1593 lines (1502 loc) · 57.9 KB
/
Copy pathpagination.R
File metadata and controls
1593 lines (1502 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## #' Page Dimensions
## #'
## #' Dimensions for mapping page dimensions to text dimensions
## #' @references https://www.ietf.org/rfc/rfc0678.txt
## #' @export
## #' @rdname pagedims
## lpi_vert <- 6
## #' @export
## #' @rdname pagedims
## cpi_horiz <- 10
## #' @export
## #' @rdname pagedims
## horiz_margin_chars <- 13
## #' @export
## #' @rdname pagedims
## horiz_margin_inches <- horiz_margin_chars / cpi_horiz
## #' @export
## #' @rdname pagedims
## vert_margin_lines <- 6
## #' @export
## #' @rdname pagedims
## vert_margin_inches <- vert_margin_lines / lpi_vert
## #' Physical Page dimensions to chars x lines
## #'
## #' Calculate number of lines long and characters wide a page size is,
## #' after excluding margins
## #' @export
## #' @examples
## #' phys_page_to_lc()
## phys_page_to_lc <- function(width = 8.5, len = 11,
## h_margin = horiz_margin_inches,
## v_margin = vert_margin_inches) {
## lgl_width <- width - h_margin
## lgl_len <- len - v_margin
## c(chars_wide = floor(lgl_width * cpi_horiz),
## lines_long = floor(lgl_len * lpi_vert))
## }
#' Pagination
#'
#' @section Pagination Algorithm:
#'
#' Pagination is performed independently in the vertical and horizontal
#' directions based solely on a *pagination data frame*, which includes the
#' following information for each row/column:
#'
#' - Number of lines/characters rendering the row will take **after
#' word-wrapping** (`self_extent`)
#' - The indices (`reprint_inds`) and number of lines (`par_extent`)
#' of the rows which act as **context** for the row
#' - The row's number of siblings and position within its siblings
#'
#' Given `lpp` (`cpp`) is already adjusted for rendered elements which
#' are not rows/columns and a data frame of pagination information,
#' pagination is performed via the following algorithm with `start = 1`.
#'
#' Core Pagination Algorithm:
#'
#' 1. Initial guess for pagination position is `start + lpp` (`start + cpp`)
#' 2. While the guess is not a valid pagination position, and `guess > start`,
#' decrement guess and repeat.
#' - An error is thrown if all possible pagination positions between
#' `start` and `start + lpp` (`start + cpp`) would be `< start`
#' after decrementing
#' 3. Retain pagination index
#' 4. If pagination point was less than `NROW(tt)` (`ncol(tt)`), set
#' `start` to `pos + 1`, and repeat steps (1) - (4).
#'
#' Validating Pagination Position:
#'
#' Given an (already adjusted) `lpp` or `cpp` value, a pagination is invalid if:
#'
#' - The rows/columns on the page would take more than (adjusted) `lpp` lines/`cpp`
#' characters to render **including**:
#' - word-wrapping
#' - (vertical only) context repetition
#' - (vertical only) footnote messages and/or section divider lines
#' take up too many lines after rendering rows
#' - (vertical only) row is a label or content (row-group summary) row
#' - (vertical only) row at the pagination point has siblings, and
#' it has less than `min_siblings` preceding or following siblings
#' - pagination would occur within a sub-table listed in `nosplitin`
#'
#' @name pagination_algo
NULL
#' Create a row of a pagination data frame
#'
#' @inheritParams open_font_dev
#' @param nm (`string`)\cr name.
#' @param lab (`string`)\cr label.
#' @param rnum (`numeric(1)`)\cr absolute row number.
#' @param pth (`character` or `NULL`)\cr path within larger table.
#' @param sibpos (`integer(1)`)\cr position among sibling rows.
#' @param nsibs (`integer(1)`)\cr number of siblings (including self).
#' @param extent (`numeric(1)`)\cr number of lines required to print the row.
#' @param colwidths (`numeric`)\cr column widths.
#' @param repext (`integer(1)`)\cr number of lines required to reprint all context for this row if it appears directly
#' after pagination.
#' @param repind (`integer`)\cr vector of row numbers to be reprinted if this row appears directly after pagination.
#' @param indent (`integer`)\cr indent.
#' @param rclass (`string`)\cr class of row object.
#' @param nrowrefs (`integer(1)`)\cr number of row referential footnotes for this row.
#' @param ncellrefs (`integer(1)`)\cr number of cell referential footnotes for the cells in this row.
#' @param nreflines (`integer(1)`)\cr total number of lines required by all referential footnotes.
#' @param force_page (`flag`)\cr currently ignored.
#' @param page_title (`flag`)\cr currently ignored.
#' @param trailing_sep (`string`)\cr the string to use as a separator below this row during printing.
#' If `NA_character_`, no separator is used.
#' @param row (`ANY`)\cr object representing the row, which is used for default values of `nm`, `lab`,
#' `extent`, and `rclass` if provided. Must have methods for `obj_name`, `obj_label`, and `nlines`, to retrieve
#' default values of `nm`, `lab`, and `extent`, respectively.
#'
#' @return A single row `data.frame` with the appropriate columns for a pagination info data frame.
#'
#' @export
pagdfrow <- function(row,
nm = obj_name(row),
lab = obj_label(row),
rnum,
pth,
sibpos = NA_integer_,
nsibs = NA_integer_,
extent = nlines(row, colwidths, fontspec = fontspec),
colwidths = NULL,
repext = 0L,
repind = integer(),
indent = 0L,
rclass = class(row),
nrowrefs = 0L,
ncellrefs = 0L,
nreflines = 0L,
# ref_df = .make_ref_df(NULL, NULL),
force_page = FALSE,
page_title = NA_character_,
trailing_sep = NA_character_,
fontspec) {
data.frame(
label = lab,
name = nm,
abs_rownumber = rnum,
path = I(list(pth)),
pos_in_siblings = sibpos,
n_siblings = nsibs,
self_extent = extent,
par_extent = repext,
reprint_inds = I(rep(list(unlist(repind)), length.out = length(nm))),
node_class = rclass,
indent = max(0L, indent),
nrowrefs = nrowrefs,
ncellrefs = ncellrefs,
nreflines = nreflines,
# ref_info_df = I(list(ref_df)),
force_page = force_page,
page_title = page_title,
trailing_sep = trailing_sep,
stringsAsFactors = FALSE,
row.names = NULL,
check.names = FALSE,
fix.empty.names = FALSE
)
}
calc_ref_nlines_df <- function(pagdf) {
## XXX XXX XXX this is dangerous and wrong!!!
if (is.null(pagdf$ref_info_df) && sum(pagdf$nreflines) == 0) {
return(ref_df_row()[0, ])
}
refdf <- do.call(rbind.data.frame, pagdf$ref_info_df)
if (NROW(refdf) == 0) {
return(ref_df_row()[0, ])
}
unqsyms <- !duplicated(refdf$symbol)
refdf[unqsyms, , drop = FALSE]
}
build_fail_msg <- function(row, lines, raw_rowlines,
allowed_lines, lpp, decoration_lines,
start, guess, rep_ext, n_reprint,
reflines, n_refs, sectlines) {
if (row) {
spacetype <- "lines"
spacetype_abr <- "lns"
structtype_abr <- "rws"
sprintf(
paste0(
" FAIL: rows selected for pagination require %d %s while only %d are available from ",
"lpp = %d and %d header/footers lines.\n",
" details: [raw: %d %s (%d %s), rep. context: %d %s (%d %s), ",
"refs: %d %s (%d) sect. divs: %d %s]."
),
lines,
spacetype,
allowed_lines,
lpp,
decoration_lines, # header + footers
raw_rowlines,
spacetype_abr,
guess - start + 1, # because it includes both start and guess
structtype_abr,
rep_ext,
spacetype_abr,
n_reprint,
structtype_abr,
reflines,
spacetype_abr,
n_refs,
sectlines,
spacetype_abr
)
} else { ## !row
spacetype <- "chars"
spacetype_abr <- "chars"
structtype_abr <- "cols"
raw_ncol <- guess - start + 1
tot_ncol <- raw_ncol + n_reprint
rep_ext <- rep_ext
sprintf(
paste0(
" FAIL: selected %d columns require %d %s, while only %d are available. \n",
" details: [raw: %d %s (%d %s), rep. cols: %d %s (%d %s), tot. colgap: %d %s]."
),
guess - start + 1,
lines + rep_ext + sectlines,
spacetype,
lpp,
lines,
spacetype_abr,
raw_ncol,
structtype_abr,
rep_ext,
spacetype_abr,
n_reprint,
structtype_abr,
sectlines,
spacetype
)
}
}
valid_pag <- function(pagdf,
guess,
start,
rlpp,
lpp, # for informational purposes only
context_lpp, # for informational purposes only (headers/footers)
min_sibs,
nosplit = NULL,
div_height = 1L,
verbose = FALSE,
row = TRUE,
have_col_fnotes = FALSE,
col_gap,
has_rowlabels) {
# FALSE output from this function means that another guess is taken till success or failure
rw <- pagdf[guess, ]
if (verbose) {
message(
"-> Attempting pagination between ", start, " and ", guess, " ",
paste(ifelse(row, "row", "column"))
)
}
# Fix for counting the right number of lines when there is wrapping on a keycols
if (.is_listing_mf(pagdf) && !is.null(pagdf$self_extent_page_break)) {
pagdf$self_extent[start] <- pagdf$self_extent_page_break[start]
}
raw_rowlines <- sum(pagdf[start:guess, "self_extent"] - pagdf[start:guess, "nreflines"])
refdf_ii <- calc_ref_nlines_df(pagdf[start:guess, ])
reflines <- if (row) sum(refdf_ii$nlines, 0L) else 0L
if (reflines > 0 && !have_col_fnotes) {
reflines <- reflines + div_height + 1L
}
rowlines <- raw_rowlines + reflines ## sum(pagdf[start:guess, "self_extent"]) - reflines
## self extent includes reflines
## self extent does ***not*** currently include trailing sep for rows
## self extent does ***not*** currently include col_gap for columns
## we don't include the trailing_sep for guess because if we paginate here it won't be printed
ncols <- 0L
if (row) {
sectlines <- if (start == guess) 0L else sum(!is.na(pagdf[start:(guess - 1), "trailing_sep"]))
} else { ## columns
ncols <- guess - start + 1 + length(pagdf$reprint_inds[[start]]) ## +1 because its inclusive, 5-6 is 2 columns
sectlines <- col_gap * (ncols - as.integer(!has_rowlabels)) ## -1 if no row labels
}
lines <- rowlines + sectlines
rep_ext <- pagdf$par_extent[start]
if (lines > rlpp) {
if (verbose) {
structtype <- ifelse(row, "rows", "columns")
structtype_abr <- ifelse(row, "rows", "cols")
spacetype <- ifelse(row, "lines", "chars")
spacetype_abr <- ifelse(row, "lns", "chrs")
msg <- build_fail_msg(
row, lines, raw_rowlines,
allowed_lines = rlpp, lpp = lpp, decoration_lines = context_lpp,
start, guess, rep_ext, length(pagdf$reprint_inds[[start]]),
reflines, NROW(refdf_ii), sectlines
)
message(msg)
}
return(FALSE)
}
# Special cases: is it a label or content row?
if (rw[["node_class"]] %in% c("LabelRow", "ContentRow")) {
# check if it has children; if no children then valid
has_children <- rw$abs_rownumber %in% unlist(pagdf$reprint_inds)
if (rw$abs_rownumber == nrow(pagdf)) {
if (verbose) {
message(" EXCEPTION: last row is a label or content row but in lpp")
}
} else if (!any(has_children)) {
if (verbose) {
message(
" EXCEPTION: last row is a label or content row\n",
"but does not have rows and row groups depending on it"
)
}
} else {
if (verbose) {
message(" FAIL: last row is a label or content row")
}
return(FALSE)
}
}
# Siblings handling
sibpos <- rw[["pos_in_siblings"]]
nsib <- rw[["n_siblings"]]
# okpos <- min(min_sibs + 1, rw[["n_siblings"]])
if (sibpos != nsib) {
retfalse <- FALSE
if (sibpos < min_sibs + 1) {
retfalse <- TRUE
if (verbose) {
message(
" FAIL: last row had only ", sibpos - 1,
" preceding siblings, needed ", min_sibs
)
}
} else if (nsib - sibpos < min_sibs + 1) {
retfalse <- TRUE
if (verbose) {
message(
" FAIL: last row had only ", nsib - sibpos - 1,
" following siblings, needed ", min_sibs
)
}
}
if (retfalse) {
return(FALSE)
}
}
if (guess < nrow(pagdf) && length(nosplit > 0)) {
## paths end at the leaf name which is *always* different
curpth <- head(unlist(rw$path), -1)
nxtpth <- head(unlist(pagdf$path[[guess + 1]]), -1)
inplay <- nosplit[(nosplit %in% intersect(curpth, nxtpth))]
if (length(inplay) > 0) {
ok_split <- vapply(inplay, function(var) {
!identical(curpth[match(var, curpth) + 1], nxtpth[match(var, nxtpth) + 1])
}, TRUE)
curvals <- curpth[match(inplay, curpth) + 1]
nxtvals <- nxtpth[match(inplay, nxtpth) + 1]
if (!all(ok_split)) {
if (verbose) {
message(
" FAIL: nosplit variable [",
inplay[min(which(!ok_split))], "] would be constant [",
curvals, "] across this pagebreak."
)
}
return(FALSE)
}
}
}
# Usual output when found
if (verbose) {
message(" OK [", lines + rep_ext, if (row) " lines]" else " chars]")
}
TRUE
}
find_pag <- function(pagdf,
current_page,
start,
guess,
rlpp,
lpp_or_cpp,
context_lpp_or_cpp,
min_siblings,
nosplitin = character(),
verbose = FALSE,
row = TRUE,
have_col_fnotes = FALSE,
div_height = 1L,
do_error = FALSE,
col_gap,
has_rowlabels) {
if (verbose) {
if (row) {
message("--------- ROW-WISE: Checking possible pagination for page ", current_page)
} else {
message("========= COLUMN-WISE: Checking possible pagination for page ", current_page)
}
}
origuess <- guess
while (guess >= start && !valid_pag(
pagdf, guess,
start = start,
rlpp = rlpp, lpp = lpp_or_cpp, context_lpp = context_lpp_or_cpp, # only lpp goes to row pagination
min_sibs = min_siblings,
nosplit = nosplitin, verbose, row = row,
have_col_fnotes = have_col_fnotes,
div_height = div_height,
col_gap = col_gap,
has_rowlabels = has_rowlabels
)) {
guess <- guess - 1
}
if (guess < start) {
# Repeat pagination process to see what went wrong with verbose on
if (isFALSE(do_error) && isFALSE(verbose)) {
find_pag(
pagdf = pagdf,
current_page = current_page,
start = start,
guess = origuess,
rlpp = rlpp, lpp_or_cpp = lpp_or_cpp, context_lpp_or_cpp = context_lpp_or_cpp,
min_siblings = min_siblings,
nosplitin = nosplitin,
verbose = TRUE,
row = row,
have_col_fnotes = have_col_fnotes,
div_height = div_height,
do_error = TRUE, # only used to avoid loop
col_gap = col_gap,
has_rowlabels = has_rowlabels
)
}
stop(
"-------------------------------------- Error Summary ----------------------------------------\n",
"Unable to find any valid pagination split for page ", current_page, " between ",
ifelse(row, "rows ", "columns "), start, " and ", origuess, ". \n",
"Inserted ", ifelse(row, "lpp (row-space, lines per page) ", "cpp (column-space, content per page) "),
": ", lpp_or_cpp, "\n",
"Context-relevant additional ", ifelse(row, "header/footers lines", "fixed column characters"),
": ", context_lpp_or_cpp, "\n",
ifelse(row,
paste("Limit of allowed row lines per page:", rlpp, "\n"),
paste("Check the minimum allowed column characters per page in the last FAIL(ed) attempt. \n")
),
"Note: take a look at the last FAIL(ed) attempt above to see what went wrong. It could be, for example, ",
"that the inserted column width induces some wrapping, hence the inserted number of lines (lpp) is not enough."
)
}
guess
}
#' Find pagination indices from pagination info data frame
#'
#' Pagination methods should typically call the `make_row_df` method
#' for their object and then call this function on the resulting
#' pagination info `data.frame`.
#'
#' @param pagdf (`data.frame`)\cr a pagination info `data.frame` as created by
#' either `make_rows_df` or `make_cols_df`.
#' @param rlpp (`numeric`)\cr maximum number of *row* lines per page (not including header materials), including
#' (re)printed header and context rows.
#' @param lpp_or_cpp (`numeric`)\cr total maximum number of *row* lines or content (column-wise characters) per page
#' (including header materials and context rows). This is only for informative results with `verbose = TRUE`.
#' It will print `NA` if not specified by the pagination machinery.
#' @param context_lpp_or_cpp (`numeric`)\cr total number of context *row* lines or content (column-wise characters)
#' per page (including header materials). Uses `NA` if not specified by the pagination machinery and is only
#' for informative results with `verbose = TRUE`.
#' @param min_siblings (`numeric`)\cr minimum sibling rows which must appear on either side of pagination row for a
#' mid-subtable split to be valid. Defaults to 2 for tables. It is automatically turned off (set to 0) for listings.
#' @param nosplitin (`character`)\cr list of names of subtables where page breaks are not allowed, regardless of other
#' considerations. Defaults to none.
#' @param verbose (`flag`)\cr whether additional informative messages about the search for
#' pagination breaks should be shown. Defaults to `FALSE`.
#' @param row (`flag`)\cr whether pagination is happening in row space (`TRUE`, the default) or column
#' space (`FALSE`).
#' @param have_col_fnotes (`flag`)\cr whether the table-like object being rendered has column-associated
#' referential footnotes.
#' @param div_height (`numeric(1)`)\cr the height of the divider line when the associated object is rendered.
#' Defaults to `1`.
#' @param col_gap (`numeric(1)`)\cr width of gap between columns, in same units as extent in `pagdf` (spaces
#' under a particular font specification).
#' @param has_rowlabels (`logical(1)`)\cr whether the object being paginated has row labels.
#'
#' @details `pab_indices_inner` implements the core pagination algorithm (see below)
#' for a single direction (vertical if `row = TRUE` (the default), horizontal otherwise)
#' based on the pagination data frame and (already adjusted for non-body rows/columns)
#' lines (or characters) per page.
#'
#' @inheritSection pagination_algo Pagination Algorithm
#'
#' @return A `list` containing a vector of row numbers, broken up by page.
#'
#' @examples
#' mypgdf <- basic_pagdf(row.names(mtcars))
#'
#' paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0)
#' lapply(paginds, function(x) mtcars[x, ])
#'
#' @export
pag_indices_inner <- function(pagdf,
rlpp,
lpp_or_cpp = NA_integer_, context_lpp_or_cpp = NA_integer_, # Context number of lines
min_siblings,
nosplitin = character(),
verbose = FALSE,
row = TRUE,
have_col_fnotes = FALSE,
div_height = 1L,
col_gap = 3L,
has_rowlabels) {
start <- 1
current_page <- 1
nr <- nrow(pagdf)
ret <- list()
while (start <= nr) {
adjrlpp <- rlpp - pagdf$par_extent[start]
if (adjrlpp <= 0) {
if (row) {
stop("Lines of repeated context (plus header materials) larger than specified lines per page")
} else {
stop("Width of row labels equal to or larger than specified characters per page.")
}
}
guess <- min(nr, start + adjrlpp - 1)
end <- find_pag(
pagdf = pagdf,
current_page = current_page, start = start, guess = guess,
rlpp = adjrlpp, lpp_or_cpp = lpp_or_cpp, context_lpp_or_cpp = context_lpp_or_cpp,
min_siblings = min_siblings,
nosplitin = nosplitin,
verbose = verbose,
row = row,
have_col_fnotes = have_col_fnotes,
div_height = div_height,
col_gap = col_gap,
has_rowlabels = has_rowlabels
)
ret <- c(ret, list(c(
pagdf$reprint_inds[[start]],
start:end
)))
start <- end + 1
current_page <- current_page + 1
}
ret
}
#' Find column indices for vertical pagination
#'
#' @inheritParams pag_indices_inner
#' @inheritParams open_font_dev
#' @inheritParams format_value
#' @param obj (`ANY`)\cr object to be paginated. Must have a [matrix_form()] method.
#' @param cpp (`numeric(1)`)\cr number of characters per page (width).
#' @param colwidths (`numeric`)\cr vector of column widths (in characters) for use in vertical pagination.
#' @param rep_cols (`numeric(1)`)\cr number of *columns* (not including row labels) to be repeated on every page.
#' Defaults to 0.
#'
#' @return A `list` partitioning the vector of column indices into subsets for 1 or more horizontally paginated pages.
#'
#' @examples
#' mf <- basic_matrix_form(df = mtcars)
#' colpaginds <- vert_pag_indices(mf, fontspec = font_spec())
#' lapply(colpaginds, function(j) mtcars[, j, drop = FALSE])
#'
#' @export
vert_pag_indices <- function(obj,
cpp = 40,
colwidths = NULL,
verbose = FALSE,
rep_cols = 0L,
fontspec,
nosplitin = character(),
round_type = c("iec", "sas")) {
if (is.list(nosplitin)) {
nosplitin <- nosplitin[["cols"]]
}
mf <- matrix_form(obj, indent_rownames = TRUE, fontspec = fontspec, round_type = round_type)
clwds <- colwidths %||% propose_column_widths(mf, fontspec = fontspec)
if (is.null(mf_cinfo(mf))) { ## like always, ugh.
mf <- mpf_infer_cinfo(mf, colwidths = clwds, rep_cols = rep_cols, fontspec = fontspec)
}
num_rep_cols(mf) <- rep_cols
has_rlabs <- mf_has_rlabels(mf)
rlabs_flag <- as.integer(has_rlabs)
rlab_extent <- if (has_rlabs) clwds[1] else 0L
# rep_extent <- pdf$par_extent[nrow(pdf)]
rcpp <- cpp - table_inset(mf) - rlab_extent # rep_extent - table_inset(mf) - rlab_extent
if (verbose) {
message(
"Adjusted characters per page: ", rcpp,
" [original: ", cpp,
", table inset: ", table_inset(mf), if (has_rlabs) paste0(", row labels: ", clwds[1]),
"]"
)
}
res <- pag_indices_inner(mf_cinfo(mf),
rlpp = rcpp, lpp_or_cpp = cpp, context_lpp_or_cpp = cpp - rcpp,
# cpp - sum(clwds[seq_len(rep_cols)]),
verbose = verbose,
min_siblings = 1,
nosplitin = nosplitin,
row = FALSE,
col_gap = mf_colgap(mf),
has_rowlabels = mf_has_rlabels(mf)
)
res
}
mpf_infer_cinfo <- function(mf, colwidths = NULL, rep_cols = num_rep_cols(mf), fontspec, colpaths = NULL) {
if (!is.null(mf_cinfo(mf))) {
return(mf_update_cinfo(mf, colwidths = colwidths))
}
new_dev <- open_font_dev(fontspec)
if (new_dev) {
on.exit(close_font_dev())
}
if (!is(rep_cols, "numeric") || is.na(rep_cols) || rep_cols < 0) {
stop("got invalid number of columns to be repeated: ", rep_cols)
}
clwds <- (colwidths %||% mf_col_widths(mf)) %||% propose_column_widths(mf, fontspec = fontspec)
has_rlabs <- mf_has_rlabels(mf)
rlabs_flag <- as.integer(has_rlabs)
rlab_extent <- if (has_rlabs) clwds[1] else 0L
sqstart <- rlabs_flag + 1L # rep_cols + 1L
pdfrows <- lapply(
(sqstart):ncol(mf$strings),
function(i) {
rownum <- i - rlabs_flag
rep_inds <- seq_len(rep_cols)[seq_len(rep_cols) < rownum]
rep_extent_i <- sum(
0L,
clwds[rlabs_flag + rep_inds]
) ## colwidths
pagdfrow(
row = NA,
nm = rownum,
lab = rownum,
rnum = rownum,
pth = NA,
extent = clwds[i],
repext = rep_extent_i, # sum(clwds[rep_cols]) + mf$col_gap * max(0, (length(rep_cols) - 1)),
repind = rep_inds, # rep_cols,
rclass = "stuff",
sibpos = 1 - 1,
nsibs = 1 - 1,
fontspec = fontspec
)
}
)
pdf <- do.call(rbind, pdfrows)
refdf <- mf_fnote_df(mf)
pdf <- splice_fnote_info_in(pdf, refdf, row = FALSE)
if (!is.null(colpaths)) {
if (length(colpaths) != NROW(pdf)) {
## nocov start
stop(
"Got non-null colpaths with length not equal to number of columns (",
length(colpaths),
"!=",
NROW(pdf),
") during MatrixPrintForm construction. Please contact the maintainers."
)
## nocov end
}
pdf[["path"]] <- colpaths
}
mf_cinfo(mf) <- pdf
mf
}
#' Basic/spoof pagination info data frame
#'
#' Returns a minimal pagination info `data.frame` (with no info on siblings, footnotes, etc.).
#'
#' @inheritParams test_matrix_form
#' @inheritParams open_font_dev
#' @param rnames (`character`)\cr vector of row names.
#' @param labs (`character`)\cr vector of row labels. Defaults to `rnames`.
#' @param rnums (`integer`)\cr vector of row numbers. Defaults to `seq_along(rnames)`.
#' @param extents (`integer`)\cr number of lines each row requires to print. Defaults to 1 for all rows.
#' @param rclass (`character`)\cr class(es) for the rows. Defaults to `"DataRow"`.
#' @param paths (`list`)\cr list of paths to the rows. Defaults to `lapply(rnames, function(x) c(parent_path, x))`.
#'
#' @return A `data.frame` suitable for use in both the `MatrixPrintForm` constructor and the pagination machinery.
#'
#' @examples
#' basic_pagdf(c("hi", "there"))
#'
#' @export
basic_pagdf <- function(rnames,
labs = rnames,
rnums = seq_along(rnames),
extents = 1L,
rclass = "DataRow",
parent_path = NULL,
paths = lapply(rnames, function(x) c(parent_path, x)),
fontspec = font_spec()) {
rws <- mapply(pagdfrow,
nm = rnames, lab = labs, extent = extents,
rclass = rclass, rnum = rnums, pth = paths,
MoreArgs = list(fontspec = fontspec),
SIMPLIFY = FALSE, nsibs = 1, sibpos = 1
)
res <- do.call(rbind.data.frame, rws)
res$n_siblings <- nrow(res)
res$pos_in_siblings <- seq_along(res$n_siblings)
if (!all(rclass == "DataRow")) {
# These things are used in the simple case of a split, hence having labels.
# To improve and extend to other cases
res$pos_in_siblings <- NA
res$pos_in_siblings[rclass == "DataRow"] <- 1
res$par_extent[rclass == "DataRow"] <- 1 # the rest is 0
res$n_siblings <- res$pos_in_siblings
res$reprint_inds[which(rclass == "DataRow")] <- res$abs_rownumber[which(rclass == "DataRow") - 1]
}
res
}
## write paginate() which operates **solely** on a MatrixPrintForm obj
page_size_spec <- function(lpp, cpp, max_width,
font_family,
font_size,
lineheight,
fontspec = font_spec(
font_family = font_family,
font_size = font_size,
lineheight = lineheight
)) {
structure(list(
lpp = lpp,
cpp = cpp,
max_width = max_width,
font_spec = fontspec
), class = "page_size_spec")
}
get_font_spec <- function(obj) {
if (!is(obj, "page_size_spec")) {
stop("get_font_spec is only currently defined for page_size_spec objects")
}
obj$font_spec
}
non_null_na <- function(x) !is.null(x) && is.na(x)
calc_lcpp <- function(page_type = NULL,
landscape = FALSE,
pg_width = page_dim(page_type)[if (landscape) 2 else 1],
pg_height = page_dim(page_type)[if (landscape) 1 else 2],
fontspec = font_spec(),
## font_family = "Courier",
## font_size = 8, # grid parameters
cpp = NA_integer_,
lpp = NA_integer_,
tf_wrap = TRUE,
max_width = NULL,
## lineheight = 1,
margins = c(bottom = .5, left = .75, top = .5, right = .75),
colwidths,
col_gap,
inset) {
pg_lcpp <- page_lcpp(
page_type = page_type,
landscape = landscape,
## font_family = font_family,
## font_size = font_size,
## lineheight = lineheight,
fontspec = fontspec,
margins = margins,
pg_width = pg_width,
pg_height = pg_height
)
if (non_null_na(lpp)) {
lpp <- pg_lcpp$lpp
}
if (non_null_na(cpp)) {
cpp <- pg_lcpp$cpp
}
stopifnot(!is.na(cpp))
max_width <- .handle_max_width(tf_wrap, max_width, cpp, colwidths, col_gap, inset)
page_size_spec(
lpp = lpp, cpp = cpp, max_width = max_width,
## font_family = font_family,
## font_size = font_size,
## lineheight = lineheight
fontspec = fontspec
)
}
calc_rlpp <- function(pg_size_spec, mf, colwidths, tf_wrap, verbose) {
lpp <- pg_size_spec$lpp
max_width <- pg_size_spec$max_width
fontspec <- get_font_spec(pg_size_spec)
dh <- divider_height(mf)
if (any(nzchar(all_titles(mf)))) {
## +1 is for blank line between subtitles and divider
## dh is for divider line **between subtitles and column labels**
## other divider line is accounted for in cinfo_lines
if (!tf_wrap) {
tlines <- length(all_titles(mf))
} else {
tlines <- sum(nlines(all_titles(mf), colwidths = colwidths, max_width = max_width, fontspec = fontspec))
}
tlines <- tlines + dh + 1L
} else {
tlines <- 0
}
## dh for divider line between column labels and table body
cinfo_lines <- mf_nlheader(mf) + dh
if (verbose) {
message(
"Determining lines required for header content: ",
tlines, " title and ", cinfo_lines, " table header lines"
)
}
refdf <- mf_fnote_df(mf)
cfn_df <- refdf[is.na(refdf$row) & !is.na(refdf$col), ]
flines <- 0L
mnfoot <- main_footer(mf)
havemn <- length(mnfoot) && any(nzchar(mnfoot))
if (havemn) {
flines <- nlines(
mnfoot,
colwidths = colwidths,
max_width = max_width - table_inset(mf),
fontspec = fontspec
)
}
prfoot <- prov_footer(mf)
if (length(prfoot) && any(nzchar(prfoot))) {
flines <- flines + nlines(prov_footer(mf), colwidths = colwidths, max_width = max_width, fontspec = fontspec)
if (havemn) {
flines <- flines + 1L
} ## space between main and prov footer.
}
## this time its for the divider between the footers and whatever is above them
## (either table body or referential footnotes)
if (flines > 0) {
flines <- flines + dh + 1L
}
## this time its for the divider between the referential footnotes and
## the table body IFF we have any, otherwise that divider+blanks pace doesn't get drawn
if (NROW(cfn_df) > 0) {
cinfo_lines <- cinfo_lines + sum(cfn_df$nlines)
flines <- flines + dh + 1L
}
if (verbose) {
message(
"Determining lines required for footer content",
if (NROW(cfn_df) > 0) " [column fnotes present]",
": ", flines, " lines"
)
}
ret <- lpp - flines - tlines - cinfo_lines
if (verbose) {
message("Lines per page available for tables rows: ", ret, " (original: ", lpp, ")")
}
ret
}
## this is ok to be unchanged because by this point
## all of these are in terms of space widths
calc_rcpp <- function(pg_size_spec, mf, colwidths) {
cpp <- pg_size_spec$cpp
cpp - table_inset(mf) - colwidths[1] - mf_colgap(mf)
}
splice_idx_lists <- function(lsts) {
list(
pag_row_indices = do.call(c, lapply(lsts, function(xi) xi$pag_row_indices)),
pag_col_indices = do.call(c, lapply(lsts, function(yi) yi$pag_col_indices))
)
}
#' Paginate a table-like object for rendering
#'
#' These functions perform or diagnose bi-directional pagination on an object.
#'
#' `paginate_indices` renders `obj` into a `MatrixPrintForm` (MPF), then uses that representation to
#' calculate the rows and columns of `obj` corresponding to each page of the pagination of `obj`, but
#' simply returns these indices rather than paginating `obj` itself (see Details for an important caveat).
#'
#' `paginate_to_mpfs` renders `obj` into its MPF intermediate representation, then paginates that MPF into
#' component MPFs each corresponding to an individual page and returns those in a `list`.
#'
#' `diagnose_pagination` attempts pagination via `paginate_to_mpfs`, then returns diagnostic information
#' which explains why page breaks were positioned where they were, or alternatively why no valid pagination
#' could be found.
#'
#' @details
#' All three of these functions generally support all classes which have a corresponding [matrix_form()]
#' method which returns a valid `MatrixPrintForm` object (including `MatrixPrintForm` objects themselves).
#'
#' `paginate_indices` is directly called by `paginate_to_mpfs` (and thus `diagnose_pagination`). For most
#' classes, and most tables represented by supported classes, calling `paginate_to_mpfs` is equivalent to a
#' manual `paginate_indices -> subset obj into pages -> matrix_form` workflow.
#'
#' The exception to this equivalence is objects which support "forced pagination", or pagination logic which
#' is built into the object itself rather than being a function of space on a page. Forced pagination
#' generally involves the creation of, e.g., page-specific titles which apply to these forced paginations.
#' `paginate_to_mpfs` and `diagnose_pagination` support forced pagination by automatically calling the
#' [do_forced_paginate()] generic on the object and then paginating each object returned by that generic
#' separately. The assumption here, then, is that page-specific titles and such are handled by the class'
#' [do_forced_paginate()] method.
#'
#' `paginate_indices`, on the other hand, *does not support forced pagination*, because it returns only a
#' set of indices for row and column subsetting for each page, and thus cannot retain any changes, e.g.,
#' to titles, done within [do_forced_paginate()]. `paginate_indices` does call [do_forced_paginate()], but
#' instead of continuing it throws an error in the case that the result is larger than a single "page".
#'
#' @inheritParams vert_pag_indices
#' @inheritParams pag_indices_inner
#' @inheritParams page_lcpp
#' @inheritParams toString
#' @inheritParams propose_column_widths
#' @param lpp (`numeric(1)` or `NULL`)\cr lines per page. If `NA` (the default), this is calculated automatically
#' based on the specified page size). `NULL` indicates no vertical pagination should occur.
#' @param cpp (`numeric(1)` or `NULL`)\cr width (in characters) per page. If `NA` (the default), this is calculated
#' automatically based on the specified page size). `NULL` indicates no horizontal pagination should occur.
#' @param pg_size_spec (`page_size_spec`)\cr. a pre-calculated page size specification. Typically this is not set by
#' end users.
#' @param col_gap (`numeric(1)`)\cr The number of spaces to be placed between columns
#' in the rendered table (and assumed for horizontal pagination).
#' @param page_num (`string`)\cr placeholder string for page numbers. See [default_page_number] for more
#' information. Defaults to `NULL`.
#'
#' @return
#' * `paginate_indices` returns a `list` with two elements of the same length: `pag_row_indices` and `pag_col_indices`.
#' * `paginate_to_mpfs` returns a `list` of `MatrixPrintForm` objects representing each individual page after
#' pagination (including forced pagination if necessary).
#'
#' @examples
#' mpf <- basic_matrix_form(mtcars)
#'
#' paginate_indices(mpf, pg_width = 5, pg_height = 3)
#'
#' paginate_to_mpfs(mpf, pg_width = 5, pg_height = 3)
#'
#' @aliases paginate pagination
#' @export
paginate_indices <- function(obj,
page_type = "letter",
font_family = "Courier",
font_size = 8,
lineheight = 1,
landscape = FALSE,
pg_width = NULL,
pg_height = NULL,
margins = c(top = .5, bottom = .5, left = .75, right = .75),
lpp = NA_integer_,
cpp = NA_integer_,
min_siblings = 2,
nosplitin = list(
rows = character(),
cols = character()
),
colwidths = NULL,
tf_wrap = FALSE,
max_width = NULL,
indent_size = 2,
pg_size_spec = NULL,
rep_cols = num_rep_cols(obj),