126 lines
2.9 KiB
C
126 lines
2.9 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* xpm.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/01/04 13:53:03 by cchauvet #+# #+# */
|
|
/* Updated: 2023/01/08 17:06:34 by cchauvet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "solong.h"
|
|
|
|
static char *ft_square(void)
|
|
{
|
|
char *map;
|
|
size_t x;
|
|
size_t y;
|
|
|
|
map = malloc(((CASE_SIZE + 4) * CASE_SIZE) * sizeof(char));
|
|
if (map == NULL)
|
|
return (map);
|
|
y = 0;
|
|
while (y < CASE_SIZE)
|
|
{
|
|
map[(CASE_SIZE + 4) * y] = '"';
|
|
x = 0;
|
|
while (x < CASE_SIZE)
|
|
{
|
|
map[y * (CASE_SIZE + 4) + x + 1] = 'a';
|
|
x++;
|
|
}
|
|
map[(CASE_SIZE + 4) * y + CASE_SIZE + 1] = '"';
|
|
map[(CASE_SIZE + 4) * y + CASE_SIZE + 2] = ',';
|
|
map[(CASE_SIZE + 4) * y + CASE_SIZE + 3] = '\n';
|
|
y++;
|
|
}
|
|
map[(CASE_SIZE + 4) * CASE_SIZE - 2] = '\0';
|
|
return (map);
|
|
}
|
|
|
|
char *name_generator(t_square square)
|
|
{
|
|
char *out;
|
|
char *size;
|
|
char *temp;
|
|
|
|
size = ft_itoa(square.size);
|
|
if (size == NULL)
|
|
return (NULL);
|
|
temp = ft_strmerger(3, XPM_PATH, square.color, "_");
|
|
if (temp == NULL)
|
|
{
|
|
free(size);
|
|
return (NULL);
|
|
}
|
|
out = ft_strmerger(5, temp, size, "x", size, ".xpm");
|
|
free(size);
|
|
free(temp);
|
|
return (out);
|
|
}
|
|
|
|
static char *ft_gen_xpm_content(t_square square)
|
|
{
|
|
char *content;
|
|
char *temp;
|
|
char *map;
|
|
|
|
temp = ft_itoa(square.size);
|
|
if (temp == NULL)
|
|
return (NULL);
|
|
content = ft_strmerger(5, XPM_HEADER, temp, " ", temp, " 1 1\",\n\"");
|
|
free(temp);
|
|
if (content == NULL)
|
|
return (NULL);
|
|
temp = ft_strmerger(5, "/* XPM */", content, "a c ", square.color, "\",\n");
|
|
free(content);
|
|
if (temp == NULL)
|
|
return (NULL);
|
|
map = ft_square();
|
|
if (map == NULL)
|
|
{
|
|
free(temp);
|
|
return (NULL);
|
|
}
|
|
content = ft_strmerger(3, temp, map, "};");
|
|
free(temp);
|
|
free(map);
|
|
return (content);
|
|
}
|
|
|
|
char *ft_xpm_gen_file(t_square square)
|
|
{
|
|
char *file_content;
|
|
char *path;
|
|
int fd;
|
|
|
|
path = name_generator(square);
|
|
if (path == NULL)
|
|
return (NULL);
|
|
fd = open(path, O_RDONLY);
|
|
if (fd == -1)
|
|
{
|
|
file_content = ft_gen_xpm_content(square);
|
|
if (file_content == NULL)
|
|
{
|
|
free(path);
|
|
return (NULL);
|
|
}
|
|
fd = open(path, O_WRONLY | O_CREAT, 0644);
|
|
if (fd == -1)
|
|
{
|
|
free(path);
|
|
free(file_content);
|
|
return (NULL);
|
|
}
|
|
write(fd, file_content, ft_strlen(file_content));
|
|
close(fd);
|
|
free(file_content);
|
|
}
|
|
else
|
|
close(fd);
|
|
return (path);
|
|
}
|