Пример #1
0
int
main(int argc, char **argv) {
    int rc = 1;
    opts.spaces = 2;

    command_t cmd;
    command_init(&cmd, argv[0], "1.0.0");
    command_option(&cmd
                   , "-v"
                   , "--verbose"
                   , "enable verbose stuff"
                   , set_verbose);
    command_option(&cmd
                   , "-s"
                   , "--spaces [count]"
                   , "optional number of spaces (defaults to 2)"
                   , set_spaces);
    command_parse(&cmd, argc, argv);

    for (int i = 0; i < cmd.argc; ++i) {
        if (-1 == convert_file(cmd.argv[i])) goto cleanup;
    }

    rc = 0;

cleanup:
    command_free(&cmd);
    return rc;
}
Пример #2
0
void
command_init(command_t *self, const char *name, const char *version) {
  self->arg = NULL;
  self->name = name;
  self->version = version;
  self->option_count = self->argc = 0;
  self->usage = "[options]";
  command_option(self, "-V", "--version", "output program version", command_version);
  command_option(self, "-h", "--help", "output help information", command_help);
  self->exit = doExit;
}
Пример #3
0
void Arguments::parse(int argc, char* argv[])
{
	// commander internal data structure
	command_t cmd;
	command_init(&cmd, argv[0], VERSION);

	command_option(&cmd, "-v", "--version", "Show game version and build date", version);
	command_option(&cmd, "-h", "--help",    "Show instructions", help);

	command_parse(&cmd, argc, argv);
	command_free(&cmd);
}
Пример #4
0
int
main1(int argc, char **argv) {
    command_t cmd;
    command_init(&cmd, argv[0], "0.0.1");
    command_option(&cmd, "-v", "--verbose", "enable verbose stuff", verbose);
    command_option(&cmd, "-r", "--required <arg>", "required arg", required);
    command_option(&cmd, "-o", "--optional [arg]", "optional arg", optional);
    command_parse(&cmd, argc, argv);
    printf("additional args:\n");
    for (int i = 0; i < cmd.argc; ++i) {
        printf("  - '%s'\n", cmd.argv[i]);
    }
    command_free(&cmd);
    return 0;
}
Пример #5
0
int
main(int argc, char **argv){
  command_t cmd;
  command_init(&cmd, argv[0], "0.0.1");
  command_option(&cmd, "-d", "--detached", "spawn a detached process", verbose);
  command_option(&cmd, "-i", "--ipc [arg]", "listen to a pipe", required);
  command_option(&cmd, "-f", "--fd [arg]", "listen and track a file descriptor", required);
  command_option(&cmd, "-a", "--auth [arg]", "fd to get authorization information from", optional);
  command_parse(&cmd, argc, argv);
  printf("additional args:\n");
  for (int i = 0; i < cmd.argc; ++i) {
    printf("  - '%s'\n", cmd.argv[i]);
  }
  command_free(&cmd);
  return 0;
}
Пример #6
0
int main(int argc, const char **argv) {
	puts("Hello World"); /* prints Hello World */

	command_init(&cmd, argv[0], "0.0.1", "[options] command");
	command_option(&cmd, "-w", "--wait <ms>", "wait before spawning, default 3100ms", wait_handler);
	command_option(&cmd, "-m", "--multicast-wait <ms>", "wait between multicasts, default 1000ms", multicast_wait_handler);
	command_parse(&cmd, argc, argv);
	printf("additional args:\n");
	for (int i = 0; i < cmd.argc; ++i) {
	  printf("  - '%s'\n", cmd.argv[i]);
	}

	loop(2345, inet_addr("239.0.0.0"));
	command_free(&cmd);


	return EXIT_SUCCESS;
}
Пример #7
0
void
command_init(command_t *self, const char *name, const char *version) {
  self->arg = NULL;
  self->name = name;
  self->version = version;
  self->option_count = self->argc = 0;
  self->usage = "[options]";
  self->nargv = NULL;
  command_option(self, "-V", "--version", "output program version", command_version);
}
Пример #8
0
int
main(int argc, char *argv[]) {
#ifdef _WIN32
  opts.dir = ".\\deps";
#else
  opts.dir = "./deps";
#endif
  opts.verbose = 1;
  opts.dev = 0;

  command_t program;

  command_init(&program
    , "clib-install"
    , CLIB_VERSION);

  program.usage = "[options] [name ...]";

  command_option(&program
    , "-o"
    , "--out <dir>"
    , "change the output directory [deps]"
    , setopt_dir);
  command_option(&program
    , "-q"
    , "--quiet"
    , "disable verbose output"
    , setopt_quiet);
  command_option(&program
    , "-d"
    , "--dev"
    , "install development dependencies"
    , setopt_dev);
  command_parse(&program, argc, argv);

  int code = 0 == program.argc
    ? install_local_packages()
    : install_packages(program.argc, program.argv);

  command_free(&program);
  return code;
}
Пример #9
0
int
main(int argc, char **argv) {
  filter.executables = true;
  filter.utilities = true;

  command_t program;
  command_init(&program, "clib-search", CLIB_SEARCH_VERSION);
  program.usage = "[options] [query ...]";
  command_option(&program, "-a", "--author <author>", "filter by author", author);
  command_option(&program, "-e", "--executables", "filter by executables", executables);
  command_option(&program, "-u", "--utilities", "filter by utilities", utilities);
  command_parse(&program, argc, argv);

  char *html = wiki_html_cache();
  if (NULL == html) {
    fprintf(stderr, "Failed to fetch wiki HTML\n");
    return 1;
  }

  list_t *pkgs = wiki_registry_parse(html);

  list_node_t *node;
  list_iterator_t *it = list_iterator_new(pkgs, LIST_HEAD);
  while ((node = list_iterator_next(it))) {
    package_t *pkg = (package_t *) node->val;
    if (matches(program.argc, program.argv, pkg)) {
      printf("  \033[36m%s\033[m\n", pkg->repo);
      printf("  url: \033[90m%s\033[m\n", pkg->href);
      printf("  desc: \033[90m%s\033[m\n", pkg->description);
      printf("\n");
    }
  }
  list_iterator_destroy(it);
  list_destroy(pkgs);
  command_free(&program);

  return 0;
}
Пример #10
0
int
main(int argc, char **argv){
  monitor_t monitor;
  monitor.pidfile = NULL;
  monitor.mon_pidfile = NULL;
  monitor.on_error = NULL;
  monitor.logfile = "mon.log";
  monitor.daemon = 0;
  monitor.sleepsec = 1;

  command_t program;
  program.data = &monitor;
  command_init(&program, "mon", VERSION);
  command_option(&program, "-l", "--log <path>", "specify logfile [mon.log]", on_log);
  command_option(&program, "-s", "--sleep <sec>", "sleep seconds before re-executing [1]", on_sleep);
  command_option(&program, "-S", "--status", "check status of --pidfile", on_status);
  command_option(&program, "-p", "--pidfile <path>", "write pid to <path>", on_pidfile);
  command_option(&program, "-m", "--mon-pidfile <path>", "write mon(1) pid to <path>", on_mon_pidfile);
  command_option(&program, "-P", "--prefix <str>", "add a log prefix", on_prefix);
  command_option(&program, "-d", "--daemonize", "daemonize the program", on_daemonize);
  command_option(&program, "-e", "--on-error <cmd>", "execute <cmd> on errors", on_error);
  command_parse(&program, argc, argv);

  // command required
  if (!program.argc) error("<cmd> required");
  const char *cmd = program.argv[0];
  
  // signals
  signal(SIGTERM, graceful_exit);
  signal(SIGQUIT, graceful_exit);
  
  // daemonize
  if (monitor.daemon) {
    daemonize();
    redirect_stdio_to(monitor.logfile);
  }
  
  // write mon pidfile
  if (monitor.mon_pidfile) {
    log("write mon pid to %s", monitor.mon_pidfile);
    write_pidfile(monitor.mon_pidfile, getpid());
  }
  
  start(cmd, &monitor);

  return 0;
}
Пример #11
0
int main (int argc, char **argv) {
    unsigned char *buf;
    long bufSize = 0;
    unsigned char *original;
    long originalSize = 0;
    unsigned char *originalGray = NULL;
    long originalGraySize = 0;
    unsigned char *compressed = NULL;
    unsigned long compressedSize = 0;
    unsigned char *compressedGray;
    long compressedGraySize = 0;
    unsigned char *tmpImage;
    int width, height;
    unsigned char *metaBuf;
    unsigned int metaSize = 0;
    FILE *file;

    // Parse commandline options
    command_t cmd;
    command_init(&cmd, argv[0], VERSION);
    cmd.usage = "[options] input.jpg compressed-output.jpg";
    command_option(&cmd, "-t", "--target [arg]", "Set target quality [0.9999]", setTarget);
    command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality);
    command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum);
    command_option(&cmd, "-x", "--max [arg]", "Maximum JPEG quality [95]", setMaximum);
    command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts);
    command_option(&cmd, "-a", "--accurate", "Favor accuracy over speed", setAccurate);
    command_option(&cmd, "-m", "--method [arg]", "Set comparison method to one of 'mpe', 'ssim', 'ms-ssim', 'smallfry' [ssim]", setMethod);
    command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip);
    command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish);
    command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom);
    command_option(&cmd, "-r", "--ppm", "Parse input as PPM instead of JPEG", setPpm);
    command_option(&cmd, "-c", "--no-copy", "Disable copying files that will not be compressed", setCopyFiles);
    command_option(&cmd, "-p", "--no-progressive", "Disable progressive encoding", setNoProgressive);
    command_parse(&cmd, argc, argv);

    if (cmd.argc < 2) {
        command_help(&cmd);
        return 255;
    }

    if (method == UNKNOWN) {
        fprintf(stderr, "Invalid method!");
        command_help(&cmd);
        return 255;
    }

    // No target passed, use preset!
    if (!target) {
        setTargetFromPreset();
    }

    // Read original
    bufSize = readFile((char *) cmd.argv[0], (void **) &buf);

    if (!bufSize) { return 1; }

    if (!ppm) {
        // Decode the JPEG
        originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB);
    } else {
        // Decode the PPM
        originalSize = decodePpm(buf, bufSize, &original, &width, &height);
    }

    if (defishStrength) {
        fprintf(stderr, "Defishing...\n");
        tmpImage = malloc(width * height * 3);
        defish(original, tmpImage, width, height, 3, defishStrength, defishZoom);
        free(original);
        original = tmpImage;
    }

    // Convert RGB input into Y
    originalGraySize = grayscale(original, &originalGray, width, height);

    if (!ppm) {
        // Read metadata (EXIF / IPTC / XMP tags)
        if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) {
            fprintf(stderr, "File already processed by jpeg-recompress!\n");
            if (copyFiles) {
                file = openOutput(cmd.argv[1]);
                fwrite(buf, bufSize, 1, file);
                fclose(file);

                free(buf);

                return 0;
            } else {
                free(buf);
                return 2;
            }
        }
    }

    if (strip) {
        // Pretend we have no metadata
        metaSize = 0;
    } else {
        fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024);
    }

    if (!originalSize || !originalGraySize) { return 1; }

    // Do a binary search to find the optimal encoding quality for the
    // given target SSIM value.
    int min = jpegMin, max = jpegMax;
    for (int attempt = attempts - 1; attempt >= 0; --attempt) {
        float metric;
        int quality = min + (max - min) / 2;
        int progressive = attempt ? 0 : !noProgressive;
        int optimize = accurate ? 1 : (attempt ? 0 : 1);

        // Recompress to a new quality level, without optimizations (for speed)
        compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, progressive, optimize);

        // Load compressed luma for quality comparison
        compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE);

        if (!compressedGraySize) {
          fprintf(stderr, "Unable to decode file that was just encoded!\n");
          return 1;
        }

        if (!attempt) {
            fprintf(stderr, "Final optimized ");
        }

        // Measure quality difference
        switch (method) {
            case MS_SSIM:
                metric = iqa_ms_ssim(originalGray, compressedGray, width, height, width, 0);
                fprintf(stderr, "ms-ssim");
                break;
            case SMALLFRY:
                metric = smallfry_metric(originalGray, compressedGray, width, height);
                fprintf(stderr, "smallfry");
                break;
            case MPE:
                metric = meanPixelError(originalGray, compressedGray, width, height, 1);
                fprintf(stderr, "mpe");
                break;
            case SSIM: default:
                metric = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0);
                fprintf(stderr, "ssim");
                break;
        }

        if (attempt) {
            fprintf(stderr, " at q=%i (%i - %i): %f\n", quality, min, max, metric);
        } else {
            fprintf(stderr, " at q=%i: %f\n", quality, metric);
        }

        if (metric < target) {
            if (compressedSize >= bufSize) {
                fprintf(stderr, "Output file would be larger than input!\n");
                free(compressed);
                free(compressedGray);

                if (copyFiles) {
                    file = openOutput(cmd.argv[1]);
                    fwrite(buf, bufSize, 1, file);
                    fclose(file);

                    free(buf);

                    return 0;
                } else {
                    free(buf);
                    return 1;
                }
            }

            switch (method) {
                case SSIM: case MS_SSIM: case SMALLFRY:
                    // Too distorted, increase quality
                    min = quality + 1;
                    break;
                case MPE:
                    // Higher than required, decrease quality
                    max = quality - 1;
                    break;
            }
        } else {
            switch (method) {
                case SSIM: case MS_SSIM: case SMALLFRY:
                    // Higher than required, decrease quality
                    max = quality - 1;
                    break;
                case MPE:
                    // Too distorted, increase quality
                    min = quality + 1;
                    break;
            }
        }

        // If we aren't done yet, then free the image data
        if (attempt) {
            free(compressed);
            free(compressedGray);
        }
    }

    free(buf);

    // Calculate and show savings, if any
    int percent = (compressedSize + metaSize) * 100 / bufSize;
    unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0;
    fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024);

    if (compressedSize >= bufSize) {
        fprintf(stderr, "Output file is larger than input, aborting!\n");
        return 1;
    }

    // Open output file for writing
    file = openOutput(cmd.argv[1]);

    // Write output
    fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */

    // Write comment so we know not to reprocess this file
    // in the future if it gets passed in again.
    // 0xfffe (COM marker), two-byte big-endian length, string
    fputc(0xff, file);
    fputc(0xfe, file);
    fputc(0x00, file);
    fputc(32, file);
    fwrite(COMMENT, 30, 1, file);

    // Write metadata markers
    if (!strip && !ppm) {
        fwrite(metaBuf, metaSize, 1, file);
    }

    // Write image data
    fwrite(compressed + 20, compressedSize - 20, 1, file);
    fclose(file);

    // Cleanup
    command_free(&cmd);

    if (!strip && !ppm) {
        free(metaBuf);
    }

    free(compressed);
    free(original);
    free(originalGray);

    return 0;
}
Пример #12
0
int main(int argc, char *argv[])
{
    cli_init();
    log_init();
    thread_init();
    cmd_init();
    dev_addr_mgr_init();
    addr_sock_init();
    socket_init();
    dev_router_init();
    cli_commands_init();

    broadcast_msg_t msg;
    dev_addr_mgr_add_support_dev_type(1);
    dev_addr_mgr_set_network_type(NETWORK_TYPE_CENTER);
    dev_addr_mgr_set_addr_mac(0x89ABCDE0);

    dev_router_set_mac_local(0x89ABCDE0);

#ifdef TEST_CLIENT
    ex_memzero_one(&msg);
    strcpy(msg.dev_name, "1004");
    msg.router_list_lens[0] = 3;
    msg.router_list_lens[1] = 3;
    msg.router_list_lens[2] = 0;
    msg.router_list_lens[3] = 0;
    msg.router_cnt = 7;
    msg.router_list_cnt = 2;
    msg.network_nodes[0].dev_type = 1;
    msg.network_nodes[0].addr_mac = 0x89ABCDE0;
    msg.network_nodes[0].subnet_cnt = 4;
    msg.network_nodes[0].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[0].dev_name, "1004");

    msg.network_nodes[1].dev_type = 1;
    msg.network_nodes[1].addr_mac = 0x89ABCDE1;
    msg.network_nodes[1].subnet_cnt = 4;
    msg.network_nodes[1].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[1].dev_name, "1003");

    msg.network_nodes[2].dev_type = 1;
    msg.network_nodes[2].addr_mac = 0x89ABCDE2;
    msg.network_nodes[2].subnet_cnt = 4;
    msg.network_nodes[2].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[2].dev_name, "1002");

    msg.network_nodes[3].dev_type = 1;
    msg.network_nodes[3].addr_mac = 0x89ABCDE3;
    msg.network_nodes[3].subnet_cnt = 4;
    msg.network_nodes[3].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[3].dev_name, "1001");

    msg.network_nodes[4].dev_type = 1;
    msg.network_nodes[4].addr_mac = 0x89ABCDE4;
    msg.network_nodes[4].subnet_cnt = 4;
    msg.network_nodes[4].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[4].dev_name, "1005");

    msg.network_nodes[5].dev_type = 1;
    msg.network_nodes[5].addr_mac = 0x89ABCDE5;
    msg.network_nodes[5].subnet_cnt = 4;
    msg.network_nodes[5].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[5].dev_name, "1006");

    msg.network_nodes[6].dev_type = 1;
    msg.network_nodes[6].addr_mac = 0x89ABCDE6;
    msg.network_nodes[6].subnet_cnt = 4;
    msg.network_nodes[6].network_type = NETWORK_TYPE_ROUTER;
    strcpy(msg.network_nodes[6].dev_name, "1007");
#endif

    socket_listen_async(50002);
    socket_listen_cli(49999);
    socket_recv_start();
#ifdef TEST_SERVER
    socket_bc_tx_start("test", 50000, 50001, 50002);
#endif
#ifdef TEST_CLIENT
    socket_bc_rx_start("test", 50000, 50001, &msg);
#endif

#if 0
    cstr *json = cstr_new();
    int fd = 0;
    fd = socket_cli_send_request("127.0.0.1", 49999, "test");
    socket_cli_recv_response(fd, json);
    cstr_clear(json);
    fd = socket_cli_send_request("127.0.0.1", 49999, "test f**k");
    socket_cli_recv_response(fd, json);
    cstr_clear(json);
    fd = socket_cli_send_request("127.0.0.1", 49999, "f**k f**k f**k you test f**k");
    socket_cli_recv_response(fd, json);
    cstr_free(json);
#endif

    cli_loop();

    dev_addr_mgr_release();
    socket_release();
    cmd_release();
    thread_release();
    log_release();
    cli_release();
#if 0
  cli_cmd_t cmd;
  int i = 0;

  command_init(&cmd, argv[0], "0.0.1");
  command_option(&cmd, "-v", "--verbose", "enable verbose stuff", verbose);
  command_option(&cmd, "-r", "--required <arg>", "required arg", required);
  command_option(&cmd, "-o", "--optional [arg]", "optional arg", optional);
  command_parse(&cmd, argc, argv);
  printf("additional args:\n");
  for (i = 0; i < cmd.argc; ++i) {
    printf("  - '%s'\n", cmd.argv[i]);
  }
  command_free(&cmd);
#endif
    return 0;
}
Пример #13
0
int main (int argc, char **argv) {
    unsigned char *buf;
    long bufSize = 0;
    unsigned char *original;
    long originalSize = 0;
    unsigned char *originalGray;
    long originalGraySize = 0;
    unsigned char *compressed = NULL;
    unsigned long compressedSize = 0;
    unsigned char *compressedGray;
    long compressedGraySize = 0;
    unsigned char *tmpImage;
    int width, height;
    unsigned char *metaBuf;
    unsigned int metaSize = 0;

    // Parse commandline options
    command_t cmd;
    command_init(&cmd, argv[0], "1.0.1");
    cmd.usage = "[options] input.jpg compressed-output.jpg";
    command_option(&cmd, "-t", "--target [arg]", "Set target SSIM [0.9999]", setTarget);
    command_option(&cmd, "-q", "--quality [arg]", "Set a quality preset: low, medium, high, veryhigh [medium]", setQuality);
    command_option(&cmd, "-n", "--min [arg]", "Minimum JPEG quality [40]", setMinimum);
    command_option(&cmd, "-m", "--max [arg]", "Maximum JPEG quality [95]", setMaximum);
    command_option(&cmd, "-l", "--loops [arg]", "Set the number of runs to attempt [6]", setAttempts);
    command_option(&cmd, "-p", "--progressive", "Set progressive JPEG output", setProgressive);
    command_option(&cmd, "-s", "--strip", "Strip metadata", setStrip);
    command_option(&cmd, "-d", "--defish [arg]", "Set defish strength [0.0]", setDefish);
    command_option(&cmd, "-z", "--zoom [arg]", "Set defish zoom [1.0]", setZoom);
    command_parse(&cmd, argc, argv);

    if (cmd.argc < 2) {
        command_help(&cmd);
        return 255;
    }

    // Read original
    bufSize = readFile((char *) cmd.argv[0], (void **) &buf);

    if (!bufSize) { return 1; }

    // Decode the JPEG
    originalSize = decodeJpeg(buf, bufSize, &original, &width, &height, JCS_RGB);

    if (defishStrength) {
        fprintf(stderr, "Defishing...\n");
        tmpImage = malloc(width * height * 3);
        defish(original, tmpImage, width, height, 3, defishStrength, defishZoom);
        free(original);
        original = tmpImage;
    }

    // Convert RGB input into Y
    originalGraySize = width * height;
    originalGray = malloc(originalGraySize);
    int stride = width * 3;
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // Y = 0.299R + 0.587G + 0.114B
            originalGray[y * width + x] = original[y * stride + x * 3] * 0.299 +
                                          original[y * stride + x * 3 + 1] * 0.587 +
                                          original[y * stride + x * 3 + 2] * 0.114 + 0.5;
        }
    }

    // Read metadata (EXIF / IPTC / XMP tags)
    if (getMetadata(buf, bufSize, &metaBuf, &metaSize, COMMENT)) {
        fprintf(stderr, "File already processed by jpeg-recompress!\n");
        return 2;
    }

    if (strip) {
        // Pretend we have no metadata
        metaSize = 0;
    } else {
        fprintf(stderr, "Metadata size is %ukb\n", metaSize / 1024);
    }

    if (!originalSize || !originalGraySize) { return 1; }
    free(buf);

    // Do a binary search to find the optimal encoding quality for the
    // given target SSIM value.
    int min = jpegMin, max = jpegMax;
    for (int attempt = attempts - 1; attempt >= 0; --attempt) {
        int quality = min + (max - min) / 2;

        // Recompress to a new quality level (progressive only on last run if
        // it was requested, as this saves time)
        compressedSize = encodeJpeg(&compressed, original, width, height, JCS_RGB, quality, (attempt == 0) ? progressive : 0);

        // Load compressed luma for quality comparison
        compressedGraySize = decodeJpeg(compressed, compressedSize, &compressedGray, &width, &height, JCS_GRAYSCALE);

        // Measure structural similarity (SSIM)
        float ssim = iqa_ssim(originalGray, compressedGray, width, height, width, 0, 0);
        fprintf(stderr, "ssim at q=%i (%i - %i): %f\n", quality, min, max, ssim);

        if (ssim < target) {
            if (compressedSize >= bufSize) {
                fprintf(stderr, "Output file would be larger than input, aborting!\n");
                free(compressed);
                free(compressedGray);
                return 1;
            }

            // Too distorted, increase quality
            min = quality + 1;
        } else {
            // Higher SSIM than required, decrease quality
            max = quality - 1;
        }

        // If we aren't done yet, then free the image data
        if (attempt) {
            free(compressed);
            free(compressedGray);
        }
    }

    // Calculate and show savings, if any
    int percent = (compressedSize + metaSize) * 100 / bufSize;
    unsigned long saved = (bufSize > compressedSize) ? bufSize - compressedSize - metaSize : 0;
    fprintf(stderr, "New size is %i%% of original (saved %lu kb)\n", percent, saved / 1024);

    if (compressedSize >= bufSize) {
        fprintf(stderr, "Output file is larger than input, aborting!\n");
        return 1;
    }

    // Write output
    FILE *file;

    if (strcmp("-", cmd.argv[1]) == 0) {
        file = stdout;
    } else {
        file = fopen(cmd.argv[1], "wb");
    }

    fwrite(compressed, 20, 1, file); /* 0xffd8 and JFIF marker */

    // Write comment so we know not to reprocess this file
    // in the future if it gets passed in again.
    // 0xfffe (COM marker), two-byte big-endian length, string
    fputc(0xff, file);
    fputc(0xfe, file);
    fputc(0x00, file);
    fputc(32, file);
    fwrite(COMMENT, 30, 1, file);

    // Write metadata markers
    if (!strip) {
        fwrite(metaBuf, metaSize, 1, file);
    }

    // Write image data
    fwrite(compressed + 20, compressedSize - 20, 1, file);
    fclose(file);

    // Cleanup
    command_free(&cmd);

    if (!strip) {
        free(metaBuf);
    }

    free(compressed);
    free(original);
    free(originalGray);
    free(compressedGray);

    return 0;
}
Пример #14
0
int main(int argc, char** argv)
{
    struct paki_args args;

    // read arguments
    memset(&args, 0x00, sizeof(args));

    args.compress_mode = COMPRESS_NORMAL;
    command_t cmd;
    command_init(&cmd, argv[0], VERSION);
    command_option_pos(&cmd, "pakfile", "pakfile (.pak)", 0, cmdline_pakfile);
    command_option_pos(&cmd, "path", "path to input directory (for compress mode) or"
                       " path to a file in pakfile (for extract mode)", 1, cmdline_path);
    command_option(&cmd, "-v", "--verbose", "enable verbose mode", cmdline_verbose);
    command_option(&cmd, "-l", "--list", "list files in pak", cmdline_list);
    command_option(&cmd, "-x", "--extract", "extract a file from pak", cmdline_extract);
    command_option(&cmd, "-c", "--compress", "compress a directory into pak", cmdline_compress);
    command_option(&cmd, "-z", "--zmode <mode>", "define compression mode, "
                   "compression modes are (none, normal, best, fast)", cmdline_compressmode);
    cmd.data = &args;
    command_parse(&cmd, argc, argv, NULL);
    command_free(&cmd);

    core_init(CORE_INIT_ALL);
    log_outputconsole(TRUE);

    /* check for arguments validity */
    if (args.pakfile[0] == 0 ||
            ((BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT) +
              BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS) +
              BIT_CHECK(args.usage, PAKI_USAGE_LIST)) != 1))
    {
        printf(TERM_BOLDRED "Invalid arguments\n" TERM_RESET);
        core_release(FALSE);
        return -1;
    }

    if (BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT) || BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS)) {
        if (str_isempty(args.path)) {
            printf(TERM_BOLDRED "'path' argument is not provided\n" TERM_RESET);
            core_release(FALSE);
            return -1;
        }
    }

    /* creating archive (-c flag) */
    if (BIT_CHECK(args.usage, PAKI_USAGE_COMPRESS))     {
        save_pak(&args);
    }   else if(BIT_CHECK(args.usage, PAKI_USAGE_EXTRACT))  {
        load_pak(&args);
    } else if(BIT_CHECK(args.usage, PAKI_USAGE_LIST))	{
        list_pak(&args);
    }

#if defined(_DEBUG_)
    core_release(TRUE);
#else
    core_release(FALSE);
#endif
    return 0;
}
Пример #15
0
int main( int   argc,
	  char *argv[])
#endif
{
#if defined(USE_GTK2_GEOMETRY_METHOD) && defined (GEOMETRY)
	g_debug("GEOMETRY_NONE  = 0x%X", GEOMETRY_NONE );
	g_debug("GEOMETRY_UPDATE_PAGE_NAME = 0x%X", GEOMETRY_UPDATE_PAGE_NAME);
	g_debug("GEOMETRY_UPDATE_PAGE_NAME_MASK = 0x%X", GEOMETRY_UPDATE_PAGE_NAME_MASK);
	g_debug("GEOMETRY_CHANGING_THEME = 0x%X", GEOMETRY_CHANGING_THEME);
	g_debug("GEOMETRY_SHOW_HIDE_SCROLL_BAR = 0x%X", GEOMETRY_SHOW_HIDE_SCROLL_BAR);
	g_debug("GEOMETRY_SHOW_HIDE_TAB_BAR = 0x%X", GEOMETRY_SHOW_HIDE_TAB_BAR);
	g_debug("GEOMETRY_CHANGING_FONT = 0x%X", GEOMETRY_CHANGING_FONT);

	g_debug("GEOMETRY_NEEDS_RUN_SIZE_REQUEST_MASK = 0x%X", GEOMETRY_NEEDS_RUN_SIZE_REQUEST_MASK);
	g_debug("GEOMETRY_NEEDS_RUN_SIZE_REQUEST_AGAIN_MASK = 0x%X", GEOMETRY_NEEDS_RUN_SIZE_REQUEST_AGAIN_MASK);
	g_debug("GEOMETRY_HAD_BEEN_RESIZED_ONCE_MASK = 0x%X", GEOMETRY_HAD_BEEN_RESIZED_ONCE_MASK);
#endif
	// command_line_path = argv[0];

	// g_debug ("argc = %d", argc);
	// print_array ("argv", argv);
	// i18n support. We need to support i18n under console, too.
	setlocale(LC_ALL, "");
	bindtextdomain(BINARY, LOCALEDIR);
	bind_textdomain_codeset(BINARY, "UTF-8");
	textdomain(BINARY);

#if ! defined(SAFEMODE) && defined(DEVELOP)
	g_message("Running %s without SAFE MODE!", PACKAGE);
#endif

#ifdef OUT_OF_MEMORY
#  undef g_strdup_printf
#endif
#ifdef ENABLE_PROFILE
	const gchar *user_config_dir = g_get_user_config_dir();
	if (user_config_dir) profile_dir = g_strdup_printf("%s/%s", user_config_dir, BINARY);
#endif
#ifdef OUT_OF_MEMORY
	#define g_strdup_printf(...) NULL
#endif
	// in BSD system, /proc may not exist.
	proc_exist = check_if_default_proc_dir_exist(NULL);
	// g_debug ("Get proc_exist = %d, proc_file_system_path = %s", proc_exist, proc_file_system_path);

	shell = g_getenv("SHELL");
	if (shell==NULL) shell = "";

	gboolean pwd_need_be_free = FALSE;
	pwd = (gchar *)g_getenv("PWD");
	if (pwd==NULL)
	{
		pwd_need_be_free = TRUE;
		pwd = g_get_current_dir();
	}
	if (pwd==NULL)
	{
		pwd_need_be_free = FALSE;
		pwd = "";
	}
	// g_debug("Got $PWD = %s", pwd);

	home = g_getenv("HOME");
	if (home==NULL) home = "";
	// g_debug("Get $HOME = %s", home);

	// deal the command line options
	command_option(argc, argv);
	if (wmclass_name==NULL) wmclass_name = g_getenv("RESOURCE_NAME");
	if (wmclass_name==NULL) wmclass_name = "";
	if (wmclass_class==NULL) wmclass_class = "";
	// g_debug("Got wmclass_name = %s, wmclass_class = %s", wmclass_name, wmclass_class);

	// init the gtk+2 engine

	// GTK3: get gtk_test_widget_click() working...
	// gdk_disable_multidevice();

#ifndef UNIT_TEST
	gtk_init(&argc, &argv);
#endif
	// FIXME: we should get the single_process from profile. Current is command-line option only.
	if (single_process)
	{
		gchar *socket_str = convert_socket_data_to_string(argv);
		if (init_gtk_socket(SOCKET_FILE, socket_str, (GSourceFunc)convert_string_to_socket_data) == UNIX_SOCKET_DATA_SENT)
		{
			g_free(profile_dir);
			exit (0);
		}
		g_free(socket_str);
	}

	// start LilyTerm

	// empty_environ = g_strsplit("", " ", -1);
	extern gchar **environ;
	// print_array("main(): environ", environ);
	gchar *environ_str = convert_array_to_string(environ, '\t');
	// if (window_list) g_error("CHECK: window_list = %p !!", window_list);
	// g_debug("Got environ_str (in main.c) = %s", environ_str);
	selection_clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
	selection_primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
	system_locale_list = get_locale_list();
	// g_debug("Got system_locale_list = %s", system_locale_list);
	init_LC_CTYPE = g_strdup(get_default_lc_data(LC_CTYPE));
	// g_debug("Got init_LC_CTYPE = %s", init_LC_CTYPE);
	init_LANGUAGE = g_strdup(get_default_lc_data(LANGUAGE));
	// g_debug("Got init_LANGUAGE = %s", init_LANGUAGE);
	init_LC_MESSAGES = g_strdup(get_default_lc_data(LC_MESSAGES));
	// g_debug("init_LC_MESSAGES = %s", init_LC_MESSAGES);
	init_encoding = (gchar *)get_encoding_from_locale(NULL);
	if (! compare_strings(init_encoding, "ANSI_X3.4-1968", TRUE))
	{
		g_free(init_encoding);
		init_encoding = g_strdup("UTF-8");
	}
	// g_debug("init_encoding = %s", init_encoding);
	SYSTEM_VTE_CJK_WIDTH_STR = g_getenv("VTE_CJK_WIDTH");
	// g_debug ("Got SYSTEM_VTE_CJK_WIDTH_STR = %s", SYSTEM_VTE_CJK_WIDTH_STR);
	// FIXME: signal(SIGCHLD, SIG_IGN);
	// The first window of LilyTerm

	// Convert the GdkColor to GdkRGBA
	convert_system_color_to_rgba();

	// g_debug("Got original encoding = %s", get_encoding_from_locale(NULL));
	//GtkNotebook *new_window(int argc,
	//			char *argv[],
	//			gchar *shell,
	//			gchar *environment,
	//			gchar *locale_list,
	//			gchar *PWD,
	//			gchar *HOME,
	//			gchar *VTE_CJK_WIDTH_STR,
	//			gboolean VTE_CJK_WIDTH_STR_overwrite_profile,
	//			gchar *wmclass_name,
	//			gchar *wmclass_class,
	//			gchar *user_environ,
	//			gchar *encoding,
	//			gboolean encoding_overwrite_profile,
	//			gchar *lc_messages,
	//			struct Window *win_data_orig,
	//			struct Page *page_data_orig)

	// g_debug("main(1): gtk_main_level = %d, g_list_length(window_list) = %d", gtk_main_level(), g_list_length(window_list));
	if ((new_window(argc,
			argv,
			(gchar *) shell,
			environ_str,
			system_locale_list,
			(gchar *) pwd,
			(gchar *) home,
			SYSTEM_VTE_CJK_WIDTH_STR,
			FALSE,
			wmclass_name,
			wmclass_class,
			NULL,
			init_encoding,
			FALSE,
			init_LC_MESSAGES,
			NULL,
			NULL)) ||
	     g_list_length(window_list))
	{
		// The argv of "main" LilyTerm can't be free.
		// Set it to NULL here to avoid double_free().
		argv=NULL;
#ifdef ENABLE_X_STARTUP_NOTIFICATION_ID
		gdk_notify_startup_complete_with_id(PACKAGE);
#endif
		// g_debug("main(2): gtk_main_level = %d, g_list_length(window_list) = %d", gtk_main_level(), g_list_length(window_list));
		if (! gtk_main_level())
			gtk_main();
	}
#ifdef DETAIL
	else
	{
//		g_debug("Got window_list = %p", window_list);
//		GList *win_list = window_list;
//		gint i=0;
//
//		while (win_list)
//		{
//			g_debug("Got %d win_data = %p", ++i, win_list->data);
//			win_list = win_list->next;
//		}
		g_debug("??? The creation of first window is FAIL!!!");
	}
#endif
	extern struct KeyValue system_keys[KEYS];
	gint i;
	// g_debug("Clear function key data!!");
	for (i=KEY_SWITCH_TO_TAB_1; i<=KEY_SWITCH_TO_TAB_12; i++)
	{
		g_free(system_keys[i].name);
		g_free(system_keys[i].topic);
		g_free(system_keys[i].comment);
		g_free(system_keys[i].translation);
#ifdef UNIT_TEST
		system_keys[i].name = NULL;
		system_keys[i].topic = NULL;
		system_keys[i].comment = NULL;
		system_keys[i].translation = NULL;
#endif
	}

	// g_free(pwd);
	// g_strfreev(empty_environ);
	g_free(environ_str);
	g_free(init_encoding);
	g_free(system_locale_list);
	g_free(profile_dir);
	if (pwd_need_be_free) g_free(pwd);
	g_free(restricted_locale_message);
	g_list_free(window_list);
	g_free(init_LC_CTYPE);
	g_free(init_LC_MESSAGES);
#ifdef UNIT_TEST
	// empty_environ = NULL;
	environ_str = NULL;
	init_encoding = NULL;
	system_locale_list = NULL;
	profile_dir = NULL;
	restricted_locale_message = NULL;
	window_list = NULL;
	init_LC_CTYPE = NULL;
	init_LC_MESSAGES = NULL;
#endif
	return 0;
}
Пример #16
0
int main( int   argc,
	  char *argv[])
#endif
{
	// command_line_path = argv[0];

	// g_debug ("argc = %d", argc);
	// print_array ("argv", argv);
	// i18n support. We need to support i18n under console, too.
	setlocale(LC_ALL, "");
	bindtextdomain (BINARY, LOCALEDIR);
	bind_textdomain_codeset (BINARY, "UTF-8");
	textdomain (BINARY);

	const gchar *user_config_dir = g_get_user_config_dir();

#ifdef OUT_OF_MEMORY
#  undef g_strdup_printf
#endif
	if (user_config_dir) profile_dir = g_strdup_printf("%s/%s", user_config_dir, BINARY);
#ifdef OUT_OF_MEMORY
	#define g_strdup_printf(...) NULL
#endif

	// g_debug("profile_dir = %s", profile_dir);
	proc_exist = g_file_test("/proc", G_FILE_TEST_EXISTS);

	if (proc_exist)
	{
		gboolean proc_is_exist = FALSE;
		GDir *dir  = g_dir_open ("/proc", 0, NULL);
		if (dir)
		{
			const gchar *entry = g_dir_read_name(dir);
			if (entry) proc_is_exist = TRUE;
		}
		g_dir_close(dir);
		// g_debug ("Got proc_is_exist = %d", proc_is_exist);
		proc_exist = proc_is_exist;
	}

	shell = g_getenv("SHELL");
	if (shell==NULL) shell = "";

	pwd = g_getenv("PWD");
	// pwd = g_get_current_dir();
#ifdef SAFEMODE
	if (pwd==NULL) pwd = g_strdup("");
#endif
	// g_debug("Got $PWD = %s", pwd);
	home = g_getenv("HOME");
	if (home==NULL) home = "";
	// g_debug("Get $HOME = %s", home);

	// deal the command line options
	command_option(argc, argv);
	if (wmclass_name==NULL) wmclass_name = g_getenv("RESOURCE_NAME");
	if (wmclass_name==NULL) wmclass_name = "";
	if (wmclass_class==NULL) wmclass_class = "";
	// g_debug("Got wmclass_name = %s, wmclass_class = %s", wmclass_name, wmclass_class);

	// init the gtk+2 engine
#ifndef UNIT_TEST
	gtk_init(&argc, &argv);
#endif
	// FIXME: we should get the single_process from profile. Current is command-line option only.
	if (single_process)
	{
		// init socket data
		if (init_socket_data())
		{
			// trying to connect to an existing LilyTerm
			if (query_socket())
			{
				// success, sent the argc/argv to socket then quit
				// g_debug("A LilyTerm socket server is exist already. exiting...");
				if (send_socket(argc, argv, TRUE))
				{
					g_free(profile_dir);
					exit (0);
				}
			}
			// no LilyTerm exist. create a socket server
			// g_debug("Creating a LilyTerm socket server...");
			init_socket_server();
			g_atexit((GVoidFunc)shutdown_socket_server);
		}
	}

	// start LilyTerm

	// empty_environ = g_strsplit("", " ", -1);
	extern gchar **environ;
	// print_array("main(): environ", environ);
	gchar *environ_str = convert_array_to_string(environ, '\t');
	window_list = NULL;
	// g_debug("Got environ_str (in main.c) = %s", environ_str);
	selection_clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
	selection_primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
	system_locale_list = get_locale_list();
	// g_debug("Got system_locale_list = %s", system_locale_list);
	init_LC_CTYPE = g_strdup(get_default_lc_data(LC_CTYPE));
	// g_debug("Got init_LC_CTYPE = %s", init_LC_CTYPE);
	init_LC_MESSAGES = g_strdup(get_default_lc_data(LC_MESSAGES));
	// g_debug("init_LC_MESSAGES = %s", init_LC_MESSAGES);
	init_encoding = (gchar *)get_encoding_from_locale(NULL);
	if (! compare_strings(init_encoding, "ANSI_X3.4-1968", TRUE))
	{
		g_free(init_encoding);
		init_encoding = g_strdup("UTF-8");
	}
	// g_debug("init_encoding = %s", init_encoding);
	SYSTEM_VTE_CJK_WIDTH_STR = g_getenv("VTE_CJK_WIDTH");
	// g_debug ("Got SYSTEM_VTE_CJK_WIDTH_STR = %s", SYSTEM_VTE_CJK_WIDTH_STR);
	// FIXME: signal(SIGCHLD, SIG_IGN);
	// The first window of LilyTerm

	// g_debug("Got original encoding = %s", get_encoding_from_locale(NULL));
	//GtkNotebook *new_window(int argc,
	//			char *argv[],
	//			gchar *shell,
	//			gchar *environment,
	//			gchar *locale_list,
	//			gchar *PWD,
	//			gchar *HOME,
	//			gchar *VTE_CJK_WIDTH_STR,
	//			gboolean VTE_CJK_WIDTH_STR_overwrite_profile,
	//			gchar *wmclass_name,
	//			gchar *wmclass_class,
	//			gchar *user_environ,
	//			gchar *encoding,
	//			gboolean encoding_overwrite_profile,
	//			gchar *lc_messages,
	//			struct Window *win_data_orig,
	//			struct Page *page_data_orig)

	if ((new_window(argc,
			argv,
			(gchar *) shell,
			environ_str,
			system_locale_list,
			(gchar *) pwd,
			(gchar *) home,
			SYSTEM_VTE_CJK_WIDTH_STR,
			FALSE,
			wmclass_name,
			wmclass_class,
			NULL,
			init_encoding,
			FALSE,
			init_LC_MESSAGES,
			NULL,
			NULL)) ||
	     window_list)
	{
		// The argv of "main" LilyTerm can't be free.
		// Set it to NULL here to avoid double_free().
		argv=NULL;
		// g_debug("gtk_main_level = %d", gtk_main_level());
		if (! gtk_main_level())
			gtk_main();
	}
#ifdef DETAIL
	else
	{
//		g_debug("Got window_list = %p", window_list);
//		GList *win_list = window_list;
//		gint i=0;
//
//		while (win_list)
//		{
//			g_debug("Got %d win_data = %p", ++i, win_list->data);
//			win_list = win_list->next;
//		}
		g_debug("??? The creation of first window is FAIL!!!");
	}
#endif
	extern struct KeyValue system_keys[KEYS];
	gint i;
	// g_debug("Clear function key data!!");
	for (i=KEY_SWITCH_TO_TAB_1; i<=KEY_SWITCH_TO_TAB_12; i++)
	{
		g_free(system_keys[i].name);
		g_free(system_keys[i].topic);
		g_free(system_keys[i].comment);
		g_free(system_keys[i].translation);
#ifdef UNIT_TEST
		system_keys[i].name = NULL;
		system_keys[i].topic = NULL;
		system_keys[i].comment = NULL;
		system_keys[i].translation = NULL;
#endif
	}

	// g_free(pwd);
	// g_strfreev(empty_environ);
	g_free(environ_str);
	g_free(init_encoding);
	g_free(system_locale_list);
	g_free(profile_dir);
	g_free(restricted_locale_message);
	g_list_free(window_list);
	g_free(init_LC_CTYPE);
	g_free(init_LC_MESSAGES);
#ifdef UNIT_TEST
	// empty_environ = NULL;
	environ_str = NULL;
	init_encoding = NULL;
	system_locale_list = NULL;
	profile_dir = NULL;
	restricted_locale_message = NULL;
	window_list = NULL;
	init_LC_CTYPE = NULL;
	init_LC_MESSAGES = NULL;
#endif
	return 0;
}