文書の過去の版を表示しています。


サンプルアプリケーション: カウントダウンタイマー

FLTK

スクリーンショット

プロジェクトレイアウト

countdown_timer/
├── CMakeLists.txt
└── main.cpp

CMakeファイル

CMakeLists.txt:

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)

project(countdown_timer LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED YES)
set(CMAKE_CXX_EXTENSIONS OFF)

find_package(FLTK 1.4 REQUIRED CONFIG)

add_executable(countdown_timer main.cpp)

target_link_libraries(countdown_timer PRIVATE fltk::fltk)

プログラムのソースコード

main.cpp:

#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Window.H>

#include <array>
#include <cstdio>

struct AppContext {
  int start = 10;
  int count = 0;
  Fl_Box *countdown_digits;
  Fl_Button *start_button;
  Fl_Button *reset_button;
  std::array<char, 100> cbuf;
};

AppContext *as_app_context(void *ptr) { return static_cast<AppContext *>(ptr); }

void update_countdown_digits_label(AppContext *ctx) {
  snprintf(ctx->cbuf.data(), sizeof(ctx->cbuf), "%d", ctx->count);
  ctx->countdown_digits->label(ctx->cbuf.data());
}

void timeout_cb(void *data) {
  auto ctx = as_app_context(data);

  if (ctx->count <= 0) {
    ctx->start_button->activate();
    return;
  }

  --ctx->count;

  update_countdown_digits_label(ctx);

  Fl::repeat_timeout(1.0, timeout_cb, ctx);
}

void start_button_cb(Fl_Widget *w, void *data) {
  Fl::add_timeout(1.0, timeout_cb, data);
  w->deactivate();
}

void reset_button_cb(Fl_Widget *w, void *data) {
  auto ctx = as_app_context(data);
  ctx->count = ctx->start;
  update_countdown_digits_label(ctx);
}

int main() {
  auto window = new Fl_Window(600, 600, "Timer foo");

  auto countdown_digits = new Fl_Box(200, 200, 200, 200);
  countdown_digits->box(FL_DOWN_BOX);
  countdown_digits->labelfont(FL_BOLD);
  countdown_digits->labelsize(80);
  countdown_digits->labeltype(FL_SHADOW_LABEL);

  auto start_button = new Fl_Button(210, 420, 80, 30, "スタート");
  auto reset_button = new Fl_Button(310, 420, 80, 30, "リセット");

  int const countdown_start = 10;

  AppContext ctx{
      .start = countdown_start,
      .count = countdown_start,
      .countdown_digits = countdown_digits,
      .start_button = start_button,
      .reset_button = reset_button,
  };

  update_countdown_digits_label(&ctx);
  start_button->callback(start_button_cb, &ctx);
  reset_button->callback(reset_button_cb, &ctx);

  window->end();
  window->show();
  return Fl::run();
}

文書の編集
文書の先頭へ