Debian Codegraph @

inst/hclcolorpicker/server.R

raw
1 #' Shiny app to pick colors in HCL space
2 #'
3 #' The app visualizes colors either along the hue-chroma plane for a given luminance value or along the
4 #' luminance-chroma plane for a given hue. Colors can be entered by specifying the hue (H), chroma (C),
5 #' and luminance (L) values via sliders, by entering an RGB hex code, or by clicking on a color in the
6 #' hue-chroma or luminance-chroma plane. It is also possible to select individual colors and add them
7 #' to a palette for comparison and future reference.
8 #'
9 #' @return \code{hclcolorpicker} invisibly returns a vector of colors choosen.
10 #' If no colors have been selected \code{NULL} will be returned.
11 #' @examples
12 #' \dontrun{
13 #' hclcolorpicker()
14 #' }
15 #' @export
16 #' @importFrom methods as
17
18 ##options( shiny.trace = TRUE )
19
20 shiny::shinyServer(function(input, output, session) {
21
22 ##if ( Sys.info()["nodename"] == "sculptor.uberspace.de" ) {
23 ## delay(0, toggleState("closeapp", condition = F))
24 ##}
25
26 picked_color_list <- shiny::reactiveValues(cl=c())
27
28 # ----------------------------------------------------------------
29 # Switch between dark mode (black background) and normal mode
30 # (white background). Also used for the demo plots.
31 # ----------------------------------------------------------------
32 observeEvent(input$darkmode, {
33 if ( ! input$darkmode ) {
34 shinyjs::removeClass(selector = "body", class = "darkmode")
35 } else {
36 shinyjs::addClass(selector = "body", class = "darkmode")
37 }
38 })
39
40 # ----------------------------------------------------------------
41 # Clicking on HC plot plane
42 # ----------------------------------------------------------------
43 shiny::observeEvent({input$HC_plot_click}, {
44 # store the old colors
45 coords_old_LUV <- colorspace::coords(as(colorspace::polarLUV(as.numeric(input$L),
46 as.numeric(input$C),
47 as.numeric(input$H)), "LUV"))
48 U <- input$HC_plot_click$x
49 if (is.null(U)) U <- coords_old_LUV[2L]
50 V <- input$HC_plot_click$y
51 if (is.null(V)) V <- coords_old_LUV[3L]
52 L <- input$L
53 coords_HCL <- colorspace::coords(as(colorspace::LUV(L, U, V), "polarLUV"))
54 shiny::updateSliderInput(session, "C", value = round(coords_HCL[2L]))
55 shiny::updateSliderInput(session, "H", value = round(coords_HCL[3L]))
56 })
57
58 # ----------------------------------------------------------------
59 # Clicking on LC plot plane
60 # ----------------------------------------------------------------
61 shiny::observeEvent({input$LC_plot_click}, {
62 # store the old colors
63 Lold <- as.numeric(input$L)
64 Cold <- as.numeric(input$C)
65 C <- input$LC_plot_click$x
66 if (is.null(C)) C <- Cold
67 L <- input$LC_plot_click$y
68 if (is.null(L)) L <- Lold
69 shiny::updateSliderInput(session, "C", value = round(C))
70 shiny::updateSliderInput(session, "L", value = round(L))
71 })
72
73 # ----------------------------------------------------------------
74 # Palette click: event triggered when clicking on the
75 # "palette of selected colors".
76 # ----------------------------------------------------------------
77 shiny::observeEvent({input$palette_click}, {
78 x <- input$palette_click$x
79 if ( length(picked_color_list$cl) == 0 ) return()
80 if ( is.null(x) ) return()
81 i <- ceiling(x * length(picked_color_list$cl))
82 col_RGB <- colorspace::hex2RGB(picked_color_list$cl[i])
83 coords_HCL <- colorspace::coords(as(col_RGB, "polarLUV"))
84 shiny::updateSliderInput(session, "L", value = round(coords_HCL[1L]))
85 shiny::updateSliderInput(session, "C", value = round(coords_HCL[2L]))
86 shiny::updateSliderInput(session, "H", value = round(coords_HCL[3L]))
87 })
88
89 # ----------------------------------------------------------------
90 # Clicking on Hue gradient area
91 # ----------------------------------------------------------------
92 shiny::observeEvent({input$Hgrad_click}, {
93 H <- input$Hgrad_click$x
94 if (!is.null(H))
95 shiny::updateSliderInput(session, "H", value = round(H))
96 })
97
98 # ----------------------------------------------------------------
99 # Clicking on Luminance gradient area
100 # ----------------------------------------------------------------
101 shiny::observeEvent({input$Lgrad_click}, {
102 L <- input$Lgrad_click$x
103 if (!is.null(L))
104 shiny::updateSliderInput(session, "L", value = round(L))
105 })
106
107 # ----------------------------------------------------------------
108 # Clicking on Chroma gradient area
109 # ----------------------------------------------------------------
110 shiny::observeEvent({input$Cgrad_click}, {
111 C <- input$Cgrad_click$x
112 if (!is.null(C))
113 shiny::updateSliderInput(session, "C", value = round(C))
114 })
115
116 # ----------------------------------------------------------------
117 # ----------------------------------------------------------------
118 shiny::observeEvent({input$set_hexcolor}, {
119 # only execute this on complete color hex codes
120 if (grepl("^#[0123456789ABCDEFabcdef]{6}$", input$hexcolor)) {
121 col_RGB <- colorspace::hex2RGB(input$hexcolor)
122 coords_HCL <- colorspace::coords(as(col_RGB, "polarLUV"))
123 shiny::updateSliderInput(session, "L", value = round(coords_HCL[1L]))
124 shiny::updateSliderInput(session, "C", value = round(coords_HCL[2L]))
125 shiny::updateSliderInput(session, "H", value = round(coords_HCL[3L]))
126 }
127 })
128
129
130 # ----------------------------------------------------------------
131 # save color code
132 # ----------------------------------------------------------------
133 shiny::observeEvent(input$color_picker, {
134 # cannot rely on hex color in text-input field, so recalculate from set H, C, L values
135 hexcolor <- colorspace::hex(colorspace::polarLUV(as.numeric(input$L), as.numeric(input$C), as.numeric(input$H)))
136 # only add color if it's not already in the list
137 if ( ! is.na(hexcolor) && ! hexcolor %in% picked_color_list$cl) {
138 picked_color_list$cl <- c(picked_color_list$cl, hexcolor)
139 } else {
140 showNotification("No valid color selected.")
141 }
142 if ( length(picked_color_list$cl) == 0 ) return()
143 generateExport(output, picked_color_list$cl)
144 })
145
146 # ----------------------------------------------------------------
147 # undo pick color
148 # ----------------------------------------------------------------
149 shiny::observeEvent(input$color_unpicker, {
150 if (input$hexcolor %in% picked_color_list$cl)
151 picked_color_list$cl <- picked_color_list$cl[picked_color_list$cl != input$hexcolor]
152 #} else {
153 # # It's a better user interface to leave the list alone if the color is not in the list
154 # # picked_color_list$cl <- head(picked_color_list$cl,-1)
155 #}
156 })
157
158 # ----------------------------------------------------------------
159 # clear saved color code
160 # ----------------------------------------------------------------
161 shiny::observeEvent(input$clear_color_picker, {
162 picked_color_list$cl <- c()
163 })
164
165 # ----------------------------------------------------------------
166 # ----------------------------------------------------------------
167 shiny::observe({
168 shiny::updateTextInput(session, "hexcolor",
169 value = colorspace::hex(colorspace::polarLUV(as.numeric(input$L),
170 as.numeric(input$C),
171 as.numeric(input$H))))
172 })
173
174 # ----------------------------------------------------------------
175 # ----------------------------------------------------------------
176 output$colorbox <- shiny::renderUI({
177 shiny::tags$div(style=paste0("width: 100%; height: 40px; ",
178 "border: 1px solid rgba(0, 0, 0, .2); background: ",
179 colorspace::hex(colorspace::polarLUV(as.numeric(input$L),
180 as.numeric(input$C),
181 as.numeric(input$H))), ";"))
182 })
183
184 # generate HC plot with given inputs
185 output$HC_plot <- shiny::renderPlot({
186 par(bg = ifelse(input$darkmode, "black", "white"),
187 fg = ifelse(input$darkmode, "white", "black"),
188 col.axis = ifelse(input$darkmode, "white", "black"))
189 color_picker_hue_chroma_plot(as.numeric(input$L),
190 as.numeric(input$C),
191 as.numeric(input$H))
192 })
193
194 # generate LC plot with given inputs
195 output$LC_plot <- shiny::renderPlot({
196 par(bg = ifelse(input$darkmode, "black", "white"),
197 fg = ifelse(input$darkmode, "white", "black"),
198 col.axis = ifelse(input$darkmode, "white", "black"))
199 color_picker_luminance_chroma_plot(as.numeric(input$L),
200 as.numeric(input$C),
201 as.numeric(input$H))
202 })
203
204
205 output$Hgrad <- shiny::renderPlot({
206 par(bg = ifelse(input$darkmode, "black", "white"),
207 fg = ifelse(input$darkmode, "white", "black"),
208 col.axis = ifelse(input$darkmode, "white", "black"))
209 color_picker_H_gradient(as.numeric(input$L),
210 as.numeric(input$C),
211 as.numeric(input$H))
212 })
213
214 output$Hgrad2 <- shiny::renderPlot({
215 par(bg = ifelse(input$darkmode, "black", "white"),
216 fg = ifelse(input$darkmode, "white", "black"),
217 col.axis = ifelse(input$darkmode, "white", "black"))
218 color_picker_H_gradient(as.numeric(input$L),
219 as.numeric(input$C),
220 as.numeric(input$H))
221 })
222
223 output$Cgrad <- shiny::renderPlot({
224 par(bg = ifelse(input$darkmode, "black", "white"),
225 fg = ifelse(input$darkmode, "white", "black"),
226 col.axis = ifelse(input$darkmode, "white", "black"))
227 color_picker_C_gradient(as.numeric(input$L),
228 as.numeric(input$C),
229 as.numeric(input$H))
230 })
231
232 output$Cgrad2 <- shiny::renderPlot({
233 par(bg = ifelse(input$darkmode, "black", "white"),
234 fg = ifelse(input$darkmode, "white", "black"),
235 col.axis = ifelse(input$darkmode, "white", "black"))
236 color_picker_C_gradient(as.numeric(input$L),
237 as.numeric(input$C),
238 as.numeric(input$H))
239 })
240
241
242 output$Lgrad <- shiny::renderPlot({
243 par(bg = ifelse(input$darkmode, "black", "white"),
244 fg = ifelse(input$darkmode, "white", "black"),
245 col.axis = ifelse(input$darkmode, "white", "black"))
246 color_picker_L_gradient(as.numeric(input$L),
247 as.numeric(input$C),
248 as.numeric(input$H))
249 })
250
251 output$Lgrad2 <- shiny::renderPlot({
252 par(bg = ifelse(input$darkmode, "black", "white"),
253 fg = ifelse(input$darkmode, "white", "black"),
254 col.axis = ifelse(input$darkmode, "white", "black"))
255 color_picker_L_gradient(as.numeric(input$L),
256 as.numeric(input$C),
257 as.numeric(input$H))
258 })
259
260 # generate palette plot with given hex code
261 output$palette_plot <- shiny::renderPlot({
262 par(bg = ifelse(input$darkmode, "black", "white"),
263 fg = ifelse(input$darkmode, "white", "black"),
264 col.axis = ifelse(input$darkmode, "white", "black"))
265 pal_plot(picked_color_list$cl)
266 })
267
268 # add R color code line
269 output$palette_line_R <- shiny::renderText({
270 if (length(picked_color_list$cl) != 0) {
271 color_list <- picked_color_list$cl
272 color_list <- paste(color_list, collapse = "', '")
273 color_string <- paste("<code>colors <- c('", color_list, "')</code>", sep = '')
274 sprintf("<b style=\"display:block;margin-top:5px\">R style color vector</b>%s", color_string)
275 } else {
276 paste("Currently no colors picked. Go to the \"<b>Luminance-Chroma plane</b>\"",
277 "or the \"<b>Hue-Chroma plane</b>\" tab, define a color,",
278 "and press <b>pick</b> to add the color to your selection.")
279 }
280 })
281 # Add matlab style output
282 output$palette_line_matlab <- shiny::renderText({
283 if (length(picked_color_list$cl) != 0){
284 # Convert colors to RGB for matlab
285 color_string <- sprintf("<code>colors = [%s]</code>",
286 paste0(base::apply(colorspace::hex2RGB(picked_color_list$cl)@coords,1, function(x)
287 sprintf("%.3f,%.3f,%.3f",x[1L],x[2L],x[3L])),collapse="; "))
288 sprintf("<b style=\"display:block;margin-top:5px\">matlab style color vector</b>%s", color_string)
289 }
290 })
291
292 # ----------------------------------------------------------------
293 # Return data to R-console
294 # ----------------------------------------------------------------
295 shiny::observeEvent(input$closeapp,
296 shiny::stopApp(invisible(picked_color_list$cl))
297 );
298
299 # ----------------------------------------------------------------
300 # Version information lower right corner
301 # ----------------------------------------------------------------
302 output$version_info <- renderText(sprintf("<a href=\"%s\">R colorspace %s</a>",
303 "https://cran.r-project.org/package=colorspace",
304 packageVersion("colorspace")))
305
306
307
308 # downloadHandler() takes two arguments, both functions.
309 # The content function is passed a filename as an argument, and
310 # it should write out data to that filename.
311 getRGB <- function(int=FALSE) {
312 colors <- picked_color_list$cl
313 if ( int ) { scale = 255; digits = 0 } else { scale = 1; digits = 3 }
314 RGB <- round(attr(colorspace::hex2RGB(colors), "coords")*scale, digits)
315 return(RGB)
316 }
317 getHCL <- function() {
318 HCL <- colorspace::coords(as(colorspace::hex2RGB(picked_color_list$cl), "polarLUV"))
319 HCL <- round(HCL)[,c("H","C","L")]
320 if ( is.null(nrow(HCL)) ) HCL <- as.matrix(t(HCL))
321 return(HCL)
322 }
323 output$downloadRAW1 <- downloadHandler(
324 file <- "colormap_HCL.txt",
325 content = function(file) {
326 if ( length(picked_color_list$cl) > 0 ) {
327 write.table(getHCL(), file, sep = ",",
328 col.names = TRUE, row.names = FALSE)
329 } else {
330 write(file = file, "No colors selected.")
331 }
332 }
333 )
334 output$downloadRAW2 <- downloadHandler(
335 file <- "colormap_RGB.txt",
336 content = function(file) {
337 if ( length(picked_color_list$cl) > 0 ) {
338 write.table(getRGB(TRUE), file, sep = ",",
339 col.names = TRUE, row.names = FALSE)
340 } else {
341 write(file = file, "No colors selected.")
342 }
343 }
344 )
345 output$downloadRAW3 <- downloadHandler(
346 file <- "colormap_hex.txt",
347 content = function(file) {
348 if ( length(picked_color_list$cl) > 0 ) {
349 write.table(picked_color_list$cl, file, sep = ",",
350 col.names = FALSE, row.names = FALSE)
351 } else {
352 write(file = file, "No colors selected.")
353 }
354 }
355 )
356
357 })
358
359
360 color_picker_hue_chroma_plot <- function(L = 75, C = 20, H = 0, n = 200) {
361
362 Cmax <- max(colorspace::max_chroma(0:360, L))
363 Vmax <- Cmax
364 Umax <- Cmax
365 U <- seq(-Umax, Umax, length.out = n)
366 V <- seq(Vmax, -Vmax, length.out = n)
367 grid <- expand.grid(U = U, V = V)
368 image <- matrix(colorspace::hex(colorspace::LUV(L, grid$U, grid$V)), nrow = n, byrow = TRUE)
369 grob <- grid::rasterGrob(image)
370
371 sel_col <- colorspace::polarLUV(L, C, H) # selected color in polar LUV
372 sel_pt <- colorspace::coords(as(sel_col, "LUV")) # coordinates of selected point in LUV
373 df_sel <- data.frame(U = sel_pt[2L], V = sel_pt[3L])
374
375 grid$hex <- as.vector(t(image))
376 limits <- lapply(na.omit(grid), function(x)
377 if ( ! is.numeric(x) ) { return(NULL) } else { max(abs(x))*c(-1,1) } )
378 par(mar = c(3, 3, 1, 1))
379 with(grid, graphics::plot(V ~ U, type="n", bty = "n", axes = FALSE,
380 xaxs = "i", yaxs = "i", asp = 1, xlim=limits$U, ylim=limits$V))
381 graphics::abline(h = seq(-200,200,by=25), v = seq(-200,200,by=25), col = "gray80")
382 graphics::axis(side = 1, at = seq(-200,200,by=50), col = NA, col.ticks = 1)
383 graphics::axis(side = 2, at = seq(-200,200,by=50), col = NA, col.ticks = 1)
384 graphics::points(grid$V ~ grid$U, col = grid$hex, pch = 19)
385
386 # Selected color
387 graphics::points(sel_pt[1,"V"] ~ sel_pt[1,"U"], cex = 2)
388 sel_radius <- sqrt(sum(sel_pt[1, c("U", "V")]^2))
389 graphics::lines(sin(seq(0, 2 * pi, length.out = 300)) * sel_radius,
390 cos(seq(0, 2 * pi, length.out = 300)) * sel_radius, col = "gray40")
391
392 # Box
393 graphics::box(col = "gray40")
394
395 }
396
397 color_picker_luminance_chroma_plot <- function(L = 75, C = 20, H = 0, n = 200) {
398
399 Cmax <- max(C + 5, 150)
400 Cseq <- seq(0, Cmax, length.out = n)
401 Lseq <- seq(100, 0, length.out = n)
402 grid <- expand.grid(C = Cseq, L = Lseq)
403 # Remove points with L == 0 & C > 0
404 grid[which(grid$L == 0 & grid$C > 0),] <- NA
405 image <- matrix(colorspace::hex(colorspace::polarLUV(grid$L, grid$C, H)), nrow = n, byrow = TRUE)
406 grob <- grid::rasterGrob(image, width = 1, height = 1)
407
408 sel_col <- colorspace::polarLUV(L, C, H) # selected color in polar LUV
409 df_sel <- data.frame(C = C, L = L)
410
411 grid$hex <- as.vector(t(image))
412 limits <- with(na.omit(grid), list( L = c(0,100), C = c(0,max(C))))
413 par( mar = c(3, 3, 1, 1) )
414 with( grid, graphics::plot(L ~ C, type="n", bty = "n", axes = FALSE,
415 asp = 1, xaxs = "i", yaxs = "i", xlim=limits$C, ylim=limits$L))
416 graphics::abline(h = seq(-200,200,by=25), v = seq(-200,200,by=25), col = "gray80")
417 graphics::axis(side = 1, at = seq(limits$C[1L],limits$C[2L],by=25), col = NA, col.ticks = 1)
418 graphics::axis(side = 2, at = seq(limits$L[1L],limits$L[2L],by=25), col = NA, col.ticks = 1)
419 graphics::points(grid$L ~ grid$C, col = grid$hex, pch = 19 )
420 # Selected color
421 graphics::points(df_sel[1,"L"] ~ df_sel[1,"C"], cex = 2)
422 # Box
423 graphics::box(col = "gray40")
424
425 }
426
427 # Helper function to draw the color bar (gradient's).
428 # Input \code{seq} has to be numeric, sequence of values
429 # along the color bar dimension. Cols is an object of
430 # NA's and hex colors which can be converted to a vector.
431 # Typically a matrix. Length of \code{cols} has to be equal to
432 # length of \code{seq}.
433 plot_color_gradient <- function( seq, cols, sel, ylab = NA, ticks ) {
434
435 par(mar = c(2, 2, .1, 1))
436 # Compute args
437 dx <- 0.5 * median(diff(seq))
438 seq <- seq(min(seq), max(seq), length.out=length(cols))
439 args <- list(ybottom = rep(0,length(cols)), ytop = rep(1,length(cols)))
440 args$xleft <- seq - dx; args$xright <- seq + dx
441 args$col <- as.vector(cols); args$border <- NA
442 # Create color bar
443 graphics::plot(NA, ylim = c(0, 1), xlim = range(seq), xaxs = "i", yaxs = "i",
444 xlab = NA, ylab = NA, bty = "n", axes = FALSE)
445 do.call("rect", args)
446 if ( ! is.na(ylab) ) graphics::mtext(side = 2, line = 0.5, ylab, las = 2)
447 if ( missing(ticks) ) ticks <- base::pretty(seq)
448 graphics::points(sel, 0.5, cex = 2)
449 graphics::axis(side = 1, at = ticks, col = NA, col.ticks = 1)
450 graphics::box(col = "gray40")
451
452 }
453
454 color_picker_C_gradient <- function(L = 75, C = 20, H = 0, n = 100) {
455
456 Cmax <- max(C + 5, 150)
457 Cseq <- seq(0, Cmax, length.out = n)
458 image <- matrix(colorspace::hex(colorspace::polarLUV(L, Cseq, H)), nrow = 1, byrow = TRUE)
459 grob <- grid::rasterGrob(image, width = 1, height = 1)
460
461 sel_col <- colorspace::hex(colorspace::polarLUV(L, C, H))
462 df_sel <- data.frame(C = C, H = H, L = L, y = 0)
463
464 # Craw color gradient/color bar
465 plot_color_gradient(Cseq, image, df_sel$C, "C")
466
467 }
468
469 color_picker_H_gradient <- function(L = 75, C = 20, H = 0, n = 100) {
470
471 Hseq = seq(0, 360, length.out = n)
472 image <- matrix(colorspace::hex(colorspace::polarLUV(L, C, Hseq)), nrow = 1, byrow = TRUE)
473 grob <- grid::rasterGrob(image, width = 1, height = 1)
474
475 sel_col <- colorspace::hex(colorspace::polarLUV(L, C, H))
476 df_sel <- data.frame(C = C, H = H, L = L, y = 0)
477
478 # Craw color gradient/color bar
479 plot_color_gradient(Hseq, image, df_sel$H, "H", seq(0,360,by=45))
480 }
481
482 color_picker_L_gradient <- function(L = 75, C = 20, H = 0, n = 100) {
483
484 Lseq = seq(0, 100, length.out = n)
485 image <- matrix(colorspace::hex(colorspace::polarLUV(Lseq, C, H)), nrow = 1, byrow = TRUE)
486 if ( C > 0 ) image[1,1] <- "#ffffff"
487 grob <- grid::rasterGrob(image, width = 1, height = 1)
488
489 sel_col <- colorspace::hex(colorspace::polarLUV(L, C, H))
490 df_sel <- data.frame(C = C, H = H, L = L, y = 0)
491
492 # Craw color gradient/color bar
493 plot_color_gradient(Lseq, image, df_sel$L, "L")
494 }
495
496 pal_plot <- function(colors) {
497
498 # Base plot
499 graphics::par(mai = rep(0,4), mar = rep(0,4))
500 graphics::plot(0, 0, type = "n", xlim = c(0, 1), ylim = c(0, 1),
501 xaxs = "i", yaxs = "i", axes = FALSE, xlab = "", ylab="")
502
503 # convert colors to hex and find luminance for each
504 n <- length(colors)
505 if ( n == 0 ) {
506 text(0, 0.5, pos = 4, col = "#BFBEBD", "No colors selected")
507 } else {
508 col <- colorspace::hex2RGB(colors)
509 # Convert to HCL to define the text color
510 HCL <- as(colorspace::hex2RGB(colors), "polarLUV")
511 text_col <- cursor_color(HCL@coords[, 1L])
512 # Calculate rectangle width/position
513 if ( n == 1 ) {
514 w = 1; x = 0
515 } else {
516 w <- 0.95 / n
517 x <- seq(0, 1, by = w + 0.05 / (n - 1))
518 }
519 graphics::rect(x, 0, x + w, 1, col = colors, border = NA)
520 graphics::text(x + w / 2., .5, labels = colors, col = text_col, cex = 1.2)
521 #graphics::rect((0:(n-1)+.1)/n, 0, (1:n-.1)/n, 1, col = colors, border = NA)
522 #graphics::text((0:(n-1)+.5)/n, .5, labels = colors, col = text_col, cex = 1.2)
523 }
524
525 }
526
527 cursor_color <- function(L) ifelse(L >= 50, "#000000", "#FFFFFF")
528
529 # ----------------------------------------------------------------
530 # Export colors: generate export content
531 # ----------------------------------------------------------------
532 generateExport <- function(output, colors) {
533
534 # Setting "NA" colors if fixup=FALSE to white and
535 # store the indizes on colors.na. Replacement required
536 # to be able to convert hex->RGB, index required to
537 # create proper output (where NA values should be displayed).
538 colors.na <- which(is.na(colors))
539 colors[is.na(colors)] <- "#ffffff"
540
541 # --------------------------
542 # RAW
543 # --------------------------
544 # Generate RGB coordinates
545 sRGB <- colorspace::hex2RGB(colors)
546 RGB <- attr( sRGB, "coords" )
547 HCL <- round(attr( as( sRGB, "polarLUV" ), "coords" ))
548
549 # Generate output string
550 append <- function(x,new) c(x,new)
551 raw1 <- raw2 <- raw3 <- raw4 <- list()
552 # RGB 0-1
553 raw1 <- append(raw1, "<div style=\"clear: both;\">")
554 raw1 <- append(raw1, "<span class=\"output-raw\">")
555 raw1 <- append(raw1, "HCL values")
556 for ( i in 1:nrow(HCL) )
557 raw1 <- append(raw1,ifelse(i %in% colors.na,
558 gsub(" ", "&nbsp;", sprintf("<code>%5s %5s %5s</code>", "NA", "NA", "NA")),
559 gsub(" ", "&nbsp;", sprintf("<code>%4d %4d %4d</code>", HCL[i,"H"], HCL[i,"C"], HCL[i,"L"]))))
560 raw1 <- append(raw1, "</span>")
561 # RGB 0-255
562 raw2 <- append(raw2, "<span class=\"output-raw\">")
563 raw2 <- append(raw2, "RGB values [0-255]")
564 RGB <- round(RGB * 255)
565 for ( i in 1:nrow(RGB) )
566 raw2 <- append(raw2,ifelse(i %in% colors.na,
567 gsub(" ", "&nbsp;", sprintf("<code>%4s %4s %4s</code>", "NA", "NA", "NA")),
568 gsub(" ", "&nbsp;", sprintf("<code>%4d %4d %4d</code>", RGB[i,1], RGB[i,2], RGB[i,3]))))
569 raw2 <- append(raw2,"</span>")
570 # HEX colors
571 raw3 <- append(raw3,"<span class=\"output-raw\">")
572 raw3 <- append(raw3,"HEX colors, no alpha")
573 for ( i in seq_along(colors) )
574 raw3 <- append(raw3,ifelse(i %in% colors.na,
575 gsub(" ","&nbsp;",sprintf("<code>%7s</code>","NA")),
576 sprintf("<code>%s</code>",colors[i])))
577 raw3 <- append(raw3, "</span>")
578 # Color boxes (visual bar)
579 raw4 <- append(raw4, "<span class=\"output-raw\">")
580 raw4 <- append(raw4, "Color Map")
581 for ( col in colors )
582 raw4 <- append(raw4, sprintf("<cbox style='background-color: %s'></cbox>", col))
583 raw4 <- append(raw4, "</span>")
584 raw4 <- append(raw4, "</div>")
585
586 output$exportRAW1 <- renderText(paste(raw1, collapse = "\n"))
587 output$exportRAW2 <- renderText(paste(raw2, collapse = "\n"))
588 output$exportRAW3 <- renderText(paste(raw3, collapse = "\n"))
589 output$exportRAW4 <- renderText(paste(raw4, collapse = "\n"))
590
591
592 # -----------------------------
593 # For GrADS
594 # -----------------------------
595 gastr <- c()
596 gastr <- append(gastr, "<div class=\"output-grads\">")
597 gastr <- append(gastr, "<comment>** Define colors palette</comment>")
598 if ( length(colors.na) > 0 )
599 gastr <- append(gastr, "<comment>** WARNING undefined colors in color map!</comment>")
600 for ( i in 1:nrow(RGB) ) {
601 gastr <- append(gastr,ifelse(i %in% colors.na,
602 gsub(" ", "&nbsp;",sprintf("<code>'set rgb %02d %4s %4s %4s'</code>",
603 i + 19, "NA", "NA", "NA")),
604 gsub(" ", "&nbsp;",sprintf("<code>'set rgb %02d %4d %4d %4d'</code>",
605 i + 19, RGB[i,1], RGB[i,2], RGB[i,3]))))
606 }
607 gastr <- append(gastr, sprintf("<code>'set ccols %s'</code>",
608 paste(1:nrow(RGB) + 19, collapse = " ")))
609 gastr <- append(gastr, sprintf("<code>'set clevs %s'</code>",
610 paste(round(seq(0, 100, length.out=nrow(RGB) - 1), 1), collapse=" ")))
611 gastr <- append(gastr, "<comment>** Open data set via DODS</comment>")
612 gastr <- append(gastr, "<comment>** Open data set via DODS</comment>")
613 gastr <- append(gastr, strftime(Sys.Date() - 1, "<code>'sdfopen http://nomads.ncep.noaa.gov:9090/dods/gfs_1p00/gfs%Y%m%d/gfs_1p00_00z_anl'</code>"))
614 output$exportGrADS <- renderText(paste(gastr, collapse = "\n"))
615
616 # -----------------------------
617 # For Python
618 # -----------------------------
619 pystr <- c()
620 pystr <- append(pystr, "<div class=\"output-python\">")
621 pystr <- append(pystr, "<comment>## Define choosen color palette first</comment>")
622 pystr <- append(pystr, "<comment>## WARNING undefined colors in color map!</comment>")
623 pycolors <- sprintf("\"%s\"", colors)
624 if ( length(colors.na) > 0 ) pycolors[colors.na] <- "None"
625 pystr <- append(pystr, sprintf("<code>colors = (%s)</code>",
626 paste(sprintf("%s", pycolors), collapse = ",")))
627 pystr <- append(pystr, "</div>")
628
629 output$exportPython <- renderText(paste(pystr, collapse = "\n"))
630
631 # -----------------------------
632 # For Matlab
633 # -----------------------------
634 RGB <- attr(colorspace::hex2RGB(colors),"coords")
635 mstr <- c()
636 mstr <- append(mstr, "<div class=\"output-matlab\">")
637 mstr <- append(mstr, "<comment>%% Define rgb matrix first (matrix size ncolors x 3)</comment>")
638 if ( length(colors.na) > 0 )
639 mstr <- append(mstr, "<comment>%% WARNING undefined colors in color map!</comment>")
640 vardef <- "colors = ["
641 for ( i in 1:nrow(RGB) ) {
642 if ( i == 1 ) { pre <- vardef; post <- ";" }
643 else if ( i < nrow(RGB) ) { pre <- paste(rep(" ", nchar(vardef)), collapse = ""); post <- ";" }
644 else { pre <- paste(rep(" ", nchar(vardef)), collapse = ""); post <- "]" }
645 if ( i %in% colors.na ) {
646 tmp <- sprintf("<code>%s%5s,%5s,%5s%s</code>",
647 pre, "NaN", "NaN", "NaN", post)
648 } else {
649 tmp <- sprintf("<code>%s%5.3f,%5.3f,%5.3f%s</code>",
650 pre, RGB[i, 1], RGB[i, 2], RGB[i, 3], post)
651 }
652 mstr <- append(mstr, gsub(" ", "&nbsp;", tmp))
653 }
654 mstr <- append(mstr, "</div>")
655
656 output$exportMatlab <- renderText(paste(mstr, collapse="\n"))
657
658 }