Debian Codegraph @

inst/hclwizard/server.R

raw
1 # -------------------------------------------------------------------
2 # - NAME: server.R
3 # - AUTHOR: Reto Stauffer
4 # - DATE: 2015-05-01
5 # -------------------------------------------------------------------
6 # - DESCRIPTION: This is the shiny guitar server script here.
7 # -------------------------------------------------------------------
8 # - EDITORIAL: 2015-05-01, RS: Created file on thinkreto.
9 # -------------------------------------------------------------------
10 # - L@ST MODIFIED: 2019-01-13 10:05 on marvin
11 # -------------------------------------------------------------------
12
13 #options( shiny.trace = TRUE )
14
15 bpy <- eval(parse(text = "colorspace:::bpy"))
16
17 # Define server logic required to draw a histogram
18 shinyServer(function(input, output, session) {
19
20
21 if ( Sys.info()["nodename"] == "sculptor.uberspace.de" ) {
22 delay(0, toggleState("closeapp", condition = F))
23 }
24
25 # ----------------------------------------------------------------
26 # The different slider elements. Used later to show/hide or
27 # set the sliders.
28 # ----------------------------------------------------------------
29 sliderElements <- c("H1", "H2", "C1", "CMAX", "C2", "L1", "L2", "P1", "P2")
30
31 # ----------------------------------------------------------------
32 # Loading PAL palette information and examples
33 # ----------------------------------------------------------------
34 palettes <- colorspace:::GetPaletteConfig(gui = TRUE)
35 updateSelectInput(session,"EXAMPLE",
36 choices = colorspace:::example.plots[!colorspace:::example.plots %in% c("HCL Plot","Spectrum")])
37
38 # ----------------------------------------------------------------
39 # Package version information
40 # ----------------------------------------------------------------
41 output$version_info <- shiny::renderText(sprintf("<a href=\"%s\">R colorspace %s</a>",
42 "https://CRAN.R-project.org/package=colorspace",
43 packageVersion("colorspace")))
44
45 # ----------------------------------------------------------------
46 # Helper function. Input: character vectors to show/hide.
47 # ----------------------------------------------------------------
48 showHideElements <- function(show,hide) {
49 for ( elem in hide ) shinyjs::addClass( elem, "hcl-is-hidden")
50 for ( elem in show ) shinyjs::removeClass(elem, "hcl-is-hidden")
51 }
52
53 # ----------------------------------------------------------------
54 # Used in different functions: returns the current settings for all
55 # Parameters
56 # ----------------------------------------------------------------
57 getCurrentPalette <- function() {
58 pal <- list()
59 for ( elem in sliderElements ) {
60 eval(parse(text = sprintf("pal$%s <- as.numeric(input$%s)", elem, elem)))
61 }
62 pal$N <- input$N
63 if ( ! "register" %in% names(pal) ) pal$register <- ""
64 return(pal)
65 }
66
67 # ----------------------------------------------------------------
68 # Change PAL (palettes to chose) whenever the typ changes
69 # ----------------------------------------------------------------
70 observeEvent(input$typ, {
71 x <- list()
72 if ( grepl("^base$", input$typ) ) {
73 shinyjs::disable("registerpalettebutton")
74 shinyjs::disable("registerpalettename")
75 } else {
76 shinyjs::enable("registerpalettebutton")
77 shinyjs::enable("registerpalettename")
78 }
79 for ( i in which(palettes$typ == input$typ) )
80 x[[sprintf("%s", rownames(palettes)[i])]] <- rownames(palettes)[i]
81 updateSelectInput(session, "PAL", choices = x)
82 })
83
84 # ----------------------------------------------------------------
85 # Switch between dark mode (black background) and normal mode
86 # (white background). Also used for the demo plots.
87 # ----------------------------------------------------------------
88 observeEvent(input$darkmode, {
89 if ( ! input$darkmode ) {
90 shinyjs::removeClass(selector = "body", class = "darkmode")
91 } else {
92 shinyjs::addClass(selector = "body", class = "darkmode")
93 }
94 colors <- getColors()
95 plotExample(colors)
96 showSpectrum()
97 showColorplane(colors)
98 })
99
100 # ----------------------------------------------------------------
101 # Change palettes whenever the palette "typ" changes
102 # ----------------------------------------------------------------
103 observeEvent(input$PAL, {
104
105 # Getting settings of the choosen color palette
106 idx <- which(palettes$typ == input$typ & rownames(palettes) == input$PAL)
107 if ( length(idx) == 0 ) { return(FALSE); }
108 name <- input$PAL
109 curPAL <- as.list(palettes[idx,])
110
111 # In this case we have to set the slider values as
112 # the user selected a new scheme!
113 for (elem in sliderElements) {
114 if ( is.na(palettes[idx, elem]) ) next
115 updateSliderInput(session, elem, value = curPAL[[elem]])
116 }
117
118 # Show or hide sliders depending on the palette typ configuration
119 showColorSliders(input$typ)
120 showColorMap()
121
122 })
123
124 # ----------------------------------------------------------------
125 # When the user changes the slider settings
126 # ----------------------------------------------------------------
127 sliderChanged <- function(elem) {
128 # Load color palette
129 pal <- getCurrentPalette()
130 # Show new color map
131 showColorMap()
132 }
133 observeEvent(input$N, { sliderChanged("N") })
134 observeEvent(input$H1, { sliderChanged("H1") })
135 observeEvent(input$H2, { sliderChanged("H2") })
136 observeEvent(input$C1, { sliderChanged("C1") })
137 observeEvent(input$CMAX, { sliderChanged("CMAX") })
138 observeEvent(input$C2, { sliderChanged("C2") })
139 observeEvent(input$L1, { sliderChanged("L1") })
140 observeEvent(input$L2, { sliderChanged("L2") })
141 observeEvent(input$P1, { sliderChanged("P1") })
142 observeEvent(input$P2, { sliderChanged("P2") })
143 # Do the same whenever the example changes
144 observeEvent(input$EXAMPLE, { sliderChanged("EXAMPLE") })
145
146 # ----------------------------------------------------------------
147 # When the user changes the options (like setting visual
148 # constraints or the desaturate option).
149 # ----------------------------------------------------------------
150 observeEvent(input$reverse, { showColorMap() });
151 observeEvent(input$fixup, { showColorMap() });
152 observeEvent(input$desaturate, { showColorMap() });
153 observeEvent(input$constraint, { showColorMap() });
154
155 # ----------------------------------------------------------------
156 # When the user changes one of the values
157 # ----------------------------------------------------------------
158 setValueByUser <- function(elem) {
159 value = eval(parse(text = sprintf("input$%sval", elem)))
160 if ( nchar(value) > 0 ) {
161 updateSliderInput(session,elem,value = value)
162 updateTextInput(session, sprintf("%sval", elem), value = "")
163 }
164 }
165 observeEvent(input$H1set, { setValueByUser("H1") })
166 observeEvent(input$H2set, { setValueByUser("H2") })
167 observeEvent(input$C1set, { setValueByUser("C1") })
168 observeEvent(input$CMAXset, { setValueByUser("CMAX") })
169 observeEvent(input$C2set, { setValueByUser("C2") })
170 observeEvent(input$L1set, { setValueByUser("L1") })
171 observeEvent(input$L2set, { setValueByUser("L2") })
172 observeEvent(input$P1set, { setValueByUser("P1") })
173 observeEvent(input$P2set, { setValueByUser("P2") })
174 observeEvent(input$Nset, { setValueByUser("N") })
175
176 # ----------------------------------------------------------------
177 # Register custom palette by user-defined name
178 # ----------------------------------------------------------------
179 observeEvent(input$registerpalettebutton, {
180 if ( nchar(input$registerpalettename) > 0 ) {
181 cmd <- function_to_string(input$N, register = input$registerpalettename)
182 eval(parse(text = cmd))
183 showNotification(sprintf("Custom palette \"%s\" registered in current R session.",
184 input$registerpalettename))
185 }
186 })
187
188 # ----------------------------------------------------------------
189 # Getting currently selected color scheme
190 # ----------------------------------------------------------------
191 getColors <- function(N = NULL, fun = FALSE) {
192 # Current palette settings
193 curtyp <- input$typ
194 curPAL <- getCurrentPalette()
195 if ( ! is.null(N) ) curPAL$N <- N
196 fixup <- input$fixup
197 # Getting palette function
198 if ( input$typ == "base" ) {
199 # Avoids running into shiny errors when the palette
200 # switches faster than the type.
201 if ( ! exists(input$PAL) ) return(NULL)
202 base_pal <- eval(parse(text = input$PAL))
203 pal <- function(..., fixup = FALSE) if(input$reverse) rev(base_pal(...)) else base_pal(...)
204 } else {
205 # Set elements of curPAL to "NA" for those elements which are
206 # NA in the palettes (palette config). Same is used to hide
207 # the sliders, if a value in palettes is NA the slider should
208 # also be hidden on the UI.
209 cnf <- which(palettes$typ == curtyp & rownames(palettes) == input$PAL)
210 if ( length(cnf) > 0 ) {
211 cnf <- as.list(palettes[cnf,])
212 for ( elem in names(cnf) ) {
213 if ( elem %in% names(curPAL) & is.na(cnf[[elem]]) ) curPAL[[elem]] = NA
214 }
215 }
216 # Calling GetPalette with args list
217 args <- curPAL
218 names(args) <- tolower(names(args))
219 args$fixup <- input$fixup
220 args$type <- input$typ
221 args$reverse <- input$reverse
222 pal <- do.call(colorspace:::GetPalette, args)
223 }
224 # If fun is set to FALSE: return values
225 if ( ! fun ) {
226 # Remove alpha (base color maps)
227 colors <- substr(pal(curPAL$N, fixup = input$fixup), 0, 7)
228 # Add desaturation or constraints
229 if ( input$desaturate ) colors <- colorspace::desaturate(colors)
230 if ( any(tolower(input$constraint) %in% c("protan", "deutan", "tritan")) ) {
231 cvdfun <- switch(tolower(input$constraint),
232 "protan" = colorspace::protan,
233 "deutan" = colorspace::deutan,
234 "tritan" = colorspace::tritan)
235 colors <- do.call(cvdfun, list("col" = colors))
236 }
237 # Reverse if required
238 #if ( input$reverse ) colors <- rev(colors)
239 return(colors)
240 } else {
241 return(pal)
242 }
243 }
244
245 # ----------------------------------------------------------------
246 # Show color map
247 # Note that showColorMap also controls the output in the main
248 # panel. Depending on the user view (if the user is on the
249 # export or plotexample tab) we have to update the export
250 # tab or the image. Not both.
251 # ----------------------------------------------------------------
252 showColorMap <- function() {
253
254 colors <- getColors()
255
256 output$colormap <- renderPlot({
257 bg <- ifelse(input$darkmode, "black", "white") # background
258 fg <- ifelse(input$darkmode, "white", "black") # foreground
259 par(mar = rep(0,4), xaxt = "n", yaxt = "n", oma = rep(0,4), bty = "n",
260 bg = bg, fg = fg)
261 image(matrix(1:length(colors),ncol = 1),col = colors)
262 }, width = 500, height = 5)
263
264 # Update the export tabs
265 if ( input$maintabs == "export" ) {
266 generateExport()
267 # Show image (plot)
268 } else if ( input$maintabs == "plotexample" & nchar(input$PAL) > 0 ) {
269 plotExample(colors)
270 # Show spectrum
271 } else if ( input$maintabs == "spectrum" ) {
272 showSpectrum()
273 # Show color plane
274 } else if ( input$maintabs == "colorplane" ) {
275 showColorplane()
276 }
277
278 # Save color set to parent environment as we use it to generate
279 # the output on the export tabs on demand.
280 colormap <<- colors
281 }
282
283 # ----------------------------------------------------------------
284 # Display spectrum
285 # ----------------------------------------------------------------
286 showSpectrum <- function() {
287 colors <- getColors(100)
288 fn <- sprintf(paste("fn <- function(colors, ...) {\n",
289 " par(bg = \"%1$s\", fg = \"%2$s\", col.axis = \"%2$s\")\n",
290 " colorspace::specplot(colors, cex = 1.4, plot = TRUE, rgb = TRUE, ...)\n",
291 "}"),
292 ifelse(input$darkmode, "black", "white"), # background
293 ifelse(input$darkmode, "white", "black")) # foreground, col.axis
294 fn <- eval(parse(text = fn))
295 output$spectrum <- renderPlot(
296 fn(colors), width = 800, height = 800
297 )
298 }
299
300 # ----------------------------------------------------------------
301 # Display colorplane
302 # ----------------------------------------------------------------
303 showColorplane <- function(colors) {
304 if ( missing(colors) ) colors <- getColors( input$N )
305
306 # dimension to collapse. If autohclplot option has been set to TRUE: take NULL.
307 if ( colorspace:::.colorspace_get_info("hclwizard_autohclplot") ) {
308 plot_type <- NULL
309 } else if ( grepl("^qual", input$typ) ) {
310 plot_type <- "qualitative"
311 } else if ( grepl("^dive", input$typ) ) {
312 plot_type <- "diverging"
313 } else if ( grepl("^(seqm|seqs)", input$typ) ) {
314 plot_type <- "sequential"
315 } else {
316 plot_type <- NULL # Let the plotting function decide
317 }
318 fn <- sprintf(paste("fn <- function(colors, type, ...) {\n",
319 " par(bg = \"%1$s\", fg = \"%2$s\", col.axis = \"%2$s\")\n",
320 " colorspace::hclplot(colors, type = type, cex = 1.4, ...)\n",
321 "}"),
322 ifelse(input$darkmode, "black", "white"), # background
323 ifelse(input$darkmode, "white", "black")) # foreground, col.axis
324 fn <- eval(parse(text = fn))
325 output$colorplane <- renderPlot(
326 fn(colors, plot_type), width = 800, height = 800
327 )
328 }
329
330 # ----------------------------------------------------------------
331 # Plotting example
332 # ----------------------------------------------------------------
333 plotExample <- function(colors) {
334 if ( nchar(input$EXAMPLE) > 0 ) {
335 fn <- sprintf(paste("fn <- function(x, type, ...) {\n",
336 " par(bg = \"%1$s\", fg = \"%2$s\", col.axis = \"%2$s\")\n",
337 " colorspace::demoplot(x, type, ...)\n",
338 "}"),
339 ifelse(input$darkmode, "black", "white"), # background
340 ifelse(input$darkmode, "white", "black")) # foreground, col.axis
341 fn <- eval(parse(text = fn))
342 cmd <- sprintf(paste("output$plot <- renderPlot({fn(colors, \"%s\")},",
343 "width = 800, height = 600)"),
344 tolower(input$EXAMPLE))
345 eval(parse(text = cmd))
346 }
347 }
348
349 # ----------------------------------------------------------------
350 # Getting currently selected color scheme and draws the
351 # corresponding color bar using shiny
352 # ----------------------------------------------------------------
353 showColorSliders <- function(curtyp) {
354 idx <- which(palettes$typ == curtyp & rownames(palettes) == input$PAL)
355 show <- hide <- c()
356 for ( elem in sliderElements ) {
357 if ( is.na(palettes[idx,elem]) ) { hide <- c(hide, sprintf("%s-wrapper", elem)) }
358 else { show <- c(show, sprintf("%s-wrapper", elem)) }
359 showHideElements(show,hide)
360 if ( any(grepl("^CMAX-wrapper$", show)) ) {
361 updateSliderInput(session, "C1", max = 180)
362 updateSliderInput(session, "C2", max = 180)
363 updateSliderInput(session, "CMAX", max = 180)
364 } else {
365 updateSliderInput(session, "C1", max = 100)
366 updateSliderInput(session, "C2", max = 100)
367 updateSliderInput(session, "CMAX", max = 100)
368 }
369 }
370 }
371
372
373 # ----------------------------------------------------------------
374 # Returns the R function call of the current palette as specified
375 # by the user.
376 # ----------------------------------------------------------------
377 function_to_string <- function(n, register = "") {
378
379 # It is possible that the function cannot be evaluated
380 # at the moment shiny changes the palette typ. In these
381 # cases "getColors" returns NULL. In these cases return
382 # "..."
383 pal <- getColors(fun = TRUE)
384 if ( is.null(pal) ) return("...")
385
386 arglist <- list()
387 for ( arg in names(formals(pal)) ) {
388 if ( arg == "..." ) break;
389 arglist[[arg]] <- formals(pal)[[arg]]
390 }
391 arglist[["n"]] <- sprintf("%d", n)
392 if ( nchar(register) > 0 )
393 arglist[["register"]] <- sprintf("\"%s\"", register)
394
395 # Remove defaults
396 if ( "fixup" %in% names(arglist) )
397 if ( arglist[["fixup"]] == TRUE ) arglist[["fixup"]] <- NULL
398 if ( "alpha" %in% names(arglist) )
399 if ( arglist[["alpha"]] == 1 ) arglist[["alpha"]] <- NULL
400 if ( "rev" %in% names(arglist) )
401 if ( arglist[["rev"]] == FALSE ) arglist[["rev"]] <- NULL
402
403 # Name of the method
404 if ( input$typ %in% c("Qualitative", "qual") ) {
405 fname <- "qualitative_hcl"
406 } else if ( grepl("^seq", tolower(input$typ)) ) {
407 fname <- "sequential_hcl"
408 } else if ( grepl("^div", tolower(input$typ)) ) {
409 fname <- "diverging_hcl"
410 } else {
411 fname <- input$PAL
412 }
413 if ( nchar(register) > 0 ) {
414 if ( grepl("^base$", input$typ ) ) return("# Not possible for legacy schemes.")
415 fname <- sprintf("colorspace::%s", fname)
416 }
417
418 # Create the result
419 argstr <- paste(names(arglist), arglist, sep = " = ", collapse = ", ")
420 result <- sprintf("%s(%s)", fname, argstr)
421
422 # Default palette, reversed?
423 if ( input$typ == "base" & input$reverse )
424 result <- sprintf("rev(%s)", result)
425
426
427 # If visual constraints are selected: add wrapping function
428 if ( nchar(register) == 0 ) {
429 if ( input$desaturate )
430 result <- sprintf("colorspace::desaturate(%s)", result)
431 if ( input$constraint == "Deutan" ) {
432 result <- sprintf("colorspace::deutan(%s)", result)
433 } else if ( input$constraint == "Protan" ) {
434 result <- sprintf("colorspace::protan(%s)", result)
435 } else if ( input$constraint == "Tritan" ) {
436 result <- sprintf("colorspace::tritan(%s)", result)
437 }
438 }
439
440 return(result)
441 }
442
443
444 # ----------------------------------------------------------------
445 # Generates the call for Python colorspace
446 # ----------------------------------------------------------------
447 function_to_pythoncolorspace <- function(n) {
448
449 # It is possible that the function cannot be evaluated
450 # at the moment shiny changes the palette typ. In these
451 # cases "getColors" returns NULL. In these cases return
452 # "..."
453 pal <- getColors(fun = TRUE)
454 if ( is.null(pal) ) return("...")
455
456 arglist <- list()
457 for (arg in names(formals(pal))) {
458 if (arg == "...") break;
459 arglist[[arg]] <- formals(pal)[[arg]]
460 }
461
462 # Remove n, alpha, and register entries
463 arglist$n <- arglist$alpha <- arglist$register <- NULL
464
465 for (tmp in c("h", "c", "l", "power")) {
466 if (tmp %in% names(arglist)) {
467 arglist[[tmp]] <- as.vector(na.omit(arglist[[tmp]]))
468 }
469 }
470
471 # Remove defaults
472 if ("fixup" %in% names(arglist))
473 if (arglist[["fixup"]] == TRUE) arglist[["fixup"]] <- NULL
474 if ("rev" %in% names(arglist))
475 if (arglist[["rev"]] == FALSE) arglist[["rev"]] <- NULL
476
477 # Name of the method
478 if (input$typ %in% c("Qualitative", "qual")) {
479 fname <- "qualitative_hcl"
480 } else if (grepl("^seq", tolower(input$typ))) {
481 fname <- "sequential_hcl"
482 } else if (grepl("^div", tolower(input$typ))) {
483 fname <- "diverging_hcl"
484 } else {
485 fname <- input$PAL
486 }
487
488 # Deparse arguments and convert to python-style strings;
489 # * 'c(1, 2)' gets `[1, 2]`.
490 # * `NA` = `None` (if it occurs)
491 # * `TRUE` = `True`
492 # * `FALSE` = `False`
493 arglist <- lapply(arglist, function(x) {
494 x <- gsub("\\)$", "]", gsub("^c\\(", "[", deparse(x)))
495 x <- gsub("FALSE", "False", gsub("TRUE", "True", x))
496 gsub("NA", "None", x)
497 })
498
499 # Create the result
500 argstr <- paste(names(arglist), arglist, sep = " = ", collapse = ", ")
501 palcmd <- sprintf("%s(%s)", fname, argstr)
502
503 # Imports list used for "from colorspace import *"
504 imports <- fname
505
506 # Default palette, reversed?
507 if (input$typ == "base" & input$reverse) palcmd <- sprintf("rev(%s)", palcmd)
508 palcmd <- paste0("pal = ", palcmd)
509
510 # Command to extract N colors
511 colcmd <- sprintf("pal.colors(%s)", n)
512
513 # If visual constraints are selected: add wrapping function
514 if (input$desaturate)
515 colcmd <- sprintf("desaturate(%s)", colcmd)
516 imports <- c(imports, "desaturate")
517 if (input$constraint == "Deutan") {
518 colcmd <- sprintf("%s(%s)", tolower(input$constraint), colcmd)
519 imports <- c(imports, tolower(input$constraint))
520 } else if (input$constraint == "Protan") {
521 colcmd <- sprintf("%s(%s)", tolower(input$constraint), colcmd)
522 imports <- c(imports, tolower(input$constraint))
523 } else if (input$constraint == "Tritan") {
524 colcmd <- sprintf("%s(%s)", tolower(input$constraint), colcmd)
525 imports <- c(imports, tolower(input$constraint))
526 }
527
528 # Creating final result
529 pystr <- c("<comment>## Import and define palette</comment>",
530 sprintf("<code>from colorspace import %s</code>", paste(imports, collapse = ", ")),
531 sprintf("<code>%s</code>", palcmd),
532 sprintf("<comment>## To get %s colors simply call</comment>", input$N),
533 sprintf("<code>%s</code>", colcmd))
534
535 return(paste(pystr, collapse = "\n"))
536 }
537
538 # ----------------------------------------------------------------
539 # Export colors: generate export content
540 # ----------------------------------------------------------------
541 generateExport <- function() {
542
543 # Setting "NA" colors if fixup=FALSE to white and
544 # store the indizes on colors.na. Replacement required
545 # to be able to convert hex->RGB, index required to
546 # create proper output (where NA values should be displayed).
547 colors <- getColors()
548 colors.na <- which(is.na(colors))
549 colors[is.na(colors)] <- "#ffffff"
550
551 # --------------------------
552 # RAW
553 # --------------------------
554 # Generate RGB coordinates
555 sRGB <- colorspace::hex2RGB(colors)
556 RGB <- attr( sRGB, "coords" )
557 HCL <- round(attr( as( sRGB, "polarLUV" ), "coords" ))
558
559 # Generate output string
560 append <- function(x,new) c(x,new)
561 raw1 <- raw2 <- raw3 <- raw4 <- list()
562 # RGB 0-1
563 raw1 <- append(raw1, "<div style=\"clear: both;\">")
564 raw1 <- append(raw1, "<span class=\"output-raw\">")
565 raw1 <- append(raw1, "HCL values")
566 for ( i in 1:nrow(HCL) )
567 raw1 <- append(raw1,ifelse(i %in% colors.na,
568 gsub(" ", "&nbsp;", sprintf("<code>%5s %5s %5s</code>", "NA", "NA", "NA")),
569 gsub(" ", "&nbsp;", sprintf("<code>%4d %4d %4d</code>", HCL[i,"H"], HCL[i,"C"], HCL[i,"L"]))))
570 raw1 <- append(raw1, "</span>")
571 # RGB 0-255
572 raw2 <- append(raw2, "<span class=\"output-raw\">")
573 raw2 <- append(raw2, "RGB values [0-255]")
574 RGB <- round(RGB * 255)
575 for ( i in 1:nrow(RGB) )
576 raw2 <- append(raw2,ifelse(i %in% colors.na,
577 gsub(" ", "&nbsp;", sprintf("<code>%4s %4s %4s</code>", "NA", "NA", "NA")),
578 gsub(" ", "&nbsp;", sprintf("<code>%4d %4d %4d</code>", RGB[i,1], RGB[i,2], RGB[i,3]))))
579 raw2 <- append(raw2,"</span>")
580 # HEX colors
581 raw3 <- append(raw3,"<span class=\"output-raw\">")
582 raw3 <- append(raw3,"HEX colors, no alpha")
583 for ( i in seq_along(colors) )
584 raw3 <- append(raw3,ifelse(i %in% colors.na,
585 gsub(" ","&nbsp;",sprintf("<code>%7s</code>","NA")),
586 sprintf("<code>%s</code>",colors[i])))
587 raw3 <- append(raw3, "</span>")
588 # Color boxes (visual bar)
589 raw4 <- append(raw4, "<span class=\"output-raw\">")
590 raw4 <- append(raw4, "Color Map")
591 for ( col in colors )
592 raw4 <- append(raw4, sprintf("<cbox style='background-color: %s'></cbox>", col))
593 raw4 <- append(raw4, "</span>")
594 raw4 <- append(raw4, "</div>")
595
596 output$exportRAW1 <- renderText(paste(raw1, collapse = "\n"))
597 output$exportRAW2 <- renderText(paste(raw2, collapse = "\n"))
598 output$exportRAW3 <- renderText(paste(raw3, collapse = "\n"))
599 output$exportRAW4 <- renderText(paste(raw4, collapse = "\n"))
600
601 # The corresponding R call
602 output$exportFun <- renderText(sprintf("<code>%s</code>",
603 function_to_string(input$N)))
604 output$exportFunReg2 <- output$exportFunReg <- renderText(
605 sprintf("<code>%s</code>",
606 function_to_string(input$N, register = "Custom-Palette")))
607
608
609 # -----------------------------
610 # For GrADS
611 # -----------------------------
612 gastr <- c()
613 gastr <- append(gastr, "<div class=\"output-grads\">")
614 gastr <- append(gastr, "<comment>** Define colors palette</comment>")
615 if ( length(colors.na) > 0 )
616 gastr <- append(gastr, "<comment>** WARNING undefined colors in color map!</comment>")
617 for ( i in 1:nrow(RGB) ) {
618 gastr <- append(gastr,ifelse(i %in% colors.na,
619 gsub(" ", "&nbsp;",sprintf("<code>'set rgb %02d %4s %4s %4s'</code>",
620 i + 19, "NA", "NA", "NA")),
621 gsub(" ", "&nbsp;",sprintf("<code>'set rgb %02d %4d %4d %4d'</code>",
622 i + 19, RGB[i,1], RGB[i,2], RGB[i,3]))))
623 }
624 gastr <- append(gastr, sprintf("<code>'set ccols %s'</code>",
625 paste(1:nrow(RGB) + 19, collapse = " ")))
626 gastr <- append(gastr, sprintf("<code>'set clevs %s'</code>",
627 paste(round(seq(0, 100, length.out=nrow(RGB) - 1), 1), collapse=" ")))
628 gastr <- append(gastr, "<comment>** Open data set via DODS</comment>")
629 gastr <- append(gastr, "<comment>** Open data set via DODS</comment>")
630 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>"))
631 output$exportGrADS <- renderText(paste(gastr, collapse = "\n"))
632
633 # -----------------------------
634 # For Python colorspacd
635 # -----------------------------
636 if (input$typ != "base") {
637 output$exportPython <- renderText(function_to_pythoncolorspace(input$N))
638 } else {
639 output$exportPython <- renderText("<comment>## No equivalent to base R colors in Python colorspace</comment>")
640 }
641
642 # -----------------------------
643 # For Matlab
644 # -----------------------------
645 RGB <- attr(colorspace::hex2RGB(colors), "coords")
646 mstr <- c()
647 mstr <- append(mstr, "<div class=\"output-matlab\">")
648 mstr <- append(mstr, "<comment>%% Define rgb matrix first (matrix size ncolors x 3)</comment>")
649 if ( length(colors.na) > 0 )
650 mstr <- append(mstr, "<comment>%% WARNING undefined colors in color map!</comment>")
651 vardef <- "colors = ["
652 for ( i in 1:nrow(RGB) ) {
653 if ( i == 1 ) { pre <- vardef; post <- ";" }
654 else if ( i < nrow(RGB) ) { pre <- paste(rep(" ", nchar(vardef)), collapse = ""); post <- ";" }
655 else { pre <- paste(rep(" ", nchar(vardef)), collapse = ""); post <- "]" }
656 if ( i %in% colors.na ) {
657 tmp <- sprintf("<code>%s%5s,%5s,%5s%s</code>",
658 pre, "NaN", "NaN", "NaN", post)
659 } else {
660 tmp <- sprintf("<code>%s%5.3f,%5.3f,%5.3f%s</code>",
661 pre, RGB[i, 1], RGB[i, 2], RGB[i, 3], post)
662 }
663 mstr <- append(mstr, gsub(" ", "&nbsp;", tmp))
664 }
665 mstr <- append(mstr, "</div>")
666
667 output$exportMatlab <- renderText(paste(mstr, collapse="\n"))
668
669 }
670
671 # ----------------------------------------------------------------
672 # Update main tabs (show export output, spectrum, or example plot)
673 # ----------------------------------------------------------------
674 updateMainTabContent <- function() {
675 # Update the export tabs
676 if ( input$maintabs == "export" ) {
677 generateExport()
678 # Show image (plot)
679 } else if ( input$maintabs == "plotexample" & nchar(input$PAL) > 0 ) {
680 plotExample(colormap)
681 # Spectrum plot
682 } else if ( input$maintabs == "spectrum" ) {
683 showSpectrum()
684 # Color plane plot
685 } else if ( input$maintabs == "colorplane" ) {
686 showColorplane()
687 }
688 }
689 observeEvent(input$maintabs, updateMainTabContent());
690
691
692 # downloadHandler() takes two arguments, both functions.
693 # The content function is passed a filename as an argument, and
694 # it should write out data to that filename.
695 getRGB <- function(int=FALSE) {
696 colors <- getColors()
697 NAidx <- which(is.na(colors))
698 if (length(NAidx) > 0) colors[NAidx] <- "#FFFFFF"
699 if (int) { scale = 255; digits = 0 } else { scale = 1; digits = 3 }
700 RGB <- round(attr(colorspace::hex2RGB(colors), "coords") * scale, digits)
701 if (length(NAidx) > 0) RGB[NAidx,] <- NA
702 return(RGB)
703 }
704 getHCL <- function() {
705 colors <- getColors()
706 NAidx <- which(is.na(colors))
707 if (length(NAidx) > 0) colors[NAidx] <- "#FFFFFF"
708 HCL <- colorspace::coords(as(colorspace::hex2RGB(colors), "polarLUV"))
709 if (length(NAidx) > 0) HCL[NAidx,] <- NA
710 return(round(HCL)[,c("H","C","L")])
711 }
712 output$downloadRAW1 <- downloadHandler(
713 file <- "colormap_HCL.txt",
714 content = function(file) {
715 write.table(getHCL(), file, sep = ",", col.names = TRUE, row.names = FALSE)
716 }
717 )
718 output$downloadRAW2 <- downloadHandler(
719 file <- "colormap_RGB.txt",
720 content = function(file) {
721 write.table(getRGB(TRUE), file, sep = ",", col.names = TRUE, row.names = FALSE)
722 }
723 )
724 output$downloadRAW3 <- downloadHandler(
725 file <- "colormap_hex.txt",
726 content = function(file) {
727 write.table(getColors(), file, sep = ",",
728 col.names = FALSE, row.names = FALSE)
729 }
730 )
731
732 # ----------------------------------------------------------------
733 # Returns color function
734 # ----------------------------------------------------------------
735 observeEvent(input$closeapp, stopApp(invisible(getColors(fun = TRUE))));
736
737 # - Configuration
738 ticks <- FALSE # to show ticks or not to show ticks
739
740
741 })
742